Blockchain | web3.js 合约交互模板

Mz1 / 2023-08-20 / 原文

Blockchain | web3.js 合约交互模板

最近发现ethers.js没有想象的那么好用了。。。
就换成了web3.js。
环境是node和web3.js v4。

const Web3 = require('web3');
const fs = require('fs');

const rpcURL = 'http://127.0.0.1:8545';
const addr = '0xda8e0A6Becd46E3C1d25BEbcc0E8f6723Cf2F924';
const web3 = new Web3.Web3(rpcURL);    // 链接网络节点

const privateKey = '0x957c03cef7400defc7585d5dd81c48455557aa29c12c627ad0fd17d73effe696';
web3.eth.accounts.wallet.add(privateKey);
const wallet = web3.eth.accounts.wallet[0];
console.log(wallet)
var money = 0;
web3.eth.getBalance(wallet.address).then((res)=>{console.log(res); money=res});


let deploy_contract_addr = "0x17260589889da9c7319DC5b4a22e9416275fD48c";
let deploy_token = "********************"

// const transaction = {
//   from: wallet.address,
//   to: deploy_contract_addr,
//   value: '10000000000000000'
// }
// web3.eth.sendTransaction(transaction).then(console.log);   // 转账至部署合约的账户



const contract_addr = "0xE0b01dDEB9045D6d5683170490ec36d2972092F8";

let jsonabi = JSON.parse(fs.readFileSync('Challenge.json', 'utf8')).abi
var myContract = new web3.eth.Contract(jsonabi, contract_addr, {
    from: wallet.address
});

// console.log(myContract);

// 调用合约函数
const run = async function(){
	// 读取存储
	var num = await web3.eth.getStorageAt(contract_addr, 1);
	console.log(num);
	var result = await myContract.methods.guessNumber(num).send(
		{
			from: wallet.address,
			gas: 1000000,
            gasPrice: 10000000000
        }
	);
	console.log(result);
	result = await myContract.methods.isSolved().call(
		{from: wallet.address}
	);
	console.log(result);
	var ok = await web3.eth.getStorageAt(contract_addr, 0);
	console.log(ok);
}

run();