Skip to content

Instantly share code, notes, and snippets.

@swkim109
Last active November 11, 2023 05:45
Show Gist options
  • Save swkim109/ddab7545cd98468a6bd6a26c770c305b to your computer and use it in GitHub Desktop.
Save swkim109/ddab7545cd98468a6bd6a26c770c305b to your computer and use it in GitHub Desktop.
Function calldata
const abi = [
"function withdraw(address,uint256)"
];
const iface = new ethers.utils.Interface(abi);
const calldata = iface.encodeFunctionData("withdraw", ["0x0000000000000000000000000000000000000000", ethers.BigNumber.from("10000000000000000")]);
console.log(calldata)
// Solidity
address _addr = 0x0000000000000000000000000000000000000000;
uint256 _val = 100;
bytes memory payload = abi.encodeWithSelector(bytes4(keccak256(bytes("withdraw(address,uint256)"))), _addr, _val);
@swkim109
Copy link
Author

swkim109 commented Dec 26, 2022

함수 시그너처는 "함수명(...파라미터)"의 keccak256 해시의 앞 4바이트이다.

ethers.utils.keccak256(ethers.utils.toUtf8Bytes("withdraw(address,uint256)"))
ethers.utils.id("withdraw(address,uint256)")

@swkim109
Copy link
Author

swkim109 commented Oct 27, 2023

함수 전달 파라미터나 리턴 값을 ABI 인코딩할 때

const abiCoder = ethers.utils.defaultAbiCoder;
const v = abiCoder.encode(["address","bytes"], ["0x9a508486f8e338b79258F4A918b27AaE63c54501", "0x"]);
console.log(v);

ethers에서는 bytes 타입의 빈 값은 "0x", 솔리디티에서는 ""을 넣어야 한다("0x"라고 하면 아스키 문자로 인식하여 0x3078이 들어간다).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment