簡體   English   中英

使用 web3 ethereum 調用智能合約方法

[英]calling smart contracts methods using web3 ethereum

嘗試使用以太坊解決區塊鏈問題時,我在嘗試與已部署的合約交互時遇到了問題。 我將嘗試實現的是調用一種方法來顯示添加到使用 Geth 本地部署的私有區塊鏈的信息。

我無法從我的智能合約中調用任何函數,我一直在想我是否做錯了什么......有人可以告訴我如何從這個合約中實現對其中一種方法的簡單調用嗎? 假設顯示現有機構,或用戶所屬的機構名稱。

我的合同: agent.sol

pragma solidity ^0.4.18;
// We have to specify what version of compiler this code will compile with

contract Agency {

  event NewAgency(uint agencyId, string name, uint dna);

  uint dnaDigits = 16;
  uint dnaModulus = 10 ** dnaDigits;

  //agency structure
  struct Agency {
    string name;
    uint dna;
  }

  Agency[] public agencies;

  mapping (uint => address) public agencyToOwner;
  mapping (address => uint) ownerAgencyCount;

  function _createAgency(string _name, uint _dna) private {
    uint id = agencies.push(Agency(_name, _dna)) - 1;
    agencyToOwner[id] = msg.sender;
    ownerAgencyCount[msg.sender]++;
    NewAgency(id, _name, _dna);
  } 

  function _generateRandomDna(string _str) private view returns (uint) {
    uint rand = uint(keccak256(_str));
    return rand % dnaModulus;
  }

  function createRandomAgency(string _name) public {
    //make sure contract can only execute if user is not part of an agency
    require(ownerAgencyCount[msg.sender] == 0);
    uint randDna = _generateRandomDna(_name);
    _createAgency(_name, randDna);
  }
}

abi定義

> abiDefinition
[ { constant: true,
    inputs: [ [Object] ],
    name: 'agencies',
    outputs: [ [Object], [Object] ],
    payable: false,
    stateMutability: 'view',
    type: 'function' },
  { constant: true,
    inputs: [ [Object] ],
    name: 'agencyToOwner',
    outputs: [ [Object] ],
    payable: false,
    stateMutability: 'view',
    type: 'function' },
  { constant: false,
    inputs: [ [Object] ],
    name: 'createRandomAgency',
    outputs: [],
    payable: false,
    stateMutability: 'nonpayable',
    type: 'function' },
  { anonymous: false,
    inputs: [ [Object], [Object], [Object] ],
    name: 'NewAgency',
    type: 'event' } ]

成功部署:

INFO [01-09|19:09:14] Submitted contract creation              fullhash=0x7c43e896329138a6778938ca30d2f5f17f9a63062b359a4fccbd1a1be439f385 contract=0x65175d22C56E1Bad976A331A8B6B448cd4B3995d

最后是contractInstance

> contractInstance = AgencyContract.at(0x65175d22C56E1Bad976A331A8B6B448cd4B3995d)
Contract {
  _eth: 
   Eth {
     _requestManager: RequestManager { provider: [Object], polls: {}, timeout: null },
     getBalance: { [Function: send] request: [Function: bound ], call: 'eth_getBalance' },
     getStorageAt: { [Function: send] request: [Function: bound ], call: 'eth_getStorageAt' },
     getCode: { [Function: send] request: [Function: bound ], call: 'eth_getCode' },
     getBlock: { [Function: send] request: [Function: bound ], call: [Function: blockCall] },
     getUncle: { [Function: send] request: [Function: bound ], call: [Function: uncleCall] },
     getCompilers: { [Function: send] request: [Function: bound ], call: 'eth_getCompilers' },
     getBlockTransactionCount: 
      { [Function: send]
        request: [Function: bound ],
        call: [Function: getBlockTransactionCountCall] },
     getBlockUncleCount: 
      { [Function: send]
        request: [Function: bound ],
        call: [Function: uncleCountCall] },
     getTransaction: 
      { [Function: send]
        request: [Function: bound ],
        call: 'eth_getTransactionByHash' },
     getTransactionFromBlock: 
      { [Function: send]
        request: [Function: bound ],
        call: [Function: transactionFromBlockCall] },
     getTransactionReceipt: 
      { [Function: send]
        request: [Function: bound ],
        call: 'eth_getTransactionReceipt' },
     getTransactionCount: { [Function: send] request: [Function: bound ], call: 'eth_getTransactionCount' },
     call: { [Function: send] request: [Function: bound ], call: 'eth_call' },
     estimateGas: { [Function: send] request: [Function: bound ], call: 'eth_estimateGas' },
     sendRawTransaction: { [Function: send] request: [Function: bound ], call: 'eth_sendRawTransaction' },
     signTransaction: { [Function: send] request: [Function: bound ], call: 'eth_signTransaction' },
     sendTransaction: { [Function: send] request: [Function: bound ], call: 'eth_sendTransaction' },
     sign: { [Function: send] request: [Function: bound ], call: 'eth_sign' },
     compile: { solidity: [Object], lll: [Object], serpent: [Object] },
     submitWork: { [Function: send] request: [Function: bound ], call: 'eth_submitWork' },
     getWork: { [Function: send] request: [Function: bound ], call: 'eth_getWork' },
     coinbase: [Getter],
     getCoinbase: { [Function: get] request: [Function: bound ] },
     mining: [Getter],
     getMining: { [Function: get] request: [Function: bound ] },
     hashrate: [Getter],
     getHashrate: { [Function: get] request: [Function: bound ] },
     syncing: [Getter],
     getSyncing: { [Function: get] request: [Function: bound ] },
     gasPrice: [Getter],
     getGasPrice: { [Function: get] request: [Function: bound ] },
     accounts: [Getter],
     getAccounts: { [Function: get] request: [Function: bound ] },
     blockNumber: [Getter],
     getBlockNumber: { [Function: get] request: [Function: bound ] },
     protocolVersion: [Getter],
     getProtocolVersion: { [Function: get] request: [Function: bound ] },
     iban: 
      { [Function: Iban]
        fromAddress: [Function],
        fromBban: [Function],
        createIndirect: [Function],
        isValid: [Function] },
     sendIBANTransaction: [Function: bound transfer] },
  transactionHash: null,
  address: 5.771290982673958e+47,
  abi: 
   [ { constant: true,
       inputs: [Array],
       name: 'agencies',
       outputs: [Array],
       payable: false,
       stateMutability: 'view',
       type: 'function' },
     { constant: true,
       inputs: [Array],
       name: 'agencyToOwner',
       outputs: [Array],
       payable: false,
       stateMutability: 'view',
       type: 'function' },
     { constant: false,
       inputs: [Array],
       name: 'createRandomAgency',
       outputs: [],
       payable: false,
       stateMutability: 'nonpayable',
       type: 'function' },
     { anonymous: false,
       inputs: [Array],
       name: 'NewAgency',
       type: 'event' } ],
  agencies: 
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     uint256: [Circular] },
  agencyToOwner: 
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     uint256: [Circular] },
  createRandomAgency: 
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     string: [Circular] },
  allEvents: [Function: bound ],
  NewAgency: { [Function: bound ] 'uint256,string,uint256': [Function: bound ] } }

我試過了:

contractInstance.agencies()
contractInstance.agencies.call()
contractInstance.agencies.call({from:ak})

導致Error: Invalid number of arguments to Solidity function

contractInstance.agencies.call("name" {from:ak})

導致Error: invalid address我也嘗試調用agencyToOwnercreateRandomAgency但沒有任何效果。

任何幫助都會很高興收到! 謝謝,

您可以使用contract.methodName.call()contract.methodName.sendTransaction()contract.methodName()方法調用合約函數。 最后一個版本只是根據方法類型(即,如果它是一個constant )委托給前兩個中的一個。 請參閱文檔中的合同方法部分。

參數列表以函數本身的參數(如果有)開始,然后是可選的事務對象,然后是回調。 要調用您的createRandomAgency()方法,您可以這樣做:

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 });

可以在此處找到事務對象的可用選項列表。

要調用您的公共agencies數組,它看起來像

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

我認為您應該嘗試這樣的事情-:

 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);
 });

測試一次。

嘗試使用回調或承諾。 當我想從合同的一種方法中獲取返回值時,以下代碼對我有用:

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>;

另請查看: https ://github.com/ethereum/wiki/wiki/JavaScript-API#using-callbacks

現在是 2022 年,web3/contracts 似乎有一些變化,所以讓我在這里留下一個答案。

假設您使用的是松露。

步驟1。 創建一個 truffle 項目,並在本地機器上安裝一個 ganache 網絡。

第2步。 創建一個合約並部署它。 獲取它的地址和網絡(例如 ganache )

truffle deploy --network=ganache

第三步。 通過以下方式運行腳本文件: truffle exec call.js --network=ganache

// Filename is:  call.js

// you need an address of the contract
const CONTRACT_ADDRESS = "0x7545eCD147210f38EF88142cd94f5Dd0C98E418D"
// you also need the abi of the contract
const contractJson = require('./build/contracts/VeryGoodNftWithMaxSupply.json')


module.exports = async function (callback) {
  // initialize the contract from web3, 
  const contract = new web3.eth.Contract( contractJson.abi, CONTRACT_ADDRESS );

  // get the network
  const network = await web3.eth.net.getNetworkType()

  // call the  `name` method. which is a view method.
  let result = await contract.methods.name().call()
  console.info("name: ", result)  

  // call the `mint` method. which need a TX operation,
  const tx = contract.methods.mint('0xc0dD5021e298dB57bEF361C735cd1C04cef2E48A')

  // send this tx.
  const receipt = await tx
  .send({
    // used first account from your wallet. 
    from: (await web3.eth.getAccounts())[0],
    gas: await tx.estimateGas(),
  })
  .on('transactionHash', (txhash) => {
    console.log(`Mining transaction ... network: ${network}, tx: ${txhash}`)
  })
  .on('error', function(error){
    console.error(`An error happened: ${error}`)
    callback()
  })
  .then(function(receipt){
    // Success, you've minted the NFT. The transaction is now on chain!
    console.log(
        `Success: The NFT has been minted and mined in block ${receipt.blockNumber}`)
    callback()
  })

}

結論

對於“查看”功能,您應該使用“呼叫”

對於需要 tx 的函數,你應該使用“send”和“once”,“on”

有關更多詳細信息,請查看此演示: https ://github.com/sg552/test_erc721_in_truffle_ganache

另請參考: http ://siwei.me/blog/posts/blockchain-web3-contract

遇到同樣的錯誤,只想將其添加到線程中。

Make sure the variable you are calling, is defined as public in your smart contract.

目前(如 2022 年)您必須在 javascript 中執行。

contact.methods.methodName().call()

但是如果您希望方法調用作為事務執行,則必須運行此命令。

contact.methods.methodName(value).send()

這是來源https://web3js.readthedocs.io/en/v1.7.4/web3-eth-contract.html#methods-mymethod-call

暫無
暫無

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

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