问题描述
我一直在尝试使用新的 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”)的示例:
作为一个副项目,我已经坚持了几个星期了发布。谢谢
另请注意,我正在链接此版本的 web3 https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js
解决方法
嗨,我在寻找类似问题时遇到了您的问题。 web3.eth 方法对我不起作用。
根据 MetaMask 有重大更改,请查看以下链接 https://medium.com/metamask/breaking-changes-to-the-metamask-provider-are-here-7b11c9388be9 按照这个
As of today,MetaMask has stopped injecting window.web3,and made a limited number of breaking changes to our Ethereum Provider API (window.ethereum).
MetaMask 有用于遗留代码的库,但他们不推荐它。
因此,我们必须使用 window.ethereum 而不是 window.web3。 Web3 文档仍然有旧的方法和教程。没用。
就我而言,我正在尝试转换来自 Dapp 大学 ( https://www.youtube.com/watch?v=CgXQC4dbGUE ) 的现有 React 教程 到 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 的更多信息,请分享。