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

Laravel Evm Laravel Package

farbcode/laravel-evm

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require farbcode/laravel-evm
    php artisan evm:install
    

    This publishes the config file (config/evm.php) and creates a migration for transaction records.

  2. Configuration: Update config/evm.php with your Ethereum node provider (e.g., Infura, Alchemy) and private key:

    'providers' => [
        'mainnet' => [
            'url' => env('ETHEREUM_NODE_URL'),
            'private_key' => env('ETHEREUM_PRIVATE_KEY'),
        ],
    ],
    
  3. First Use Case: Send a test transaction via a controller:

    use Farbcode\Evm\Facades\Evm;
    
    public function sendTestTransaction()
    {
        $transaction = Evm::sendTransaction(
            from: '0xFromAddress',
            to: '0xToAddress',
            value: 100000000000000000, // 0.1 ETH
            gasLimit: 21000,
            nonce: 5
        );
    
        return response()->json($transaction);
    }
    

Key Files to Review

  • Config: config/evm.php (node providers, defaults).
  • Migrations: database/migrations/[timestamp]_create_evm_transactions_table.php (track transactions).
  • Facade: Farbcode\Evm\Facades\Evm (main API entry point).
  • Events: Farbcode\Evm\Events\TransactionSent, Farbcode\Evm\Events\TransactionConfirmed (listen for async updates).

Implementation Patterns

Core Workflows

1. Synchronous Transactions (Simple Calls)

Use for read operations (e.g., balance checks, contract calls):

$balance = Evm::call([
    'to' => '0xContractAddress',
    'data' => '0x...', // ABI-encoded function call
]);

2. Asynchronous Transactions (Queue-Based)

For production-grade reliability, leverage Laravel Queues:

// Dispatch a job
SendEvmTransaction::dispatch(
    from: '0xFromAddress',
    to: '0xToAddress',
    value: wei(0.1),
    gasLimit: 21000,
    description: 'User payment'
);

// Listen for events (e.g., in a service)
Event::listen(TransactionConfirmed::class, function ($event) {
    // Update DB, notify user, etc.
});

3. Contract Interactions

Use Evm::contract() to interact with smart contracts:

$contract = Evm::contract('0xContractAddress', $abi);
$result = $contract->call('balanceOf', ['0xUserAddress']);
$tx = $contract->send('transfer', ['0xRecipient', wei(0.1)]);

4. Gas Estimation & EIP-1559

Dynamically estimate fees:

$gasPrice = Evm::estimateGasPrice(); // Legacy
$maxFeePerGas = Evm::estimateMaxFeePerGas(); // EIP-1559
$maxPriorityFeePerGas = Evm::estimateMaxPriorityFeePerGas();

$transaction = Evm::sendTransaction([
    'to' => '0xToAddress',
    'value' => wei(0.1),
    'maxFeePerGas' => $maxFeePerGas,
    'maxPriorityFeePerGas' => $maxPriorityFeePerGas,
]);

Integration Tips

Queue Configuration

Ensure your queue worker processes SendEvmTransaction jobs:

php artisan queue:work --queue=evm
  • Queue Name: Defaults to evm, but configurable in config/evm.php.

Event Listeners

Extend the package’s events for custom logic:

// app/Listeners/HandleTransactionConfirmed.php
public function handle(TransactionConfirmed $event)
{
    // Log, notify, or update models
    Log::info("Transaction confirmed: {$event->hash}");
}

Testing

Use the EvmServiceProvider in tests to mock the provider:

use Farbcode\Evm\Testing\MockEvm;

beforeEach(function () {
    MockEvm::shouldReceive('sendTransaction')
        ->once()
        ->andReturn(['hash' => '0xMockHash']);
});

Multi-Provider Support

Configure multiple providers (e.g., mainnet, testnet) in config/evm.php and switch contexts:

Evm::setProvider('testnet');
$balance = Evm::getBalance('0xAddress');

Gotchas and Tips

Pitfalls

1. Nonce Management

  • Issue: Reusing nonces causes transaction failures.
  • Fix: Let the package auto-increment nonces via the nonce field in the evm_transactions table. Avoid manual nonce handling unless absolutely necessary.
  • Debug: Check TransactionFailed events for nonce-related errors.

2. Gas Limits

  • Issue: Underestimating gasLimit results in failed transactions.
  • Tip: Use Evm::estimateGas() for dynamic limits:
    $gasLimit = Evm::estimateGas([
        'to' => '0xToAddress',
        'data' => '0x...',
    ]);
    

3. Private Key Security

  • Issue: Hardcoding private keys in config.
  • Fix: Use Laravel’s .env and restrict file permissions:
    chmod 600 .env
    
  • Alternative: Use a vault like laravel/vault or AWS Secrets Manager.

4. Async Race Conditions

  • Issue: Duplicate transactions if jobs retry.
  • Fix: Implement idempotency in your SendEvmTransaction job:
    public function handle()
    {
        if (Transaction::where('hash', $this->hash)->exists()) {
            return; // Skip if already processed
        }
        // Proceed with sending
    }
    

5. Provider Rate Limits

  • Issue: Free tiers (e.g., Infura) throttle requests.
  • Fix: Monitor TransactionFailed events for rate-limit errors and implement retries with exponential backoff in your job.

Debugging Tips

Log Transactions

Enable debug logging in config/evm.php:

'debug' => env('EVM_DEBUG', false),

Logs will appear in storage/logs/laravel.log.

Inspect Failed Transactions

Listen for TransactionFailed events to capture errors:

Event::listen(TransactionFailed::class, function ($event) {
    Log::error("Failed TX: {$event->hash}. Error: {$event->error}");
});

Testnet Sandboxing

Use a local EVM node (e.g., Ganache) for testing:

config([
    'evm.providers.testnet.url' => 'http://localhost:8545',
]);

Extension Points

1. Custom Transaction Models

Extend the evm_transactions table by publishing and modifying the migration:

php artisan vendor:publish --tag="evm-migrations"

Add fields like user_id or metadata:

Schema::table('evm_transactions', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->nullable();
    $table->json('metadata')->nullable();
});

2. Custom Providers

Implement Farbcode\Evm\Contracts\Provider for non-Ethereum EVMs (e.g., Polygon, BSC):

class PolygonProvider implements Provider {
    public function sendTransaction(array $payload): array {
        // Custom logic
    }
}

Register in config/evm.php:

'providers' => [
    'polygon' => [
        'class' => \App\Providers\PolygonProvider::class,
    ],
],

3. Webhook Notifications

Extend the package to emit webhooks on transaction confirmation:

Event::listen(TransactionConfirmed::class, function ($event) {
    Http::post(env('WEBHOOK_URL'), [
        'hash' => $event->hash,
        'status' => 'confirmed',
    ]);
});

4. Gas Price Oracles

Replace the default gas estimation with a custom oracle (e.g., Chainlink):

Evm::extend(function ($evm) {
    $evm->estimateMaxFeePerGas = function () {
        return request('chainlink_oracle')->maxFeePerGas;
    };
});

Configuration Quirks

  • Default Provider: Set
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui