合约代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

contract Incrementer {
event Reset();
uint256 public number;

constructor(uint256 _initaNumer) {
number = _initaNumer;
}

function increment(uint256 _value) public {
number = number + _value;
}

function reset() public {
number = 0;
emit Reset();
}

function getNumber() public view returns (uint256) {
return number;
}
}

js合约交互代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
let Web3 = require('web3');
let solc = require('solc');
let fs = require('fs');

//从配置中获取私钥
require('dotenv').config();
const privatekey = process.env.PRIVATE_KEY;

//加载合约
const source = fs.readFileSync('Incrementer.sol', 'utf8');
//编译solidity文件
const input = {
language: 'Solidity',
sources: {
"Incrementer.sol": {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Incrementer.sol']['Incrementer'];

const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

//创建一个web3的提供者
const web3 = new Web3('https://goerli.infura.io/v3/' + process.env.INFURA_ID);

//根据私钥创建账户
const account = web3.eth.accounts.privateKeyToAccount(privatekey);

const account_from = {
privateKey: privatekey,
accountAddress: account.address,
};

//部署合约
const Deploy = async () => {
// //创建合约实例
// const deployContract = new web3.eth.Contract(abi);
// //发送部署tx
// const deployTx = deployContract.deploy({
// data: bytecode,
// arguments: [111],
// });
// //签名tx
// const deployTransaction = await web3.eth.accounts.signTransaction(
// {
// data: deployTx.encodeABI(),
// gas: 8000000,
// },
// account_from.privateKey
// );
// const deployReceipt = await web3.eth.sendSignedTransaction(deployTransaction.rawTransaction);
// console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);

console.log("============================================");

console.log("通过getnumber获取参数的值");

let incrementInstance = new web3.eth.Contract(abi, "0xAdD6C000C32c1A672f252fFf458e366948921C97");
let initNum = await incrementInstance.methods.getNumber().call();
console.log("当前初始化值是" + initNum);

console.log("通过调用合约的自增方法来给合约num附上新值");
const newValue = 2024;
console.log(newValue);
let incrementTx01 = incrementInstance.methods.increment(newValue);
let incrementTransation = await web3.eth.accounts.signTransaction({
to: "0xAdD6C000C32c1A672f252fFf458e366948921C97",
data: incrementTx01.encodeABI(),
gas:8000000,
},
account_from.privateKey
)
// const incrementRes = await web3.eth.sendSignedTransaction(incrementTransation.rawTransaction);

// console.log('Tx successful with hash ' + incrementRes.transactionHash);

console.log("调用reset方法发出的事件");
let incrementTx02 = incrementInstance.methods.reset();
let incrementTransation02 = await web3.eth.accounts.signTransaction({
to: "0xAdD6C000C32c1A672f252fFf458e366948921C97",
data: incrementTx02.encodeABI(),
gas:8000000,
},
account_from.privateKey
)
// const incrementRes = await web3.eth.sendSignedTransaction(incrementTransation02.rawTransaction);

let ResetNum = await incrementInstance.methods.getNumber().call();

console.log("Reset后值" +ResetNum);
console.log("--------监听事件---------");
const web3Scoket = new Web3(new Web3.providers.WebsocketProvider(process.env.Sockets))

let increment = new web3Scoket.eth.Contract(abi, "0xAdD6C000C32c1A672f252fFf458e366948921C97");
increment.once('Reset', (error, event) => {
console.log("我是一个监听事件");
})
};
Deploy()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

eth.Contract

通过此方法获得合约实列incrementInstance

1
let incrementInstance =new web3.eth.Contract(abi, "0xAdD6C000C32c1A672f252fFf458e366948921C97");

methods获取实例的函数方法

call调用,initNum接受返回值

1
let initNum = await incrementInstance.methods.getNumber().call();

需要账户签名交互的函数

incrementTx01里面有他自己的abi编码,通过encodeABI()获得

1
2
3
4
5
6
7
8
9
let incrementTx01 = incrementInstance.methods.increment(newValue);
let incrementTransation = await web3.eth.accounts.signTransaction({
to: "0xAdD6C000C32c1A672f252fFf458e366948921C97",
data: incrementTx01.encodeABI(),
gas:8000000,
},
account_from.privateKey
)
const incrementRes = await web3.eth.sendSignedTransaction(incrementTransation.rawTransaction);

如何监听事件

1
2
3
4
5
6
7
8
console.log("--------监听事件---------");

const web3Scoket = new Web3(new Web3.providers.WebsocketProvider(process.env.Sockets))

let increment = new web3Scoket.eth.Contract(abi, "0xAdD6C000C32c1A672f252fFf458e366948921C97");
increment.once('Reset', (error, event) => {
console.log("我是一个监听事件");
})