Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ethereum Util Laravel Package

web3p/ethereum-util

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package to your Laravel project via Composer:

    composer require web3p/ethereum-util
    

    Ensure your composer.json pins elliptic-php to 1.0.6 to avoid CVE risks:

    "require": {
        "elliptic-php/elliptic-php": "1.0.6"
    }
    
  2. First Use Case: Validate an Ethereum address and derive its public key from a private key:

    use Web3p\EthereumUtil\EthereumUtil;
    
    // Validate an address
    $address = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F';
    if (EthereumUtil::isAddress($address)) {
        echo "Valid Ethereum address!";
    }
    
    // Derive public key from private key
    $privateKey = '0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d';
    $publicKey = EthereumUtil::privateKeyToPublicKey($privateKey);
    echo "Public Key: " . $publicKey;
    
  3. Where to Look First:

    • README.md: Quick overview of available functions.
    • Tests: Browse the test directory for usage examples and edge cases.
    • Release Notes: Check for recent changes (e.g., toBn in v0.1.4).

Implementation Patterns

Usage Patterns

  1. Address Validation and Manipulation: Use isAddress, stripZero, and isZeroPrefixed to sanitize and validate Ethereum addresses in Laravel requests or database storage:

    // Laravel Request Validation
    $validator = Validator::make($request->all(), [
        'eth_address' => 'required|string',
    ], [
        'eth_address.required' => 'Ethereum address is required.',
    ]);
    
    $validator->after(function ($validator) use ($request) {
        if ($validator->passes() && !EthereumUtil::isAddress($request->eth_address)) {
            $validator->errors()->add('eth_address', 'Invalid Ethereum address.');
        }
    });
    
  2. Cryptographic Operations: Securely handle private keys and signatures using privateKeyToPublicKey, ecsign, and recoverPublicKey. Never log or expose private keys:

    // Sign a message (e.g., for API authentication)
    $message = 'Hello, Ethereum!';
    $privateKey = env('ETH_PRIVATE_KEY');
    $signature = EthereumUtil::ecsign($message, $privateKey);
    
    // Recover public key from signature (e.g., for verification)
    $recoveredPublicKey = EthereumUtil::recoverPublicKey($message, $signature);
    
  3. Hashing: Use sha3 for deterministic hashing (e.g., generating unique identifiers or hashing transaction data):

    $data = '0x' . bin2hex(random_bytes(32));
    $hash = EthereumUtil::sha3($data);
    // Use $hash in Laravel models or caches
    
  4. BigNumber Conversion: Convert between hex strings and BigNumbers (e.g., for ERC-20 token amounts) with toBn:

    $hexAmount = '0xde0b6b3a7640000'; // 10000000000000000000 wei (100 ETH)
    $bn = EthereumUtil::toBn($hexAmount);
    $decimalAmount = $bn->toString(); // '10000000000000000000'
    

Workflows

  1. Wallet Service Integration:

    • Address Generation: Use privateKeyToPublicKey and publicKeyToAddress to generate and validate wallet addresses.
    • Transaction Signing: Sign raw transactions offline (e.g., in a Laravel queue job) and broadcast via a Web3 provider like web3.php.
    • Signature Verification: Verify user-signed messages (e.g., for login) with recoverPublicKey.
  2. Smart Contract Interaction:

    • Data Encoding: Use sha3 to encode function selectors or data payloads for contract calls.
    • Event Handling: Hash event topics (e.g., sha3('Transfer(address,address,uint256)')) to filter logs.
  3. DeFi/Token Integrations:

    • Token Amounts: Convert token amounts to/from hex with toBn for ERC-20/ERC-721 interactions.
    • Address Validation: Ensure user-provided addresses are valid before processing transfers.

Integration Tips

  1. Laravel Service Providers: Register the package as a service provider to centralize configuration and utilities:

    // app/Providers/EthereumServiceProvider.php
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Web3p\EthereumUtil\EthereumUtil;
    
    class EthereumServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('ethereum.util', function () {
                return new class {
                    public function sha3(string $input): string {
                        return EthereumUtil::sha3($input);
                    }
                    // Add other utilities as needed
                };
            });
        }
    }
    
  2. Facade for Clean Syntax: Create a facade to simplify usage across your application:

    // app/Facades/Ethereum.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class Ethereum extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'ethereum.util';
        }
    }
    

    Usage:

    $hash = \App\Facades\Ethereum::sha3('0xdata');
    
  3. Console Commands: Build CLI tools for Ethereum operations (e.g., key recovery, address validation):

    // app/Console/Commands/RecoverKey.php
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Web3p\EthereumUtil\EthereumUtil;
    
    class RecoverKey extends Command
    {
        protected $signature = 'ethereum:recover-key {message} {signature}';
        protected $description = 'Recover public key from a message and signature';
    
        public function handle()
        {
            $publicKey = EthereumUtil::recoverPublicKey($this->argument('message'), $this->argument('signature'));
            $this->info("Recovered Public Key: {$publicKey}");
        }
    }
    
  4. Middleware for Authentication: Verify Ethereum signatures in incoming requests (e.g., for API authentication):

    // app/Http/Middleware/VerifyEthereumSignature.php
    namespace App\Http\Middleware;
    
    use Closure;
    use Web3p\EthereumUtil\EthereumUtil;
    
    class VerifyEthereumSignature
    {
        public function handle($request, Closure $next)
        {
            $signature = $request->header('X-Ethereum-Signature');
            $message = $request->header('X-Ethereum-Message');
    
            if (!$this->validateSignature($message, $signature)) {
                abort(401, 'Invalid Ethereum signature.');
            }
    
            return $next($request);
        }
    
        protected function validateSignature(string $message, string $signature): bool
        {
            try {
                $recoveredKey = EthereumUtil::recoverPublicKey($message, $signature);
                // Optionally verify against a known public key
                return !is_null($recoveredKey);
            } catch (\Exception $e) {
                return false;
            }
        }
    }
    
  5. Queue Jobs for Offline Processing: Offload CPU-intensive operations (e.g., batch signing) to Laravel queues:

    // app/Jobs/SignTransactions.php
    namespace App\Jobs;
    
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    use Web3p\EthereumUtil\EthereumUtil;
    
    class SignTransactions implements ShouldQueue
    {
        use Dispatchable, Queueable;
    
        public function handle()
        {
            $privateKey = env('ETH_PRIVATE_KEY');
            $transactions = Transaction::unsigned()->get();
    
            foreach ($transactions as $tx) {
                $signedTx = EthereumUtil::ecsign($tx->data, $privateKey);
                // Broadcast $signedTx via web3.php or Infura
            }
        }
    }
    

Gotchas and Tips

Pit

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium