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

amashukov/ton-wallet-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require amashukov/ton-wallet-php
    

    Ensure your project meets the requirements: PHP 8.3+, ext-sodium, and ext-bcmath.

  2. Initialize a wallet:

    use Amashukov\TonCrypto\Mnemonic;
    use Amashukov\TonWallet\WalletV4R2;
    
    $keys = Mnemonic::toKeyPair('your 24 mnemonic words here');
    $wallet = new WalletV4R2($keys);
    
  3. Derive and display the wallet address:

    echo $wallet->address()->toString(); // Outputs user-friendly UQ... address
    

First Use Case: Sending a Transfer

Use the sendTransfer method to send a transfer with a single message:

use Amashukov\TonWallet\Address;
use Amashukov\TonWallet\InternalMessage;

$messages = [
    new InternalMessage(
        dest: Address::parse('EQDrjaLahLkMB-hMCmkzOyBuHJ139ZUYmPHu6RRBKnbdLIYI'),
        value: '1000000000', // 1 TON in nano-TON
        bounce: false,
    ),
];

// Assuming $rpc is an instance of WalletRpcInterface
$wallet->sendTransfer($rpc, $messages, validUntil: time() + 60);

Implementation Patterns

Workflows

  1. Offline Transfer Assembly:

    • Use createTransfer to build and sign a transfer without network interaction.
    • Use wrapExternalInMessage to wrap the transfer in an external message.
    $seqno = $wallet->getSeqno($rpc); // Fetch sequence number from RPC
    $body = $wallet->createTransfer($seqno, time() + 60, $messages);
    $ext = $wallet->wrapExternalInMessage($body);
    
  2. Batch Transfers:

    • Assemble up to four InternalMessage objects in a single transfer.
    $messages = [
        new InternalMessage(dest: $addr1, value: '1000000000', bounce: false),
        new InternalMessage(dest: $addr2, value: '2000000000', bounce: true),
    ];
    
  3. Address Handling:

    • Parse and re-serialize addresses in various formats.
    $address = Address::parse('UQ...');
    echo $address->toString(userFriendly: false); // Raw format
    echo $address->toTonscanFormat(); // URL-safe format
    

Integration Tips

  • Pluggable RPC: Implement WalletRpcInterface to integrate with any RPC provider (e.g., Toncenter, custom node).

    class CustomRpc implements WalletRpcInterface {
        public function getSeqno(Address $address): int { /* ... */ }
        public function sendBoc(string $boc): string { /* ... */ }
    }
    
  • Dependency Injection: Use Laravel's service container to bind the wallet and RPC interfaces.

    $this->app->bind(WalletRpcInterface::class, function ($app) {
        return new ToncenterRpc($app['config']['toncenter.api_key']);
    });
    
  • Testing: Use the WalletRpcInterface to mock RPC calls for unit testing.

    $mockRpc = Mockery::mock(WalletRpcInterface::class);
    $mockRpc->shouldReceive('getSeqno')->andReturn(123);
    $mockRpc->shouldReceive('sendBoc')->andReturn('success');
    

Gotchas and Tips

Pitfalls

  1. Sequence Number Management:

    • Always fetch the latest sequence number before sending a transfer to avoid replay attacks.
    • If using offline signing, ensure the sequence number is up-to-date before wrapping the external message.
  2. Address Validation:

    • Always validate addresses before parsing to avoid exceptions.
    if (!Address::isValid('invalid-address')) {
        throw new \InvalidArgumentException('Invalid TON address');
    }
    
  3. Bounceable vs Non-Bounceable:

    • Ensure the bounce flag in InternalMessage matches the recipient's address type to avoid funds being lost.
  4. Time Validation:

    • The validUntil timestamp must be in the future. If set too far in the past, the transfer may be rejected by the network.

Debugging

  • Check BOC Encoding:

    • If transfers fail silently, verify the BOC encoding with Boc::encodeBase64($ext) and decode it using a TON blockchain explorer.
  • Sequence Number Mismatch:

    • If a transfer fails with a sequence number error, ensure you’re fetching the latest sequence number from the RPC.

Config Quirks

  • Key Generation:

    • Use Mnemonic::toKeyPair to generate keys from a mnemonic phrase. Ensure the mnemonic is secure and backed up.
  • Workchain Handling:

    • The default workchain for TON Wallet v4r2 is 0. If you need to use a different workchain, ensure it’s correctly set in the address.

Extension Points

  • Custom RPC Providers:

    • Extend WalletRpcInterface to support additional RPC providers or custom logic.
  • Address Serialization:

    • Override Address::toString() to customize address formatting for specific use cases.
  • Transfer Customization:

    • Extend InternalMessage or WalletV4R2 to add custom payloads or additional metadata to transfers.

Laravel-Specific Tips

  • Service Provider Binding:

    • Bind the wallet and RPC interfaces in a service provider for easy dependency injection.
    public function register() {
        $this->app->singleton(WalletV4R2::class, function ($app) {
            $keys = Mnemonic::toKeyPair(config('ton.wallet.mnemonic'));
            return new WalletV4R2($keys);
        });
    }
    
  • Configuration:

    • Store wallet mnemonics and RPC endpoints in Laravel's config.
    // config/ton.php
    return [
        'wallet' => [
            'mnemonic' => env('TON_WALLET_MNEMONIC'),
        ],
        'rpc' => [
            'provider' => 'toncenter',
            'api_key' => env('TONCENTER_API_KEY'),
        ],
    ];
    
  • Jobs for Async Transfers:

    • Use Laravel queues to handle transfer broadcasting asynchronously.
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class SendTonTransfer implements ShouldQueue {
        use Queueable;
    
        public function handle() {
            $wallet = app(WalletV4R2::class);
            $rpc = app(WalletRpcInterface::class);
            $wallet->sendTransfer($rpc, $this->messages, validUntil: time() + 60);
        }
    }
    
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