使用Web3调用以太智能合约的朋友可能都知道,从Web3的接口调用以太的智能合约有两种方式:eth_call和eth_sendTransaction。
eth_call不消耗gas,而eth_sendTransaction需要消耗gas。
本文从以太源代码详细解释两种调用方式的实现:
1)智能合约的接口
以以太坊的ERC20接口为例,接口有一个描述字:constant。
带constant的函数,web3会自动使用eth_call远程调用。
不带constant的函数,web3使用eth_sendTransaction远程调用。
比如查询地址余额的函数balanceOf带有constant描述字,web3会使用eth_call远程调用。
2)eth_sendTransaction调用过程
eth_sendTransaction调用发起一笔交易,并等待打包。
3)eth_call调用过程
eth_call调用只是在本地调用evm虚拟机执行获取状态,并没有打包操作。
总结:eth_call调用只是本地查询调用,不会发送交易,记录在链。eth_sendTransaction调用会发起交易请求,交易会打包记录在链。Web3会根据智能合约中函数有无constant描述字自动区分两种调用。
https://mp.weixin.qq.com/s/4ntwZlajGA-Z4j6LzB_LHA