问题描述
我正在学习 dapp,并尝试创建从 Dapp 大学 (https://www.youtube.com/watch?v=CgXQC4dbGUE) 到 Angular 11 项目的现有 React 教程。 松露 (v5.4.1)、web3.js (v1.4.0)、Ganache、MetaMask chrome 扩展版本 9.8.2
根据 MetaMask 有重大更改,请查看以下链接 https://medium.com/metamask/breaking-changes-to-the-metamask-provider-are-here-7b11c9388be9
截至今天,MetaMask 已停止注入 window.web3,并对我们的 Ethereum Provider API (window.ethereum) 进行了数量有限的重大更改。
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) {
this.accounts = await window.ethereum.request({
method: 'eth_requestAccounts',});
// await window.ethereum.enable(); // no longer required
this.web3 = new Web3(window.ethereum);
} else {
window.alert(
'Non-Ethereum browser detected. You should consider trying MetaMask!'
);
}
}
async loadBlockchainData() {
// const accounts = await this.web3.eth.getAccounts(); <----- Not working with latest Metamask changes
// 'eth_requestAccounts' returns accounts
this.investorAccount = this.accounts[0];
try {
// const networkId = await this.web3.eth.net.getId().then(console.log);
// this.web3.eth.net.getId() method Not working,nothing happens,no error
// but method below returns networkId
const networkId = await window.ethereum.request({
method: 'net_version',});
const daiTokenData = DaiToken.networks[networkId];
// Load DaiToken
if (daiTokenData) {
// Contract
const daiToken = new this.web3.eth.Contract(
DaiToken.abi,daiTokenData.address
);
this.daiToken = daiToken;
// balanceOf not working,no error
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);
}
}
}
问。为什么 web3 方法不起作用,例如window.web3.eth.net.getId() 或 window.web3.eth.getBalance 或 getAccounts 或合约方法,如 contract.methods.balanceOf(address).call() ?
问:这是否意味着不需要 web3js 或其方法,使用 MetaMask 指定的 JSON RPC 方法就足够了? https://metamask.github.io/api-playground/api-documentation。
如果有人有最新更新的javascript示例代码,请发布。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)