狼爱上狸

我胡汉三又回来了

调用智能合约简单运算总返回0的问题

1.合约内容
pragma
solidity ^0.5.9;

contract hello {

function mutiply(uint a) public pure returns (uint result) {

return a*3;

}
}
2.部署合约:
var Web3 = require("web3");
var fs = require("fs");
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
var code = '0x' + fs.readFileSync("2_sol_hello.bin").toString();
var abi = JSON.parse(fs.readFileSync("2_sol_hello.abi").toString());
var contract = web3.eth.contract(abi);
console.log(web3.eth.accounts);
console.log('account balance:' + web3.eth.getBalance(web3.eth.accounts[0]))

web3.personal.unlockAccount(web3.eth.accounts[0],"123")
var contract = contract.new({from: web3.eth.accounts[0], data: code, gas: 470000},
function(e, contract){

if(!contract.address) {
console.log("已经发起交易,交易地址:" + contract.transactionHash + "\n正在等待挖矿");
} else {
console.log("智能合约部署成功,地址:" + contract.address);

}

}
)
3.调用合约
var Web3 = require("web3");
var fs = require("fs");
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
var abi = JSON.parse(fs.readFileSync("2_sol_hello.abi").toString());
var contract = web3.eth.contract(abi);
var instance = contract.at('0xb06846c54c6ae67102ed67ce57a357a643d1f1b8')
web3.personal.unlockAccount(web3.eth.accounts[0],"123")
console.log(instance.mutiply(12).toString())
4.显示结果为:
0
原因:solc版本0.5.9太高,可能调用的方法不对。
解决方法:npm install -g solc@0.4.22
降低版本,然后把合约第一行改为:
pragma solidity ^0.4.22;
问题解决。

posted on 2019-06-23 18:12 狼爱上狸 阅读(292) 评论(0)  编辑  收藏 所属分类: Blockchain


只有注册用户登录后才能发表评论。


网站导航: