### Install Garden SDK Packages Source: https://context7.com/gardenfi/garden.js/llms.txt Installs the necessary Garden SDK packages using npm. For browser environments using Vite, additional development plugins are also installed. ```bash # Install individual packages as needed npm install @gardenfi/core @gardenfi/orderbook @gardenfi/react-hooks @gardenfi/utils @gardenfi/wallet-connectors # For browser environments with Vite, install required plugins npm install vite-plugin-wasm vite-plugin-top-level-await vite-plugin-node-polyfills --save-dev ``` -------------------------------- ### Install @gardenfi/core Package Source: https://github.com/gardenfi/garden.js/blob/main/packages/core/README.md Installs the @gardenfi/core package using npm. This package is essential for performing atomic swaps. ```bash npm install `@gardenfi/core` ``` -------------------------------- ### Get Available Trading Strategies Source: https://context7.com/gardenfi/garden.js/llms.txt Retrieves all available trading strategies, including their minimum and maximum tradeable amounts, and fee structures. The strategies are returned as an object where keys represent order pairs. ```typescript import { Quote } from '@gardenfi/core'; const quote = new Quote('https://testnet.api.garden.finance/quote'); const strategiesResult = await quote.getStrategies(); if (strategiesResult.ok) { const strategies = strategiesResult.val; // Key format: "source_chain:source_asset::dest_chain:dest_asset" for (const [orderPair, strategy] of Object.entries(strategies)) { console.log(`Strategy: ${orderPair}`); console.log(` ID: ${strategy.id}`); console.log(` Min Amount: ${strategy.minAmount}`); console.log(` Max Amount: ${strategy.maxAmount}`); console.log(` Fee: ${strategy.fee} bps`); } } ``` -------------------------------- ### Get Swap Quotes with Quote Class Source: https://context7.com/gardenfi/garden.js/llms.txt Retrieves current pricing and available strategies for token swaps using the `Quote` class. It allows fetching quotes based on asset pairs or order pair strings, and optionally includes affiliate fees. ```typescript import { Quote } from '@gardenfi/core'; import { SupportedAssets } from '@gardenfi/orderbook'; const quote = new Quote('https://testnet.api.garden.finance/quote'); // Get quote using assets const quoteResult = await quote.getQuoteFromAssets( SupportedAssets.testnet.arbitrum_sepolia_WBTC, // From asset SupportedAssets.testnet.bitcoin_testnet_BTC, // To asset 10000, // Amount in lowest denomination false, // isExactOut (false = exact input) { affiliateFee: 10 } // Optional affiliate fee in bps ); if (quoteResult.ok) { console.log('Quotes:', quoteResult.val.quotes); // { "strategy_id_1": "9970", "strategy_id_2": "9965" } console.log('Input token price:', quoteResult.val.input_token_price); console.log('Output token price:', quoteResult.val.output_token_price); } // Or get quote using orderpair string const orderpair = 'arbitrum_sepolia:0xE918A5a47b8e0AFAC2382bC5D1e981613e63fB07::bitcoin_testnet:primary'; const quoteByPair = await quote.getQuote(orderpair, 10000, false); ``` -------------------------------- ### Execute Orders with Garden.js Source: https://context7.com/gardenfi/garden.js/llms.txt Starts a background process to monitor and execute pending orders for redeem/refund operations across various blockchain types. It utilizes event listeners for order status updates and can be stopped by calling the returned unsubscribe function. ```typescript import Garden from '@gardenfi/core'; const garden = new Garden({ /* config */ }); // Set up event listeners for order status updates garden.on('error', (order, error) => { console.error('Order error:', order.create_order.create_id, error); }); garden.on('success', (order, action, txHash) => { console.log('Order success:', order.create_order.create_id, action, txHash); }); garden.on('onPendingOrdersChanged', (orders) => { console.log('Pending orders count:', orders.length); orders.forEach(order => { console.log(`Order ${order.create_order.create_id}: ${order.status}`); }); }); garden.on('log', (orderId, message) => { console.log(`[${orderId}] ${message}`); }); garden.on('rbf', (order, txHash) => { console.log('RBF replacement:', order.create_order.create_id, txHash); }); // Start execution (returns unsubscribe function) const unsubscribe = await garden.execute(5000); // Poll every 5 seconds // Stop execution when done setTimeout(() => { unsubscribe(); console.log('Stopped order execution'); }, 300000); ``` -------------------------------- ### Initialize Garden SDK with EVM Wallet Source: https://context7.com/gardenfi/garden.js/llms.txt Demonstrates how to initialize the Garden SDK using an EVM wallet client. It shows creating a wallet client with Viem and then initializing the Garden class with environment and digest key. ```typescript import { Garden, Quote } from '@gardenfi/core'; import { Environment, DigestKey } from '@gardenfi/utils'; import { createWalletClient, http } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { arbitrumSepolia } from 'viem/chains'; // Create EVM wallet client const account = privateKeyToAccount('0x8fe869193b5010d1ee36e557478b43f2ade908f23cac40f024d4aa1cd1578a61'); const arbitrumWalletClient = createWalletClient({ account, chain: arbitrumSepolia, transport: http(), }); // Initialize Garden from wallets (recommended approach) const garden = Garden.fromWallets({ environment: Environment.TESTNET, // or Environment.MAINNET digestKey: '7fb6d160fccb337904f2c630649950cc974a24a2931c3fdd652d3cd43810a857', wallets: { evm: arbitrumWalletClient, // starknet: starknetAccountInterface, // Optional // solana: anchorProvider, // Optional }, }); // Or generate a random digest key const randomDigestKey = DigestKey.generateRandom(); if (randomDigestKey.ok) { const gardenWithRandomKey = Garden.fromWallets({ environment: Environment.TESTNET, digestKey: randomDigestKey.val, wallets: { evm: arbitrumWalletClient }, }); } ``` -------------------------------- ### Execute Atomic Swap with Garden.swap() Source: https://context7.com/gardenfi/garden.js/llms.txt Demonstrates how to use the `garden.swap()` method to create, quote, and match an atomic swap order. It includes defining swap parameters like assets, amounts, and additional data, and handling the result. ```typescript import { SupportedAssets } from '@gardenfi/orderbook'; // Define swap parameters const swapParams = { fromAsset: SupportedAssets.testnet.arbitrum_sepolia_WBTC, toAsset: SupportedAssets.testnet.bitcoin_testnet_BTC, sendAmount: '10000', // Amount in lowest denomination (satoshis for BTC) receiveAmount: '9970', // Expected receive amount after fees additionalData: { strategyId: 'ambcbnyr', // Strategy ID from quote btcAddress: 'tb1qxtztdl8qn24axe7dnvp75xgcns6pl5ka9tzjru', // Required for BTC swaps }, affiliateFee: [ // Optional integrator fee { fee: 10, address: '0x...' } // 10 bps ], }; // Execute swap const result = await garden.swap(swapParams); if (result.ok) { const matchedOrder = result.val; console.log('Order created and matched:', matchedOrder.create_order.create_id); console.log('Source swap:', matchedOrder.source_swap); console.log('Destination swap:', matchedOrder.destination_swap); } else { console.error('Swap failed:', result.error); } ``` -------------------------------- ### SupportedAssets: Predefined Asset Configurations (TypeScript) Source: https://context7.com/gardenfi/garden.js/llms.txt The SDK provides a comprehensive list of predefined asset configurations for various supported chains and tokens, available through the `SupportedAssets` and `Chains` objects. This simplifies the process of referencing assets for swaps and other operations by offering structured data including names, decimals, symbols, and chain identifiers for both testnet and mainnet environments. ```typescript import { SupportedAssets, Chains } from '@gardenfi/orderbook'; // Testnet assets const btcTestnet = SupportedAssets.testnet.bitcoin_testnet_BTC; // { name: 'BTC', decimals: 8, symbol: 'BTC', chain: 'bitcoin_testnet', ... } const wbtcArbitrum = SupportedAssets.testnet.arbitrum_sepolia_WBTC; // { name: 'Wrapped Bitcoin', decimals: 8, symbol: 'WBTC', chain: 'arbitrum_sepolia', ... } // Mainnet assets const btcMainnet = SupportedAssets.mainnet.bitcoin_BTC; const cbBTCBase = SupportedAssets.mainnet.base_cbBTC; const wbtcEthereum = SupportedAssets.mainnet.ethereum_WBTC; const solMainnet = SupportedAssets.mainnet.solana_SOL; const wbtcStarknet = SupportedAssets.mainnet.starknet_WBTC; // All supported chains console.log(Chains); // { bitcoin: 'bitcoin', ethereum: 'ethereum', arbitrum: 'arbitrum', // base: 'base', solana: 'solana', starknet: 'starknet', ... } ``` -------------------------------- ### Initiate EVM Swap with EvmRelay Source: https://context7.com/gardenfi/garden.js/llms.txt Initiates an EVM swap by locking funds in the HTLC contract on the source EVM chain. This method is part of the EVM-to-any swap process and requires the `evmHTLC` instance to be available. ```typescript import { isBitcoin } from '@gardenfi/orderbook'; import Garden from '@gardenfi/core'; // Assuming 'garden' is an instance of Garden and 'result' contains a matched order // const garden = new Garden({ /* config */ }); // const result = await garden.swap(...); const matchedOrder = result.val; // Check if source chain requires manual initiation if (!isBitcoin(matchedOrder.source_swap.chain)) { if (garden.evmHTLC) { const initResult = await garden.evmHTLC.initiate(matchedOrder); if (initResult.ok) { console.log('Initiate transaction hash:', initResult.val); } else { console.error('Initiate failed:', initResult.error); } } } ``` -------------------------------- ### Configure Vite for WASM and Polyfills Source: https://github.com/gardenfi/garden.js/blob/main/packages/core/README.md Sets up Vite for using WebAssembly (WASM) and Node.js polyfills. This configuration is necessary for browser environments that rely on these features, often required by packages like @gardenfi/core. ```bash npm install vite-plugin-wasm vite-plugin-top-level-await vite-plugin-node-polyfills --save-dev ``` ```typescript import { defineConfig } from "vite"; import wasm from "vite-plugin-wasm"; import { nodePolyfills } from "vite-plugin-node-polyfills"; import topLevelAwait from "vite-plugin-top-level-await"; export default defineConfig({ plugins: [ nodePolyfills(), wasm(), topLevelAwait(), //other plugins ], //other settings }); ``` -------------------------------- ### Vite Configuration for WebAssembly and Node.js Polyfills (TypeScript) Source: https://context7.com/gardenfi/garden.js/llms.txt This Vite configuration enables essential features for applications utilizing WebAssembly and Node.js modules. It includes plugins for `vite-plugin-wasm`, `vite-plugin-node-polyfills`, and `vite-plugin-top-level-await` to ensure proper handling of these functionalities. Additionally, it excludes `@gardenfi/core` from `optimizeDeps` to prevent potential build issues. ```typescript // vite.config.ts import { defineConfig } from 'vite'; import wasm from 'vite-plugin-wasm'; import { nodePolyfills } from 'vite-plugin-node-polyfills'; import topLevelAwait from 'vite-plugin-top-level-await'; export default defineConfig({ plugins: [ nodePolyfills(), wasm(), topLevelAwait(), ], optimizeDeps: { exclude: ['@gardenfi/core'], }, }); ``` -------------------------------- ### Create Orders Directly with Orderbook.createOrder() Source: https://context7.com/gardenfi/garden.js/llms.txt Allows direct order creation with full control over order parameters using the Orderbook class. Requires an attested quote and authentication object. Returns the created order ID or an error. ```typescript import { Orderbook } from '@gardenfi/orderbook'; import { Siwe, Url } from '@gardenfi/utils'; const orderbook = new Orderbook(new Url('https://testnet.api.garden.finance')); const auth = Siwe.fromDigestKey( new Url('https://testnet.api.garden.finance/auth'), digestKey ); // Create order with attested quote const createResult = await orderbook.createOrder(attestedQuote, auth); if (createResult.ok) { const createOrderId = createResult.val; console.log('Order created with ID:', createOrderId); // Fetch the matched order const orderResult = await orderbook.getOrder(createOrderId, true); // true = matched if (orderResult.ok) { console.log('Matched order:', orderResult.val); } } ``` -------------------------------- ### Webpack/Next.js Configuration for WebAssembly (JavaScript) Source: https://context7.com/gardenfi/garden.js/llms.txt This configuration snippet demonstrates how to enable asynchronous WebAssembly support within a Next.js or Webpack environment. By modifying the webpack configuration, specifically by setting `config.experiments.asyncWebAssembly` to `true`, it ensures that WebAssembly modules can be loaded and executed correctly in the application. ```javascript // next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { webpack: function (config, options) { config.experiments = { ...config.experiments, asyncWebAssembly: true, }; return config; }, }; module.exports = nextConfig; ``` -------------------------------- ### GardenProvider: React Integration for Garden SDK (TypeScript) Source: https://context7.com/gardenfi/garden.js/llms.txt The GardenProvider component facilitates the integration of the Garden SDK into React applications by providing necessary context and hooks. It requires configuration including the environment and wallet clients. Child components can then use the useGarden hook to access core functionalities like fetching quotes, managing orders, and initiating swaps. ```typescript import { GardenProvider, useGarden } from '@gardenfi/react-hooks'; import { Environment } from '@gardenfi/utils'; import { createWalletClient, http } from 'viem'; import { arbitrumSepolia } from 'viem/chains'; // Wrap your app with GardenProvider function App() { const walletClient = createWalletClient({ account, chain: arbitrumSepolia, transport: http(), }); return ( ); } // Use the hook in child components function SwapComponent() { const { garden, swapAndInitiate, pendingOrders, getQuote, orderBook } = useGarden(); const handleSwap = async () => { // Get quote first const quoteResult = await getQuote({ fromAsset: SupportedAssets.testnet.arbitrum_sepolia_WBTC, toAsset: SupportedAssets.testnet.bitcoin_testnet_BTC, amount: 10000, }); if (!quoteResult.ok) return; // Execute swap with automatic initiation const result = await swapAndInitiate({ fromAsset: SupportedAssets.testnet.arbitrum_sepolia_WBTC, toAsset: SupportedAssets.testnet.bitcoin_testnet_BTC, sendAmount: '10000', receiveAmount: Object.values(quoteResult.val.quotes)[0], additionalData: { strategyId: Object.keys(quoteResult.val.quotes)[0], btcAddress: 'tb1q...', }, }); if (result.ok) { console.log('Swap initiated:', result.val.create_order.create_id); } }; return (

Pending orders: {pendingOrders.length}

); } ``` -------------------------------- ### Configure Webpack for Async WASM Source: https://github.com/gardenfi/garden.js/blob/main/packages/core/README.md Configures Webpack to enable asynchronous WebAssembly (WASM) support. This is particularly relevant for frameworks like Next.js and is crucial for integrating WASM modules within the build process. ```typescript /** @type {import('next').NextConfig} */ const nextConfig = { //other nextConfig options webpack: function (config, options) { //other webpack config options config.experiments = { ...config.experiments, asyncWebAssembly: true, }; return config; }, }; module.exports = nextConfig; ``` -------------------------------- ### Query User Orders with Orderbook.getMatchedOrders() Source: https://context7.com/gardenfi/garden.js/llms.txt Retrieves orders associated with a specific user address, supporting pagination and status filtering. It returns an array of orders, pagination details, and total counts. Useful for fetching pending or fulfilled orders. ```typescript // Get all matched orders for a user const ordersResult = await orderbook.getMatchedOrders( '0x52FE8afbbB800a33edcbDB1ea87be2547EB30000', // User address 'pending', // Status: 'all' | 'pending' | 'fulfilled' { page: 1, per_page: 10 } // Pagination ); if (ordersResult.ok) { const { data, page, total_pages, total_items } = ordersResult.val; console.log(`Page ${page} of ${total_pages} (${total_items} total orders)`); data.forEach(order => { console.log(`Order: ${order.create_order.create_id}`); console.log(` From: ${order.source_swap.chain} -> To: ${order.destination_swap.chain}`); console.log(` Amount: ${order.source_swap.amount} -> ${order.destination_swap.amount}`); console.log(` Status: ${order.source_swap.redeem_tx_hash ? 'Completed' : 'Pending'}`); }); } ``` -------------------------------- ### Real-time Order Updates with Orderbook.subscribeOrders() Source: https://context7.com/gardenfi/garden.js/llms.txt Subscribes to real-time order updates via polling. The provided callback function is invoked whenever orders change. Supports filtering by status and pagination. An unsubscribe function is returned to stop updates. ```typescript const handleOrderUpdate = async (orders) => { console.log(`Received ${orders.data.length} orders`); orders.data.forEach(order => { console.log(`Order ${order.create_order.create_id} updated`); }); }; // Subscribe to matched orders (polling every 5 seconds) const unsubscribe = await orderbook.subscribeOrders( '0x52FE8afbbB800a33edcbDB1ea87be2547EB30000', // Account address true, // matched = true 5000, // Polling interval in ms handleOrderUpdate, // Callback 'pending', // Status filter { page: 1, per_page: 100 } // Pagination ); // Unsubscribe after 60 seconds setTimeout(() => { unsubscribe(); console.log('Unsubscribed from orders'); }, 60000); ``` -------------------------------- ### Generate User Identity with DigestKey Source: https://context7.com/gardenfi/garden.js/llms.txt The DigestKey class generates deterministic user identities (Ethereum addresses) and secrets from a 32-byte private key. It can create from an existing key or generate a random one. This is crucial for atomic swaps and user authentication within Garden. ```typescript import { DigestKey } from '@gardenfi/utils'; // Create from existing key const digestKeyResult = DigestKey.from('7fb6d160fccb337904f2c630649950cc974a24a2931c3fdd652d3cd43810a857'); if (digestKeyResult.ok) { const digestKey = digestKeyResult.val; console.log('User ID (address):', digestKey.userId); // Output: 0x52FE8afbbB800a33edcbDB1ea87be2547EB30000 console.log('Digest Key:', digestKey.digestKey); } // Generate random key const randomResult = DigestKey.generateRandom(); if (randomResult.ok) { const randomKey = randomResult.val; console.log('Random User ID:', randomKey.userId); console.log('Random Digest Key:', randomKey.digestKey); } // Use with Garden const garden = Garden.fromWallets({ environment: Environment.TESTNET, digestKey: digestKey, // Can pass DigestKey instance or string wallets: { evm: walletClient }, }); ``` -------------------------------- ### SecretManager: Generate Atomic Swap Secrets (TypeScript) Source: https://context7.com/gardenfi/garden.js/llms.txt The SecretManager class generates deterministic secrets for HTLC swaps using a digest key and nonce. It can be initialized either from a digest key directly or by deriving it from a wallet client via a user signature. The generated secret and its corresponding hash are crucial for setting up and resolving HTLC contracts. ```typescript import { SecretManager } from '@gardenfi/core'; // Create from digest key const secretManager = SecretManager.fromDigestKey( '7fb6d160fccb337904f2c630649950cc974a24a2931c3fdd652d3cd43810a857' ); // Generate secret for a specific nonce (usually timestamp or order count) const nonce = Date.now().toString(); const secretResult = await secretManager.generateSecret(nonce); if (secretResult.ok) { console.log('Secret:', secretResult.val.secret); // 0x... (32-byte hex) console.log('Secret Hash:', secretResult.val.secretHash); // 0x... (SHA256 of secret, used in HTLC) } // Or create from wallet client (derives key via signature) const secretManagerFromWallet = SecretManager.fromWalletClient(walletClient); await secretManagerFromWallet.initialize(); // Prompts user signature const digestKey = await secretManagerFromWallet.getDigestKey(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.