Explore the interactive call with Ethereum smart contract

Big tail 2022-04-04 09:19:14 阅读数:276

explore interactive ethereum smart contract

summary

Smart contract is a series of code deployed on the blockchain , Usually we deal with smart contracts It can be through the front-end Dapp,etherscan,metamask Methods such as . As a developer, you can interact with it by calling the relevant package provided , Such as web3.js,ether.js , web3.j(java Language pack ). So can we bypass these things and interact directly with the chain ? Certainly. !
First, let's understand the first concept , Blockchain nodes
Any computer ( Can be networked , And the configuration is enough ), You can start Ethereum's client to join the blockchain , After joining, this node will synchronize the state of the whole chain , That is, the state of the whole chain and the state that can be changed through this node can be obtained through this node .
the second , Intelligent contract . In short , Smart contracts are code deployed on nodes , When called by the user, it will execute... On the node .
Third ,jsonrpc.jsonrpc Is a protocol specification for remote call , Specified format of the input and output of the interaction .
jsonrpc Chinese document

This is followed by , Contract code is an example to demonstrate interaction

// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
contract Test {

uint256 private value;
function setValue(uint256 _value) public {

value = _value;
}
function getValue() public view returns(uint256){

return value;
}
}

Use remix Interact with contracts

 Insert picture description here

adopt remix After deployment, there will be , The name of the function that can be called . This is the most basic usage

But when the page refreshes , The callable function name in the lower left corner is gone , In this case, you need to use At Address This button
![[Pasted image 20220402120058.png]]

In the code box, you only need to provide the interface to call the contract method , Then put the contract to be called into At Address In the box , Click button , There will be methods in the interface . This is not the realization of the contract , Just know the method interface and address, you can call .
The core of contract invocation is two things , One is the contract address after deployment , The other is the interface of the method ABI

Use ethscan Interact with smart contracts

Another way to interact with the contract , It's through ethscan. The premise of this is , The contract code is already in ethscan Open source on .
![[Pasted image 20220402135533.png]]

among Read Contact Reading method , No need to consume gas.
Write Contact It's the way to write , Calling these methods will change the state of the chain , Will consume gas.

Use web3.js Interact with contracts

Another is through web3.js Interact with the library

var fs = require('fs');
var Web3 = require('web3');
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"
}
]
address = " Contract address "
pk = " Wallet private key "
main()
.then(() => process.exit(0))
.catch(error => {

console.error(error);
process.exit(1);
});
async function getValue(){

var contract = new web3.eth.Contract(abi, address);
var value = await contract.methods.getValue().call();
console.log(value);
}
async function setValue(){

value = 123
var contract = new web3.eth.Contract(abi, address);
var encodeABI = await contract.methods.setValue(value).encodeABI();
var signResult = await web3.eth.accounts.signTransaction({

gas: 3000000,
to: address,
data: encodeABI
}, pk);
console.log(signResult);
var result = await web3.eth.sendSignedTransaction(signResult.rawTransaction);
console.log(result);
}
async function main(){

await setValue();
await getValue();
}

Use http Request interaction with smart contract

ethreum json rpc API

The above methods are more conventional , Next, we show an unconventional operation , That is, through http Request to interact

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 = " Contract address "
pk = " Wallet private key "
userAccount = " The account address corresponding to the private key "
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(){

// The method is carried out sha3 code , Then take the first four bytes 
// 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;
// If there is any input , Code the input parameters 
// encodeParams = web3.eth.abi.encodeParameters(['uint256'],[456]);
// Splice method name and input parameters as jsonrpc Of params Medium data Field data 
// data +=encodeParams.substr(2,encodeParams.length)
console.log(data)
// structure post Requested body Parameters 
var input = {
"jsonrpc":"2.0","id":3,"method":"eth_call","params":[{
"to":contractAddress,"data":data},"latest"]}
// http You can request more than one at a time 
var inputs = [input,input]
// send out post request 
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)
// use ethers The method parsing in the package returns the result 
var ethersResult = await ethers.utils.defaultAbiCoder.decode(['uint256'], rpcResult[0].result)
// use web3 The method in the package parses the protection result 
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(){

// Borrow here web3 Method to sign the content to be sent 
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
// structure post Requested body Parameters 
var input = {
"jsonrpc":"2.0","id":3,"method":"eth_sendRawTransaction","params":[rawTransaction]}
console.log(input)
var inputs = [input]
// send out post request 
const resp = await fetch(ethRpcUrl, {

method: "POST",
body: JSON.stringify(inputs),
headers: {

"Content-Type": "application/json"
}
});
var rpcResult = await resp.json();
console.log(rpcResult)
}

adopt jsonrpc The way , It can interact with the contract more flexibly , Just get someone else's signature information , Only hair http The request can interact with the chain , As for who sent this http, It doesn't matter .

review

Whether it's remix 、etherscan still web3.js These ways , In essence, they are all right jsonrpc Method encapsulation . Understand their underlying interaction logic , It can let us have a deeper understanding of these technologies , So we can find that they are still used in our daily life http request , It won't be so mysterious .

版权声明:本文为[Big tail]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2022/04/202204040602305687.html