
本文旨在帮助开发者解决在Solidity迁移部署过程中遇到的“Migrations hit an invalid opcode while deploying”错误。该错误通常是由于Solidity编译器版本高于目标网络支持的版本,导致编译器输出了包含目标网络不支持的操作码的字节码。本文将提供三种解决方案,包括降级编译器版本、指定目标EVM版本以及升级本地网络,帮助开发者顺利完成智能合约的部署。
当你在使用Truffle进行Solidity智能合约迁移部署时,可能会遇到 "Migrations hit an invalid opcode while deploying" 错误。这个错误通常意味着你的Solidity编译器版本生成了包含目标网络不支持的操作码(opcode)的字节码。 简单来说,就是你的编译器“太新”了,而你的目标网络“太旧”了。
以下是几种解决此问题的方案:
这是最常见且通常最简单的解决方案。你需要将Solidity编译器版本降级到目标网络支持的版本。
修改Solidity文件中的pragma语句: 在你的.sol文件中,修改pragma solidity语句,指定一个较低的编译器版本。例如,将pragma solidity ^0.8.0; 改为 pragma solidity 0.8.19;。
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.19;
contract Migrations {
address public owner = msg.sender;
uint public last_completed_migration;
modifier restricted() {
require(
msg.sender == owner,
"This function is restricted to the contract's owner"
);
_;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}修改Truffle配置文件(truffle-config.js): 在truffle-config.js文件中,修改solc部分的version属性,与你在Solidity文件中指定的版本一致。
module.exports = {
// ...
compilers: {
solc: {
version: "0.8.19"
}
},
// ...
};原因: solc 0.8.20 及更高版本默认使用 PUSH0 操作码,如果你的目标网络不支持 PUSH0,就会出现 "invalid opcode" 错误。 降级到 0.8.19 就可以避免这个问题。
如果你想继续使用最新的Solidity编译器,可以指定一个较低的EVM版本。
修改Truffle配置文件(truffle-config.js): 在truffle-config.js文件中,在solc部分的settings属性中添加evmVersion属性。
module.exports = {
// ...
compilers: {
solc: {
version: "^0.8.0",
settings: {
evmVersion: 'london' // 或者 'istanbul', 'berlin' 等
}
}
},
// ...
};原因: 通过指定evmVersion,你可以告诉Solidity编译器生成与特定EVM版本兼容的字节码。 例如,london EVM版本不支持PUSH0,因此编译器不会生成包含该操作码的字节码。
如果你的目标网络是本地运行的(例如,Ganache),可以尝试升级到最新版本。
更新Ganache: 确保你使用的是最新版本的Ganache。 可以通过 npm 全局安装或更新:
npm install -g ganache
重启Ganache: 更新完成后,重启Ganache。
原因: 新版本的Ganache可能已经支持了最新的操作码,从而解决了 "invalid opcode" 错误。
通过以上方法,你应该能够解决 "Migrations hit an invalid opcode while deploying" 错误,并成功部署你的Solidity智能合约。
以上就是解决Solidity迁移部署时遇到的“Invalid Opcode”错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号