Problem in calling an Ethereum contract method using Web3.php

113 views Asked by At

I am using Web3.php to read an ERC20 token balance of a wallet from its contract.

use Web3\Web3;
use Web3\Contract;
use Web3\Utils;
$web3 = new Web3('https://...');
$contractAbi = file_get_contents("abi.json");
$contractAddress = "0x...";
$contract = new Contract($web3->getProvider(), $contractAbi);
$params = [ $account ];
$result = $contract->at($contractAddress)->call('balanceOf', $params);

But this error is displayed for the last line:

Error: The last param must be callback function.

Although this is not mentioned in the documents, I changed the source to:

$result = $contract->at($contractAddress)->call('balanceOf', $params, function($error,$result){
        ...
    });

But it says:

Error: Please make sure you have put all function params and callback

Note that there is not enough help document for Web3.php.

How can I call the balanceOf method of an ERC20 contract?

1

There are 1 answers

1
muhammad Heidari On

use callback function :

  $contract_address = $contrat;
  $rpc_endpoint = $rpc;
  $params = [ $account ];
  $abi=file_get_contents("abi.json");

  $contractAbi =json_decode(file_get_contents($abi), true); 
  // Connect to Ethereum node
        $web3 = new \Web3\Web3($rpc_endpoint);
        $contract = new Contract($web3->provider, $contractAbi);
        $result='';
        // Call a function from the contract
        $assets = $contract->at($contract_address)->call('YOUR_METHOD'
        ,$params
        ,function ($err, $data) use (&$result) {
                $result = $data;
            }
        );
        return  $result;
  }