You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solidity返回字符串数组被JS识别为bigNumber溢出报错如何解决

问题修复方案

根因

你遇到的是web3.js低版本和Solidity 0.5.x版本 experimental ABIEncoderV2 返回动态字符串数组的解码兼容bug:ABIEncoderV2返回的string数组结构里,web3旧版本解码时误将字符串相关的长度/偏移字段尝试转为JS Number类型,而对应数值远超JS安全整数范围(2^53-1),就触发了BigNumber溢出错误。

可选修复方案

方案1:升级web3.js到最新稳定版(成本最低)

web3.js 1.3.0及以上版本已经修复了动态string数组的解码问题,直接升级依赖即可,原有业务代码不需要改动:

npm install web3@latest

升级后直接调用contract.methods.get().call()就能正常拿到字符串数组。


方案2:修改Solidity合约逻辑(无法升级依赖时可选)

如果受项目限制不能升级web3版本,可以调整合约逻辑,不直接返回整个string数组,改为先返回数组长度,再单个查询对应下标的哈希:
修改后的Solidity代码:

pragma solidity 0.5.16;

contract storeHash {
    string[] public fileHash;

    function set(string memory _fileHash) public {
        fileHash.push(_fileHash);
    }

    // 新增:返回数组总长度
    function getHashCount() public view returns (uint256) {
        return fileHash.length;
    }

    // 可选:显式声明按索引查询哈希的方法,也可直接用public数组默认生成的getter
    function getHashByIndex(uint256 index) public view returns (string memory) {
        require(index < fileHash.length, "index out of bound");
        return fileHash[index];
    }
}

对应的JS查询代码修改为批量按索引拉取:

// 原有合约初始化逻辑不变
if(networkData) {
    const abi = storeHash.abi
    const address = networkData.address
    const contract = new web3.eth.Contract(abi, address)
    this.setState({ contract })
    
    // 先拉取数组总长度
    const hashCount = await contract.methods.getHashCount().call()
    const fileHashList = []
    // 循环拉取每个下标对应的哈希
    for(let i=0; i < hashCount; i++) {
        const hash = await contract.methods.fileHash(i).call()
        fileHashList.push(hash)
    }
    console.log(fileHashList)
} 

方案3:改用ethers.js交互(新项目可选)

如果你还没有确定用web3作为交互库,可以切换为ethers.js,它对Solidity ABI的兼容性更好,不需要修改合约就能直接解析返回的string数组:
安装依赖:

npm install ethers

基础交互代码示例:

const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()
const contract = new ethers.Contract(address, abi, signer)
const fileHashList = await contract.get()
console.log(fileHashList)

内容的提问来源于stack exchange,提问作者supdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 20:45:04