一、链接网络并获取账号信息1、通过浏览器钱包链接网络constweb3=newWeb3((windowasany).ethereum);//通过MeteMask钱包链接网络letgetAccounts=awaitweb3.eth.requestAccounts();
const web3 = new Web3((window as any).ethereum); //通过MeteMask钱包链接网络
let getAccounts = await web3.eth.requestAccounts(); //请求获取钱包账号
const web3 = new Web3("https://rpc-mumbai.maticvigil.com"); //通过RPC URL链接网络
const account = web3.eth.accounts.create() //创建一个新账号
const account = web3.eth.accounts.privateKeyToAccount("private_key");//通过私钥导入账号
这里说一下,如果想使用助记词的话,需要安装其他库 bip39 和@truffle/hdwallet-provider,只是我用了一下各种报错,还没调通
npm i @truffle/hdwallet-provider bip39
官方代码如下:
const { Web3 } = require('web3');
const HDWalletProvider = require('@truffle/hdwallet-provider');
const bip39 = require('bip39');
const mnemonic = bip39.generateMnemonic(); // generates seed phrase
const provider = new HDWalletProvider(mnemonic,'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID',);
const web3 = new Web3(provider);
let wei = await web3.eth.getBalance(address);
let balance = web3.utils.fromWei(wei, 'ether')
console.log("balance: " + balance)
这个签名需要钱包打开eth_sign开关,比如MetaMask钱包如下
let transaction = await web3.eth.sendTransaction(
{
from:address,
to:"0xCe06B0A53b08C10fa508BF16D02bBdDc6961E3B3",
value: 0.001 * Math.pow(10,18), //Web3.utils.toWei('0.0001', 'ether'),
});
web3.utils.fromWei("1", "ether") //wei转成eth
web3.utils.toWei("0.001", "ether") //eth转成wei
web3.utils.toBigInt(1) //转成bigint
ENS就是域名,常用方法有getAddress 和 getResolver;
let contract = new web3.eth.Contract(abi,'0x2be62e7117967ea61aC6371Ac2F50318e58Ecaf9');
call的话是调用solidity的pure和view只读方法,不消耗gas
let result = await contract.methods.balanceOf(address).call();
send方法的话,是调用改变合约状态的方法,会消耗gas, send需要传一个from,也就是当前操作合约的账号地址,也就会扣这个账号的gas, 如果不填from的话,会读取contract.defaultAccount。
let result = await contract.methods.transfer(toAddress).send({from: address});
let getPastEvents = await contract.getPastEvents('Transfer',
{
filter: { from: address },
fromBlock: 43244550,
toBlock: 43244558
});
contract.events.事件名称 用于监听某个事件
let event = contract.events.Transfer({
filter: { from: address },
fromBlock: 'latest',
})
event.on('data', function (event) {
console.log("event data", event);
})
event.on('changed', function (event) { })
event.on("error", function (error) { });
event.on("connected", function (event) {});
contract.events.allEvents 监听所有事件
let event = contract.events.allEvents({
filter: { from: address },
fromBlock: 'latest',
})
event.on('data', function (event) {
console.log("event data", event);
})
event.on('changed', function (event) { })
event.on("error", function (error) { });
event.on("connected", function (event) {});
web3.js整体体验下来没有ethers.js 好,还是建议用ethers.js 。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!