I want to update my old javascript file that interacts with metamask and solidity. On the server it says metamask no longer injects web3? How do I change the following code for the server to request a metamask account?
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);
}
Try that:
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
It is a tiny utility for detecting the MetaMask Ethereum provider, or any provider injected at 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");
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.