Human-Readable ABI

约 301 字大约 1 分钟

Human-Readable ABI

进行开发时,一般使用npx hardhat compile后导入Abi,但是不够直观,正好找到一篇文章open in new window,这也算开发中小技巧,这里进行记录。

An image

来看下ethers支持的几种格式ABI Formatsopen in new window

An image

进行转换

import { ethers } from 'ethers';

async function main() {
    const jsonAbi =
        require('../artifacts-zk/contracts/IL2Weth.sol/IL2Weth.json').abi;
    const iface = new ethers.utils.Interface(jsonAbi);
    console.log(iface.format(ethers.utils.FormatTypes.full));
}

main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});

执行脚本npx hardhat run ./scripts/convert-abi.ts,输出结果为:

[
  'event Initialize(string name, string symbol, uint8 decimals)',
  'function allowance(address owner, address spender) view returns (uint256)',
  'function approve(address spender, uint256 value) returns (bool)',
  'function balanceOf(address account) view returns (uint256)',
  'function deposit() payable',
  'function depositTo(address _to) payable',
  'function withdraw(uint256 _amount)',
  'function withdrawTo(address _to, uint256 _amount)'
]

将打印ABI粘贴到代码中,然后删除无用的ABI

import { BigNumber, Wallet, ethers } from 'ethers';

const abi = ['function approve(address spender, uint256 value) returns (bool)'];

async function approveToken(
    wallet: Wallet,
    tokenAddress: string,
    spender: string,
    approveValue: BigNumber
) {
    const tokenContract = new ethers.Contract(tokenAddress, abi, wallet);
    const txApprove = await tokenContract.approve(spender, approveValue);
    return await txApprove.wait();
}

export default approveToken;

总结

  • 使用人类可读abi可以删除无用提高效率。
  • 知道当前脚本调用了那些abi。