智能合约是运行在区块链公链上的一种代码,该代码由Solidity编写,并通过区块链的智能合约虚拟机来执行,以达到对区块链编程的目标。可以将区块链公联理解为操作系统,Solidity是编写该操作系统应用程序的编程语言,智能合约虚拟机则是编程语言编译之后的代码运行环境。
var fs=require('fs');
const fetch=require('node-fetch')
var Web3=require('web3');
const ethers=require('ethers');
const infuraKey=fs.readFileSync("../.infuraKey").toString().trim();
var ethRpcUrl=https://rinkeby.infura.io/v3/
+infuraKey
var web3=new Web3(ethRpcUrl);
abi=[
{
"inputs":[],
"name":"getValue",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"_value",
"type":"uint256"
}
],
"name":"setValue",
"outputs":[],
"stateMutability":"nonpayable",
"type":"function"
}
]
contractAddress="合约地址"
pk="钱包私钥"
userAccount="私钥对应的账户地址"
main()
.then(()=>process.exit(0))
.catch(error=>{
console.error(error);
process.exit(1);
});
async function main(){
await setValue();
await getValue();
}
async function getNonce(account){
let nonce=await web3.eth.getTransactionCount(account);
console.log('nonce=',nonce)
return nonce;
}
async function getValue(){
//对方法进行sha3编码,然后取前四个字节
//var methodSign=await web3.utils.keccak256("getValue()").substr(0,10);
var methodSign=await web3.utils.keccak256("getValue()").substr(0,10);
//console.log(methodSign)
data=methodSign;
//如果有入参,对入参进行编码
//encodeParams=web3.eth.abi.encodeParameters(['uint256'],[456]);
//拼接方法名和入参作为jsonrpc的params中的data字段的数据
//data+=encodeParams.substr(2,encodeParams.length)
console.log(data)
//构造post请求的body参数
var input={"jsonrpc":"2.0","id":3,"method":"eth_call","params":[{"to":contractAddress,"data":data},"latest"]}
//http可以一次多个请求
var inputs=[input,input]
//发送post请求
const resp=await fetch(ethRpcUrl,{
method:"POST",
body:JSON.stringify(inputs),
headers:{
"Content-Type":"application/json"
}
});
var rpcResult=await resp.json();
console.log(rpcResult[0].result)
//用ethers包中的方法解析返回结果
var ethersResult=await ethers.utils.defaultAbiCoder.decode(['uint256'],rpcResult[0].result)
//用web3包中的方法解析防护结果
var decodeResult=await web3.eth.abi.decodeParameters(['uint256'],rpcResult[0].result);
console.log("vaule is"+ethersResult)
console.log("value is"+decodeResult[0])
}
async function setValue(){
//这里借用web3的方法对要发送的内容进行签名
var contract=new web3.eth.Contract(abi,contractAddress);
value=456;
var encodeABI=contract.methods.setValue(value).encodeABI();
var signResult=await web3.eth.accounts.signTransaction({
gas:3000000,
to:contractAddress,
data:encodeABI,
nonce:await getNonce(userAccount)
},pk);
console.log(signResult);
rawTransaction=signResult.rawTransaction
//构造post请求的body参数
var input={"jsonrpc":"2.0","id":3,"method":"eth_sendRawTransaction","params":[rawTransaction]}
console.log(input)
var inputs=[input]
//发送post请求
const resp=await fetch(ethRpcUrl,{
method:"POST",
body:JSON.stringify(inputs),
headers:{
"Content-Type":"application/json"
}
});
var rpcResult=await resp.json();
console.log(rpcResult)
}