web3p / web3.php

A php interface for interacting with the Ethereum blockchain and ecosystem. Native ABI parsing and smart contract interactions.
MIT License
1.15k stars 540 forks source link

$contract->at($erc20TokenAddress)->call('balanceOf', [$accountAddress], function($err, $result) { } function call with params giving error while function call without params is working #354

Open wtmit opened 2 months ago

wtmit commented 2 months ago

<?php

require('../vendor/autoload.php');

use Web3\Providers\HttpProvider; use Web3\Web3; use Web3\Contract;

$accountAddress = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; $erc20TokenAddress = '0x11B9EC22a5fe98a5b2566E508cc66fCB44Ab1506'; $erc20TokenDecimal = 18;

$rpcUrl = "https://polygon-amoy.infura.io/v3/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

// Connect to Ethereum node
$web3 = new Web3(new HttpProvider($rpcUrl, 5)); // Update with your Ethereum node URL

// Load ERC20 token contract ABI
$erc20TokenABI = json_decode(file_get_contents('ERC20_TOKEN_ABI.json'), true); // Update with your ABI file path

// Create contract instance $contract = new Contract($web3->provider, $erc20TokenABI);

 $contract->at($erc20TokenAddress)->call('symbol', function ($err, $result) {
    if ($err !== null) { return; } 
    echo 'The symbol: ' .  $result[0];
  });

  $contract->at($erc20TokenAddress)->call('balanceOf', [$accountAddress], function($err, $result)  {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage() . PHP_EOL;
        // return;
    }
    // Print balance
    print_r($result);
    });

The symbol: WTM PHP Warning: Array to string conversion in D:\xampp\htdocs\web3.php-master\src\Contracts\Types\Address.php on line 63

Warning: Array to string conversion in D:\xampp\htdocs\web3.php-master\src\Contracts\Types\Address.php on line 63 PHP Fatal error: Uncaught InvalidArgumentException: Please make sure you have put all function params and callback. in D:\xampp\htdocs\web3.

                                                                                                                                        .php-master\src\Contract.php:625
wtmit commented 2 months ago

$erc20TokenBalance = $contract->at($erc20TokenAddress)->call('balanceOf', [$accountAddress], function($err, $result) { if ($err !== null) { echo 'Error: ' . $err->getMessage() . PHP_EOL; // return; }

    print_r($result);
        });
wenzhuangz commented 1 month ago

Try this: $contract = new Contract(rpcurl, abi);

    $contract->at(tokenAddress)->call('balanceOf', address, [
        'from' => address,
    ], function ($err, $result) use ($contract) {
        if ($err !== null) {
            $this->res['err'] = $err->getMessage();
        }
        if (isset($result)) {;
            $bn = Utils::toBn($result[0]);
            $this->res['amount'] = bcdiv($bn->toString(), 10 ** 18, 18);
        }
    });