如何将参数作为字节在solid上传递



我有两个合约函数:

函数1接收bytes params变量

function foo1(bytes memory params)

函数2接收两个参数:address param1, uint256 param2

function foo2(address param1, uint256 param2)

我的目标以某种方式将参数作为字节传递给foo1,在函数上解码,并将解码后的参数传递给foo2

:

function foo2(address param1, uint256 param2) {
// do something
}
function decode(bytes params) private returns(???){
// decode
}
function foo1(bytes params) public {
var decodedParams = fromBytes(params)
foo2(decodedParams.param1, decodedParams.param2)
}

from frontend我希望是这样的:

const params = toBytes({param1: '0xAddRess', param2: 1})
myContract.foo1(params)

您可以使用abi.encodeParameters(前端)

const bytesHex = web3.eth.abi.encodeParameters(
['address', 'uint256'],
['0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', '1']
);

和合同中的abi.decode()

pragma solidity ^0.8;
contract MyContract {
function foo2(address param1, uint256 param2) external {
// do something
}

function foo1(bytes memory params) external {
(address decodedAddress, uint256 decodedUint) = abi.decode(params, (address, uint256));
this.foo2(decodedAddress, decodedUint);
}
}

相关内容

  • 没有找到相关文章

最新更新