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 Php Laravel Package

amashukov/ton-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require amashukov/ton-php
    

    Ensure your environment meets requirements: PHP 8.3+, ext-gmp, ext-sodium, and ext-bcmath.

  2. First Use Case: Wallet Creation & Transaction

    use Amashukov\TonWallet\WalletV4R2;
    use Amashukov\TonWallet\Mnemonic;
    use Amashukov\Toncenter\ToncenterClient;
    use Amashukov\Toncenter\ToncenterWalletRpc;
    use Amashukov\HttpClient\CurlHttpClient;
    
    // 1. Generate a mnemonic and derive a wallet
    $mnemonic = Mnemonic::generate();
    $wallet = WalletV4R2::fromMnemonic($mnemonic);
    
    // 2. Set up toncenter client
    $httpClient = new CurlHttpClient();
    $toncenter = new ToncenterClient($httpClient, 'https://toncenter.com/api/v2/jsonRPC');
    $walletRpc = new ToncenterWalletRpc($toncenter, $wallet->getAddress());
    
    // 3. Get wallet balance and send a transaction
    $balance = $walletRpc->getBalance();
    $walletRpc->sendTransfer('EQD...', 1000000000); // 1 TON
    
  3. Key Files to Explore

    • src/Amashukov/TonWallet/WalletV4R2.php (Wallet logic)
    • src/Amashukov/TonCell/Builder.php (Cell construction)
    • src/Amashukov/Toncenter/ToncenterClient.php (TON Center API)

Implementation Patterns

Core Workflows

  1. Wallet Management

    • Derive from Mnemonic: Use Mnemonic::generate() and WalletV4R2::fromMnemonic() for secure wallet creation.
    • Sign Transactions: Leverage WalletV4R2::sign() for transaction signing before broadcasting.
    • Portable RPC: Use ToncenterWalletRpc to abstract wallet operations (balance, transfers) via TON Center.
  2. Cell & BOC Handling

    • Build Cells: Use Builder to construct TON cells (e.g., for smart contract interactions).
      $builder = new Builder();
      $builder->storeUint(123, 32); // Store a 32-bit unsigned integer
      $cell = $builder->asCell();
      
    • Parse BOC: Use Slice to decode BOC-encoded cells (e.g., from contract state).
  3. Typed Toncenter Client

    • PSR-18 Integration: Use ToncenterClient with any PSR-18 HTTP client (e.g., CurlHttpClient).
    • Typed Responses: Avoid raw arrays; use typed value objects (e.g., ToncenterClient::getWalletBalance() returns Balance).
  4. Address Parsing

    • Parse/Validate: Use Address::parse() to validate and parse TON addresses (UQ/EQ, bounceable flags).
      $address = Address::parse('EQD...'); // Returns Address object
      

Integration Tips

  • Laravel Service Providers: Register the SDK as a service provider to manage wallet instances and HTTP clients.
    public function register()
    {
        $this->app->singleton(ToncenterClient::class, function ($app) {
            return new ToncenterClient(
                new CurlHttpClient(),
                config('toncenter.endpoint')
            );
        });
    }
    
  • Event-Driven Workflows: Use Laravel events to trigger actions after wallet operations (e.g., wallet.transfer.sent).
  • Testing: Mock ToncenterWalletRpc for unit tests by implementing WalletRpcInterface.

Gotchas and Tips

Pitfalls

  1. BOC Canonical Encoding

    • Cells built with Builder must match @ton/core byte-for-byte. Test with:
      $boc = $cell->toBoc();
      $expectedBoc = file_get_contents('expected.boc');
      assert($boc === $expectedBoc);
      
    • Non-canonical BOC may fail on TON blockchain or in contracts.
  2. Mnemonic Security

    • TON-Flavored PBKDF2: Unlike BIP-39, this SDK uses TON-specific mnemonic derivation. Ensure compatibility with TON wallets.
    • Backup: Store mnemonics securely (e.g., encrypted in a database).
  3. Toncenter Rate Limits

    • TON Center may throttle requests. Implement retries with exponential backoff:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      
      $httpClient = new RetryableHttpClient(
          new CurlHttpClient(),
          [
              'max_retries' => 3,
              'delay' => 100,
          ]
      );
      
  4. Address Formats

    • Bounceable Flag: Always specify whether an address is bounceable (e.g., Address::parse('EQD...', true)).
    • Validation: Use Address::isValid() to catch malformed addresses early.

Debugging Tips

  • Cell Inspection: Use Builder::debug() to visualize cell structure:
    $builder->debug(); // Outputs human-readable cell layout
    
  • Toncenter Logs: Enable verbose logging for ToncenterClient:
    $toncenter = new ToncenterClient($httpClient, 'https://toncenter.com/api/v2/jsonRPC', [
        'logger' => new \Monolog\Logger('toncenter'),
    ]);
    
  • Ed25519 Signing: Verify signatures with:
    $keyPair = $wallet->getKeyPair();
    $signature = $keyPair->sign('message');
    $keyPair->verify('message', $signature); // Returns bool
    

Extension Points

  1. Custom RPC Clients

    • Implement WalletRpcInterface for alternative backends (e.g., Jetton, Tonkeeper).
    class CustomWalletRpc implements WalletRpcInterface {
        public function getBalance(): Balance { ... }
        public function sendTransfer(string $to, int $amount): void { ... }
    }
    
  2. Smart Contract Interactions

    • Extend Builder to support custom contract messages:
    class MyContractBuilder extends Builder {
        public function buildCustomMessage(): Cell {
            // Add contract-specific fields
            return $this->asCell();
        }
    }
    
  3. Symfony Integration

    • Use blockchain-context-bundle to wire the SDK into Symfony services:
    # config/packages/amashukov_blockchain.yaml
    amashukov_blockchain:
        ton:
            wallet: '@Amashukov\TonWallet\WalletV4R2'
            rpc: '@Amashukov\Toncenter\ToncenterWalletRpc'
    
  4. Testing Utilities

    • Mock ToncenterClient for tests:
    $mockToncenter = $this->createMock(ToncenterClient::class);
    $mockToncenter->method('getWalletBalance')
        ->willReturn(new Balance(1000000000));
    

```markdown
### Config Quirks
- **HTTP Client**: The SDK expects a PSR-18 client. Avoid `GuzzleHttp\Client` directly; use `amashukov/http-client-php` for compatibility.
- **Toncenter Endpoint**: Hardcode endpoints in config or use environment variables:
  ```php
  $toncenter = new ToncenterClient($httpClient, env('TONCENTER_ENDPOINT'));
  • GMP Precision: For large integers (e.g., gas fees), ensure gmp extension is enabled and configured for high precision.

Performance Notes

  • Cell Building: Reuse Builder instances for multiple operations to avoid overhead.
  • Batch Requests: Use ToncenterClient::batch() to reduce API calls:
    $toncenter->batch([
        'getWalletBalance',
        'getTransaction',
    ]);
    
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
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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