使用deployed()创建Ganache部署的合约实例时遇解析错误求助
解决Truffle中
SimpleLearn.deployed()解析错误的方案 核心原因
你的SimpleLearn合约带有构造函数参数,deployed()方法在部分场景下无法正确关联部署时传入的参数,导致实例化时出现解析错误。以下是具体解决步骤:
1. 改用直接指定合约地址的方式实例化
跳过deployed()方法,直接通过Ganache上的合约部署地址创建实例,这是最可靠的方式:
// 替换为你Ganache上实际的SimpleLearn合约地址 const contractAddr = '0x...'; let newinst = await SimpleLearn.at(contractAddr);
2. 验证部署脚本与合约状态
- 执行
truffle networks命令,查看输出中SimpleLearn合约的部署地址和状态,确认合约确实已成功部署且地址正确。 - 确保部署脚本
2_deploy_contract.js中的构造参数格式正确,地址和数值没有拼写错误。
3. 重新编译部署合约
如果本地编译的ABI与链上合约不匹配,也会触发解析错误。执行以下命令重新部署:
truffle compile --all truffle migrate --reset
4. 确认控制台上下文正确
在Truffle控制台中操作时,先确保已正确引入合约:
const SimpleLearn = artifacts.require("SimpleLearn"); // 再执行实例化操作 let newinst = await SimpleLearn.at(contractAddr);
用户提供的原始代码:
SimpleLearn.sol
contract SimpleLearn { address public payer; address public thirdParty; address public receiver; uint public amt; uint senderBal; uint remamount; constructor (address _payer, uint amount, address _receiver) // constructor is invoked only once for entire // contract. mostly thats why invoked by thirdParty { payer = _payer; receiver = _receiver; amt = amount; thirdParty = msg.sender; remamount = amount; } mapping (address=>uint) public balances; function deposit(uint transferm) public returns (uint) { require (msg.sender == payer, "Sender must be payer"); require (transferm< remamount, "Amount to transfer should be lesser than remaining amount"); remamount = remamount - transferm; balances[thirdParty] += transferm; return remamount; //return msg.sender.balance; } }
2_deploy_contract.js
module.exports = function(deployer) { deployer.deploy(SimpleLearn,'0x21DB98979bc3a42D58648cC22c47C11610f2E094',50,'0x62F49aE035648325320454cC8B3934F3c8c36A77'); };
内容的提问来源于stack exchange,提问作者Aditi
相关产品推荐
相关产品推荐

