欢迎订阅专栏:3分钟Solidity--智能合约--Web3区块链技术必学
如需获取本内容的最新版本,请参见 Cyfrin.io 上的ABI编码(代码示例)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface IERC20 {
function transfer(address, uint256) external;
}
contract Token {
function transfer(address, uint256) external {}
}
contract AbiEncode {
function test(address _contract, bytes calldata data) external {
(bool ok,) = _contract.call(data);
require(ok, "call failed");
}
function encodeWithSignature(address to, uint256 amount)
external
pure
returns (bytes memory)
{
// 不检查拼写错误 - "transfer(address, uint)"
return abi.encodeWithSignature("transfer(address,uint256)", to, amount);
}
function encodeWithSelector(address to, uint256 amount)
external
pure
returns (bytes memory)
{
// 类型未检查 - (IERC20.transfer.selector, true, amount)
return abi.encodeWithSelector(IERC20.transfer.selector, to, amount);
}
function encodeCall(address to, uint256 amount)
external
pure
returns (bytes memory)
{
// 拼写和类型错误将无法编译// 拼写和类型错误将无法编译
return abi.encodeCall(IERC20.transfer, (to, amount));
}
}
Remix Lite 尝试一下
END