Injected Provider API for TON: Connect Browser Extension Wallets and Web3 Wallets

ยท

What is Injected Provider API?

The Injected Provider API is a JavaScript interface that enables decentralized applications (DApps) to interact with cryptocurrency wallets directly through users' browsers. This API allows DApps to:

Key Features

  1. TON Connect Protocol Compliance: Fully compatible with the TON Connect Protocol
  2. Simplified Integration: Works with TON Connect SDK for easier implementation
  3. Cross-Platform Support: Functions across browser extensions and Web3 wallets

Accessing the Injected Object

The wallet injects the following properties into DApps according to TON Connect specifications:

deviceInfo Structure

Retrieves device and wallet metadata:

- `platform`: Operating system/device type
- `appName`: Wallet application name
- `appVersion`: Current wallet version
- `maxProtocolVersion`: Highest supported protocol version
- `features`: Supported wallet capabilities

walletInfo Structure

Provides wallet-specific details:

- `name`: Official wallet name
- `app_name`: Unique application identifier
- `image`: Wallet logo/icon URL
- `about_url`: Information page link
- `platforms`: Supported operating systems

protocolVersion

Currently supports TON Connect version 2


Core API Methods

connect()

Establishes wallet connection with optional signature verification.

Parameters:

- `protocolVersion`: Required TON Connect version (returns error if unsupported)
- `message`: Connection request object containing:
  - `manifestUrl`: DApp metadata file URL
  - `items`: Requested actions:
    - `ton_addr`: Retrieve address/public key
    - `ton_proof`: Signature verification

Return Value:
Promise resolving to ConnectEvent object

Example Usage:

// Basic address request
await wallet.connect({
  protocolVersion: 2,
  message: {
    manifestUrl: 'https://dapp.com/manifest.json',
    items: [{ type: 'ton_addr' }]
  }
});

// With signature verification
await wallet.connect({
  protocolVersion: 2,
  message: {
    manifestUrl: 'https://dapp.com/manifest.json',
    items: [
      { type: 'ton_addr' },
      { type: 'ton_proof', payload: 'verification_data' }
    ]
  }
});

restoreConnection()

Re-establishes previous connection (only returns ton_addr results).

Example:

try {
  const address = await wallet.restoreConnection();
} catch (error) {
  console.error('Connection failed:', error);
}

send()

Communicates transaction requests to the wallet.

Message Structure:

- `method`: Either `sendTransaction` or `disconnect`
- `params`: Method-specific parameters
- `id`: Incremental request identifier

Transaction Requests (sendTransaction)

Parameters:

- `valid_until`: Optional expiration timestamp
- `network`: Currently only 'mainnet'
- `from`: Sender address (wc:hex format)
- `messages`: Array of 1-4 transaction messages containing:
  - `address`: Recipient
  - `amount`: TON amount in nano-tokens
  - `payload`: Optional Base64-encoded cell BoC
  - `stateInit`: Optional Base64-encoded cell BoC

Example:

await wallet.send({
  method: 'sendTransaction',
  params: {
    messages: [{
      address: 'EQABC...',
      amount: '1000000000',
      payload: 'base64_data'
    }]
  },
  id: 1
});

Disconnection (disconnect)

Terminates wallet connection.

Example:

await wallet.send({
  method: 'disconnect',
  params: {},
  id: 2
});

Event Handling

listen()

Subscribes to wallet events.

Parameters:

- `callback`: Function handling incoming events

Returns:
Unsubscribe function

on()/off()

OKX Wallet-specific methods for account change events.

Supported Events:

- `connect`: Successful connection
- `disconnect`: Session termination
- `accountChanged`: Wallet/account switch

Example:

const handler = (event) => {
  console.log('Account changed:', event);
};
wallet.on('accountChanged', handler);

// Later...
wallet.off('accountChanged', handler);

๐Ÿ‘‰ Explore advanced wallet integration techniques


FAQ

Q: How do I detect if the provider is available?
A: Check for window.ton or window.okxwallet existence before calling methods.

Q: What happens if users don't have the wallet installed?
A: Implement graceful degradation with installation prompts or fallback options.

Q: Can I use this with mobile wallets?
A: Yes, when accessed through compatible in-app browsers that support the injection.

Q: How do I handle transaction errors?
A: Always wrap calls in try/catch blocks and validate responses.

Q: Is there rate limiting?
A: Follow standard web3 practices to avoid excessive requests that might trigger wallet-side protections.

๐Ÿ‘‰ Learn about optimizing DApp performance


Best Practices

  1. User Experience

    • Always request minimal permissions initially
    • Provide clear explanations for signature requests
    • Handle disconnections gracefully
  2. Security

    • Validate all responses
    • Implement CSRF protection
    • Use nonces for sensitive operations
  3. Performance

    • Cache static wallet information
    • Batch requests when possible
    • Optimize payload sizes

By following this comprehensive guide, developers can seamlessly integrate TON blockchain functionality while ensuring optimal user experience and security. The API's standardized approach combined with OKX Wallet's extensions provides a robust foundation for Web3 application development.