【问题标题】:Stuck trying to write web3 RPC BalanceOf to get users metamask smartcontract token balance尝试编写 web3 RPC BalanceOf 以获取用户元掩码智能合约代币余额
【发布时间】:2021-09-20 17:47:46
【问题描述】:

我一直在尝试使用新的 JSON RPC 方法 https://docs.metamask.io/guide/rpc-api.html#ethereum-json-rpc-methods 创建一个简单的网页,该网页可以返回元掩码帐户中 ERC20 智能合约的代币余额。

我只能成功找回以太坊的余额(使用以下代码)

  try {
     balance = await ethereum
    .request({
      method: 'eth_getBalance',
      params: [address,"latest"],
    })
    // covert to readable format (account for decimals)
     read = parseInt(balance) / 10**18; // will need change based on what token
    console.log( "Smart Contract Token Balance:" + read.toFixed(5) );

  } catch (error) {
    console.log(error);
  }

当然,上面返回地址的以太坊数量。

在我的一生中,我无法使用新的 JSON-RPC 方法计算出这个版本,也没有看到任何调用智能合约方法的示例,例如“balanceOf”:

  var contract = new web3.eth.Contract(theAbi, theTokenAddress);

  balance = await contract.methods.balanceOf(theTokenAddress).call().then(console.log);

作为一个副项目,我已经坚持了几个星期了,好吧,我确信我正在尝试做的任何指示都是基本的 - 我只是第一次在 StackOverflow 上设置了一个帐户发布。谢谢

另外请注意,我正在链接这个版本的 web3 https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js

【问题讨论】:

    标签: javascript solidity smartcontracts web3 metamask


    【解决方案1】:

    您好,我在寻找类似问题时遇到了您的问题。 web3.eth 方法对我不起作用。

    根据 MetaMask 有重大更改,请查看以下链接 https://medium.com/metamask/breaking-changes-to-the-metamask-provider-are-here-7b11c9388be9 按照这个

    截至今天,MetaMask 已停止注入 window.web3,并对我们的 Ethereum Provider API (window.ethereum) 进行了有限数量的重大更改。

    MetaMask 有遗留代码库,但他们不推荐它。

    所以我们必须使用 window.ethereum 来代替 window.web3。 Web3 文档仍然有旧的方法和教程。没用。

    就我而言,我正在尝试从 Dapp 大学转换现有的反应教程 (https://www.youtube.com/watch?v=CgXQC4dbGUE) 到 Angular 11、松露 (v5.4.1)、web3.js (v1.4.0)、Ganache。但无法保持平衡。

    这是我的代码

    import { Component, OnInit } from '@angular/core';
    import Web3 from 'web3';
    import DaiToken from '../../build/contracts/DaiToken.json';
    import DappToken from '../../build/contracts/DappToken.json';
    import TokenFarm from '../../build/contracts/TokenFarm.json';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss'],
    })
    
    export class AppComponent implements OnInit {
      accounts: any;
      investorAccount: string = '0x0';
      daiToken: any = {};
      dappToken: any = {};
      tokenFarm: any = {};
      daiTokenBalance: string = '0';
      dappTokenBalance: string = '0';
      stakingBalance: string = '0';
      loading: boolean = true;
      web3: any;
    
      constructor() {}
        ngOnInit() {
          this.bootstrapWeb3();
        }
        async bootstrapWeb3() {
          await this.loadWeb3();
          await this.loadBlockchainData();
        }
    
        async loadWeb3() {
          if (window.ethereum) {
            // await window.ethereum.enable();  
            // no longer required, as line below does the same thing
    
            this.accounts = await window.ethereum.request({
              method: 'eth_requestAccounts'
            });
            window.web3 = new Web3(window.ethereum);
    
          } else if (window.web3) {
            window.web3 = new Web3(window.web3.currentProvider);
          } else {
            window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!');
          }
        }
    
        async loadBlockchainData() {
          this.web3 = window.web3;
          // const accounts = await web3.eth.getAccounts();  <-----   Not working with latest metamask changes
          this.investorAccount = this.accounts[0];
          try {
            // Get networkId
            const networkId = await window.ethereum.request({
              method: 'net_version'
            });
            // const networkId = await web3.eth.net.getId().then(id => console.log(id)); // Not working
    
            const daiTokenData = DaiToken.networks[networkId];
    
            // Load DaiToken
            if (daiTokenData) {
              const daiToken = new window.web3.eth.Contract(DaiToken.abi, daiTokenData.address);
              this.daiToken = daiToken;
    
              //  balanceOf not working
              let daiTokenBalance = await daiToken.methods.balanceOf(this.investorAccount).call();
    
              this.daiTokenBalance = daiTokenBalance.toString();
            } else {
              window.alert('DaiToken contract not deployed to detected network.');
            }
          } catch (error) {
            console.log(error);
          }
        }
    }
    

    每当我尝试调用 window.web3.eth 或其他方法时,它都不会运行或返回任何错误。不确定需要进行哪些更改。 仍在寻找 MetaMask 和 web3.js 的最新更改的示例。找到后会尝试更新。

    如果有人有关于最新 MetaMask、web3js 的更多信息,请分享。

    【讨论】:

      【解决方案2】:

      简短的回答是从客户端获取用户帐户地址,然后从服务器端检索您感兴趣的任何令牌的帐户余额。

      【讨论】:

        猜你喜欢
        • 2018-05-04
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 2019-03-08
        • 1970-01-01
        • 2022-08-20
        相关资源
        最近更新 更多