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

Rlp Laravel Package

web3p/rlp

PHP implementation of Ethereum Recursive Length Prefix (RLP) encoding/decoding. Encode strings, integers, numeric strings, or nested arrays; decode 0x-prefixed RLP hex back to values. Simple API via Web3p\RLP\RLP with helper hex string decoding.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require web3p/rlp
    

    Ensure your composer.json has "minimum-stability": "dev" if not already set.

  2. First Use Case: Encode a simple array of strings (e.g., Ethereum transaction data):

    use Web3p\RLP\RLP;
    
    $rlp = new RLP();
    $encoded = $rlp->encode(['nonce', 'gasPrice', 'gasLimit', 'to', 'value', 'data']);
    

    Decode the encoded data:

    $decoded = $rlp->decode('0x' . $encoded);
    
  3. Where to Look First:

    • RLP class: Core functionality for encoding/decoding.
    • Types\Str: Helper for hex-to-string conversion (e.g., Str::decodeHex($hex)).
    • README.md: API documentation and usage examples.

Implementation Patterns

Common Workflows

  1. Encoding Ethereum-Specific Data: Encode transaction inputs (e.g., for eth_sendRawTransaction):

    $txData = [
        '0x123', // nonce
        '0x456', // gasPrice
        '0x789', // gasLimit
        '0xabc', // to
        '0xdef', // value
        '0x0'    // data (empty)
    ];
    $encodedTx = $rlp->encode($txData);
    
  2. Decoding RLP-Encoded Data: Parse raw RLP data (e.g., from blockchain nodes):

    $rawRlp = '0xc483646f678365746883736f6c6964697479';
    $decoded = $rlp->decode('0x' . $rawRlp);
    foreach ($decoded as $item) {
        echo Str::decodeHex($item) . "\n"; // Output: dog, eth, solidity
    }
    
  3. Handling Nested Structures: Encode arrays of arrays (e.g., multi-signature transactions):

    $nestedData = [
        ['sig1', 'sig2'],
        ['addr1', 'addr2']
    ];
    $encoded = $rlp->encode($nestedData);
    
  4. Integration with Web3 Libraries: Use RLP to pre-process data before sending to Web3.js or Ethers.js:

    $rlpEncoded = $rlp->encode([$to, $value, $data]);
    $tx = $web3->eth.accounts.signTransaction(...);
    

Integration Tips

  • Hex Prefix Handling: Always prepend 0x to encoded strings when decoding (e.g., '0x' . $encoded).
  • Type Consistency: Ensure inputs are strings or integers (avoid floats or booleans).
  • Error Handling: Wrap calls in try-catch for InvalidArgumentException (e.g., unsupported types).
  • Performance: For large datasets, batch encode/decode operations to minimize overhead.

Gotchas and Tips

Pitfalls

  1. Hex Prefix Requirement:

    • Issue: Decoding fails without 0x prefix (e.g., decode('c483646f67') throws an error).
    • Fix: Always use '0x' . $encoded for decoding.
  2. Integer Limits:

    • Issue: Integers > 160 bits may lose precision (fixed in v0.3.4, but test edge cases).
    • Fix: Use strings for very large numbers (e.g., '12345678901234567890').
  3. String vs. Hex:

    • Issue: decode() returns hex strings, not raw bytes. Use Str::decodeHex() for human-readable output.
    • Example:
      $hex = $decoded[0]; // '646f67'
      echo Str::decodeHex($hex); // 'dog'
      
  4. Empty/Invalid Inputs:

    • Issue: encode([]) returns 0xc0 (empty list), but encode(null) throws an exception.
    • Fix: Explicitly handle null or empty arrays:
      $rlp->encode(is_null($data) ? [] : $data);
      
  5. Nested Decoding:

    • Issue: Deeply nested RLP structures may require recursive decoding.
    • Fix: Loop through decoded arrays and re-encode/re-decode if needed:
      $decoded = $rlp->decode($rlpData);
      foreach ($decoded as $item) {
          if (is_array($item)) {
              $item = $rlp->encode($item);
          }
      }
      

Debugging Tips

  1. Validate Encoded Output: Use online RLP decoders (e.g., RLP Tools) to verify your encoded data matches expectations.

  2. Log Raw Data: Log hex strings before/after encoding to spot discrepancies:

    error_log('Encoded: ' . bin2hex($encoded));
    
  3. Check for 0x Prefixes: Use str_starts_with() to validate inputs:

    if (!str_starts_with($hex, '0x')) {
        throw new \InvalidArgumentException('Hex string must start with 0x');
    }
    

Extension Points

  1. Custom Type Handling: Extend the RLP class to support additional types (e.g., DateTime):

    class CustomRLP extends RLP {
        public function encode($input) {
            if ($input instanceof DateTime) {
                return parent::encode($input->format('Y-m-d'));
            }
            return parent::encode($input);
        }
    }
    
  2. Batch Processing: Optimize for bulk operations by implementing a batchEncode() method:

    public function batchEncode(array $data): array {
        return array_map([$this, 'encode'], $data);
    }
    
  3. Integration with Laravel: Bind the RLP class to the container for global access:

    $app->singleton(RLP::class, function () {
        return new RLP();
    });
    

    Then inject via constructor or resolve with app(RLP::class).

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