簡體   English   中英

使用Web3.js版本在智能合約中調用公共方法:“ 1.0.0-beta.46”

[英]Calling a public method in smart contract with Web3.js version: '1.0.0-beta.46'

我開始在私有網絡上以奇偶校驗開始以太坊區塊鏈的第一步。 通過Parity UI,我可以配置奇偶校驗並在我的專用網絡上的開發人員模式鏈上執行智能合約的部署,該UI也可以調用合約的方法。

我面臨的問題與使用Web3.js在智能合約中調用函數有關。 我能夠使用Web.js庫連接到鏈。

Web3 = require('web3')

web3 = new Web3('ws://localhost:8546')

mycontract = web3.eth.Contract([{"constant":false,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}],0xEb112542a487941805F7f3a04591F1D6b04D513c)

當我調用下面的方法時;

mycontract.methods.greet().call()

它給了我以下輸出,而不是通過智能合約greet函數中編寫的promise對象返回期望的字符串“ OK Computer”。

{ [Function: anonymousFunction]
  send: { [Function] request: [Function] },
  estimateGas: [Function],
  encodeABI: [Function] }

智能合約代碼:

pragma solidity ^0.4.22;
//Compiler Version: 0.4.22
contract Greeter {
    address owner;

    constructor() public { 
        owner = msg.sender; 
    }    
    function greet() public returns(string){
        return "OK Computer";
    }
}

每個涉及區塊鏈狀態變化的交易或智能合約方法調用都將返回一個承諾 因此,您只需要相應地履行承諾即可:

mycontract.methods.greet.call().then(function(resp) {
   console.log(resp) // This will output "OK Computer"
}

網絡文檔中的更多內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM