区块链智能合约--使用web3链接metaMask调用合约转账代币

在开发项目的时候可能会有个场景需要前端和metaMask交互调用合约方法,下面就是我写的一个例如web3.js链接MeatMask调用合约转账代币的一个例子 。

需要的Jar包 :

const.js big.js    web3.js

<!doctype html>
<html class="no-js" lang="en">
<meta charset="UTF-8">

<head>
  <script src="js/const.js"></script>
  <script src="js/big.js/big.js"></script>
  <script src="js/web3.js"></script>
  <script type="text/javascript">

    send = async () =>{
      const web3 = new Web3(window.ethereum);
      ethereum.enable()
      //获取地址
      let accounts = await  web3.eth.getAccounts();
      let account = accounts[0];
      console.log("地址:"+account)
      // 返回指定地址账户的余额
      let balance = await web3.eth.getBalance(account);
      console.log("账户余额:"+balance)
      let contractAbi = [这里输入你要交互合约的ABI]
      let contractAddress = '这里输入你自己要交互的0X开头的合约地址'
      let myContract = new web3.eth.Contract(contractAbi, contractAddress, {
        from: account, // default from address
        gasLimit: 70000,
        gasPrice: 1000000000 // default gas price in wei, 10 gwei in this case
      });
      let a = 1000000
      let toAddress = document.getElementById("toAddress").value;
      console.log("转账地址:"+toAddress)
      myContract.methods.transfer(toAddress, 1 * a,).send({from: account}, function(error, transactionHash){
        if(!error) {
          console.log('transactionHash is' + transactionHash);
        } else {
          console.log(error);
        }
      });
    }


  </script>
</head>

<body>
<!-- 会导出一个全局的变量: ethers -->
<input type="text" id="toAddress" placeholder="to transfer address" />
<input type="button" onclick="send()" value="有签名转账(无需提供privateKey)需要metamask解锁"  />
</body>

</html>

以上是一个可运行的demo,完成了网页版兼容Imtoken ,MeatMask等主流钱包的链接,和交互调用合约的方法.


如果有遇到不懂得或者有疑问欢迎联系本人进行交流

WC:luo425116243

猜你喜欢

转载自blog.csdn.net/qq_33842966/article/details/123317789