PHP code example of phpmac / ethers-php

1. Go to this page and download the library: Download phpmac/ethers-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpmac / ethers-php example snippets


use Ethers\Ethers;
use Ethers\Provider\JsonRpcProvider;

// Create Provider
$provider = new JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_KEY');

// Or use static method
$provider = Ethers::getDefaultProvider('https://mainnet.infura.io/v3/YOUR_KEY');

// Get network info
$network = $provider->getNetwork();
echo "Chain ID: " . $network['chainId'];  // 1
echo "Name: " . $network['name'];         // mainnet

// Get current block number
$blockNumber = $provider->getBlockNumber();

// Get account balance
$balance = $provider->getBalance('0x...');
echo Ethers::formatEther($balance) . " ETH";

// Get gas price
$gasPrice = $provider->getGasPrice();

// Get fee data (EIP-1559)
$feeData = $provider->getFeeData();

use Ethers\Signer\Wallet;

// Create wallet from private key
$wallet = new Wallet('0x...');

// Connect to Provider
$wallet = $wallet->connect($provider);

// Get address
$address = $wallet->getAddress();

// Get balance
$balance = $wallet->getBalance();

// Get nonce
$nonce = $wallet->getNonce();

// Sign message
$signature = $wallet->signMessage('Hello World');

// Send transaction
$response = $wallet->sendTransaction([
    'to' => '0x...',
    'value' => Ethers::parseEther('0.1'),
]);

// Wait for confirmation
$receipt = $response['wait'](1);  // wait for 1 confirmation

use Ethers\Ethers;

$provider = Ethers::getDefaultProvider('https://mainnet.infura.io/v3/YOUR_KEY');
$contractAddress = '0x...';

// Human-readable ABI - same syntax as ethers.js
$abi = [
    'function name() view returns (string)',
    'function symbol() view returns (string)',
    'function decimals() view returns (uint8)',
    'function balanceOf(address owner) view returns (uint256)',
    'function transfer(address to, uint256 amount) returns (bool)',
    'event Transfer(address indexed from, address indexed to, uint256 value)',
];

$contract = Ethers::contract($contractAddress, $abi, $provider);

// Call read-only methods - same as ethers.js
$name = $contract->name();
$symbol = $contract->symbol();
$balance = $contract->balanceOf($userAddress);

echo "$name ($symbol): $balance";

use Ethers\Contract\Contract;

// Standard JSON ABI
$erc20Abi = [
    [
        'type' => 'function',
        'name' => 'balanceOf',
        'inputs' => [['name' => 'account', 'type' => 'address']],
        'outputs' => [['name' => '', 'type' => 'uint256']],
        'stateMutability' => 'view',
    ],
    [
        'type' => 'function',
        'name' => 'transfer',
        'inputs' => [
            ['name' => 'to', 'type' => 'address'],
            ['name' => 'amount', 'type' => 'uint256'],
        ],
        'outputs' => [['name' => '', 'type' => 'bool']],
        'stateMutability' => 'nonpayable',
    ],
];

$contract = new Contract($tokenAddress, $erc20Abi, $provider);
$balance = $contract->balanceOf($userAddress);

// Connect Wallet for write operations
$wallet = Ethers::wallet($privateKey, $provider);
$contract = Ethers::contract($tokenAddress, $abi, $wallet);

// Send transaction - same as ethers.js
$response = $contract->transfer($toAddress, Ethers::parseUnits('100', 18));
$receipt = $response['wait']();

echo "Tx Hash: " . $response['hash'];

// Estimate gas
$gas = $contract->estimateGas('transfer', [$toAddress, Ethers::parseUnits('100', 18)]);

// Static call
$result = $contract->staticCall('transfer', [$toAddress, Ethers::parseUnits('100', 18)]);

// Get function object - similar to ethers.js contract.transfer
$transferFunc = $contract->getFunction('transfer');

// staticCall
$result = $transferFunc->staticCall([$to, $amount]);

// estimateGas
$gas = $transferFunc->estimateGas([$to, $amount]);

// send
$response = $transferFunc->send([$to, $amount]);

// populateTransaction
$tx = $transferFunc->populateTransaction([$to, $amount]);

$name = $contract->call('name');
$balance = $contract->call('balanceOf', [$address]);

/**
 * @method string name()
 * @method string symbol()
 * @method string balanceOf(string $owner)
 * @method array transfer(string $to, string $amount)
 */
class TokenContract extends Contract {}

$contract = new TokenContract($address, $abi, $provider);
$name = $contract->name(); // IDE recognizes with full type hints

use Ethers\Contract\Contract;
use Ethers\Provider\JsonRpcProvider;
use Ethers\Utils\Units;

$provider = new JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_KEY');
$contract = new Contract($tokenAddress, $abi, $provider);

// Prepare batch calls
$calls = [
    ['method' => 'name', 'args' => []],
    ['method' => 'symbol', 'args' => []],
    ['method' => 'decimals', 'args' => []],
    ['method' => 'totalSupply', 'args' => []],
];

// Execute batch - one HTTP request for all calls
$results = $contract->multicall($calls);

// Results are in the same order as calls
echo "Name: " . $results[0][0];
echo "Symbol: " . $results[1][0];
echo "Decimals: " . $results[2][0];
echo "TotalSupply: " . Units::formatUnits($results[3][0], (int) $results[2][0]);

use Ethers\Ethers;
use Ethers\Contract\ContractFactory;

// Human-readable ABI
$abi = [
    'constructor(string name, string symbol)',
    'function name() view returns (string)',
    'function symbol() view returns (string)',
    'function totalSupply() view returns (uint256)',
];

// Contract bytecode (from compiler)
$bytecode = '0x608060405234801561001057600080fd5b50...';

// Create Factory
$factory = Ethers::contractFactory($abi, $bytecode, $wallet);

// Or instantiate directly
$factory = new ContractFactory($abi, $bytecode, $wallet);

// Deploy contract - pass constructor arguments
$contract = $factory->deploy('My Token', 'MTK');

// Wait for deployment
$contract->waitForDeployment();

echo "Deployed to: " . $contract->target;

// Get deployment transaction
$deployTx = $contract->deploymentTransaction();
echo "Tx Hash: " . $deployTx['hash'];

// Call contract methods
$name = $contract->name();  // "My Token"

use Ethers\Ethers;
use Ethers\Contract\Interface_;

// Create Interface from human-readable format
$interface = Ethers::parseAbi([
    'function transfer(address to, uint256 amount) returns (bool)',
    'event Transfer(address indexed from, address indexed to, uint256 value)',
]);

// Or instantiate directly
$interface = new Interface_([
    'function transfer(address to, uint256 amount) returns (bool)',
]);

// Encode function call
$data = $interface->encodeFunctionData('transfer', [$to, $amount]);

// Decode function call
$args = $interface->decodeFunctionData('transfer', $data);

// Get function selector
$func = $interface->getFunction('transfer');
echo $func['selector'];  // 0xa9059cbb

// Format to human-readable
$fragments = $interface->format('minimal');

use Ethers\Ethers;

// Unit conversion
$wei = Ethers::parseEther('1.5');         // "1500000000000000000"
$ether = Ethers::formatEther($wei);       // "1.5"

$units = Ethers::parseUnits('100', 6);    // USDT 6 decimals
$formatted = Ethers::formatUnits($units, 6);

// Hash
$hash = Ethers::keccak256('Hello');

// Function selector
$selector = Ethers::id('transfer(address,uint256)');  // "0xa9059cbb"

// Address validation
$isValid = Ethers::isAddress('0x...');
$checksumAddress = Ethers::getAddress('0x...');

// Constants
$zero = Ethers::zeroAddress();
$zeroHash = Ethers::zeroHash();

// ethers-php - exactly the same syntax
$abi = [
    'function name() view returns (string)',
    'function transfer(address to, uint256 amount) returns (bool)',
    'event Transfer(address indexed from, address indexed to, uint256 value)',
];
$contract = new Contract($address, $abi, $provider);
bash
composer