我正在尝试将MetaMask版本5.3.1集成到我的Dapp中。我无法用给定的实例调用web3函数(如getBalance ),也无法发布事务。
这方面有什么文件吗?
错误:
ethereum.eth是未定义的,用于调用getBalance等web函数我使用的代码:
let metamaskTx = async () => {
console.log("is metamask" , ethereum.isMetaMask) // true
let accounts = await ethereum.enable()
console.log(ethereum.selectedAddress) // prints selected address
console.log(ethereum.networkVersion) // prints network ID
// ethereum.eth is undefined
let balance = await ethereum.eth.getBalance(ethereum.selectedAddress)
console.log(balance)
let transactionParameters = {
to: '0xe58db6b23575a93c185f756618f8e42745d7292b',
value: '0x1'
}
// fails with RPC Error: Error: Transaction from address isn't valid for this account
ethereum.sendAsync({
method: 'eth_sendTransaction',
params: [transactionParameters],
from: ethereum.selectedAddress,
}, function(err, res){
console.log({err})
console.log({res})
})
}发布于 2019-01-24 13:12:09
我找到了答案。我需要用户web3,按规定传递由Metamask注入的ethereum。守则如下:
async sendTxWithMetamask() => {
const ethereum = window.ethereum;
let web3 = new Web3()
let accounts = await ethereum.enable()
web3.setProvider(ethereum);
let selectedAddress = ethereum.selectedAddress
let balance = await web3.eth.getBalance(selectedAddress)
console.log('Balance', balance)
await web3.eth.sendTransaction({
to: '0xe58db6b23575a93c185f756618f8e42745d7292b', value: web3.utils.toWei('1', 'ether'), from: selectedAddress
})
};https://ethereum.stackexchange.com/questions/66064
复制相似问题