metamask环境中,使用metamask注入的 ethereum 对象来实例化
if (window.ethereum) {
window.web3 = new Web3(ethereum);
// 拿默认账户
ethereum.request({ method: 'eth_requestAccounts' }).then((accounts) => {
resolve(accounts);
// Request account access if needed
}).catch(() => {
Toast.fail('User denied account access...')
reject('User denied account access...');
});
} else {
Toast.fail('Please install MetaMask!')
}
也可以实例化一个provider对象:
import Web3 from 'web3';
window.web3 = new Web3(Web3.givenProvider);
// 拿默认账户
resolve(await window.web3.eth.getAccounts())