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

Ton Cell Php Laravel Package

amashukov/ton-cell-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require amashukov/ton-cell-php
    

    Ensure ext-gmp is enabled in your PHP environment.

  2. First Use Case: Build a simple cell for a Jetton transfer:

    use Amashukov\TonCell\Builder;
    
    $cell = (new Builder())
        ->storeUint(0xF8A7EA5, 32)  // Jetton transfer opcode
        ->storeUint(12345, 64)      // Query ID
        ->storeCoins('1000000')     // Amount in nanoTON
        ->storeAddress(new AddressData(0, 'hashPart32'))  // Destination address
        ->endCell();
    
  3. Key Classes to Explore:

    • Builder: For constructing cells.
    • Slice: For parsing cells.
    • Boc: For serializing cells to BOC format.
    • AddressData: For handling TON addresses.

Implementation Patterns

Common Workflows

1. Building Complex Cells

Use nested builders for hierarchical data:

$nestedCell = (new Builder())
    ->storeUint(1, 8)
    ->endCell();

$mainCell = (new Builder())
    ->storeRef($nestedCell)
    ->storeUint(2, 8)
    ->endCell();

2. Parsing Cells

Mirror the builder structure in parsing:

$slice = $cell->beginParse();
$op = $slice->loadUint(32);
$queryId = $slice->loadUint(64);
$amount = $slice->loadCoins();
$address = $slice->loadAddress();

3. Handling Big Integers

Use decimal strings for values exceeding PHP_INT_MAX:

$builder->storeUint('12345678901234567890', 256);  // Big integer
$slice->loadUintString(256);  // Returns string for large values

4. BOC Serialization

Serialize cells to BOC format for network transmission:

$bocBytes = Boc::encode($cell);
$bocBase64 = Boc::encodeBase64($cell);  // Ready for toncenter API

5. Address Handling

Use AddressData for address operations:

$addressData = new AddressData(0, 'hashPart32');
$builder->storeAddress($addressData);
$parsedAddress = $slice->loadAddress();

6. Cell Hashing

Compute hashes for signing or address derivation:

$hash = $cell->hash();  // 32-byte SHA-256 hash

Integration Tips

With Laravel

  • Service Provider: Bind the package classes to Laravel's container for dependency injection:

    public function register()
    {
        $this->app->bind(Builder::class, function () {
            return new Builder();
        });
    }
    
  • Facades (Optional): Create facades for cleaner syntax:

    // app/Facades/TonCell.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    use Amashukov\TonCell\Builder;
    
    class TonCell extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return Builder::class;
        }
    }
    
  • Jobs/Commands: Use the package in Laravel jobs or Artisan commands for background processing:

    use Amashukov\TonCell\Builder;
    use Amashukov\TonCell\Boc;
    
    class ProcessTonTransaction implements ShouldQueue
    {
        public function handle()
        {
            $cell = (new Builder())->storeUint(1, 8)->endCell();
            $boc = Boc::encodeBase64($cell);
            // Send to TON network via toncenter-client-php
        }
    }
    

With External APIs

  • Toncenter Client: Combine with amashukov/toncenter-client-php for sending BOCs:
    use Amashukov\TonCenterClient\Client;
    
    $client = new Client('https://toncenter.com/api/v2/jsonRPC');
    $bocBase64 = Boc::encodeBase64($cell);
    $response = $client->sendBoc($bocBase64);
    

Gotchas and Tips

Pitfalls

1. Bit and Byte Alignment

  • TON cells are bit-level structures. Misaligned bit operations (e.g., storeUint with incorrect bit lengths) will corrupt the cell.
  • Fix: Validate bit lengths against TLB specifications (e.g., addr_std$10 requires 256 bits for the hash part).

2. Big Integer Handling

  • Values exceeding PHP_INT_MAX must be passed as strings (e.g., '12345678901234567890').
  • Gotcha: Forgetting to use strings for large values will truncate the number.
  • Tip: Use gmp_strval for debugging large integers.

3. Address Validation

  • AddressData only handles the addr_std$10 format. Full address parsing (e.g., EQ... or UQ... base64) requires additional logic.
  • Fix: Use a downstream package like amashukov/ton-wallet-php for full address handling.

4. BOC Size Limits

  • The BOC encoder auto-promotes offset_byte_size from 1 to 2 bytes if the cell data exceeds 255 bytes.
  • Warning: BOCs cannot exceed 65,535 bytes. Extend the encoder if larger BOCs are needed.

5. Cell Hashing

  • The hash() method returns a 32-byte SHA-256 hash of the recursive TLB representation, not the raw bytes.
  • Tip: Use this hash for Ed25519 signing or address derivation (e.g., in amashukov/ton-crypto-php).

6. Slice Overruns

  • Slice::load* methods throw RuntimeException if they overrun the cell's bit length.
  • Debugging: Check remainingBits() and remainingRefs() before parsing.

Debugging Tips

1. Inspect Cell Structure

Use Slice to debug cell contents:

$slice = $cell->beginParse();
while (!$slice->isEmpty()) {
    echo "Remaining bits: " . $slice->remainingBits() . "\n";
    $value = $slice->loadUint(8);  // Load 1 byte at a time
    echo "Byte: " . dechex($value) . "\n";
}

2. Compare with @ton/core

Validate outputs against the TypeScript SDK:

# Example: Compare BOC outputs
node -e "const { Cell } = require('@ton/core'); const cell = Cell.fromBoc('...'); console.log(cell.toBoc({ idx: false }).toString('base64'));"

3. Log Bit Operations

Log bit-level operations to catch misalignments:

$builder->storeUint(123, 8)->storeUint(456, 16);  // Log these operations

Extension Points

1. Custom TLB Types

Extend Builder or Slice to support custom TLB types:

class CustomBuilder extends Builder
{
    public function storeCustomType($value)
    {
        // Implement custom logic
        return $this->storeUint($value, 32);
    }
}

2. Alternative BOC Encoders

Override Boc::encode() for non-canonical formats:

class CustomBoc
{
    public static function encode(Cell $cell): string
    {
        // Custom BOC logic (e.g., no CRC32C)
        return 'custom-boc-' . $cell->hash();
    }
}

3. Address Parsing

Extend AddressData for full address support:

class FullAddressData extends AddressData
{
    public function __construct(string $address)
    {
        // Parse EQ/UQ base64, validate CRC-16, etc.
        parent::__construct(0, 'hashPart32');
    }
}

4. BitReader for Custom Parsing

Use BitReader for low-level parsing of non-TLB data:

$reader = new BitReader($binaryString, $bitLength);
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor