PHP code example of mrokwor / blockchain-sdk-php

1. Go to this page and download the library: Download mrokwor/blockchain-sdk-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/ */

    

mrokwor / blockchain-sdk-php example snippets


use BlockchainSdk\Laravel\Rules\BlockchainAddress;
use Illuminate\Http\Request;

public function swap(Request $request)
{
    $network = $request->input('destination_network'); // e.g. 'solana', 'bsc', 'tron', 'bitcoin'

    $request->validate([
        'recipient_address' => ['

use BlockchainSdk\Laravel\Facades\Blockchain;

// EVM (Ethereum, BSC, Polygon, Base, Arbitrum, etc.)
Blockchain::validateAddress('bsc', '0x55d398326f99059fF775485246999027B3197955'); // true
Blockchain::validateAddress('ethereum', '0xInvalidAddress123');                       // false

// Solana (Base58 32-byte public key)
Blockchain::validateAddress('solana', 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // true

// TRON (Base58Check T... address)
Blockchain::validateAddress('tron', 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'); // true

// Bitcoin (Bech32 SegWit & Base58 Legacy)
Blockchain::validateAddress('bitcoin', 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'); // true

use App\Models\BlockchainSdkWallet;

// Generates keypair and stores encrypted private key in database
$wallet = BlockchainSdkWallet::createForUser(
    userId: $user->id,
    network: 'bsc'
);

echo "Deposit Address: " . $wallet->address;

use BlockchainSdk\Laravel\Facades\Blockchain;

/** @var \BlockchainSdk\DTOs\Keypair $keypair */
$keypair = Blockchain::driver('ethereum')->generateWallet();

echo $keypair->address;     // "0x71C8360f3a104d31a4570b9A821929342939b422"
echo $keypair->privateKey;  // "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
echo $keypair->publicKey;   // "0x04e130f46ff5ff57a24cc634d..."
echo $keypair->mnemonic;    // Optional HD seed phrase string or null

use BlockchainSdk\Laravel\Facades\Blockchain;

// 1. Check if a token is enabled in configuration
if (Blockchain::isTokenEnabled('polygon', 'USDT')) {
    $tokenInfo = Blockchain::findToken('polygon', 'USDT');
    
    // 2. Query token balance using smart contract address
    $balance = Blockchain::driver('polygon')->getBalance(
        address: '0xYourUserDepositAddress',
        tokenContract: $tokenInfo['contract']
    );
    
    echo "Polygon USDT Balance: " . $balance->balanceFormatted; // e.g. "150.500000"
    echo "Raw Wei / Base Units: " . $balance->balanceRaw;       // e.g. "150500000"
}

// 3. Query native currency balance (e.g. ETH, BNB, SOL, TRX, BTC)
$nativeBalance = Blockchain::driver('solana')->getBalance('SolanaAddressHere...');
echo "SOL Balance: " . $nativeBalance->balanceFormatted;

use BlockchainSdk\Laravel\Facades\Blockchain;

// 1. Discover incoming ERC-20 / BEP-20 token deposit hash (e.g. USDC on BSC)
$txHash = Blockchain::driver('bsc')->getLatestIncomingTxHash(
    address: '0xDepositSubWalletAddress...',
    tokenContract: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d' // USDC
);

// 2. Discover incoming Solana SPL token or native SOL transfer signature
$solSignature = Blockchain::driver('solana')->getLatestIncomingTxHash(
    address: 'SolanaDepositAddress...'
);

// 3. Discover incoming TRON TRC-20 (USDT) or native TRX transfer
$tronTxId = Blockchain::driver('tron')->getLatestIncomingTxHash(
    address: 'TRON_Address_Here...',
    tokenContract: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' // USDT
);

// 4. Discover incoming Bitcoin SegWit transaction ID
$btcTxId = Blockchain::driver('bitcoin')->getLatestIncomingTxHash(
    address: 'bc1q...'
);

use BlockchainSdk\Laravel\Facades\Blockchain;

$driver = Blockchain::driver('ethereum');
$masterVault = Blockchain::getMasterWallet('ethereum');

$result = $driver->sweep(
    fromPrivateKey: $subWalletPrivateKey,
    toAddress: $masterVault
);

if ($result->success) {
    echo "Sweep Broadcasted. TxHash: " . $result->txHash;
}

use BlockchainSdk\Laravel\Facades\Blockchain;

$driver = Blockchain::driver('bsc');
$masterVault = Blockchain::getMasterWallet('bsc');
$token = Blockchain::findToken('bsc', 'USDT');

$result = $driver->sweep(
    fromPrivateKey: $subWalletPrivateKey,
    toAddress: $masterVault,
    tokenContract: $token['contract']
);

use BlockchainSdk\Laravel\Facades\Blockchain;

$driver = Blockchain::driver('polygon');

// Automatically fuels exact MATIC/POL gas from master gas station -> sweeps USDT
$result = $driver->sweepTokenWithGasSponsorship(
    subWalletPrivateKey: $subWalletPrivateKey,
    masterGasPrivateKey: Blockchain::getMasterGasKey('polygon'),
    toVaultAddress:      Blockchain::getMasterWallet('polygon'),
    tokenContract:       '0xc2132D05D31c914a87C6611C10748AEb04B58e8F' // USDT
);

   namespace App\Listeners;

   use BlockchainSdk\Laravel\Events\WalletSwept;

   class CreditUserOnSweepListener
   {
       /**
        * Handle the event. Replace placeholder logic with your application's accounting flow.
        */
       public function handle(WalletSwept $event): void
       {
           $sweep  = $event->sweep;
           $wallet = $sweep->wallet; // Associated BlockchainSdkWallet instance
           
           if ($wallet && $wallet->user_id) {
               $user = \App\Models\User::find($wallet->user_id);
               
               // Example: Credit your application's user balance column
               // Replace '{{your_balance_column}}' with your actual column (e.g. 'balance', 'wallet_balance', 'usd_balance')
               $user->increment('{{your_balance_column}}', $sweep->amount);
               
               // Or call your custom accounting / ledger service:
               // LedgerService::creditUser($user->id, $sweep->amount, $sweep->token_symbol, $sweep->tx_hash);
               
               // Mark the sweep as credited in the database ledger
               $sweep->markAsCredited();
               
               logger()->info("Credited {$sweep->amount} {$sweep->token_symbol} to User #{$user->id} on sweep Tx: {$sweep->tx_hash}");
           }
       }
   }
   

namespace App\Listeners;

use BlockchainSdk\Laravel\Events\DepositConfirmed;

class CreditUserOnDepositListener
{
    /**
     * Handle the event. Replace placeholder logic with your application's accounting flow.
     */
    public function handle(DepositConfirmed $event): void
    {
        $deposit = $event->deposit;
        $wallet  = $deposit->wallet;

        if ($wallet && $wallet->user_id && !$deposit->is_credited) {
            $user = \App\Models\User::find($wallet->user_id);

            // Example: Credit your application's user balance column immediately
            // Replace '{{your_balance_column}}' with your actual column name
            $user->increment('{{your_balance_column}}', $deposit->amount);

            $deposit->markAsCredited();
        }
    }
}



use BlockchainSdk\BlockchainManager;

$blockchain = new BlockchainManager([
    'default' => 'ethereum',
    'networks' => [
        'ethereum' => [
            'type'      => 'evm',
            'chain_id'  => 1,
            'rpc_nodes' => ['https://cloudflare-eth.com'],
            'tokens'    => [
                'USDT' => [
                    'name'     => 'Tether USD',
                    'contract' => '0xdAC17F958D2ee523a2206206994597C13D831ec7',
                    'decimals' => 6,
                    'status'   => 'enabled',
                ],
            ],
        ],
        'bsc' => [
            'type'      => 'evm',
            'chain_id'  => 56,
            'rpc_nodes' => ['https://bsc-dataseed.binance.org'],
            'tokens'    => [
                'USDT' => [
                    'name'     => 'Tether USD',
                    'contract' => '0x55d398326f99059fF775485246999027B3197955',
                    'decimals' => 18,
                    'status'   => 'enabled',
                ],
            ],
        ],
        'solana' => [
            'type'      => 'solana',
            'rpc_nodes' => ['https://api.mainnet-beta.solana.com'],
            'tokens'    => [
                'USDC' => [
                    'name'     => 'USD Coin',
                    'contract' => 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
                    'decimals' => 6,
                    'status'   => 'enabled',
                ],
            ],
        ],
        'tron' => [
            'type'      => 'tron',
            'rpc_nodes' => ['https://api.trongrid.io'],
            'tokens'    => [
                'USDT' => [
                    'name'     => 'Tether USD',
                    'contract' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
                    'decimals' => 6,
                    'status'   => 'enabled',
                ],
            ],
        ],
        'bitcoin' => [
            'type'      => 'bitcoin',
            'rpc_nodes' => ['https://mempool.space/api'],
            'tokens'    => [],
        ],
    ],
]);

// Validate EVM address
$isValidEth = $blockchain->driver('ethereum')->validateAddress('0xdAC17F958D2ee523a2206206994597C13D831ec7'); // true

// Validate Solana address
$isValidSol = $blockchain->driver('solana')->validateAddress('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // true

// Validate TRON address
$isValidTron = $blockchain->driver('tron')->validateAddress('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'); // true

// Or using the manager shortcut
$isValidBtc = $blockchain->validateAddress('bitcoin', 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'); // true

// Generate a Solana keypair
$solKeypair = $blockchain->driver('solana')->generateWallet();
echo "Solana Address: " . $solKeypair->address . "\n";
echo "Solana Private Key: " . $solKeypair->privateKey . "\n";

// Generate an EVM keypair
$ethKeypair = $blockchain->driver('ethereum')->generateWallet();
echo "EVM Address: " . $ethKeypair->address . "\n";
echo "EVM Private Key: " . $ethKeypair->privateKey . "\n";

// Generate a Bitcoin Bech32 SegWit keypair
$btcKeypair = $blockchain->driver('bitcoin')->generateWallet();
echo "Bitcoin Address: " . $btcKeypair->address . "\n";

// Generate a TRON Base58Check keypair
$tronKeypair = $blockchain->driver('tron')->generateWallet();
echo "TRON Address: " . $tronKeypair->address . "\n";

// 1. Query Native Balance
$nativeBalance = $blockchain->driver('ethereum')->getBalance('0xYourAddress...');
echo "ETH Balance: " . $nativeBalance->balanceFormatted . "\n";

// 2. Query Token Balance
$usdtBalance = $blockchain->driver('ethereum')->getBalance(
    address: '0xYourAddress...',
    tokenContract: '0xdAC17F958D2ee523a2206206994597C13D831ec7'
);
echo "USDT Balance: " . $usdtBalance->balanceFormatted . "\n";

// 3. Helper Token Lookups
$token = $blockchain->findToken('bsc', 'USDT');
if ($token && $blockchain->isTokenEnabled('bsc', 'USDT')) {
    echo "Found enabled token contract: " . $token['contract'] . "\n";
}

// Sweeping Native Currency
$sweepResult = $blockchain->driver('ethereum')->sweep(
    fromPrivateKey: $subWalletPrivateKey,
    toAddress: '0xMasterVaultAddress...'
);

if ($sweepResult->success) {
    echo "Sweep Successful! TxHash: " . $sweepResult->txHash . "\n";
} else {
    echo "Sweep Failed: " . $sweepResult->errorMessage . "\n";
}

// Sweeping Tokens with Gas Sponsorship
$sponsorResult = $blockchain->driver('bsc')->sweepTokenWithGasSponsorship(
    subWalletPrivateKey: $subWalletPrivateKey,
    masterGasPrivateKey: $masterGasPrivateKey,
    toVaultAddress:      '0xMasterVaultAddress...',
    tokenContract:       '0x55d398326f99059fF775485246999027B3197955' // USDT
);

if ($sponsorResult->success) {
    echo "Gas Sponsored and Swept! TxHash: " . $sponsorResult->txHash . "\n";
}

'SYMBOL' => [
    'name'     => 'Full Token Name',                  // Descriptive token name
    'contract' => '0xContractAddress...',            // Smart Contract or Mint Address
    'decimals' => 18,                                 // Decimal precision (e.g. 6 for USDT/USDC, 18 for standard)
    'status'   => 'enabled',                          // 'enabled' or 'disabled'
],
bash
composer 
bash
php artisan vendor:publish --tag="blockchainsdk-config"
bash
php artisan vendor:publish --tag="blockchainsdk-migrations"
bash
php artisan vendor:publish --tag="blockchainsdk-models"
bash
php artisan migrate
bash
   php artisan blockchainsdk:sweep --network=bsc --token=USDT --sponsor --credit
   
bash
# Standalone
composer test

# Within Laravel
php artisan test vendor/blockchain-sdk/blockchain-sdk-php/tests/BlockchainSdkTest.php