【问题标题】:Getting return value of Solidity contract function from web3-1.0.0-beta.27从 web3-1.0.0-beta.27 获取 Solidity 合约函数的返回值
【发布时间】:2018-01-28 02:20:39
【问题描述】:

我正在运行web3 1.0.0-beta.27, pragma solidity ^0.4.2;

contract Charity{

    function ping() public constant returns (uint) {
        return 200;
    }


}

我正在typescript 中编译/调用它:

import * as fs       from 'fs'       ;
import * as solc     from 'solc'     ;
import * as Web3     from 'web3'     ; 


var web3   = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

var contract_path : string = "path/to/Charity.sol"
const input       = fs.readFileSync(contract_path)
const output      = solc.compile(input.toString(), 1);
var contract_name = ":" + pr.last(contract_path.split("/")).split(".")[0]
const bytecode    = output.contracts[contract_name].bytecode
const abi_        = JSON.parse(output.contracts[contract_name].interface);

web3.eth.getAccounts().then(accounts => {

    var coinbase = accounts[0];
    var receiver = accounts[1];

    // create contract
    var myContract = new web3.eth.Contract([], {
          from     : coinbase
        , gasPrice : '20000000000'
    });

    // set address to coinbase, and jsonInterface to abi
    myContract.options.address = coinbase;
    myContract.options.jsonInterface = abi_;

    // deploy contract -> problem, how do I get the abi in here?
    var deployedContract = myContract.deploy({

        data: '0x' + bytecode,

    }).send({

        from: coinbase,
        gas : 1500000 ,
        gasPrice: '30000000000000'            

    }, (err, hash) => {

        if (err) { console.log("error on deployment: ", err) }
        console.log("Hash: ", hash)
    })

    // send contract fn to network to be executed
    // problem: this is not doing what it's suppose to 
    myContract.methods.ping().send({ from : coinbase }, (err, val) => {
        console.log("ping(): ", err, val)
    })

    myContract.methods.ping().send({from: coinbase})
    .on('transactionHash', function(hash){
        console.log("hash: ", hash)
    })
    .on('receipt', function(receipt){
        console.log("recepit: ", receipt)
    })
    .on('confirmation', function(confirmationNumber, receipt){
        console.log("conffirmation: ", receipt)
    })
    .on('error', console.error);        



});

问题是myContract.methods.ping().send... 没有按照我的意愿在回调中返回值200,有没有办法解决这个问题?

【问题讨论】:

    标签: javascript blockchain ethereum smartcontracts web3


    【解决方案1】:

    一旦你调用了一个常量函数,你应该使用 call() 而不是 send() 方法。

    查看文档: http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-call

    【讨论】:

      【解决方案2】:

      当你不修改状态时,你只需使用 call()。如果您修改状态,您需要一个交易(发送),然后您需要等待交易被挖掘。什么时候可以发出一个事件并监听它。

      【讨论】:

        猜你喜欢
        • 2018-06-18
        • 2018-09-16
        • 1970-01-01
        • 2019-08-15
        • 2021-09-14
        • 1970-01-01
        • 2022-09-29
        • 2018-04-25
        • 2020-10-25
        相关资源
        最近更新 更多