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

调用Solidity合约string变量触发VM异常:invalid opcode求助

问题:Solidity合约调用string类型变量触发invalid opcode异常

合约代码

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.25;

contract TestContract {
  string public name;
  uint public number;
  
  constructor() {
    number = 1;
    name = "Normal name";
  }
}

Web3.js测试代码

import ganache from "ganache";
import { Web3 } from "web3";

import { abi, evm } from "../compile.js";

const web3 = new Web3(ganache.provider());

let accounts;
let testContract;

describe("TestContract Test", () => {
  it("should read the value of names state variable", async () => {
    accounts = await web3.eth.getAccounts();
    testContract = await new web3.eth.Contract(abi)
      .deploy({ data: evm.bytecode.object })
      .send({ from: accounts[0], gas: "10000000"});  

    const name = await testContract.methods.name().call();

    console.log(name);
    
  });
});

错误输出

1) TestContract Test
       should read the value of names state variable:
     CallError: VM Exception while processing transaction: invalid opcode
      at Blockchain.simulateTransaction (node_modules\ganache\dist\node\1.js:2:100650)

依赖版本

"dependencies": {
    "ganache": "^7.9.2",
    "mocha": "^10.4.0",
    "solc": "^0.8.25",
    "web3": "^4.1"
  }

原因与解决方案

原因

Ganache 7.9.2版本对Solidity 0.8.20+引入的字节码变更支持不完善,尤其是处理string这类动态长度类型时,会触发无效操作码异常。uint等值类型不受影响,因为其字节码处理逻辑更简单。

解决方案

方案1:升级Ganache到兼容版本

将Ganache升级至v7.9.10及以上版本(该版本修复了与Solidity 0.8.25的兼容问题),执行命令:

npm install ganache@^7.9.10 --save-dev

方案2:降级Solidity版本

若暂时不想升级Ganache,可将Solidity版本降级至0.8.19或更早:

  1. 修改合约中的pragma声明:
pragma solidity ^0.8.19;
  1. 更新package.json中的solc版本:
"solc": "^0.8.19"
  1. 重新安装依赖:
npm install

内容的提问来源于stack exchange,提问作者Müller Espósito

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:38:08