调用智能合约写函数,会改变区块链状态,需要消耗Gas,被视为一种交易操作。
本章将使用web3.js – 部署智能合约 章节中部署好的合约,调用此合约的set()
函数。
调用智能合约写函数的执行步骤与前面章节:web3.js – 交易操作、web3.js – 部署智能合约 涉及到交易操作步骤基本相同,包括:
- 构建交易对象
- 签署交易
- 广播交易
因此我们将使用相同的基本设置,如下所示:
app.js文件
var Tx = require('ethereumjs-tx').Transaction
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/YOUR_INFURA_API_KEY')
const account1 = '' // Your account address 1
const account2 = '' // Your account address 2
const privateKey1 = Buffer.from('YOUR_PRIVATE_KEY_1', 'hex')
const privateKey2 = Buffer.from('YOUR_PRIVATE_KEY_2', 'hex')
构建交易对象
如下所示,构建交易对象:
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(800000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
to: contractAddress,
data: data
}
nonce
、gasLimit
、gasPrice
的使用,与前面章节基本相同,不再赘述。剩下2个参数说明如下:
to
– 此参数将是已部署智能合约的地址。可以从etherscan中获取。data
– 被调用的智能合约函数的十六进制表示。
const contractAddress = '0x30951343d6d80d2c94897f1a81c53cc030aef879'
const contractABI = [
{
"constant": false,
"inputs": [
{
"internalType": "string",
"name": "_value",
"type": "string"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
}
]
const contract = new web3.eth.Contract(contractABI, contractAddress)
关于data
参数,可以使用web3.js函数encodeABI()
,把contract对象中的智能合约函数转换为十六进制表示。如下所示:
const data = contract.methods.set("qikegu").encodeABI()
至此我们已经完成了准备工作,接下来就要执行调用了。