狼愛上貍

          我胡漢三又回來了

          調用智能合約簡單運算總返回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 狼愛上貍 閱讀(302) 評論(0)  編輯  收藏 所屬分類: Blockchain

          主站蜘蛛池模板: 阿尔山市| 大埔区| 高陵县| 万盛区| 纳雍县| 晋州市| 大埔区| 上虞市| 洛川县| 呼玛县| 永兴县| 西乡县| 泊头市| 青浦区| 祁阳县| 胶南市| 开封市| 东方市| 廉江市| 揭东县| 绍兴市| 顺义区| 黔东| 仲巴县| 开阳县| 涡阳县| 宝坻区| 西吉县| 田阳县| 青冈县| 贵南县| 南漳县| 曲周县| 博白县| 丰原市| 穆棱市| 巫山县| 托里县| 城固县| 合作市| 遂昌县|