如何使用web3、ethers将-1编码为uint256适配Aave liquidationCall参数
Aave liquidationCall 最大清算金额uint256编码方案
报错原因
web3/ethers的ABI编码模块会默认校验无符号整数(uint)类型入参不能为负,而Solidity语法中uint(-1)的本质是返回uint256类型的最大值(即2^256 - 1),传入等效的正整数最大值即可完成编码。
Ethers.js 实现方法
- v5版本直接调用内置常量:
// 单独编码参数 const encoded = ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.constants.MaxUint256]) // 合约调用直接传参示例 await aaveContract.liquidationCall( collateralAsset, debtAsset, userAddress, ethers.constants.MaxUint256, false )
- v6版本常量位置调整,调用方式如下:
const encoded = ethers.AbiCoder.defaultAbiCoder().encode(["uint256"], [ethers.MaxUint256])
Web3.js 实现方法
- v1/v2/v3版本手动计算最大值:
const maxUint256 = web3.utils.toBN(2).pow(web3.utils.toBN(256)).sub(web3.utils.toBN(1)) // 单独编码参数 const encoded = web3.eth.abi.encodeParameter("uint256", maxUint256) // 合约调用直接传参示例 await aaveContract.methods.liquidationCall( collateralAsset, debtAsset, userAddress, maxUint256, false ).send()
- v4版本内置了最大值常量,可直接调用:
const encoded = web3.eth.abi.encodeParameter("uint256", web3.utils.maxUint256)
内容的提问来源于stack exchange,提问作者pygeek
相关产品推荐
相关产品推荐

