Web3.js与智能合约交互

本文提供了一篇关于Web3.js的详细教程,Web3.js是用于以太坊区块链开发的JavaScript库。教程涵盖了从安装、设置到使用Web3.js进行智能合约交互的步骤,包括调用和发送交易。示例代码展示了如何在Node.js环境中以及H5版本中与以太坊网络进行通信,获取账户余额和执行智能合约操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Web3.js教程:

web3.js - 以太坊 JavaScript API — web3.js 中文文档 — 登链社区https://learnblockchain.cn/docs/web3.js/index.html

Web3js源码:

GitHub - ChainSafe/web3.js: Ethereum JavaScript APIhttps://github.com/ChainSafe/web3.js初始化

cd web3jTest
npm init

下载web3到项目中

npm install web3 --save

交互代码示例:

Nodejs版本:

var Web3 = require('web3');
var provider = new Web3.providers.HttpProvider("http://localhost:7545");

var web3 = new Web3(provider);

var json = require("./contracts/MetaCoin.json");
var contractAddr = '0x9C334Fb3287dA1E6cc063B084c5432985a708999';

var metacoin = new web3.eth.Contract(json['abi'],contractAddr);

var account = "0x060f4e095Eeb77ad987412578652a5201436E3c3";

metacoin.methods.getBalance(account).call({from: account}, function(error, result){
    console.log(error);
    console.log(result);
});

//内网测试
metacoin.methods.buyNow(10000, 1).send({from: account, gas: "300000"}, function(error, transactionHash){
  console.log(error)
  console.log(transactionHash)
});

//公网测试
var functionEncode = metacoin.methods.buyNow(10000, 1).encodeABI();
console.log(functionEncode)
var sign = web3.eth.accounts.signTransaction({
  from: account,
  gasPrice: 20000000000,
  gas: 300000,
  to: contractAddr,
  data: functionEncode,
}, privateKey, function(error, result){
  console.log(error)
  console.log("signTransaction:", result)
  var result = web3.eth.sendSignedTransaction(result.rawTransaction, function(error, result){
    console.log(error)
    console.log("sendSignedTransaction:", result)
  });
});

测试执行

node test.js

执行结果:

null
9500

H5版本:

<script src="./dist/web3.min.js"></script>
<script>
  const tokenABI = [...];
  var ethereum
  var localAccount
  if (typeof window.ethereum !== 'undefined') {
    console.log('MetaMask is installed!')
    ethereum = window.ethereum
  }
  const contractAddr = '0x28e784AB8FA34321cb78F7F92B8b374646111111';

  //获取当前钱包地址
  ethereumButton.addEventListener('click', () => {
    event.preventDefault()
    ethereum.request({
      method: 'eth_requestAccounts'
    }).then((ret) => {
      localAccount = ret[0]
      console.log('accounts: ', ret)
    })
  })

  getNonceButton.addEventListener('click', (event) => {
    event.preventDefault()
    getBalanceTx()
  })

  buyNowButton.addEventListener('click', (event) => {
    event.preventDefault()
    buyNowTx(10000, 1)
  })
</script>


<script type="text/javascript">
  const buyNowTx = async (artworkId, num) => {
    var web3 = new Web3(ethereum)
    var tokenContract = new web3.eth.Contract(tokenABI, contractAddr)
    var nonceVal = await web3.eth.getTransactionCount(localAccount);
    var ret =  await tokenContract.methods.buyNow(artworkId, num).send({
      from: localAccount,
      nonce: nonceVal,
      gas: 800000
    })
    console.log(ret.transactionHash)
    return ret
  }

  const getBalanceTx = async () => {
    var web3 = new Web3(ethereum)
    var tokenContract = new web3.eth.Contract(tokenABI, contractAddr)
    var balance = await tokenContract.methods.getBalance(localAccount).call()
    console.log("balance:", balance)
    return balance
  }
</script>
好的,以下是一个简单的前端web3应用程序,用于上面编写的ERC20智能合约交互: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Web3 App</title> <script src="https://cdn.jsdelivr.net/npm/web3@1.3.5/dist/web3.min.js"></script> </head> <body> <h1>Web3 App</h1> <p>Account: <span id="account"></span></p> <p>Balance: <span id="balance"></span> ERC20 tokens</p> <input id="to" type="text" placeholder="Recipient address"> <input id="value" type="text" placeholder="Amount"> <button onclick="transfer()">Transfer</button> <script> window.addEventListener(&#39;load&#39;, async () => { if (typeof window.ethereum !== &#39;undefined&#39;) { await window.ethereum.enable(); const web3 = new Web3(window.ethereum); const contractAddress = &#39;CONTRACT_ADDRESS&#39;; const contractAbi = [{ &#39;constant&#39;: true, &#39;inputs&#39;: [{&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;address&#39;}], &#39;name&#39;: &#39;balanceOf&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;uint256&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;view&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;constant&#39;: true, &#39;inputs&#39;: [], &#39;name&#39;: &#39;name&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;string&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;view&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;constant&#39;: false, &#39;inputs&#39;: [{&#39;name&#39;: &#39;_to&#39;, &#39;type&#39;: &#39;address&#39;}, {&#39;name&#39;: &#39;_value&#39;, &#39;type&#39;: &#39;uint256&#39;}], &#39;name&#39;: &#39;transfer&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;success&#39;, &#39;type&#39;: &#39;bool&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;nonpayable&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;constant&#39;: true, &#39;inputs&#39;: [], &#39;name&#39;: &#39;symbol&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;string&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;view&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;constant&#39;: false, &#39;inputs&#39;: [{&#39;name&#39;: &#39;_spender&#39;, &#39;type&#39;: &#39;address&#39;}, {&#39;name&#39;: &#39;_value&#39;, &#39;type&#39;: &#39;uint256&#39;}], &#39;name&#39;: &#39;approve&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;success&#39;, &#39;type&#39;: &#39;bool&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;nonpayable&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;constant&#39;: true, &#39;inputs&#39;: [{&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;address&#39;}, {&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;address&#39;}], &#39;name&#39;: &#39;allowance&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;&#39;, &#39;type&#39;: &#39;uint256&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;view&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;constant&#39;: false, &#39;inputs&#39;: [{&#39;name&#39;: &#39;_from&#39;, &#39;type&#39;: &#39;address&#39;}, {&#39;name&#39;: &#39;_to&#39;, &#39;type&#39;: &#39;address&#39;}, { &#39;name&#39;: &#39;_value&#39;, &#39;type&#39;: &#39;uint256&#39; }], &#39;name&#39;: &#39;transferFrom&#39;, &#39;outputs&#39;: [{&#39;name&#39;: &#39;success&#39;, &#39;type&#39;: &#39;bool&#39;}], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;nonpayable&#39;, &#39;type&#39;: &#39;function&#39; }, { &#39;inputs&#39;: [{&#39;name&#39;: &#39;_name&#39;, &#39;type&#39;: &#39;string&#39;}, {&#39;name&#39;: &#39;_symbol&#39;, &#39;type&#39;: &#39;string&#39;}, { &#39;name&#39;: &#39;_totalSupply&#39;, &#39;type&#39;: &#39;uint256&#39; }], &#39;payable&#39;: false, &#39;stateMutability&#39;: &#39;nonpayable&#39;, &#39;type&#39;: &#39;constructor&#39; }, { &#39;anonymous&#39;: false, &#39;inputs&#39;: [{&#39;indexed&#39;: true, &#39;name&#39;: &#39;_from&#39;, &#39;type&#39;: &#39;address&#39;}, { &#39;indexed&#39;: true, &#39;name&#39;: &#39;_to&#39;, &#39;type&#39;: &#39;address&#39; }, {&#39;indexed&#39;: false, &#39;name&#39;: &#39;_value&#39;, &#39;type&#39;: &#39;uint256&#39;}], &#39;name&#39;: &#39;Transfer&#39;, &#39;type&#39;: &#39;event&#39; }, { &#39;anonymous&#39;: false, &#39;inputs&#39;: [{&#39;indexed&#39;: true, &#39;name&#39;: &#39;_owner&#39;, &#39;type&#39;: &#39;address&#39;}, { &#39;indexed&#39;: true, &#39;name&#39;: &#39;_spender&#39;, &#39;type&#39;: &#39;address&#39; }, {&#39;indexed&#39;: false, &#39;name&#39;: &#39;_value&#39;, &#39;type&#39;: &#39;uint256&#39;}], &#39;name&#39;: &#39;Approval&#39;, &#39;type&#39;: &#39;event&#39; }]; const contract = new web3.eth.Contract(contractAbi, contractAddress); const accounts = await web3.eth.getAccounts(); const account = accounts[0]; document.getElementById(&#39;account&#39;).textContent = account; const balance = await contract.methods.balanceOf(account).call(); document.getElementById(&#39;balance&#39;).textContent = balance; transfer = async () => { const to = document.getElementById(&#39;to&#39;).value; const value = document.getElementById(&#39;value&#39;).value; await contract.methods.transfer(to, value).send({from: account}); location.reload(); }; } else { alert(&#39;Please install MetaMask to use this dApp!&#39;); } }); </script> </body> </html> ``` 在这个应用程序中,我们使用了web3.js库来以太坊网络交互,首先需要检查MetaMask是否已安装并启用。然后,我们使用智能合约地址和ABI创建了一个智能合约实例,以便可以合约交互。我们还获取了当前用户的帐户和智能合约中该帐户的余额,并将其显示在页面上。最后,我们定义了一个转移函数,该函数在用户输入收件人地址和金额后,调用智能合约的“transfer”函数来发送代币,并重新加载页面以更新余额。 请注意,在这个示例中,你需要将“CONTRACT_ADDRESS”替换为你部署的ERC20智能合约的地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值