6.DApp-Using Web3 to realize the interaction between the front end and smart contracts

Title

Use Web3 to realize the interaction between the front end and smart contracts. The following is the operation process and code.

Prepare the ganache environment

Article address: 4. How to connect DApp-MetaMask to local Ganache-CSDN blog

Prepare smart contracts

Article address: 2.DApp-Writing and running solidity smart contracts-CSDN blog

Write index.html file

Name Contract Demo

Set name

<!DOCTYPE html>
<html>
<head>
    <title>Name Contract Demo</title>
    <!--Import web3 library-->
    <script src="//i2.wp.com/cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
    <script>
    // Check if Metamask is installed
    if (typeof window.ethereum !== 'undefined') {
    console.log('Metamask is installed');
    }
  
    //Set the Web3.js provider to Metamask
    const provider = window.ethereum;
    const web3 = new Web3(provider);
  
    // Request Metamask to connect to the Ethereum network
    provider.request({ method: 'eth_requestAccounts' })
    .then(() => {
      console.log('Metamask has connected to the Ethereum network');
    })
    .catch((err) => {
      console.error('Unable to connect to the Ethereum network', err);
    });
  
    function setName() {
    //Contract address
    const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';
    //Contract ABI
    const contractABI = [
{
"inputs": [
{
"internalType": "string",
"name": "_name",
"type": "string"
}
],
"name": "setName",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "getName",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
    ];
    const contract = new web3.eth.Contract(contractABI, contractAddress);
    const name = document.getElementById('name').value;
    //Replace with your account address web3.eth.defaultAccount
    const fromAddress = '0x4e8eB4d1C203929074A3372F3703E556820fEA57';
    //contract.methods.setName(name).send({from: fromAddress})

    contract.methods.setName(name).send({from: fromAddress})
    .on('transactionHash', function(hash){
        console.log('Transaction Hash:', hash);
    })
    .on('receipt', function(receipt){
        console.log('Transaction Receipt:', receipt);
    })
    .on('error', function(error){
        console.error('Error:', error);
    });
    }

    function getName() {
    //Contract address
    const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';
    //Contract ABI
    const contractABI = [
{
"inputs": [
{
"internalType": "string",
"name": "_name",
"type": "string"
}
],
"name": "setName",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "getName",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
    ];
    const contract = new web3.eth.Contract(contractABI, contractAddress);
    contract.methods.getName().call()
    .then(function(result) {
        console.log('Name:', result);
        document.getElementById('nameValue').innerText = result;
    })
    .catch(function(error) {
        console.error('Error:', error);
    });
    }
    </script>
</head>
<body>
    <h1>Set name</h1>
    <label for="name">Name:</label>
    <input type="text" id="name">
    <button onclick="setName()">Set name</button>
    <br>
    <button onclick="getName()">Get name</button>
    <br>
    <span id="nameValue"></span>
</body>
</html>

Execute program

Use vscode’s Live Server to open a web page

Refer to the implementation method of this article: 1.Vue-implement Vue’s addition, deletion, modification and query on an independent page-CSDN Blog

Display image

Initiate transaction

Complete transaction

Postscript

If you find it useful, please like or save it!