### 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 (
Pending orders: {pendingOrders.length}