Back

blockchain - web3 - 使用metamask 调用某个contract 的方法

发布时间: 2022-06-23 03:31:00

refer to:  https://ethereum.stackexchange.com/questions/120480/how-to-send-a-value-to-smart-contract-function-using-meta-mask-and-web3-js

https://livecodestream.dev/post/interacting-with-smart-contracts-from-web-apps/

https://gist.github.com/bajcmartinez/45bb7bb39fea940cd45a5e88759f58a5

假设你有个contract

pragma solidity ^0.6.6;

contract CoolNumberContract {
   function mint() .... {}
}

那么就可以这样调用:

HTML页面:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>

<a href="#" id='do_claim_by_user'>claim(4)</a>
<script>
    async function loadWeb3() {
      if (window.ethereum) {
        window.web3 = new Web3(window.ethereum);
        window.ethereum.enable();
      }
    }

    async function loadContract() {
      let abi = <%= raw @contract.abi %>
      let address = "<%= @contract.address %>"
      return await new window.web3.eth.Contract(abi, address);
    }
    async function getCurrentAccount() {
      const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
      return accounts[0];
    }

    async function run() {
      await loadWeb3();
      window.contract = await loadContract();
      const account = await getCurrentAccount();

      let result = await window.contract.methods.mint().send({ from: account });
      console.info("== result: ", result)
      if(result.status && result.transactionHash){
        location.href="/front_ends/mark_claim_done?contract_id=" + <%= params[:id] %> + "&tx=" + result.transactionHash
      }
    }

    if(document.getElementById('do_claim_by_user')){
      document.getElementById('do_claim_by_user').addEventListener('click', async () => {
        if (typeof window.ethereum !== 'undefined') {
          run()
        }else {
          alert('You have not installed a wallet(e.g. Metamask) yet, please install.')
        }
      });
    }
</script>

也可以进一步,调用的时候传入转账的数量:

   async function run() {
      await loadWeb3();
      window.contract = await loadContract();
      const account = await getCurrentAccount();
      // 创建dialog遮罩
      jQuery('#hover_when_claiming_nft').show()

      let amount = 1 
      let value = 0.01 * 1e18 * amount
      let result = await window.contract.methods.mint(amount).send({ from: account, value: value }); 

      console.info("== result: ", result)
      console.log(JSON.stringify(result, null, 4));
      let nft_id = result.events.MintedEventLog.returnValues.nftId

      if(result.status && result.transactionHash){
        location.href="/front_ends/mark_claim_done?contract_id=" + <%= params[:id] %> + "&nft_id=" + nft_id + "&tx=" + result.transactionHash
      }   
    }   

Back