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"
}
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;
Where to Look First:
toBn in v0.1.4).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.');
}
});
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);
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
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'
Wallet Service Integration:
privateKeyToPublicKey and publicKeyToAddress to generate and validate wallet addresses.web3.php.recoverPublicKey.Smart Contract Interaction:
sha3 to encode function selectors or data payloads for contract calls.sha3('Transfer(address,address,uint256)')) to filter logs.DeFi/Token Integrations:
toBn for ERC-20/ERC-721 interactions.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
};
});
}
}
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');
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}");
}
}
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;
}
}
}
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
}
}
}
How can I help you explore Laravel packages today?