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

Larathereum Laravel Package

ranabd36/larathereum

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ranabd36/larathereum
    
  2. Publish Config:

    php artisan vendor:publish --provider="Larathereum\LarathereumServiceProvider"
    
    • Edit config/larathereum.php to define:
      • node_url (e.g., https://mainnet.infura.io/v3/YOUR_KEY)
      • port (if applicable, often omitted for HTTP/HTTPS nodes)
      • private_key (for signing transactions, stored securely in .env or encrypted config).
  3. First Use Case: Fetch an account balance:

    use Larathereum\Larathereum;
    
    $balance = Larathereum::balance('0x123...abc');
    dd($balance); // Returns wei as integer
    

Implementation Patterns

Core Workflows

  1. Contract Interactions (ERC20):

    • Deploy/read/write to ERC20 contracts via helper methods:
      // Approve tokens (spender, amount in wei)
      Larathereum::approve('0xContractAddress', '0xSpender', $amount);
      
      // Transfer tokens
      Larathereum::transfer('0xContractAddress', '0xRecipient', $amount);
      
    • Pattern: Wrap contract calls in service classes (e.g., TokenService) to abstract gas/fee logic.
  2. Transaction Handling:

    • Send raw transactions with metadata:
      Larathereum::sendTransaction([
          'to' => '0xRecipient',
          'value' => $weiAmount,
          'gas' => 21000,
          'gasPrice' => Larathereum::gasPrice(), // Auto-fetch
      ]);
      
    • Pattern: Use Laravel’s Bus queue for async transactions (e.g., SendTransactionJob).
  3. Event Listening:

    • Subscribe to contract events (e.g., Transfer):
      Larathereum::on('0xContractAddress', 'Transfer', function ($event) {
          // Log or process event data
      });
      
    • Pattern: Pair with Laravel’s Event facade for cross-cutting concerns.
  4. Multi-Network Support:

    • Switch networks via config or runtime:
      config(['larathereum.node_url' => 'https://goerli.infura.io/v3/KEY']);
      

Integration Tips

  • Laravel Mixins: Extend Larathereum with traits for reusable logic:
    trait TokenHandler {
        public function mintTokens($address, $amount) {
            return Larathereum::callContract(
                '0xMinterContract',
                'mint',
                [$address, $amount],
                ['from' => auth()->user()->walletAddress]
            );
        }
    }
    
  • Testing: Use laravel/web3-php mocks or local nodes (e.g., Ganache) for unit tests:
    $this->partialMock(Larathereum::class, function ($mock) {
        $mock->shouldReceive('balance')->andReturn(1000);
    });
    

Gotchas and Tips

Pitfalls

  1. Gas Estimation:

    • Issue: Underestimated gas leads to failed transactions.
    • Fix: Use Larathereum::estimateGas() before sending:
      $gas = Larathereum::estimateGas([
          'to' => '0xContract',
          'data' => '0x...',
      ]);
      
    • Tip: Add a 20% buffer for safety.
  2. Private Key Security:

    • Issue: Hardcoded keys in config are exposed.
    • Fix: Store in .env and use Laravel’s env():
      config(['larathereum.private_key' => env('ETH_PRIVATE_KEY')]);
      
    • Tip: Rotate keys via migrations or encrypted config.
  3. Rate Limits:

    • Issue: Free Infura/Alchemy nodes throttle requests.
    • Fix: Implement exponential backoff in retries:
      try {
          Larathereum::call(...);
      } catch (RateLimitException $e) {
          sleep(2 ** $attempt++);
          retry();
      }
      
  4. Event Log Parsing:

    • Issue: Raw logs require manual decoding.
    • Fix: Use web3-php's Log class or ABI tools:
      $event = Larathereum::decodeLog($log, $abi);
      
  5. Deprecated Methods:

    • Issue: Package lacks docs; some methods may be outdated.
    • Fix: Check src/Larathereum.php for undocumented features (e.g., callContractRaw).

Debugging

  • Enable Logging: Add to config/larathereum.php:

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

    Logs appear in storage/logs/larathereum.log.

  • Common Errors:

    Error Cause Solution
    Invalid JSON RPC response Node connection issues Verify node_url and network
    Nonce too low Stale nonce Use Larathereum::getNonce()
    Insufficient funds Wrong account or balance Check balance() and gas costs

Extension Points

  1. Custom Contracts: Extend the package by adding contract-specific methods:

    // In a service class
    public function stake($address, $amount) {
        return Larathereum::callContract(
            '0xStakingContract',
            'stake',
            [$address, $amount],
            ['gas' => 300000]
        );
    }
    
  2. Middleware: Add transaction validation middleware:

    public function handle($request, Closure $next) {
        if ($request->input('tx_hash')) {
            $receipt = Larathereum::getTransactionReceipt($request->tx_hash);
            if (!$receipt->status) throw new TransactionFailedException();
        }
        return $next($request);
    }
    
  3. Fallback Nodes: Implement multi-node redundancy:

    public function safeCall(callable $callback) {
        foreach (config('larathereum.nodes') as $node) {
            config(['larathereum.node_url' => $node]);
            try {
                return $callback();
            } catch (Exception $e) {
                continue;
            }
        }
        throw new NodeUnavailableException();
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky