探究与以太坊智能合约的交互调用

概述

智能合约是部署在区块链上的一串代代码,通常我们与智能合约的打交道 可以通过前端的Dapp,etherscan,metamask 等方式。作为开发人员可以通过调用提供的相关包来与之交互,如web3.js,ether.js , web3.j(java 语言的包)。那么能否绕过这些东西直接与链发生交互呢?当然可以!
首先来了解第一个概念,区块链节点
任何一台计算机(能联网,且配置够),都可以启动以太坊的客户端来加入区块链,加入后这个节点会同步整个链上的状态,即通过这个节点就可以获取整个链的状态以及通过这个节点可以改变的状态。
第二个,智能合约。简而言之,智能合约是在节点上部署的代码,用户调用时会在节点上执行。
第三个,jsonrpc。jsonrpc 是一个远程调用的协议规范,规定了交互时的入参和出参的格式要求。
jsonrpc中文文档

后面以这个,合约代码为示例演示交互

// 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;
    }
    
}

使用remix 与合约交互

在这里插入图片描述

通过 remix 部署后会出现,可以调用的函数名。这种是最基础的用法

但是当页面刷新后,左下角的可调用的函数名就没了,这种情况下就需要使用 At Address这个按钮了
![[Pasted image 20220402120058.png]]

在代码框只需要提供要调用合约方法的接口,再将要调用的合约放入 At Address的框里,点击按钮,就会出现接口中的方法。这种就是不要合约的实现,只知道方法接口和地址就可以调用了。
合约调用的最核心就是两个东西,一个是部署后的合约地址,另外一个就要方法的接口也就是ABI

使用ethscan 与智能合约交互

另外一种与合约交互的方式,是通过ethscan。这种的前提是,合约代码已经在ethscan上进行开源过了。
![[Pasted image 20220402135533.png]]

其中 Read Contact 是读方法,不需要消耗gas.
Write Contact 是写方法,调用这些方法会改变链上的状态,会消耗gas.

使用web3.js 与合约交互

再有就是通过web3.js 的库进行交互

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 = "合约地址"

pk = "钱包私钥"

  

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();

}

使用http 请求与智能合约交互

ethreum json rpc API

上面这几种方式都是比较常规的,接下展示一种非常规的操作,即通过http请求来交互

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)

}

通过jsonrpc 方式,可以更灵活的与合约进行交互,只要拿到别人的签名信息,只发http请求就可以和链进行交互,至于是谁发送的这个http,就关系不大了。

综述

不管是remix 、etherscan 还是web3.js 这几种方式,本质上都是对jsonrpc方法封装。理解它们的底层交互逻辑,可以让我们更深刻的认识这些技术,从而发现它们还是我们日常使用的http请求,也就没有那么神秘了。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值