diff --git a/SUMMARY.md b/SUMMARY.md index 19489db..7977162 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -20,6 +20,14 @@ * [All Modules](sdk/all-modules.md) * [Core Module](sdk/core-module/README.md) * [Usage](sdk/core-module/usage.md) + * [Installation](sdk/core-module/guides/installation.md) + * [Instantiation](sdk/core-module/guides/instantiation.md) + * [Register Wallets](sdk/core-module/guides/wallet-registration.md) + * [Account Management](sdk/core-module/guides/account-management.md) + * [Send Transactions](sdk/core-module/guides/transactions.md) + * [Protocol Integration](sdk/core-module/guides/protocol-integration.md) + * [Middleware](sdk/core-module/guides/middleware.md) + * [Error Handling](sdk/core-module/guides/error-handling.md) * [Configuration](sdk/core-module/configuration.md) * [API Reference](sdk/core-module/api-reference.md) * [Wallet Modules](sdk/wallet-modules/README.md) diff --git a/resources/concepts.md b/resources/concepts.md index 2bd9aa4..5753a10 100644 --- a/resources/concepts.md +++ b/resources/concepts.md @@ -152,3 +152,12 @@ Local networks for development and testing: - **Local Ethereum**: Private Ethereum network - **Bitcoin Regtest**: Local Bitcoin network - **Spark Regtest**: Local Spark network + +### Testnet Funds & Faucets + +To test transactions without spending real assets, developers use "Testnets"—networks that mimic the main blockchain but use tokens with no monetary value. You can obtain these tokens for free from "Faucets". + +#### Common Faucets +* **Ethereum (Sepolia)**: [Google Cloud Web3 Faucet](https://cloud.google.com/application/web3/faucet/ethereum/sepolia) +* **TON Testnet**: [Testgiver Bot](https://t.me/testgiver_ton_bot) +* **Bitcoin Testnet**: [CoinFaucet](https://coinfaucet.eu/en/btc-testnet/) diff --git a/sdk/core-module/api-reference.md b/sdk/core-module/api-reference.md index a6ff444..5c2e475 100644 --- a/sdk/core-module/api-reference.md +++ b/sdk/core-module/api-reference.md @@ -264,20 +264,29 @@ wdk.dispose() | Method | Description | Returns | |--------|-------------|---------| -| `getRandomSeedPhrase()` | Returns a random BIP-39 seed phrase | `string` | +| `getRandomSeedPhrase(wordCount?)` | Returns a random BIP-39 seed phrase (12 or 24 words) | `string` | | `isValidSeedPhrase(seedPhrase)` | Checks if a seed phrase is valid | `boolean` | -##### `getRandomSeedPhrase()` -Returns a random BIP-39 seed phrase. +##### `getRandomSeedPhrase(wordCount?)` +Returns a random BIP-39 seed phrase. Supports both 12-word (128-bit entropy) and 24-word (256-bit entropy) seed phrases. + +**Parameters:** +- `wordCount` (12 | 24, optional): The number of words in the seed phrase. Defaults to 12. **Returns:** `string` - The seed phrase **Example:** {% code title="Generate Random Seed" lineNumbers="true" %} ```javascript -const seedPhrase = WDK.getRandomSeedPhrase() -console.log('Generated seed:', seedPhrase) +// Generate 12-word seed phrase (default) +const seedPhrase12 = WDK.getRandomSeedPhrase() +console.log('Generated 12-word seed:', seedPhrase12) // Output: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" + +// Generate 24-word seed phrase (higher security) +const seedPhrase24 = WDK.getRandomSeedPhrase(24) +console.log('Generated 24-word seed:', seedPhrase24) +// Output: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art" ``` {% endcode %} diff --git a/sdk/core-module/configuration.md b/sdk/core-module/configuration.md index 4044091..d142242 100644 --- a/sdk/core-module/configuration.md +++ b/sdk/core-module/configuration.md @@ -58,15 +58,11 @@ const wdk = new WDK(seedPhrase) {% code title="Register WDK Protocol" lineNumbers="true" %} ```javascript import veloraProtocolEvm from '@tetherto/wdk-protocol-swap-velora-evm' -import Usdt0ProtocolTon from '@tetherto/wdk-protocol-bridge-usdt0-ton' const wdk = new WDK(seedPhrase) .registerProtocol('ethereum', 'velora', veloraProtocolEvm, { apiKey: 'YOUR_velora_API_KEY' }) - .registerProtocol('ton', 'usdt0', Usdt0ProtocolTon, { - tonApiKey: 'YOUR_TON_API_KEY' - }) ``` {% endcode %} @@ -96,10 +92,10 @@ wdk.registerWallet('ethereum', WalletManagerEvm, ethereumWalletConfig) {% code title="TON WDK Wallet Configuration" lineNumbers="true" %} ```javascript const tonWalletConfig = { - tonApiKey: 'YOUR_TON_API_KEY', - tonApiEndpoint: 'https://tonapi.io', - tonCenterApiKey: 'YOUR_TON_CENTER_API_KEY', - tonCenterEndpoint: 'https://toncenter.com' + tonClient: { + secretKey: 'YOUR_TON_API_KEY', + url: 'https://toncenter.com/api/v2/jsonRPC' + } } wdk.registerWallet('ton', WalletManagerTon, tonWalletConfig) @@ -125,18 +121,6 @@ wdk.registerProtocol('ethereum', 'velora', veloraProtocolEvm, veloraProtocolConf {% endcode %} -#### Bridge Protocol Configuration - -{% code title="Bridge WDK Protocol Configuration" lineNumbers="true" %} -```javascript -const usdt0ProtocolConfig = { - tonApiKey: 'YOUR_TON_API_KEY', - ethereumRpcUrl: 'https://eth.drpc.org' -} - -wdk.registerProtocol('ton', 'usdt0', Usdt0ProtocolTon, usdt0ProtocolConfig) -``` -{% endcode %} ### Middleware Configuration @@ -150,12 +134,6 @@ wdk.registerMiddleware('ethereum', async (account) => { console.log('New account created:', await account.getAddress()) }) -// Failover cascade middleware -import { getFailoverCascadeMiddleware } from '@tetherto/wdk-wrapper-failover-cascade' - -wdk.registerMiddleware('ethereum', getFailoverCascadeMiddleware(fallbackOptions)) -``` -{% endcode %} ## Environment Variables diff --git a/sdk/core-module/guides/account-management.md b/sdk/core-module/guides/account-management.md new file mode 100644 index 0000000..e0fde38 --- /dev/null +++ b/sdk/core-module/guides/account-management.md @@ -0,0 +1,117 @@ +--- +title: Manage Accounts +description: Learn how to work with accounts and addresses. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Manage Accounts + +This guide explains how to access accounts from your registered wallets. An "Account" object in WDK is your interface for inspecting balances and sending transactions on a specific blockchain. + +## Retrieve Accounts + +You can retrieve an account using a simple index or a custom derivation path. + +### By Index (Recommended) + +The simplest way to get an account is by its index (starting at `0`). This uses the default derivation path for the specified blockchain. + +{% code title="Get Account by Index" lineNumbers="true" %} +```typescript +// Get the first account (index 0) for Ethereum and TON +const ethAccount = await wdk.getAccount('ethereum', 0) +const tonAccount = await wdk.getAccount('ton', 0) +``` +{% endcode %} + +### By Derivation Path (Advanced) + +If you need a specific hierarchy, you can request an account by its unique derivation path. + +{% code title="Get Account by Path" lineNumbers="true" %} +```typescript +// Custom path for Ethereum +const customEthAccount = await wdk.getAccountByPath('ethereum', "0'/0/1") +``` +{% endcode %} + +{% hint style="info" %} +The WDK instance caches accounts. If you call `getAccount` twice using the same index, the function will return the same `Account` object instance. +{% endhint %} + +{% hint style="warning" %} +**Network Mismatch Warning** +Ensure your WDK instance configuration matches your account environment. +* If using **Testnet** keys, ensure you registered the wallet with a **Testnet RPC** (e.g., `https://sepolia.drpc.org` for ETH, `https://testnet.toncenter.com/api/v2/jsonRPC` for TON). +* If using **Mainnet** keys, ensure you registered the wallet with a **Mainnet RPC** (e.g., `https://eth.drpc.org` for ETH, `https://toncenter.com/api/v2/jsonRPC` for TON). +Using a Mainnet key on a Testnet RPC (or vice versa) will result in "Network not allowed" or zero balance errors. +{% endhint %} + +## View Addresses + +Once you have an account object, you can retrieve its public blockchain address using the `getAddress` function. + +{% code title="Get Addresses" lineNumbers="true" %} +```typescript +const ethAddress = await ethAccount.getAddress() +console.log('Ethereum address:', ethAddress) +``` +{% endcode %} + +## Check Balances + +You can check the native token balance of any account (e.g., ETH on Ethereum, TON on TON) by using the `getBalance()` function. + +{% code title="Get Balance" lineNumbers="true" %} +```typescript +try { + const balance = await ethAccount.getBalance() + console.log('Balance:', balance) +} catch (error) { + console.error('Failed to fetch balance:', error) +} +``` +{% endcode %} + +### Multi-Chain Balance Check + +Because WDK offers a unified interface, you can easily iterate through multiple chains to fetch balances. + +The following example: +1. Iterates over an array of user defined chains. +2. Retrieves the first account using the respective chain's `getAccount(index)` function. +3. Retrieves the first account's balance using the `getBalance()` function. +4. Logs the balance to the console. + +{% code title="Check All Balances" lineNumbers="true" %} +```typescript +const chains = ['ethereum', 'ton', 'bitcoin'] + +for (const chain of chains) { + try { + const account = await wdk.getAccount(chain, 0) + const balance = await account.getBalance() + console.log(`${chain} balance:`, balance) + } catch (error) { + console.log(`${chain}: Wallet not registered or unavailable`) + } +} +``` +{% endcode %} + +## Next Steps + +Now that you can access your accounts, learn how to [send transactions](./transactions.md). diff --git a/sdk/core-module/guides/error-handling.md b/sdk/core-module/guides/error-handling.md new file mode 100644 index 0000000..9c4e2c2 --- /dev/null +++ b/sdk/core-module/guides/error-handling.md @@ -0,0 +1,81 @@ +--- +title: Error Handling +description: Learn about common errors and best practices. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Error Handling & Best Practices + +This guide covers recommended patterns for error handling and security when using the WDK. + +## Handling Common Errors + +When interacting with multiple chains and protocols, various runtime issues may occur. + +### Missing Registration + +The most common error is attempting to access a wallet or protocol that hasn't been registered. + +{% code title="Check Registration Pattern" lineNumbers="true" %} +```typescript +try { + // This will throw if 'tron' was never registered via .registerWallet() + const tronAccount = await wdk.getAccount('tron', 0) +} catch (error) { + console.error('Tron wallet not available:', error.message) +} +``` +{% endcode %} + +{% hint style="tip" %} +Always use `try/catch` blocks when initializing sessions or accessing dynamic features. +{% endhint %} + +## Memory Management + +For security, you should clear sensitive data from memory when a session is complete. The WDK provides a `.dispose()` method for this purpose. + +### Disposing the Instance + +Calling `dispose()` clears the seed phrase and private keys derived in memory. + +{% code title="Dispose WDK" lineNumbers="true" %} +```typescript +function endSession(wdk) { + // 1. Clean up sensitive data + wdk.dispose() + + // 2. Modify app state to reflect logged-out status + // ... + + console.log('Session ended, wallet data cleared.') +} +``` +{% endcode %} + +{% hint style="warning" %} +**After Disposal:** Once disposed, any attempt to use the `wdk` instance or its derived accounts will result in an error. You must instantiate a new instance to resume operations. +{% endhint %} + +## Security Best Practices + +### Environment Variables + +Never hardcode API keys or seed phrases in your source code. Use environment variables (e.g., `process.env.TON_API_KEY`). + +### Secure Storage + +If you persist a session, never store the raw seed phrase in local storage. Use secure operating system storage (like Keychain on macOS or Keystore on Android). diff --git a/sdk/core-module/guides/getting-started.md b/sdk/core-module/guides/getting-started.md new file mode 100644 index 0000000..8dc881b --- /dev/null +++ b/sdk/core-module/guides/getting-started.md @@ -0,0 +1,98 @@ +--- +title: Getting Started +description: Install and instantiate the WDK Core module. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Getting Started + +This guide explains how to install the [`@tetherto/wdk`](https://www.npmjs.com/package/@tetherto/wdk) package and create a new instance to start managing your wallets. + +## 1. Installation + +### Prerequisites + +Before you begin, ensure you have the following installed: + +* **[Node.js](https://nodejs.org/)**: version 18 or higher. +* **[npm](https://www.npmjs.com/)**: usually comes with Node.js. + +### Install Package + +To install the WDK Core package, run the following command in your terminal: + +```bash +npm install @tetherto/wdk +``` + +This package allows you to manage different blockchain wallets and protocols through a single interface. + +## 2. Instantiation + +To use WDK, you must create an instance of the `WDK` class. This instance acts as the central manager for all your wallets and protocols. + +### Import the Module + +First, import the `WDK` class from the package: + +{% code title="Import WDK Core" lineNumbers="true" %} +```typescript +import WDK from '@tetherto/wdk' +``` +{% endcode %} + +### Initialize WDK + +You can initialize `WDK` in two ways: with a [new seed phrase](#generate-a-new-wallet) or an [existing one](#restore-an-existing-wallet). + +#### Generate a New Wallet + +If you are creating a fresh wallet for a user, use the static `getRandomSeedPhrase()` method to generate a secure mnemonic. + +{% code title="Create new WDK Instance" lineNumbers="true" %} +```typescript +// 1. Generate a secure random seed phrase +// Generate 24-word seed phrase for higher security +const seedPhrase = WDK.getRandomSeedPhrase(24) + +// Or use 12-word seed phrase (default) +// const seedPhrase = WDK.getRandomSeedPhrase() + +// 2. Initialize the WDK instance with the new seed +const wdk = new WDK(seedPhrase) +``` +{% endcode %} + +{% hint style="danger" %} +**Secure the Seed Phrase:** You must securely store this seed phrase immediately. If it is lost, the user will permanently lose access to their funds. +{% endhint %} + +#### Restore an Existing Wallet + +If a user already has a seed phrase (e.g., from a previous session or another wallet), you can pass it directly to the constructor. + +{% code title="Restore WDK Instance" lineNumbers="true" %} +```typescript +// Replace this string with the user's actual seed phrase +const existingSeed = 'witch collapse practice feed shame open despair creek road again ice ...' + +const wdk = new WDK(existingSeed) +``` +{% endcode %} + +## Next Steps + +With your WDK instance ready, you can now [register wallet modules](./wallet-registration.md) to interact with specific blockchains like [Ethereum](../../wallet-modules/wallet-evm/README.md), [TON](../../wallet-modules/wallet-ton/README.md), or [Bitcoin](../../wallet-modules/wallet-btc/README.md). diff --git a/sdk/core-module/guides/middleware.md b/sdk/core-module/guides/middleware.md new file mode 100644 index 0000000..07e629e --- /dev/null +++ b/sdk/core-module/guides/middleware.md @@ -0,0 +1,85 @@ +--- +title: Configure Middleware +description: Learn how to intercept and enhance wallet operations with middleware. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Configure Middleware + +Middleware allows you to intercept wallet operations. You can use this to add [logging](#logging), implement retry logic, or handle [failovers for RPC providers](#failover-protection-with-provider-failover). + +## Register Middleware + +When registering middleware, you should reference a specific chain. The middleware function runs every time an account is instantiated or an operation is performed, depending on the implementation. + +### Logging + +This simple middleware logs a message whenever a new account is accessed. + +{% code title="Logging Middleware" lineNumbers="true" %} +```typescript +wdk.registerMiddleware('ethereum', async (account) => { + const address = await account.getAddress() + console.log('Accessed Ethereum account:', address) + + // You can also attach custom properties or wrap methods here +}) +``` +{% endcode %} + +## Failover Protection with Provider Failover + +The [`@tetherto/wdk-provider-failover`](https://www.npmjs.com/package/@tetherto/wdk-provider-failover) package provides a resilient wrapper for wallet instances. Unlike standard middleware, you wrap your wallet class instantiation directly. + +### Install `@tetherto/wdk-provider-failover` + +You can install the `@tetherto/wdk-provider-failover` using npm with the following command: + +```bash +npm install @tetherto/wdk-provider-failover +``` + +### Use `createFallbackWallet` + +You can import the `createFallbackWallet` function to ensure that if your primary RPC fails, the wallet automatically retries with the fallback providers. + +With this configuration, if `sendTransaction` fails due to a network error, the WDK will automatically retry using the fallback providers without throwing an error to your application. + +{% code title="Failover Wrapper Usage" lineNumbers="true" %} +```typescript +import { createFallbackWallet } from '@tetherto/wdk-provider-failover' +import { WalletAccountReadOnlyEvm } from '@tetherto/wdk-wallet-evm' + +const wallet = createFallbackWallet( + WalletAccountReadOnlyEvm, + ['0x...'], // constructor args + { + primary: { provider: 'https://mainnet.infura.io/v3/YOUR_KEY' }, + fallbacks: [ + { provider: 'https://eth.llamarpc.com' }, + { provider: 'https://ethereum.publicnode.com' } + ] + } +) + +// Use the wallet instance directly +const balance = await wallet.getBalance() +``` +{% endcode %} + +## Next Steps + +Learn about [error handling and best practices](./error-handling.md) to ensure your application is robust and secure. diff --git a/sdk/core-module/guides/protocol-integration.md b/sdk/core-module/guides/protocol-integration.md new file mode 100644 index 0000000..f21821b --- /dev/null +++ b/sdk/core-module/guides/protocol-integration.md @@ -0,0 +1,121 @@ +--- +title: Integrate Protocols +description: Learn how to use Swaps, Bridges, and Lending protocols. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Integrate Protocols + +The WDK Core module supports registering external protocols. This allows you to extend the basic wallet functionality with advanced features like [token swapping](#swapping-tokens), [cross-chain bridging](#bridging-assets), and lending, all through a unified interface. + +## Register Protocols + +You can register protocols globally (for all new accounts). + +### Global Registration (Recommended) + +Global registration ensures that every account you retrieve already has the protocol ready to use. You can do this by chaining a call to `.registerProtocol()` on the WDK instance. + +### 1. Install Protocol Modules + +Install the [`@tetherto/wdk-protocol-swap-velora-evm`](https://www.npmjs.com/package/@tetherto/wdk-protocol-swap-velora-evm) and [`@tetherto/wdk-protocol-bridge-usdt0-evm`](https://www.npmjs.com/package/@tetherto/wdk-protocol-bridge-usdt0-evm) packages: + +```bash +npm install @tetherto/wdk-protocol-swap-velora-evm && npm install @tetherto/wdk-protocol-bridge-usdt0-evm +``` + +### 2. Register in Code + + +Now, import the protocol modules and register them with your WDK instance. This makes the protocol methods available to any account derived from that instance. + +First, import the necessary modules: + +{% code title="Import Protocols" lineNumbers="true" %} +```typescript +import veloraProtocolEvm from '@tetherto/wdk-protocol-swap-velora-evm' +import usdt0ProtocolEvm from '@tetherto/wdk-protocol-bridge-usdt0-evm' +``` +{% endcode %} + +Then, register the protocols for the specific chains they support: + +{% code title="Register Protocols" lineNumbers="true" %} +```typescript +// Register protocols for specific chains +const wdk = new WDK(seedPhrase) + .registerWallet('ethereum', WalletManagerEvm, ethConfig) + + // Register Velora Swap for Ethereum + .registerProtocol('ethereum', 'velora', veloraProtocolEvm, { + apiKey: 'YOUR_API_KEY' + }) + + // Register USDT0 Bridge for Ethereum + .registerProtocol('ethereum', 'usdt0', usdt0ProtocolEvm, { + ethereumRpcUrl: 'https://eth.drpc.org' // Configuration depends on the module + }) +``` +{% endcode %} + + +## Use Protocols + +Once [registered](#register-protocols), you can access the protocol instance using the specific getter methods: `getSwapProtocol`, `getBridgeProtocol`, or `getLendingProtocol`. + +### Swapping Tokens + +Use `getSwapProtocol` to access registered swap services on any wallet account. + +{% code title="Swap Tokens" lineNumbers="true" %} +```typescript +const ethAccount = await wdk.getAccount('ethereum', 0) +const velora = ethAccount.getSwapProtocol('velora') + +const result = await velora.swap({ + tokenIn: '0x...', // Address of token to sell + tokenOut: '0x...', // Address of token to buy + tokenInAmount: 1000000n // Amount to swap +}) +``` +{% endcode %} + +### Bridging Assets + +1. Use `getBridgeProtocol` to access cross-chain bridges. +2. Call `bridge` from the bridge protocol to send tokens from one protocol to another. + +{% code title="Bridge Assets" lineNumbers="true" %} +```typescript +const ethAccount = await wdk.getAccount('ethereum', 0) +const usdt0 = ethAccount.getBridgeProtocol('usdt0') + +const result = await usdt0.bridge({ + targetChain: 'ton', + recipient: 'UQBla...', // TON address + token: '0x...', // ERC20 Token Address + amount: 1000000n +}) +``` +{% endcode %} + +{% hint style="info" %} +**Protocol Availability:** If you try to access a protocol that hasn't been registered (e.g., `getSwapProtocol('uniswap')`), the SDK will throw an error. always ensure registration matches the ID you request. +{% endhint %} + +## Next Steps + +Learn how to [configure middleware](./middleware.md) to add logging or failover protection to your wallet interactions. diff --git a/sdk/core-module/guides/transactions.md b/sdk/core-module/guides/transactions.md new file mode 100644 index 0000000..1c69c7b --- /dev/null +++ b/sdk/core-module/guides/transactions.md @@ -0,0 +1,120 @@ +--- +title: Send Transactions +description: Learn how to send native tokens on different blockchains. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Send Transactions + + +You can send native tokens (like ETH, TON, or BTC) from any of your wallet accounts to another address. + +{% hint style="info" %} +**Get Testnet Funds:** To test these transactions without spending real money, ensure you are on a testnet and have obtained funds. See [Testnet Funds & Faucets](../../../resources/concepts.md#testnet-funds--faucets) for a list of available faucets. +{% endhint %} + +{% hint style="warning" %} +**BigInt Usage:** Always use `BigInt` (the `n` suffix) for monetary values to avoid precision loss with large numbers. +{% endhint %} + +## Send Native Tokens + +The `sendTransaction` method allows you to transfer value. It accepts a unified configuration object, though specific parameters (like `value` formatting) may vary slightly depending on the blockchain. + +### Ethereum Example + +{% hint style="tip" %} +On EVM chains, values are typically expressed in Wei (1 ETH = 10^18 Wei). +{% endhint %} + +The following example will: + +1. Retrieve the first Ethereum account (see [Manage Accounts](./account-management.md)) +2. Send 0.001 ETH (1000000000000000 wei) to an account using `sendTransaction`. + +{% code title="Send ETH" lineNumbers="true" %} +```typescript +const ethAccount = await wdk.getAccount('ethereum', 0) + +const result = await ethAccount.sendTransaction({ + to: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F', + value: 1000000000000000n // 0.001 ETH (in Wei) +}) + +console.log('Transaction sent! Hash:', result.hash) +``` +{% endcode %} + +### TON Example + +{% hint style="tip" %} +On TON, values are expressed in Nanotons (1 TON = 10^9 Nanotons). +{% endhint %} + +The following example will: + +1. Retrieve the first TON account +2. Send 1 TON (1000000000 nton) to an account using `sendTransaction`. + +{% code title="Send TON" lineNumbers="true" %} +```typescript +// Send TON transaction +const tonAccount = await wdk.getAccount('ton', 0) +const tonResult = await tonAccount.sendTransaction({ + to: 'UQCz5ON7jjK32HnqPushubsHxgsXgeSZDZPvh8P__oqol90r', + value: 1000000000n // 1 TON (in nanotons) +}) +console.log('TON transaction:', tonResult.hash) +``` +{% endcode %} + +## Handling Responses + +The `sendTransaction` method returns a [transaction result object](../api-reference.md). The most important field is typically `hash`, which represents the transaction ID on the blockchain. You can use this hash to track the status of your payment on a block explorer. + +## Multi-Chain Transactions + +You can orchestrate payments across different chains in a single function by acting on multiple account objects sequentially. + +The following example will: +1. Retrieve an ETH and ton account using the `getAccount()` method. +2. Send ETH and `await` the transaction. +3. Send TON and `await` the transaction. + +{% code title="Multi-Chain Payment" lineNumbers="true" %} +```typescript +async function sendCrossChainPayments(wdk) { + const ethAccount = await wdk.getAccount('ethereum', 0) + const tonAccount = await wdk.getAccount('ton', 0) + + // 1. Send ETH + await ethAccount.sendTransaction({ + to: '0x...', + value: 1000000000000000000n + }) + + // 2. Send TON + await tonAccount.sendTransaction({ + to: 'EQ...', + value: 1000000000n + }) +} +``` +{% endcode %} + +## Next Steps + +For more complex interactions like swapping tokens or bridging assets, learn how to [integrate protocols](./protocol-integration.md). diff --git a/sdk/core-module/guides/wallet-registration.md b/sdk/core-module/guides/wallet-registration.md new file mode 100644 index 0000000..b443b41 --- /dev/null +++ b/sdk/core-module/guides/wallet-registration.md @@ -0,0 +1,98 @@ +--- +title: Register Wallets +description: Learn how to register wallet modules for different blockchains. +layout: + width: default + title: + visible: true + description: + visible: true + tableOfContents: + visible: true + outline: + visible: true + pagination: + visible: false + metadata: + visible: false +--- + +# Register Wallets + +This guide explains how to register wallet modules with your WDK instance. The WDK Core module itself doesn't contain blockchain-specific logic; instead, you register separate modules for each chain you want to support (e.g., Ethereum, TON, Bitcoin). + +## How it works + +The WDK uses a builder pattern, allowing you to chain `.registerWallet()` calls. Each call connects a blockchain-specific manager to your central WDK instance. + +### Parameters + +The `registerWallet` method (see [API Reference](../api-reference.md#registerwalletblockchain-wallet-config)) requires three arguments: + +1. **Symbol**: A unique string identifier for the chain (e.g., `'ethereum'`, `'ton'`). You will use this ID later to retrieve accounts. +2. **Manager Class**: The wallet manager class imported from the specific module (e.g., `WalletManagerEvm`). +3. **Configuration**: An object containing the chain-specific settings (e.g., RPC providers, API keys). + +## Installation + +Install the [wallet managers](../../wallet-modules/README.md) for the blockchains you want to support: + +```bash +npm install @tetherto/wdk-wallet-evm @tetherto/wdk-wallet-ton @tetherto/wdk-wallet-btc +``` + +## Example: Registering Multiple Wallets + +### Import the Wallet Manager Packages + +First, import the necessary wallet manager packages: + +{% code title="Import Modules" lineNumbers="true" %} +```typescript +import WalletManagerEvm from '@tetherto/wdk-wallet-evm' +import WalletManagerTon from '@tetherto/wdk-wallet-ton' +import WalletManagerBtc from '@tetherto/wdk-wallet-btc' +``` +{% endcode %} + +### Register the Wallets + +Then, [instantiate WDK](./getting-started.md#initialize-wdk) and chain the registration calls: + +{% code title="Register Wallets" lineNumbers="true" %} +```typescript +const wdk = new WDK(seedPhrase) + // 1. Register Ethereum + .registerWallet('ethereum', WalletManagerEvm, { + provider: 'https://eth.drpc.org' + }) + // 2. Register TON + .registerWallet('ton', WalletManagerTon, { + // Get your API key: https://docs.ton.org/ecosystem/api/toncenter/get-api-key + tonClient: { + secretKey: 'YOUR_TON_API_KEY', + url: 'https://toncenter.com/api/v2/jsonRPC' + } + }) + // 3. Register Bitcoin + .registerWallet('bitcoin', WalletManagerBtc, { + provider: 'https://blockstream.info/api' + }) +``` +{% endcode %} + +{% hint style="info" %} +**Ethereum Networks:** Choose the RPC endpoint that matches your environment (Mainnet or Testnet). +* **Mainnet:** `https://eth.drpc.org` +* **Sepolia (Testnet):** `https://sepolia.drpc.org` +{% endhint %} + +{% hint style="info" %} +**TON Networks:** The endpoint (`url`) you use must match your API key environment. +* **Mainnet:** `https://toncenter.com/api/v2/jsonRPC` +* **Testnet:** `https://testnet.toncenter.com/api/v2/jsonRPC` +{% endhint %} + +## Next Steps + +Once your wallets are registered, you can [manage accounts and specific addresses](./account-management.md). diff --git a/sdk/core-module/usage.md b/sdk/core-module/usage.md index 3ec3395..94c3d3e 100644 --- a/sdk/core-module/usage.md +++ b/sdk/core-module/usage.md @@ -1,6 +1,6 @@ --- -title: Usage -description: Learn how to use the WDK Core module +title: WDK Core Usage +description: Guide to using the WDK Core module. icon: book-open layout: width: default @@ -18,482 +18,62 @@ layout: visible: false --- -This package serves as the main entry point and orchestrator for all WDK wallet modules, allowing you to register and manage different blockchain wallets and protocols through a single interface. +# Usage -## Installation - -Install the `@tetherto/wdk-core` package: - -```bash -npm install @tetherto/wdk -``` - -*** - -## Basic Usage - -### Importing WDK Core - -{% code title="Import WDK Core" lineNumbers="true" %} -```typescript -import WDK from '@tetherto/wdk' -``` -{% endcode %} - - -### Creating a WDK Instance - -{% code title="Create WDK Instance" lineNumbers="true" %} -```typescript -// Generate a random seed phrase -const seedPhrase = WDK.getRandomSeedPhrase() - -// Create WDK instance -const wdk = new WDK(seedPhrase) - -// Or use your own seed phrase -const wdk = new WDK('your existing seed phrase here...') -``` -{% endcode %} - -*** - -## Wallet Registration - -### Registering Wallets - -{% code title="Register Wallets" lineNumbers="true" %} -```typescript -import WalletManagerEvm from '@tetherto/wdk-wallet-evm' -import WalletManagerTon from '@tetherto/wdk-wallet-ton' -import WalletManagerBtc from '@tetherto/wdk-wallet-btc' - -// Register wallets for different blockchains -const wdk = new WDK(seedPhrase) - .registerWallet('ethereum', WalletManagerEvm, { - provider: 'https://eth.drpc.org' - }) - .registerWallet('ton', WalletManagerTon, { - tonApiKey: 'YOUR_TON_API_KEY', - tonApiEndpoint: 'https://tonapi.io' - }) - .registerWallet('bitcoin', WalletManagerBtc, { - provider: 'https://blockstream.info/api' - }) -``` -{% endcode %} - -*** - -## Account Management - -### Getting Accounts - -{% code title="Get Accounts" lineNumbers="true" %} -```typescript -// Get account by blockchain and index -const ethAccount = await wdk.getAccount('ethereum', 0) -const tonAccount = await wdk.getAccount('ton', 0) - -// Get account by derivation path -const customEthAccount = await wdk.getAccountByPath('ethereum', "0'/0/1") -const customTonAccount = await wdk.getAccountByPath('ton', "1'/2/3") - -// Get addresses -const ethAddress = await ethAccount.getAddress() -const tonAddress = await tonAccount.getAddress() -console.log('Ethereum address:', ethAddress) -console.log('TON address:', tonAddress) -``` -{% endcode %} - -### Multi-Chain Account Management - -{% code title="Multi-Chain Account Management" lineNumbers="true" %} -```typescript -// Get accounts for different chains -const accounts = { - ethereum: await wdk.getAccount('ethereum', 0), - arbitrum: await wdk.getAccount('arbitrum', 0), - ton: await wdk.getAccount('ton', 0), - bitcoin: await wdk.getAccount('bitcoin', 0) -} - -// Get all addresses -for (const [chain, account] of Object.entries(accounts)) { - const address = await account.getAddress() - console.log(`${chain} address:`, address) -} -``` -{% endcode %} - -*** - -## Balance Operations - -### Cross-Chain Balance Checking - -{% code title="Cross-Chain Balance Checking" lineNumbers="true" %} -```typescript -async function checkAllBalances(wdk) { - const chains = ['ethereum', 'arbitrum', 'ton', 'bitcoin'] - const balances = {} - - for (const chain of chains) { - try { - const account = await wdk.getAccount(chain, 0) - const balance = await account.getBalance() - balances[chain] = balance - console.log(`${chain} balance:`, balance) - } catch (error) { - console.log(`${chain}: Wallet not registered`) - } - } - - return balances -} - -// Usage -const balances = await checkAllBalances(wdk) -``` -{% endcode %} - -*** - -## Transaction Operations - -### Sending Transactions - -{% code title="Sending Transactions" lineNumbers="true" %} -```typescript -// Send Ethereum transaction -const ethAccount = await wdk.getAccount('ethereum', 0) -const ethResult = await ethAccount.sendTransaction({ - to: '0x...', - value: 1000000000000000000n // 1 ETH -}) -console.log('Ethereum transaction:', ethResult.hash) - -// Send TON transaction -const tonAccount = await wdk.getAccount('ton', 0) -const tonResult = await tonAccount.sendTransaction({ - to: 'EQ...', - value: 1000000000n // 1 TON -}) -console.log('TON transaction:', tonResult.hash) -``` -{% endcode %} - -### Multi-Chain Transaction Function - -{% code title="Multi-Chain Transaction Function" lineNumbers="true" %} -```typescript -async function sendMultiChainTransactions(wdk) { - // Ethereum transaction - const ethAccount = await wdk.getAccount('ethereum', 0) - const ethResult = await ethAccount.sendTransaction({ - to: '0x...', - value: 1000000000000000000n // 1 ETH - }) - console.log('Ethereum transaction:', ethResult.hash) - - // TON transaction - const tonAccount = await wdk.getAccount('ton', 0) - const tonResult = await tonAccount.sendTransaction({ - to: 'EQ...', - value: 1000000000n // 1 TON - }) - console.log('TON transaction:', tonResult.hash) -} -``` -{% endcode %} - -*** - -## Protocol Integration - -### Registering Protocols - -{% code title="Registering Protocols" lineNumbers="true" %} -```typescript -import veloraProtocolEvm from '@tetherto/wdk-protocol-swap-velora-evm' -import Usdt0ProtocolTon from '@tetherto/wdk-protocol-bridge-usdt0-ton' - -// Register protocols globally -const wdk = new WDK(seedPhrase) - .registerWallet('ethereum', WalletManagerEvm, ethereumWalletConfig) - .registerWallet('ton', WalletManagerTon, tonWalletConfig) - .registerProtocol('ethereum', 'velora', veloraProtocolEvm, { - apiKey: 'YOUR_velora_API_KEY' - }) - .registerProtocol('ton', 'usdt0', Usdt0ProtocolTon, { - tonApiKey: 'YOUR_TON_API_KEY' - }) -``` -{% endcode %} - -### Using Protocols - -{% code title="Using Protocols" lineNumbers="true" %} -```typescript -// Get accounts with protocol support -const ethAccount = await wdk.getAccount('ethereum', 0) -const tonAccount = await wdk.getAccount('ton', 0) - -// Use swap protocol -const velora = ethAccount.getSwapProtocol('velora') -const swapResult = await velora.swap({ - tokenIn: '0x...', - tokenOut: '0x...', - tokenInAmount: 1000000n -}) - -// Use bridge protocol -const usdt0 = tonAccount.getBridgeProtocol('usdt0') -const bridgeResult = await usdt0.bridge({ - targetChain: 'ethereum', - recipient: '0x...', - token: 'TON_TOKEN_ADDRESS', - amount: 1000000n -}) -``` -{% endcode %} - -### Multiple Protocol Types - -{% code title="Multiple Protocol Types" lineNumbers="true" %} -```typescript -// Register different protocol types -const account = await wdk.getAccount('ethereum', 0) - -// Swap protocol -account.registerProtocol('velora', veloraProtocolEvm, veloraConfig) -const velora = account.getSwapProtocol('velora') - -// Bridge protocol -account.registerProtocol('usdt0', Usdt0ProtocolEvm, usdt0Config) -const usdt0 = account.getBridgeProtocol('usdt0') - -// Lending protocol -account.registerProtocol('aave', AaveProtocolEvm, aaveConfig) -const aave = account.getLendingProtocol('aave') -``` -{% endcode %} - -*** - -## Middleware - -### Logging Middleware - -{% code title="Logging Middleware" lineNumbers="true" %} -```typescript -// Register logging middleware -wdk.registerMiddleware('ethereum', async (account) => { - const address = await account.getAddress() - console.log('New Ethereum account created:', address) -}) - -wdk.registerMiddleware('ton', async (account) => { - const address = await account.getAddress() - console.log('New TON account created:', address) -}) - -// This will trigger the middleware -const account = await wdk.getAccount('ethereum', 0) -``` -{% endcode %} - -### Failover Middleware - -{% code title="Failover Middleware" lineNumbers="true" %} -```typescript -import { getFailoverCascadeMiddleware } from '@tetherto/wdk-wrapper-failover-cascade' - -// Register failover middleware -wdk.registerMiddleware('ethereum', getFailoverCascadeMiddleware({ - retries: 3, - delay: 1000, - fallbackProviders: [ - 'https://backup-rpc-1.com', - 'https://backup-rpc-2.com' - ] -})) - -// Transactions will automatically retry with fallback providers -const account = await wdk.getAccount('ethereum', 0) -const result = await account.sendTransaction(tx) // Will retry on failure -``` -{% endcode %} - -*** - -## Complete Examples - -### Multi-Chain Wallet Setup - -{% code title="Multi-Chain Wallet Setup" lineNumbers="true" %} -```typescript -import WDK from '@tetherto/wdk' -import WalletManagerEvm from '@tetherto/wdk-wallet-evm' -import WalletManagerTon from '@tetherto/wdk-wallet-ton' -import veloraProtocolEvm from '@tetherto/wdk-protocol-swap-velora-evm' - -async function setupMultiChainWallet() { - // Generate or use existing seed phrase - const seedPhrase = WDK.getRandomSeedPhrase() - - // Initialize WDK Manager - const wdk = new WDK(seedPhrase) - .registerWallet('ethereum', WalletManagerEvm, { - provider: 'https://eth.drpc.org' - }) - .registerWallet('ton', WalletManagerTon, { - tonApiKey: 'YOUR_TON_API_KEY' - }) - .registerProtocol('ethereum', 'velora', veloraProtocolEvm, { - apiKey: 'YOUR_velora_API_KEY' - }) - - // Get accounts - const ethAccount = await wdk.getAccount('ethereum', 0) - const tonAccount = await wdk.getAccount('ton', 0) - - // Get addresses - const ethAddress = await ethAccount.getAddress() - const tonAddress = await tonAccount.getAddress() - - console.log('Ethereum address:', ethAddress) - console.log('TON address:', tonAddress) - - return { wdk, ethAccount, tonAccount } -} -``` -{% endcode %} - -*** - -## Error Handling - -### Handling Common Errors - -{% code title="Handling Common Errors" lineNumbers="true" %} -```typescript -async function handleErrors(wdk) { - try { - // This will throw if no wallet registered for 'tron' - const tronAccount = await wdk.getAccount('tron', 0) - } catch (error) { - console.error('Tron wallet not registered:', error.message) - } - - try { - const ethAccount = await wdk.getAccount('ethereum', 0) - - // This will throw if no swap protocol registered - const uniswap = ethAccount.getSwapProtocol('uniswap') - } catch (error) { - console.error('Uniswap protocol not registered:', error.message) - } -} -``` -{% endcode %} - -### Memory Management - -{% code title="Memory Management" lineNumbers="true" %} -```typescript -async function cleanupExample(wdk) { - // Use the WDK Manager - const ethAccount = await wdk.getAccount('ethereum', 0) - const tonAccount = await wdk.getAccount('ton', 0) - - // Perform operations - const ethAddress = await ethAccount.getAddress() - const tonAddress = await tonAccount.getAddress() - - // Clean up sensitive data - wdk.dispose() - - // After dispose, accounts are no longer usable - // This will throw an error - try { - await ethAccount.getAddress() - } catch (error) { - console.log('Account disposed, cannot access private keys') - } -} -``` -{% endcode %} - -*** - -## Next Steps +The WDK Core module is the central orchestrator for your wallet interactions. - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + - - - - - + + + + + - - - - - - + + + + + + + + + + + + + + + + + +
:rocket:Getting StartedInstall and instantiate the WDK.Getting Started
:wallet:Register WalletsConnect specific blockchains (Ethereum, TON, etc.).Register Wallets
- :code: - - WDK Core Configuration - Get started with WDK's configuration - WDK Core Configuration -
- :code: - - WDK Core API - Get started with WDK's API - WDK Core API -
:user:Manage AccountsRetrieve accounts and check balances.Manage Accounts
- :code: - - Wallet Modules - Explore blockchain-specific wallet modules - WDK Wallet Modules -
:exchange-alt:Send TransactionsTransfer native tokens.Send Transactions
- :code: - - Bridge Modules - Cross-chain USDâ‚®0 bridges - Bridge Modules -
:plug:Integrate ProtocolsUse Swap, Bridge, and Lending protocols.Integrate Protocols
:layer-group:Configure MiddlewareAdd logging and failover protection.Configure Middleware
:exclamation-triangle:Error HandlingBest practices for security and stability.Error Handling
- -*** - -## Need Help? - -{% include "../../.gitbook/includes/support-cards.md" %} diff --git a/sdk/get-started.md b/sdk/get-started.md index 11d2bac..23a857f 100644 --- a/sdk/get-started.md +++ b/sdk/get-started.md @@ -119,7 +119,11 @@ The WDK SDK uses a registration-based system where modules are added to a centra ```typescript import WDK from '@tetherto/wdk' -const seedPhrase = WDK.getRandomSeedPhrase() // or use your own seed phrase +// Generate 24-word seed phrase for higher security +const seedPhrase = WDK.getRandomSeedPhrase(24) + +// Or use 12-word seed phrase (default) +// const seedPhrase = WDK.getRandomSeedPhrase() const wdk = new WDK(seedPhrase) ```