Web3.js deploys and calls smart contracts on Ethereum

Web3.js deploys and calls smart contracts on Ethereum

Introduce how to use Web3.js to deploy and call smart contracts on Ethereum; Web3.js is the implementation of the Ethereum JavaScript API, which can interact with the Ethereum blockchain

Smart contract writing

Write a simple smart contract using Solidity, then deploy it to the Ethereum blockchain using Web3.js, calling the smart contract via JavaScript

solidityCopy codepragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private _value;

    function getValue() public view returns (uint256) {
        return _value;
    }

    function setValue(uint256 value) public {
        _value = value;
    }
}

This smart contract is very simple. It has two functions: getValueand setValue. getValueThe function returns _valuethe value of the private variable and setValuethe function will _valuebe set to the value passed in

Next, we will use the Truffle framework to compile, test and deploy smart contracts. If you do not have Truffle installed, enter the following command at the command line to install it:

Copy code
npm install -g truffle

Create a new directory on the command line and run the following command in the directory to create a Truffle project:

csharpCopy code
truffle init

Copy the Solidity code above into contracts/SimpleStorage.sola file. Next, we need to migrationscreate a JavaScript file in the directory that will be used to deploy the contract to the Ethereum network:

javascriptCopy codeconst SimpleStorage = artifacts.require("SimpleStorage");

module.exports = function(deployer) {
  deployer.deploy(SimpleStorage);
};

The contract can be compiled and deployed using the following commands on the command line:

pythonCopy codetruffle compile
truffle migrate

Smart contracts have been deployed into the Ethereum network. Next, we will use Web3.js to interact with this contract. We will use Web3.js in the HTML file, so we need to introduce the Web3.js library into the HTML file:

htmlCopy code<!DOCTYPE html>
<html>
<head>
  <title>Web3.js Demo</title>
  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>
<body>
  <h1>Web3.js Demo</h1>
  <div>
    <label for="value-input">Enter a value:</label>
    <input type="number" id="value-input">
    <button onclick="setValue()">Set Value</button>
  </div>
  <div>
    <label for="value-output">Current value:</label>
    <span id="value-output"></span>
    <button onclick="getValue()">Get Value</button>
  </div>
  <script src="app.js"></script>
</body>
</html>

JavaScript code to interact with smart contracts. Create a file called in the root directory of your project app.jsand copy the following code into the file:

javascriptCopy codeconst contractAddress = "0x1234567890123456789012345678901234567890"; // 智能合约地址
const abi = [
  {
     
     
    "inputs": [],
    "name": "getValue",
    "outputs": [
      {
     
     
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
     
     
    "inputs": [
      {
     
     
        "internalType": "uint256",
        "name": "value",
        "type": "uint256"
      }
    ],
    "name": "setValue",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
]; // 合约ABI

const web3 = new Web3(Web3.givenProvider || "http://localhost:8545"); // 初始化Web3实例

const simpleStorageContract = new web3.eth.Contract(abi, contractAddress); // 创建智能合约实例

async function setValue() {
     
     
  const value = document.getElementById("value-input").value;
  const accounts = await web3.eth.getAccounts();
  await simpleStorageContract.methods.setValue(value).send({
     
      from: accounts[0] });
}

async function getValue() {
     
     
  const value = await simpleStorageContract.methods.getValue().call();
  document.getElementById("value-output").textContent = value;
}

First the address and ABI of the smart contract are defined, then a new Web3 instance is created using Web3.js, and a new smart contract instance is created using this instance. Next, we defined two functions: setValueand getValue, setValuethe function sets the value in the input box to the value in the smart contract, and getValuethe function gets the value in the smart contract and displays it on the page; the local Web can be started in the command line server and open the HTML file in the browser. When we set or get the value in the smart contract, the page will interact with the smart contract using Web3.js and display the results on the page; this is how simple it is to deploy and call smart contracts on Ethereum using Web3.js Example. You can use similar steps to develop more complex smart contracts and interact with them using Web3.js

Wallet integration

Web3 technology allows your application to integrate with Ethereum wallets, which allows you to let users transact using their Ethereum wallets within your application. Using the Web3.js library you can easily integrate wallet functionality into your application

Demonstrates how to interact with an Ethereum wallet in an application:

javascriptCopy codeif (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
}

The above code will check if the MetaMask wallet is installed in the browser. If installed, the application can window.ethereuminteract with the wallet through objects; once you have established a connection with the Ethereum wallet, you can use web3.ethobjects from the Web3.js library to send ether and interact with smart contracts

Decentralized Application (DApp) Development

Web3 technology can also be used to develop decentralized applications (DApps), which are applications based on blockchain technology that do not rely on a central server but store and process data through the blockchain network; development DApp requires knowledge of the Solidity programming language, Ethereum Virtual Machine (EVM), and smart contract development. In addition to this, you also need to know about the Web3.js library and other tools and libraries in the Ethereum ecosystem.

Demonstrates how to interact with smart contracts using the Web3.js library:

javascriptCopy codeconst contractAddress = "0x1234567890123456789012345678901234567890"; // 智能合约地址
const abi = [ ... ]; // 合约ABI

const web3 = new Web3(Web3.givenProvider || "http://localhost:8545"); // 初始化Web3实例

const simpleStorageContract = new web3.eth.Contract(abi, contractAddress); // 创建智能合约实例

async function setValue() {
  const value = document.getElementById("value-input").value;
  const accounts = await web3.eth.getAccounts();
  await simpleStorageContract.methods.setValue(value).send({ from: accounts[0] });
}

async function getValue() {
  const value = await simpleStorageContract.methods.getValue().call();
  document.getElementById("value-output").textContent = value;
}

document.getElementById("set-value-button").addEventListener("click", setValue);
document.getElementById("get-value-button").addEventListener("click", getValue);

Guess you like

Origin blog.csdn.net/qq_62761962/article/details/130343856