### Setup for SilentSwap SDK with Viem (Node.js)
Source: https://docs.silentswap.com/core/silent-swap/complete-example
Sets up the SilentSwap client and EVM signer using Viem for interacting with the Avalanche and Ethereum mainnets. It configures a wallet client with a private key and initializes the SilentSwap client with environment-specific settings.
```javascript
import {
createSilentSwapClient,
createViemSigner,
parseTransactionRequestForViem,
createSignInMessage,
createEip712DocForOrder,
createEip712DocForWalletGeneration,
createHdFacilitatorGroupFromEntropy,
quoteResponseToEip712Document,
caip19FungibleEvmToken,
queryDepositCount,
solveOptimalUsdcAmount,
GATEWAY_ABI,
PublicKeyArgGroups,
DeliveryMethod,
FacilitatorKeyType,
ENVIRONMENT,
hexToBytes,
type SilentSwapClient,
type EvmSigner,
type AuthResponse,
type SolveUsdcResult,
} from '@silentswap/sdk';
import { createWalletClient, http, publicActions, erc20Abi } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { avalanche, mainnet } from 'viem/chains';
import BigNumber from 'bignumber.js';
// Create wallet client
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const client = createWalletClient({
account,
chain: avalanche,
transport: http(),
}).extend(publicActions);
// Create EVM signer
const signer = createViemSigner(account, client);
// Create SilentSwap client
const silentswap = createSilentSwapClient({
environment: ENVIRONMENT.MAINNET,
baseUrl: 'https://api.silentswap.com',
});
```
--------------------------------
### Vue Silent Swap Setup
Source: https://docs.silentswap.com/vue/overview
Sets up the Silent Swap client and composables for managing orders and authentication. This example initializes the client and retrieves essential functions like `getNonce`, `authenticate`, and `getQuote`.
```vue
Loading...
Error: {{ error.message }}
```
--------------------------------
### Setup SilentSwapProvider in React
Source: https://docs.silentswap.com/react/silent-swap/complete-example
Wraps the application with SilentSwapProvider to manage global state and provide context for hooks. It utilizes adapters for Solana and Bitcoin, and integrates with wagmi for EVM wallet management. Dependencies include @silentswap/react, @silentswap/sdk, and wagmi.
```typescript
'use client';
import React from 'react';
import { SilentSwapProvider, useSolanaAdapter, useBitcoinAdapter } from '@silentswap/react';
import { createSilentSwapClient, ENVIRONMENT } from '@silentswap/sdk';
import { useAccount, useWalletClient } from 'wagmi';
import { useUserAddress } from '@/hooks/useUserAddress';
// Initialize the client
const environment = ENVIRONMENT.STAGING;
const client = createSilentSwapClient({ environment });
export default function Provider({ children }: { children: React.ReactNode }) {
const { isConnected, connector } = useAccount();
const { data: walletClient } = useWalletClient();
const { evmAddress, solAddress, bitcoinAddress } = useUserAddress();
// Use the built-in Solana adapter hook if you need Solana support
const { solanaConnector, solanaConnectionAdapter } = useSolanaAdapter();
// Use the built-in Bitcoin adapter hook if you need Bitcoin support
const { bitcoinConnector, bitcoinConnectionAdapter } = useBitcoinAdapter();
return (
{children}
);
}
```
--------------------------------
### Create SilentSwap SDK Client
Source: https://docs.silentswap.com/example/account
Initializes the SilentSwap SDK client. This client is used for sending requests to the SilentSwap service. No specific configuration is shown in this basic example.
```typescript
import { createSilentSwapClient } from '@silentswap/sdk';
// create new SilentSwap SDK client
const silentswap = createSilentSwapClient({
});
```
--------------------------------
### Setup SilentSwap Client and Solana Connection (Node.js)
Source: https://docs.silentswap.com/core/silent-swap/solana-examples
This snippet sets up the necessary clients and connections for performing Silent Swaps on Solana. It includes creating an EVM wallet client, an EVM signer, the SilentSwap client, and a Solana connection. It also demonstrates loading a Solana keypair from environment variables.
```javascript
import {
createSilentSwapClient,
createViemSigner,
parseTransactionRequestForViem,
createSignInMessage,
createEip712DocForWalletGeneration,
createEip712DocForOrder,
createHdFacilitatorGroupFromEntropy,
queryDepositCount,
hexToBytes,
quoteResponseToEip712Document,
solveOptimalUsdcAmount,
caip19FungibleEvmToken,
caip19SplToken,
DeliveryMethod,
FacilitatorKeyType,
PublicKeyArgGroups,
ENVIRONMENT,
N_RELAY_CHAIN_ID_SOLANA,
SB58_ADDR_SOL_PROGRAM_SYSTEM,
isSolanaNativeToken,
parseSolanaCaip19,
fetchRelayQuote,
createPhonyDepositCalldata,
X_MAX_IMPACT_PERCENT,
getRelayStatus,
type SilentSwapClient,
type EvmSigner,
type SolveUsdcResult,
} from '@silentswap/sdk';
import { createWalletClient, http, publicActions, erc20Abi, encodeFunctionData, erc20Abi as erc20AbiForEncode } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { avalanche, mainnet } from 'viem/chains';
import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';
import { getAssociatedTokenAddress, createTransferInstruction, getAccount } from '@solana/spl-token';
import BigNumber from 'bignumber.js';
// Create EVM wallet client (required for facilitator operations)
const evmAccount = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const evmClient = createWalletClient({
account: evmAccount,
chain: avalanche,
transport: http(),
}).extend(publicActions);
// Create EVM signer
const evmSigner = createViemSigner(evmAccount, evmClient);
// Create SilentSwap client
const silentswap = createSilentSwapClient({
environment: ENVIRONMENT.MAINNET,
baseUrl: 'https://api.silentswap.com',
});
// Create Solana connection
const solanaConnection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');
// Load Solana keypair (in production, use secure key management)
const solanaKeypair = Keypair.fromSecretKey(
Buffer.from(JSON.parse(process.env.SOLANA_SECRET_KEY || '[]'))
);
const solanaAddress = solanaKeypair.publicKey.toString();
```
--------------------------------
### Setup SilentSwap Provider (React)
Source: https://docs.silentswap.com/react/silent-swap/solana-examples
Sets up the SilentSwapProvider component in a React application. It requires connecting both Solana and EVM wallets and utilizes hooks from 'wagmi' and custom hooks for address management. The provider facilitates swap operations by integrating with the SilentSwap SDK and adapters.
```typescript
'use client';
import React from 'react';
import { SilentSwapProvider, useSolanaAdapter } from '@silentswap/react';
import { createSilentSwapClient, ENVIRONMENT } from '@silentswap/sdk';
import { useAccount, useWalletClient } from 'wagmi';
import { useUserAddress } from '@/hooks/useUserAddress';
const environment = ENVIRONMENT.STAGING;
const client = createSilentSwapClient({ environment });
export default function Provider({ children }: { children: React.ReactNode }) {
const { isConnected, connector } = useAccount();
const { data: walletClient } = useWalletClient();
const { evmAddress, solAddress } = useUserAddress();
// Solana adapter hook - required for Solana swaps
const { solanaConnector, solanaConnectionAdapter } = useSolanaAdapter();
return (
{children}
);
}
```
--------------------------------
### Setup Node.js Environment for SilentSwap V2 SDK
Source: https://docs.silentswap.com/core/simple-bridge/complete-example
This code sets up the necessary imports and wallet client for interacting with the SilentSwap V2 SDK in a Node.js environment. It includes importing core SDK functions, viem utilities for wallet management and chain interactions, and defines a simple connector for chain switching.
```typescript
import {
getBridgeQuote,
convertQuoteResultToQuote,
executeBridgeTransaction,
getBridgeStatus,
type BridgeProvider,
type BridgeStatus,
} from '@silentswap/sdk';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { ethereum, avalanche } from 'viem/chains';
// Create wallet client
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: ethereum,
transport: http(),
});
// Simple connector implementation for chain switching
const connector = {
switchChain: async ({ chainId }: { chainId: number }) => {
// For production, you'd want to create a new client for the target chain
// This is a simplified example
console.log(`Switching to chain ${chainId}`);
},
};
```
--------------------------------
### Install SilentSwap SDK
Source: https://docs.silentswap.com/core/simple-bridge/introduction
Installs the SilentSwap SDK using pnpm. This is the first step to using the SDK's functionalities in your project.
```bash
pnpm add @silentswap/sdk
```
--------------------------------
### Create Facilitator Group from Entropy
Source: https://docs.silentswap.com/example/account
This example demonstrates creating a facilitator group from the derived secret entropy. It first retrieves the user's deposit count from the Gateway contract to ensure the group is uniquely identified for the specific order, then uses this count along with the entropy to create the group.
```typescript
import { createHdFacilitatorGroupFromEntropy } from '@silentswap/sdk';
// get the number of deposits the user has made into Gateway contract
const depositCountReturn = await client.readContract({
address: silentswap.gatewayAddress,
abi: GATEWAY_ABI,
functionName: 'signerCounts',
args: [account.address],
});
// create a new facilitator group, using the deposit count to distinguish from previous orders
const group = await createHdFacilitatorGroupFromEntropy(hexToBytes(entropy), depositCountReturn);
```
--------------------------------
### Basic Usage Example
Source: https://docs.silentswap.com/vue/get-transaction
Demonstrates how to use the `getTransaction` composable to execute a bridge transaction, including getting a quote and handling the transaction flow.
```APIDOC
## Basic Usage
### Description
This example shows how to initialize the SilentSwap client, get a bridge quote, and then execute the transaction using `getTransaction`.
### Code Example
```javascript
Error: {{ error.message }}
```
```
--------------------------------
### Accessing User Data with SilentSwap React Hooks
Source: https://docs.silentswap.com/react/silent-swap/complete-example
Demonstrates how to use `useBalancesContext`, `usePricesContext`, and `useOrdersContext` hooks from '@silentswap/react' to fetch and display a user's financial information, including their asset balances, total portfolio value in USD, and recent order history. This requires the '@silentswap/react' library to be installed and configured.
```javascript
import { useBalancesContext, usePricesContext, useOrdersContext } from '@silentswap/react';
function UserInfo() {
const { balances, totalUsdValue } = useBalancesContext();
const { prices } = usePricesContext();
const { orders } = useOrdersContext();
return (
);
}
```
--------------------------------
### Usage Example: Bridging USDC from Ethereum to Avalanche
Source: https://docs.silentswap.com/core/simple-bridge/complete-example
This example demonstrates how to use the `bridgeTokens` function to bridge USDC from the Ethereum mainnet to Avalanche. It specifies the source and destination chain IDs, token addresses, amount, and the user's address, then logs the bridge completion result.
```typescript
// Bridge USDC from Ethereum to Avalanche
const result = await bridgeTokens(
1, // Ethereum
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
'1000000', // 1 USDC (6 decimals)
43114, // Avalanche
'0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', // USDC.e
account.address
);
console.log('Bridge completed:', result);
```
--------------------------------
### Execute Solana to EVM Swap (JavaScript)
Source: https://docs.silentswap.com/core/silent-swap/solana-examples
This example demonstrates how to execute a swap from Solana (SOL) to an EVM-compatible chain (USDC on Ethereum). It requires specifying the amount, recipient EVM address, the target token on the EVM chain, and the EVM network ID. The function returns the result of the swap operation.
```javascript
const result = await executeSolanaToEvmSwap(
'1', // 1 SOL
'0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5', // Recipient EVM address
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC on Ethereum
1 // Ethereum mainnet
);
console.log('Swap completed:', result);
```
--------------------------------
### Execute EVM to Solana Swap (JavaScript)
Source: https://docs.silentswap.com/core/silent-swap/solana-examples
This example shows how to execute a swap from an EVM-compatible chain (USDC) to Solana. It requires the amount, recipient Solana address (in base58 format), and the SPL token mint address on Solana. The function returns the result of the swap operation.
```javascript
const result = await executeEvmToSolanaSwap(
'100', // 100 USDC
'9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM', // Recipient Solana address (base58)
'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // USDC SPL token mint
);
console.log('Swap completed:', result);
```
--------------------------------
### Solve Optimal USDC Amount and Bridge Transaction (TypeScript)
Source: https://docs.silentswap.com/core/simple-bridge/complete-example
This function demonstrates how to solve for the optimal USDC amount for a bridge transaction and then execute the transaction. It utilizes functions from the '@silentswap/sdk' to get a quote, solve for the best USDC amount, and execute the bridge. Dependencies include '@silentswap/sdk', walletClient, and connector.
```typescript
import {
getBridgeQuote,
convertQuoteResultToQuote,
solveOptimalUsdcAmount,
executeBridgeTransaction,
} from '@silentswap/sdk';
async function bridgeToUsdcWithDeposit(
srcChainId: number,
srcToken: string,
srcAmount: string,
userAddress: `0x${string}`,
depositCalldata: string
) {
// Step 1: Solve for optimal USDC amount
console.log('Solving for optimal USDC amount...');
const solveResult = await solveOptimalUsdcAmount(
srcChainId,
srcToken,
srcAmount,
userAddress,
depositCalldata
);
console.log('Solve result:');
console.log(` USDC Out: ${solveResult.usdcAmountOut.toString()}`);
console.log(` Amount In: ${solveResult.actualAmountIn.toString()}`);
console.log(` Provider: ${solveResult.provider}`);
console.log(` Allowance Target: ${solveResult.allowanceTarget}`);
// Step 2: Get quote with the solved amount
const quoteResult = await getBridgeQuote(
srcChainId,
srcToken,
solveResult.actualAmountIn.toString(),
43114, // Avalanche
'0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', // USDC on Avalanche
userAddress
);
// Convert to executable quote
const quote = convertQuoteResultToQuote(quoteResult, srcChainId);
// Step 3: Execute transaction
const status = await executeBridgeTransaction(
quote,
walletClient,
connector,
(step) => console.log(` → ${step}`)
);
return { solveResult, quote, status };
}
```
--------------------------------
### SilentSwap Method Usage Flow (JavaScript)
Source: https://docs.silentswap.com/core/silent-swap/complete-example
Demonstrates the typical flow for using SilentSwap methods, covering authentication, facilitator group creation, token asset definition, and order signing. This example utilizes EIP-712 for typed data signing.
```javascript
// 1. Authentication
const signInMessage = createSignInMessage(address, nonce, domain);
const entropy = await signer.signEip712TypedData(
createEip712DocForWalletGeneration(authResponse.secretToken)
);
// 2. Facilitator Group
const depositCount = await queryDepositCount(address);
const group = await createHdFacilitatorGroupFromEntropy(
hexToBytes(entropy),
depositCount
);
// 3. Token Asset
const asset = caip19FungibleEvmToken(chainId, tokenAddress);
// 4. Order Signing
const orderDoc = quoteResponseToEip712Document(quoteResponse);
const signature = await signer.signEip712TypedData(orderDoc);
```
--------------------------------
### Watch for Solana Completion (TypeScript)
Source: https://docs.silentswap.com/core/silent-swap/solana-examples
Monitors the Solana network for the completion of a swap order by checking for incoming token transfers to the recipient's associated token account. This is a simplified polling example; a production implementation might use Solana webhooks or more sophisticated event watching. Requires Solana connection, token mint, recipient address, and facilitator group information.
```typescript
// Helper: Watch for completion on Solana
async function watchForSolanaCompletion(
connection: Connection,
tokenMint: string,
recipientAddress: string,
group: Awaited>
) {
// Get facilitator account for Solana (coin type 501)
const facilitator0Sol = await group.account('501', 0);
const facilitator0SolEvm = await facilitator0Sol.evmSigner();
// In a real implementation, you would watch for SPL token transfers
// This is a simplified example - you'd use Solana webhooks or polling
const recipientPubkey = new PublicKey(recipientAddress);
const mintPubkey = new PublicKey(tokenMint);
const ata = await getAssociatedTokenAddress(mintPubkey, recipientPubkey);
console.log(`Watching for tokens at: ${ata.toString()}`);
// Poll for token account balance
return new Promise((resolve) => {
const interval = setInterval(async () => {
try {
const account = await getAccount(connection, ata);
if (account.amount > 0n) {
console.log(`✓ Recipient received ${account.amount.toString()} tokens`);
clearInterval(interval);
resolve();
}
} catch (err) {
// Ignore errors if the account doesn't exist yet, continue polling
if (err.message.includes('failed to find')) {
console.log('Associated token account not found yet, continuing to poll...');
} else {
console.error('Error checking Solana account:', err);
}
}
}, 5000); // Poll every 5 seconds
});
}
```
--------------------------------
### Solana SOL to EVM Token Swap using React SDK
Source: https://docs.silentswap.com/react/silent-swap/solana-examples
This example demonstrates how to swap native SOL on Solana to an ERC-20 token on an EVM chain (e.g., USDC on Ethereum) using the SilentSwap React SDK. It requires both Solana and EVM wallets to be connected and configured. The function handles setting source and destination assets, amounts, and executing the swap transaction.
```javascript
'use client';
import React, { useState } from 'react';
import { useSilentSwap, useSwap } from '@silentswap/react';
import { useAccount, useWalletClient } from 'wagmi';
import { useSolanaAdapter } from '@silentswap/react';
import { useUserAddress } from '@/hooks/useUserAddress';
export function SolanaToEvmSwap() {
const { evmAddress, solAddress } = useUserAddress();
const { isConnected } = useAccount();
const { data: walletClient } = useWalletClient();
const { solanaConnector, solanaConnectionAdapter } = useSolanaAdapter();
const {
executeSwap,
isSwapping,
currentStep,
orderId,
orderComplete,
swapError,
} = useSilentSwap();
const { tokenIn, inputAmount, setInputAmount, destinations, setDestinations } = useSwap();
const [amount, setAmount] = useState('');
const handleSwap = async () => {
if (!solAddress || !evmAddress) {
alert('Both Solana and EVM wallets must be connected');
return;
}
if (!solanaConnector?.publicKey) {
alert('Solana wallet not connected');
return;
}
try {
// Set source asset to native SOL on Solana
// CAIP-19 format: solana:/slip44:501
setInputAmount(amount);
// Set destination (e.g., USDC on Ethereum)
setDestinations([
{
asset: 'eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC on Ethereum
contact: `caip10:eip155:1:${evmAddress}`, // Recipient EVM address
amount: '',
},
]);
// Execute swap - all parameters are required
const result = await executeSwap({
sourceAsset: 'solana:5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1/slip44:501', // Native SOL
sourceAmount: amount,
destinations: [
{
asset: 'eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
contact: `caip10:eip155:1:${evmAddress}`,
amount: '',
},
],
splits: [1], // Split percentages (must sum to 1.0)
senderContactId: `caip10:solana:*:${solAddress}`, // Solana sender in CAIP-10 format
integratorId: process.env.NEXT_PUBLIC_INTEGRATOR_ID, // Optional: for tracking
});
if (result) {
console.log('Swap initiated:', result.orderId);
}
} catch (error) {
console.error('Swap failed:', error);
alert(`Swap failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
return (
);
}
```
--------------------------------
### Create EVM Signer for viem
Source: https://docs.silentswap.com/core/silent-swap/complete-example
Creates an EVM signer adapter specifically for viem wallet clients. This function is essential for enabling interactions with Ethereum-compatible blockchains using the viem library.
```typescript
function createViemSigner(account, walletClient) {
// Implementation details for creating a viem signer
}
```
--------------------------------
### Install SilentSwap React and SDK Packages
Source: https://docs.silentswap.com/react/overview
Installs the necessary SilentSwap React and SDK packages using pnpm. These packages provide the core components and utilities for integrating SilentSwap into your project.
```bash
pnpm add @silentswap/react @silentswap/sdk
```
--------------------------------
### Install SilentSwap Vue and SDK
Source: https://docs.silentswap.com/vue/overview
Installs the necessary SilentSwap Vue and SDK packages using pnpm. These packages are required for integrating SilentSwap functionalities into your Vue application.
```bash
pnpm add @silentswap/vue @silentswap/sdk
```
--------------------------------
### Backend API Service for Silent Swaps (Node.js/Express)
Source: https://docs.silentswap.com/core/silent-swap/complete-example
This Node.js example demonstrates a backend API service using Express.js to handle silent swap requests. It sets up a POST endpoint '/api/silent-swap' that accepts recipient address, token details, and amount in the request body. It integrates with the `executeSilentSwap` function and returns a success or error response.
```javascript
import express from 'express';
import { executeSilentSwap } from './silent-swap';
const app = express();
app.use(express.json());
app.post('/api/silent-swap', async (req, res) => {
try {
const { recipientAddress, tokenAddress, amount, decimals } = req.body;
const result = await executeSilentSwap(
recipientAddress,
tokenAddress,
amount,
decimals
);
res.json({
success: true,
orderId: result.orderId,
depositHash: result.depositHash,
});
} catch (err) {
res.status(500).json({
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
});
}
});
app.listen(3000, () => {
console.log('Silent Swap API server running on port 3000');
});
```
--------------------------------
### Basic Usage of getSilentSwapClient
Source: https://docs.silentswap.com/vue/get-silent-swap-client
Demonstrates the basic usage of the getSilentSwapClient composable in a Vue 3 script setup. It initializes the client with a configuration object specifying the environment and base URL.
```typescript
```
--------------------------------
### Get Quote with Bridge for Cross-Chain Swaps (TypeScript)
Source: https://docs.silentswap.com/core/silent-swap/complete-example
This function is designed to get a quote for cross-chain swaps using a bridge. It outlines the initial step of calculating the USDC amount from the bridge, implying further steps would involve interacting with bridge-specific functionalities.
```typescript
async function getQuoteWithBridge(
silentswap: SilentSwapClient,
signer: EvmSigner,
group: Awaited>,
recipientAddress: `0x${string}`,
destinationTokenAddress: `0x${string}`,
sourceChainId: number,
sourceTokenAddress: `0x${string}`,
sourceAmount: string,
sourceTokenDecimals: number
) {
// Step 1: Calculate USDC amount from bridge
```
--------------------------------
### Prepare viem Signer with Private Key
Source: https://docs.silentswap.com/example/account
This snippet demonstrates how to prepare an EVM signer instance using a private key and viem. It imports necessary functions from 'viem' and 'viem/chains', creates a local viem account, initializes a viem client, and then implements the EvmSigner interface.
```typescript
import { privateKeyToAccount } from 'viem/accounts';
import { createWalletClient, http } from 'viem';
import { avalanche } from 'viem/chains';
import { publicActions } from 'viem/actions';
// create local viem account using a private key
const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
// create viem client
const client = createWalletClient({
account,
chain: avalanche,
transport: http(),
}).extend(publicActions);
// implement the EvmSigner interface for viem
const viemSigner = createViemSigner(account, client);
```
--------------------------------
### Initialize getSilentSwapAuth and Destructure Functions
Source: https://docs.silentswap.com/vue/get-silent-swap-auth
This example demonstrates how to initialize the `getSilentSwapAuth` composable within a Vue `
```
--------------------------------
### Telegram Bot for Bridge Quotes (TypeScript)
Source: https://docs.silentswap.com/core/simple-bridge/complete-example
This example shows how to create a Telegram bot using the 'telegraf' library that can fetch and display bridge quotes. When a user sends the '/quote' command, the bot uses '@silentswap/sdk' to get a quote for bridging USDC from Ethereum to Avalanche and replies with the quote details. It includes basic error handling for the quote fetching process.
```typescript
import { Telegraf } from 'telegraf';
import { getBridgeQuote } from '@silentswap/sdk';
const bot = new Telegraf(process.env.BOT_TOKEN!);
bot.command('quote', async (ctx) => {
try {
const quote = await getBridgeQuote(
1, // Ethereum
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
'1000000', // 1 USDC
43114, // Avalanche
'0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', // USDC.e
ctx.from.id.toString() // Use user ID as identifier
);
await ctx.reply(
`Bridge Quote:\n` +
`Provider: ${quote.provider}\n` +
`Output: ${quote.outputAmount}\n` +
`Fee: $${quote.feeUsd.toFixed(2)}
` +
`Slippage: ${quote.slippage.toFixed(2)}%`
);
} catch (err) {
await ctx.reply(`Error: ${err.message}`);
}
});
bot.launch();
```
--------------------------------
### Configuration: Using Environment Variables
Source: https://docs.silentswap.com/vue/get-silent-swap-client
Shows how to initialize the SilentSwap client using environment variables for configuration. This example focuses on setting the environment, implying that other configurations like baseUrl might be handled externally.
```typescript
```
--------------------------------
### Get Quote for Direct Swaps (TypeScript)
Source: https://docs.silentswap.com/core/silent-swap/complete-example
Retrieves a quote for a direct swap, specifically for USDC on Avalanche. It derives a viewer account, exports public keys for the facilitator group, and then requests a quote from the SilentSwap API with specified output parameters.
```typescript
async function getQuote(
silentswap: SilentSwapClient,
signer: EvmSigner,
group: Awaited>,
recipientAddress: `0x${string}`,
tokenAddress: `0x${string}`,
tokenAmount: string,
tokenDecimals: number
) {
// Derive viewer account
const viewer = await group.viewer();
const { publicKeyBytes: pk65_viewer } = viewer.exportPublicKey(
'*',
FacilitatorKeyType.SECP256K1
);
// Export public keys for facilitator group
const groupPublicKeys = await group.exportPublicKeys(1, [
...PublicKeyArgGroups.GENERIC,
]);
// Request quote
const [quoteError, quoteResponse] = await silentswap.quote({
signer: signer.address,
viewer: pk65_viewer,
outputs: [
{
method: DeliveryMethod.SNIP,
recipient: recipientAddress,
asset: caip19FungibleEvmToken(1, tokenAddress),
value: BigNumber(tokenAmount).shiftedBy(tokenDecimals).toFixed(0) as `${bigint}`,
facilitatorPublicKeys: groupPublicKeys[0],
},
],
});
if (quoteError || !quoteResponse) {
throw new Error(`Failed to get quote: ${quoteError?.type}: ${quoteError?.error}`);
}
return quoteResponse;
}
```
--------------------------------
### Essential Imports for SilentSwap SDK (Node.js)
Source: https://docs.silentswap.com/core/silent-swap/complete-example
Imports core components from the '@silentswap/sdk' package for managing Silent Swaps. This includes client creation, signer utilities, authentication methods, facilitator group management, order processing, and bridge utilities. It also imports BigNumber for handling large numbers.
```javascript
import {
// Client & Signer
createSilentSwapClient,
createViemSigner,
parseTransactionRequestForViem,
// Authentication
createSignInMessage,
createEip712DocForWalletGeneration,
createEip712DocForOrder,
// Facilitator Group
createHdFacilitatorGroupFromEntropy,
queryDepositCount,
hexToBytes,
// Order & Quote
quoteResponseToEip712Document,
// Bridge Utilities
solveOptimalUsdcAmount,
// Token Utilities
caip19FungibleEvmToken,
// Constants
DeliveryMethod,
FacilitatorKeyType,
PublicKeyArgGroups,
ENVIRONMENT,
GATEWAY_ABI,
} from '@silentswap/sdk';
import BigNumber from 'bignumber.js';
```
--------------------------------
### Polling for Bridge Status with SilentSwap
Source: https://docs.silentswap.com/core/simple-bridge/get-bridge-status
This example provides a robust way to poll for the status of a bridge transaction. It includes a maximum number of attempts and an interval between checks, ensuring that the application doesn't get stuck in an infinite loop and respects API rate limits. It handles success, failure, and refund states.
```javascript
import { getBridgeStatus, type BridgeProvider, type BridgeStatus } from '@silentswap/sdk';
async function pollBridgeStatus(
requestId: string,
provider: BridgeProvider,
maxAttempts: number = 60,
intervalMs: number = 5000
): Promise {
for (let i = 0; i < maxAttempts; i++) {
const status = await getBridgeStatus(requestId, provider);
if (status.status === 'success') {
console.log('Bridge completed successfully!');
return status;
}
if (status.status === 'failed' || status.status === 'refund') {
console.log('Bridge failed or refunded');
return status;
}
// Still pending, wait and retry
console.log(`Attempt ${i + 1}/${maxAttempts}: Still pending...`);
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
throw new Error('Bridge status polling timeout');
}
// Usage
const status = await pollBridgeStatus(
'request-id-123',
quoteResult.provider, // Use provider from quote
60, // Max 60 attempts
5000 // 5 second intervals
);
```
--------------------------------
### Initialize SilentSwapProvider in React
Source: https://docs.silentswap.com/react/silent-swap/introduction
Initializes the SilentSwapProvider component, which is the main entry point for integrating Silent Swap into a React application. It requires various client and connection configurations for EVM, Solana, and Bitcoin. Dependencies include '@silentswap/react' and '@silentswap/sdk'.
```javascript
import { SilentSwapProvider } from '@silentswap/react';
import { createSilentSwapClient, ENVIRONMENT } from '@silentswap/sdk';
const client = createSilentSwapClient({ environment: ENVIRONMENT.STAGING });
function App() {
const { isConnected, connector } = useAccount();
const { data: walletClient } = useWalletClient();
const { evmAddress, solAddress, bitcoinAddress } = useUserAddress();
const { solanaConnector, solanaConnectionAdapter } = useSolanaAdapter();
const { bitcoinConnector, bitcoinConnectionAdapter } = useBitcoinAdapter();
return (
{/* Your app components */}
);
}
```
--------------------------------
### Estimate Live Ingress/Egress with Vue
Source: https://docs.silentswap.com/vue/get-quote
This example demonstrates using the `estimateLive` method from `@silentswap/vue` to get real-time estimates for bridge transactions, including retention rates. It supports both 'ingress' and 'egress' directions and requires specifying chain IDs, token addresses, amounts, and prices. Dependencies include `@silentswap/vue` and `@silentswap/sdk`.
```typescript
import { ref } from 'vue';
import { getQuote, getSilentSwapClient } from '@silentswap/vue';
import { ENVIRONMENT } from '@silentswap/sdk';
const { client } = getSilentSwapClient({
config: {
environment: ENVIRONMENT.MAINNET,
},
});
const { estimateLive, ingressEstimates, egressEstimates } = getQuote({
address,
depositorAddress: client.s0xDepositorAddress,
});
const handleGetEstimate = async () => {
// Get ingress estimate (source chain to Avalanche)
const ingressResult = await estimateLive(
'ingress',
'eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC on Ethereum
1, // Chain ID
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // Token address
100, // Amount in human-readable units
1.0, // USD price per token
// Optional: externalSignal for abort control
// Optional: recipientAddress for Solana destinations
// Optional: isReverseCalculation for output-to-input
// Optional: targetAmount for reverse calculation
);
if (ingressResult) {
console.log('Retention rate:', ingressResult.estimate.samples[0]?.retention);
console.log('Gas amount:', ingressResult.gasAmount);
console.log('Provider:', ingressResult.provider);
}
};
```