发布时间: 2024-03-30 04:39:00
refer to:
如下:
const fs = require('fs') const wethAbi = JSON.parse(fs.readFileSync('artifacts/contracts/WETH9.sol/WETH9.json')).abi let wethAddress = '0x8464135c8F25Da09e49BC8782676a84730C318bC' let rpcUrl = "http://localhost:8545" // Account #4: 0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65 (10000 ETH) privateKey = '0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a' async function main(){ const web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl)) const signer = web3.eth.accounts.privateKeyToAccount(privateKey) web3.eth.accounts.wallet.add(signer) let wethContract = new web3.eth.Contract(wethAbi, wethAddress) // 查询对应账户的余额 console.info("== totalSupply: ", await wethContract.methods.totalSupply().call()) console.info("== balance: contract(0x8464135c8F25Da09e49BC8782676a84730C318bC): ", await wethContract.methods.balanceOf("0x8464135c8F25Da09e49BC8782676a84730C318bC").call()) console.info("== balance: lend_to(0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65): ", await wethContract.methods.balanceOf("0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65").call()) // 尝试一下给人转账 let txOptions = { from: signer.address, to: wethAddress, value: web3.utils.toWei("10", "ether"), gasLimit: 210000 } let estimatedGas = await web3.eth.estimateGas(txOptions) txOptions.gas = estimatedGas let result = await web3.eth.sendTransaction(txOptions) console.info("== result: ", result) console.info("== balance: current account(0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65): ", await wethContract.methods.balanceOf("0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65").call()) } main()
下面是转token的。
async function main(){ const web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl)) const signer = web3.eth.accounts.privateKeyToAccount(privateKey) web3.eth.accounts.wallet.add(signer) let wethContract = new web3.eth.Contract(wethAbi, wethAddress) console.info("== before give, SafeLender balance:", await wethContract.methods.balanceOf(safeLenderAddress).call()) let tx = wethContract.methods.transfer(safeLenderAddress, web3.utils.toWei("10", "ether")) //let receipt = await tx.send({ from: signer.address, gas: await tx.estimateGas()}) let receipt = await tx.send({ from: signer.address, gasLimit: 240000}) .once("transactionHash", (txHash) => { console.info("=== mining transaction hash: ", txHash) }) console.info("== receipt: ", receipt)
特别神奇,一开始执行了 gasPrice的时候会报错:
Error: Returned error: Error: VM Exception while processing transaction: reverted with reason string ''
去掉gas price, 加上gas limit 就好了。
而且gas limit 默认是24000, 报错说gas out of range, 用光了。改成240000 ,就好了。
Back