[英][Solidity][Metamask] Metamask no longer injects web3
我想更新与元掩码和solidity 交互的旧javascript 文件。 在服务器上它说 metamask 不再注入 web3? 如何更改服务器的以下代码以请求元掩码帐户?
try {
const web3 = await getWeb3();
const instance = new web3.eth.Contract(
contractABI,
contractAddress,
);
var userAccount;
const accounts = await web3.eth.getAccounts();
if (accounts[0] !== userAccount) {
userAccount = accounts[0];
}
} catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
}
试试看:
const Web3 = require('web3');
const web3 = new Web3(window.ethereum);
const accounts = await web3.eth.getAccounts();
var userAccount = accounts[0];
npm i @metamask/detect-provider
它是一个微型实用程序,用于检测 MetaMask 以太坊提供者,或在 window.ethereum 注入的任何提供者。
import detectEthereumProvider from "@metamask/detect-provider";
import Web3 from "web3";
// in react or next.js this code should be placed in useEffect
const provider = await detectEthereumProvider();
if (provider) {
const web3 = new Web3(provider);
// now you have the provider
// after this you can place the logic
try {
const instance = new web3.eth.Contract(
contractABI,
contractAddress,
);
var userAccount;
const accounts = await web3.eth.getAccounts();
if (accounts[0] !== userAccount) {
userAccount = accounts[0];
}
} catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
}
// handle the case provider is not available
} else {
console.error("Please install Metamask");
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.