calling smart contracts methods using web3 ethereum

时光总嘲笑我的痴心妄想 提交于 2019-11-30 09:20:30

You can call contract functions by either using contract.methodName.call(), contract.methodName.sendTransaction(), or contract.methodName() methods. The last version simply delegates to one of the first two depending on the method type (ie, if it's a constant). See the Contract Methods section in the docs.

The parameter list starts with the parameters for the function itself (if any), followed by an optional transaction object, followed by the callback. To call your createRandomAgency() method, you would do this:

const contract = web3.eth.contract(contractAbi);
const contractInstance = contract.at(contractAddress);

const transactionObject = {
  from: fromAccount,
  gas: gasLimit
  gasPrice: gasPriceInWei
};

contractInstance.createRandomAgency.sendTransaction('name', transactionObject, (error, result) => { // do something with error checking/result here });

The list of available options for the transaction object can be found here.

To call your public agencies array, it would look like

contractInstance.agencies.call(0, (error, result) => {
  if (!error) {
    console.log(result.name);
    console.log(result.dna);
  }
}); // transaction object not needed
sameepsi

I think you should try something like this-:

 var contractAbi= "" //here put your contract abi in json string
 var deployedContract = web3.eth.contract(abi).at("contract address");
 //now you should be able to access contract methods
 deployedContract.agencies.call({from:address}, function(err,data){
 console.log(data);
 });

Test this out once.

Try using callbacks or promises. The following code worked for me, when I wanted to get the return value from one of my contract's methods:

const contract = web3.eth.contract(contractABI);
const contractInstance = contract.at(this.contractAddress);

return new Promise((resolve, reject) => {
  contractInstance.**yourMethod**.call(function (error, result) {
    if (error) {
      console.log(error);
    } else {
      resolve(result);
    }
  });
}) as Promise<number>;

Also check out: https://github.com/ethereum/wiki/wiki/JavaScript-API#using-callbacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!