How to calculate the data
field size
(when you're sending a transaction calling a smart contract function)
The data
field value could be divided into three parts:
0x
- 4 bytes (8 hex characters) - This is the function signature, it identifies the function that you are going to call.
- The value is first 4 bytes of keccak256 hash of the function name and argument types. Example:
transfer(address,uint256)
=> a9059cbb
- the rest of data - Arguments passed into the function.
The easiest way is to use a library that calculates the size for you. :) For example web3js
function encodeFunctionCall().
Example:
const result = web3.eth.abi.encodeFunctionCall({
name: 'transfer',
type: 'function',
inputs: [{
type: 'address',
name: ''
},{
type: 'uint256',
name: ''
}]
}, ['0x1231231231231231231231231231231231231231', '1']);
console.log(result);
Returns
0xa9059cbb00000000000000000000000012312312312312312312312312312312312312310000000000000000000000000000000000000000000000000000000000000001
a9059cbb
is the function signature
0000000000000000000000001231231231231231231231231231231231231231
is the address
type (256bit, 64 hex chars) first argument
0000000000000000000000000000000000000000000000000000000000000001
is the uint256
type (256bit, 64 hex chars) second argument
So the result is 0x
and 136 hex characters, which makes 68 bytes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…