### Local Development Setup for Sugar SDK Source: https://github.com/velodrome-finance/sdk.js/blob/main/README.md Commands for setting up the local development environment for the Sugar SDK. This includes activating the correct Node.js version, installing dependencies, and populating environment variables. ```bash nvm use && npm i ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md Installs the necessary dependencies for the Node.js demonstration scripts. This is a standard npm command. ```bash npm install ``` -------------------------------- ### Install Sugar SDK and Peer Dependencies Source: https://github.com/velodrome-finance/sdk.js/blob/main/README.md Installs the Sugar SDK along with necessary peer dependencies like @wagmi/core and viem. This is the first step to using the SDK in your project. ```bash npm install \ @dromos-labs/sdk.js \ @wagmi/core \ viem ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-web/README.md Installs all necessary packages for the project using npm. This is a prerequisite for building and running the application. ```shell npm i ``` -------------------------------- ### Swap 0.0005 ETH to Aero Example (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md An example command demonstrating how to swap 0.0005 ETH to Aero using the swap-with-pk script. It shows how to specify ETH as a token and the corresponding amount in wei. ```bash npm run swap-with-pk -- \ --fromToken eth \ --toToken 0x940181a94a35a4569e4529a3cdfb74e38fd98631 \ --amount 500000000000000 \ --slippage 0.01 \ --privateKey YOUR_PRIVATE_KEY ``` -------------------------------- ### Run Velodrome Demo App Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-web/README.md Launches the demo application configured for Velodrome. This command starts the development server for the demo app within the demo workspace. ```shell npm run dev-velo -w demo ``` -------------------------------- ### Swap 1 USDC to Aero Example (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md An example command demonstrating how to swap 1 USDC to Aero with 1% slippage using the swap-with-pk script. It includes token addresses, amount in wei, slippage, and a placeholder for the private key. ```bash npm run swap-with-pk -- \ --fromToken 0x833589fcd6edb6e08f4c7c32d4f71b54bda02913 \ --toToken 0x940181a94a35a4569e4529a3cdfb74e38fd98631 \ --amount 1000000 \ --slippage 0.01 \ --privateKey YOUR_PRIVATE_KEY ``` -------------------------------- ### Simplified Drome Initialization with Default Settings Source: https://github.com/velodrome-finance/sdk.js/blob/main/design/01-config/idea.md Provides a shortcut for initializing the Drome SDK with sensible defaults. This allows for a more compact initialization phase, reducing the setup to a single line of code for most applications, while still allowing for customization. ```typescript import { getDefaultDrome } from "sugar-sdk"; const config = getDefaultDrome(); ``` -------------------------------- ### Run Aerodrome Demo App Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-web/README.md Launches the demo application configured for Aerodrome. This command starts the development server for the demo app within the demo workspace. ```shell npm run dev-aero -w demo ``` -------------------------------- ### React Hook for Swap Execution with SDK.js Source: https://context7.com/velodrome-finance/sdk.js/llms.txt A React hook (`useSwap`) that encapsulates the process of executing a token swap using the Dromos Labs SDK.js. It manages loading states, errors, and handles token approvals before initiating the swap. Requires a `wagmi` setup for wallet connection. ```typescript import { useState } from "react"; import { useAccount } from "wagmi"; import { getListedTokens, getQuoteForSwap, swap, approve, type Token, type Quote, type SugarWagmiConfig, } from "@dromos-labs/sdk.js"; export function useSwap(config: SugarWagmiConfig) { const { address } = useAccount(); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const executeSwap = async ( fromToken: Token, toToken: Token, amountIn: bigint, slippage: number = 0.005 ) => { if (!address) { setError("Wallet not connected"); return null; } setLoading(true); setError(null); try { // Get quote const quote = await getQuoteForSwap({ config, fromToken, toToken, amountIn, }); if (!quote) { throw new Error("No route found for this swap"); } // Approve tokens await approve({ config, tokenAddress: fromToken.address, spenderAddress: quote.spenderAddress, amount: quote.amount, chainId: fromToken.chainId, waitForReceipt: true, }); // Execute swap const txHash = await swap({ config, quote, slippage, waitForReceipt: true, }); setLoading(false); return txHash; } catch (err) { setError(err instanceof Error ? err.message : "Unknown error"); setLoading(false); return null; } }; return { executeSwap, loading, error }; } // Usage in component: // function SwapButton() { // const { executeSwap, loading, error } = useSwap(config); // // const handleSwap = async () => { // const hash = await executeSwap(usdc, aero, 1000000n); // if (hash) console.log("Success:", hash); // }; // // return ( // // ); // } ``` -------------------------------- ### Initialize Drome SDK Configuration Source: https://github.com/velodrome-finance/sdk.js/blob/main/design/01-config/idea.md Initializes the Drome SDK by creating a Wagmi configuration and integrating it with Drome-specific settings. This example demonstrates how to set up chains, connectors, and transports, with options for error handling. It supports conditional configuration based on the Vite mode for 'aero' or 'velo'. ```typescript import { aerodromeConfig, type DromeWagmiConfig, initDrome, velodromeConfig } from "sugar-sdk"; import { createConfig, http, injected } from "wagmi"; import { base, celo, type Chain, fraxtal, ink, lisk, mainnet, metalL2, mode, optimism, soneium, superseed, swellchain, unichain } from "wagmi/chains"; function getTransports(chains: Chain[]) { return Object.fromEntries( chains.map((chain) => { const rpc = import.meta.env["VITE_RPC_" + chain.id]; if (!rpc) { throw new Error( `Missing RPC URL. Please pass VITE_RPC_${chain.id} as an environment variable.` ); } return [chain.id, http(rpc, { batch: true })]; }) ); } export let config: DromeWagmiConfig; if (import.meta.env.MODE === "aero") { const aerodromChains = [base, optimism] as [Chain, ...Chain[]]; config = initDrome( createConfig({ chains: aerodromChains, connectors: [injected()], transports: getTransports(aerodromChains), }), { ...aerodromeConfig, onError(error) { console.log(error); }, } ); } else if (import.meta.env.MODE === "velo") { const velodromChains = [optimism, mode, lisk, /*...*/, mainnet, ] as [Chain, ...Chain[]]; config = initDrome( createConfig({ chains: velodromChains, connectors: [injected()], transports: getTransports(velodromChains), }), { ...velodromeConfig, onError(error) { throw error; }, } ); } else { throw new Error("Vite mode must be set to aero or velo."); } ``` -------------------------------- ### Get Quote For Swap Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md Fetches the best available quote to swap a token. ```APIDOC ## GET /api/swap/quote ### Description Fetches the best available quote to swap tokens. ### Method GET ### Endpoint /api/swap/quote ### Parameters #### Query Parameters - **fromToken** (Token) - Required - Source Token object. - **toToken** (Token) - Required - Destination Token object. - **amountIn** (bigint) - Required - Amount of fromToken to swap. - **batchSize** (number) - Optional - Candidate routes per multicall batch (default 50). - **concurrentLimit** (number) - Optional - Number of batches processed in parallel (default 10). ### Request Example ```json { "fromToken": { ... }, "toToken": { ... }, "amountIn": "1000000", "batchSize": 50, "concurrentLimit": 10 } ``` ### Response #### Success Response (200) - **Quote** (object) - Best swap route information. - **null** - When no swap route is found. #### Response Example ```json { "path": [ { "fromToken": { ... }, "toToken": { ... }, "decimals": 18, "address": "0x..." }, { "fromToken": { ... }, "toToken": { ... }, "decimals": 6, "address": "0x..." } ], "amount": "950000", "amountOut": "950000", "fromToken": { ... }, "toToken": { ... }, "priceImpact": "100", "spenderAddress": "0x..." } ``` ``` -------------------------------- ### Initialize Sugar SDK with Existing Wagmi Config (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Attaches Sugar SDK configuration to an existing wagmi config instance. This is useful for custom wagmi settings or integrating with existing wagmi setups. It takes a wagmi config and a Sugar config object, returning a combined configuration. ```typescript import { createConfig } from "@wagmi/core"; import { baseConfig, init } from "@dromos-labs/sdk.js"; // Create custom wagmi config const wagmiConfig = createConfig({ chains: [optimism, base], transports: { 10: http("https://mainnet.optimism.io"), 8453: http("https://mainnet.base.org"), }, // ... other wagmi options }); // Attach Sugar config const config = init(wagmiConfig, { ...baseConfig, // Customize Sugar settings MAX_HOPS: 5, POOLS_PAGE_SIZE: 500, }); ``` -------------------------------- ### Get Quote for Token Swap with SDK.js Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Retrieves a quote for a token swap on the base chain using the SDK.js. It fetches listed tokens, finds the desired input and output tokens, and then requests a swap quote including details like amount out, price impact, and spender address. Handles cases where no route is found. ```typescript import { getDefaultConfig, getListedTokens, getQuoteForSwap, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [{ chain: base, rpcUrl: process.env.BASE_RPC }] }); // Get tokens const tokens = await getListedTokens({ config }); const usdc = tokens.find(t => t.symbol === "USDC" && t.chainId === base.id); const aero = tokens.find(t => t.symbol === "AERO" && t.chainId === base.id); // Request quote for 1000 USDC -> AERO const amountIn = 1000_000_000n; // 1000 USDC (6 decimals) const quote = await getQuoteForSwap({ config, fromToken: usdc, toToken: aero, amountIn, batchSize: 50, // Optional: routes per batch (default: 50) concurrentLimit: 10, // Optional: parallel batches (default: 10) }); if (!quote) { console.log("No route found for this swap"); process.exit(1); } // Quote includes all swap details console.log("Quote Details:"); console.log(` Amount In: ${quote.amount} (${usdc.symbol})`); console.log(` Amount Out: ${quote.amountOut} (${aero.symbol})`); console.log(` Price Impact: ${quote.priceImpact}%`); console.log(` Route Hops: ${quote.path.nodes.length}`); console.log(` Spender Address: ${quote.spenderAddress}`); // Format output for display const amountOutFormatted = Number(quote.amountOut) / 10 ** aero.decimals; console.log(` Expected: ${amountOutFormatted.toFixed(6)} ${aero.symbol}`); ``` -------------------------------- ### Get Call Data For Swap Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md Generates router calldata and minimum-out details without sending a transaction. ```APIDOC ## POST /api/swap/calldata ### Description Generates router calldata and minimum-out details without sending a transaction. Returns null when no quote is available. ### Method POST ### Endpoint /api/swap/calldata ### Parameters #### Request Body - **fromToken** (Token) - Required - Source Token. - **toToken** (Token) - Required - Destination Token. - **amountIn** (bigint) - Required - Amount to swap, expressed in smallest units. - **account** (Address) - Required - Wallet address. - **slippage** (number) - Required - Decimal slippage tolerance between 0 and 1 (e.g., 0.01 for 1%). ### Request Example ```json { "fromToken": { ... }, "toToken": { ... }, "amountIn": "1000000", "account": "0x...", "slippage": 0.05 } ``` ### Response #### Success Response (200) - **CallDataForSwap** (object) - Encoded commands, inputs, min-out, and price impact. - **null** - When no route is available. #### Response Example ```json { "commands": "0x...", "inputs": [ "0x...", "0x..." ], "minAmountOut": "900000", "priceImpact": "150" } ``` ``` -------------------------------- ### Get Call Data for Custom Swap Transaction with SDK.js Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Obtains encoded call data for a token swap without executing it, intended for custom transaction flows on the base chain. It requires configuration, token details, amount, recipient account, and slippage tolerance. The output includes commands, inputs, minimum amount out, and price impact for use in other transaction builders. ```typescript import { getDefaultConfig, getListedTokens, getCallDataForSwap, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [{ chain: base, rpcUrl: process.env.BASE_RPC }] }); const tokens = await getListedTokens({ config }); const usdc = tokens.find(t => t.symbol === "USDC" && t.chainId === base.id); const weth = tokens.find(t => t.symbol === "WETH" && t.chainId === base.id); // Get encoded call data without executing swap const callData = await getCallDataForSwap({ config, fromToken: usdc, toToken: weth, amountIn: 100_000_000n, // 100 USDC account: "0x1234567890123456789012345678901234567890", slippage: 0.01, // 1% slippage tolerance }); if (!callData) { console.log("No route found"); process.exit(1); } // callData contains encoded transaction parameters console.log("Call Data:"); console.log(` Commands: ${callData.commands}`); console.log(` Inputs: ${callData.inputs.length} input parameters`); console.log(` Min Amount Out: ${callData.minAmountOut}`); console.log(` Price Impact: ${callData.priceImpact}`); ``` -------------------------------- ### Get Swap Quote with Sugar SDK in Node.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/using-node.md Obtains the best quote for a token swap between two specified tokens using `getQuoteForSwap`. The function returns a `Quote` object containing the expected output amount, price impact, routing path, and the necessary spender address for approval. This requires the SDK `config`, `fromToken`, `toToken`, and `amountIn`. ```typescript import { getListedTokens, getQuoteForSwap } from "@dromos-labs/sdk.js"; const tokens = await getListedTokens({ config }); const usdc = tokens.find( (token) => token.chainId === 10 && token.symbol === "USDC" ); const weth = tokens.find( (token) => token.chainId === 10 && token.symbol === "WETH" ); const quote = await getQuoteForSwap({ config, fromToken: usdc, toToken: weth, amountIn: 1_000_000n, // 1,000 USDC (6 decimals) }); if (!quote) { throw new Error("No swap route found."); } console.log( `Expected output: ${quote.amountOut} of ${quote.toToken.symbol}` ); ``` -------------------------------- ### Build SDK using npm Source: https://github.com/velodrome-finance/sdk.js/blob/main/AGENTS.md Command to build the Sugar SDK. Ensure the correct Node.js environment is activated before running. This command navigates to the SDK package directory and executes the build script. ```bash cd packages/sugar-sdk && npm run build ``` -------------------------------- ### Configure Sugar SDK with Multiple Chains Source: https://github.com/velodrome-finance/sdk.js/blob/main/README.md Demonstrates how to create a multi-chain configuration using `getDefaultConfig` from the Sugar SDK. This configuration is essential for interacting with different blockchain networks. It requires RPC URLs for each chain. ```typescript import { getDefaultConfig, getListedTokens, optimism, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [ { chain: optimism, rpcUrl: process.env.OP_RPC! }, { chain: base, rpcUrl: process.env.BASE_RPC! }, ], }); const tokens = await getListedTokens({ config }); ``` -------------------------------- ### Build Sugar SDK for Aerodrome Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-web/README.md Builds the Sugar SDK specifically for the Aerodrome environment within the demo workspace. This command compiles the SDK to be used by the demo application. ```shell npm run build -w @dromos-labs/sdk.js ``` -------------------------------- ### Run Tests using npm Source: https://github.com/velodrome-finance/sdk.js/blob/main/AGENTS.md Command to execute tests for the project. It's recommended to activate the appropriate Node.js environment using `nvm use` before running this command to ensure test integrity. ```bash npm test ``` -------------------------------- ### Execute Swap with Private Key (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md Executes a token swap using an external private key for signing. This script demonstrates external transaction signing and requires specific arguments for tokens, amount, and the private key. ```bash npm run swap-with-pk -- --fromToken
--toToken
--amount --privateKey [--slippage ] [--no-wait] ``` -------------------------------- ### Complete External Signing Workflow (TypeScript) Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Demonstrates the full process of building, signing, and submitting a swap transaction using external signing. It includes token approval and the swap execution itself, leveraging read-only configuration for transaction building and external account signing. This enables separation of concerns for backend and frontend applications. ```typescript import { getDefaultConfig, getListedTokens, getQuoteForSwap, swap, submitSignedTransaction, base, } from "@dromos-labs/sdk.js"; import { privateKeyToAccount } from "viem/accounts"; import { encodeFunctionData, Hex } from "viem"; // Phase 1: Build transaction (read-only, no wallet) const readOnlyConfig = getDefaultConfig({ chains: [{ chain: base, rpcUrl: process.env.BASE_RPC }], }); const tokens = await getListedTokens({ config: readOnlyConfig }); const usdc = tokens.find(t => t.symbol === "USDC" && t.chainId === base.id); const aero = tokens.find(t => t.symbol === "AERO" && t.chainId === base.id); const quote = await getQuoteForSwap({ config: readOnlyConfig, fromToken: usdc, toToken: aero, amountIn: 1_000_000n, }); // Get unsigned swap transaction const privateKey = process.env.PRIVATE_KEY as Hex; const account = privateKeyToAccount(privateKey); const unsignedTx = await swap({ config: readOnlyConfig, quote, account: account.address, slippage: 0.01, unsignedTransactionOnly: true, }); // Phase 2: External signing (can be HSM, hardware wallet, etc.) console.log("Signing with external key..."); // Step 1: Sign approval transaction const erc20Abi = [ { type: "function", name: "approve", inputs: [ { name: "spender", type: "address" }, { name: "amount", type: "uint256" }, ], outputs: [{ name: "", type: "bool" }], stateMutability: "nonpayable", }, ] as const; const approvalData = encodeFunctionData({ abi: erc20Abi, functionName: "approve", args: [quote.spenderAddress, quote.amount], }); const signedApproval = await account.signTransaction({ to: quote.fromToken.address, data: approvalData, value: 0n, chainId: base.id, nonce: 0, // Get from getTransactionCount in production gas: 100000n, maxFeePerGas: 1000000000n, maxPriorityFeePerGas: 1000000000n, }); // Submit approval await submitSignedTransaction({ config: readOnlyConfig, signedTransaction: signedApproval, waitForReceipt: true, }); console.log("Tokens approved"); // Step 2: Sign and submit swap transaction const signedSwap = await account.signTransaction({ to: unsignedTx.to, data: unsignedTx.data, value: unsignedTx.value, chainId: unsignedTx.chainId, nonce: 1, // Get from getTransactionCount in production gas: 500000n, maxFeePerGas: 1000000000n, maxPriorityFeePerGas: 1000000000n, }); const txHash = await submitSignedTransaction({ config: readOnlyConfig, // Note: Still using read-only config! signedTransaction: signedSwap, waitForReceipt: true, }); console.log(`Swap executed: ${txHash}`); console.log(`https://basescan.org/tx/${txHash}`); // This pattern enables: // - Complete separation of transaction building from signing // - Integration with any signing infrastructure // - Backend services that build txs without wallet access // - Frontend apps that delegate signing to users // - Enterprise key management systems ``` -------------------------------- ### Configure RPC URL (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md Sets up the environment variable for the RPC URL of the Base chain. This is crucial for network communication. ```bash VITE_RPC_URL_8453=https://your-base-rpc-url ``` -------------------------------- ### Configure SDK with Chains - TypeScript Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/overview.md Sets up the Sugar SDK configuration by defining the chains to be used, including their network and RPC URL. This is a foundational step before interacting with other SDK features. It extends Wagmi's configuration with Sugar-specific settings. ```typescript import { getDefaultConfig, optimism, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [ { chain: optimism, rpcUrl: "https://mainnet.optimism.io" }, { chain: base, rpcUrl: "https://mainnet.base.org" } ] }); ``` -------------------------------- ### Execute a Token Swap with SDK.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md This snippet demonstrates a complete token swap process using the SDK.js. It includes fetching listed tokens, retrieving a swap quote, approving the necessary tokens, and executing the swap. Ensure that the 'config' object is properly initialized before use. The function returns the transaction hash upon successful swap confirmation. ```typescript import { approve, getListedTokens, getQuoteForSwap, swap, } from "@dromos-labs/sdk.js"; const tokens = await getListedTokens({ config }); const fromToken = tokens.find((token) => token.symbol === "USDC" && token.chainId === 10); const toToken = tokens.find((token) => token.symbol === "WETH" && token.chainId === 10); if (!fromToken || !toToken) { throw new Error("Required tokens are not available in the current configuration."); } const quote = await getQuoteForSwap({ config, fromToken, toToken, amountIn: 1_000_000n }); if (!quote) throw new Error("No route found."); await approve({ config, tokenAddress: quote.fromToken.address, spenderAddress: quote.spenderAddress, amount: quote.amount, chainId: quote.fromToken.chainId, }); const txHash = await swap({ config, quote, slippage: 0.005, waitForReceipt: true, }); console.log(`Swap confirmed: ${txHash}`); ``` -------------------------------- ### Configure Multi-Chain SDK with Node.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/using-node.md Sets up a multi-chain configuration for the Sugar SDK using `getDefaultConfig`. This function allows you to specify the chains and their corresponding RPC URLs, which are crucial for fetching data. It's recommended to use environment variables for RPC URLs to manage sensitive information securely. ```typescript import { getDefaultConfig, optimism, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [ { chain: optimism, rpcUrl: process.env.OP_RPC! }, { chain: base, rpcUrl: process.env.BASE_RPC! }, ], }); ``` -------------------------------- ### Execute Token Swap with Wallet Connection using SDK.js Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Executes a token swap on the optimism chain, requiring a connected wallet (e.g., via wagmi). It first retrieves tokens and a swap quote, then proceeds to approve the token spending and finally executes the swap transaction. Includes error handling and logging for transaction hashes and explorer links. Assumes `waitForReceipt` is true for confirmation. ```typescript import { getDefaultConfig, getListedTokens, getQuoteForSwap, swap, approve, optimism } from "@dromos-labs/sdk.js"; // Assumes wallet is connected via wagmi connectors (e.g., injected) const config = getDefaultConfig({ chains: [{ chain: optimism, rpcUrl: process.env.OP_RPC }] }); // Get tokens and quote const tokens = await getListedTokens({ config }); const usdc = tokens.find(t => t.symbol === "USDC" && t.chainId === optimism.id); const velo = tokens.find(t => t.symbol === "VELO" && t.chainId === optimism.id); const amountIn = 50_000_000n; // 50 USDC const quote = await getQuoteForSwap({ config, fromToken: usdc, toToken: velo, amountIn, }); if (!quote) { throw new Error("No quote available"); } try { // Step 1: Approve token spending console.log("Approving USDC..."); const approvalHash = await approve({ config, tokenAddress: usdc.address, spenderAddress: quote.spenderAddress, amount: quote.amount, chainId: optimism.id, waitForReceipt: true, }); console.log(`Approval TX: ${approvalHash}`); // Step 2: Execute swap console.log("Executing swap..."); const swapHash = await swap({ config, quote, slippage: 0.005, // 0.5% slippage (default) waitForReceipt: true, }); console.log(`Swap successful!`); console.log(`TX Hash: ${swapHash}`); console.log(`Explorer: https://optimistic.etherscan.io/tx/${swapHash}`); } catch (error) { console.error("Swap failed:", error); throw error; } ``` -------------------------------- ### Honey Configuration Structure (YAML) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/honey/README.md Defines the structure for `honey.yaml` which configures the multi-chain testing environment. It specifies wallet private keys, target chain details (name, ID), token balances with addresses and amounts, and large holder addresses for transfers. ```yaml honey: - wallet: - pk: "0x..." # Private key for test wallet - we are using Anvil's preset - chains: - name: "OP" id: "11155420" balance: - token: "USDC" address: "0x..." amount: 1000000000000000000000 holder: "0x..." # Large holder to transfer from ``` -------------------------------- ### Initialize Multi-Chain SDK Configuration (TypeScript) Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Configures the Sugar SDK to support multiple blockchain networks by providing chain objects and their respective RPC URLs. This function utilizes default configurations and is essential for multi-chain operations. It expects an array of chain configurations, each with a chain object and an RPC URL. ```typescript import { getDefaultConfig, optimism, base, mode } from "@dromos-labs/sdk.js"; // Configure SDK with multiple chains const config = getDefaultConfig({ chains: [ { chain: optimism, rpcUrl: "https://mainnet.optimism.io" }, { chain: base, rpcUrl: "https://mainnet.base.org" }, { chain: mode, rpcUrl: "https://mainnet.mode.network" } ] }); // config is type SugarWagmiConfig with sugarConfig embedded // Use this config object for all SDK function calls // Supported chains: optimism (10), unichain (130), fraxtal (252), // lisk (1135), metalL2 (1750), soneium (1868), swellchain (1923), // superseed (5330), base (8453), mode (34443), celo (42220), ink (57073) ``` -------------------------------- ### Execute Swap with Private Key using TSX (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md Executes a token swap using an external private key for signing directly with TSX. This is an alternative to using npm run scripts for executing TypeScript files. ```bash tsx swap-with-pk.ts --fromToken
--toToken
--amount --privateKey ``` -------------------------------- ### Create Default Sugar SDK Configuration (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Generates a default Sugar SDK configuration, setting up wagmi, enabling HTTP batching, and returning a combined config. It requires an array of chain configurations with chain objects and RPC URLs. ```typescript import { getDefaultConfig, optimism, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [ { chain: optimism, rpcUrl: "https://mainnet.optimism.io" }, { chain: base, rpcUrl: "https://mainnet.base.org" } ] }); // Use config throughout your app // const tokens = await getListedTokens({ config }); ``` -------------------------------- ### Run Local Quote Comparison (Bash) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/claudius/tasks/quotes.md Executes a local quote comparison using the sugar-sdk CLI. It requires specifying the 'from' token, 'to' token, amount, and chain ID. This command is used to generate local quote data for subsequent comparison with live data. ```bash npm run quote -- --fromToken --toToken --amount --chainId 10 ``` -------------------------------- ### Log Supported Chains Count and Names (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Demonstrates how to access the `supportedChains` array from the Sugar SDK to log the total number of supported chains and iterate through them to print their names and IDs. ```typescript import { supportedChains } from "@dromos-labs/sdk.js"; console.log(`Sugar SDK supports ${supportedChains.length} chains`); supportedChains.forEach(chain => { console.log(`${chain.name} (${chain.id})`); }); ``` -------------------------------- ### Access and Customize Base Sugar SDK Configuration (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Provides the default configuration object for Sugar SDK, including settings like token order, price filters, hop limits, and page sizes. It can be imported and customized. ```typescript import { baseConfig } from "@dromos-labs/sdk.js"; console.log(baseConfig.MAX_HOPS); // 3 console.log(baseConfig.DEFAULT_CHAIN_ID); // 10 console.log(baseConfig.chains.length); // 12 // Customize it const customConfig = { ...baseConfig, MAX_HOPS: 5, onError: (error) => console.error("SDK error:", error), }; ``` -------------------------------- ### Perform Token Swap with Sugar SDK in Node.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/using-node.md Executes a token swap in three steps: obtaining a quote, approving the necessary funds using the `approve` function, and finally performing the swap with the `swap` function. This process requires the SDK `config`, a valid `quote` object, and a slippage tolerance. The function returns the transaction hash upon successful execution. ```typescript import { approve, getListedTokens, getQuoteForSwap, swap, } from "@dromos-labs/sdk.js"; const tokens = await getListedTokens({ config }); const usdc = tokens.find( (token) => token.chainId === 10 && token.symbol === "USDC" ); const weth = tokens.find( (token) => token.chainId === 10 && token.symbol === "WETH" ); const quote = await getQuoteForSwap({ config, fromToken: usdc, toToken: weth, amountIn: 1_000_000n, }); if (!quote) throw new Error("No quote found."); await approve({ config, tokenAddress: usdc.address, spenderAddress: quote.spenderAddress, amount: quote.amount, chainId: usdc.chainId, }); const hash = await swap({ config, quote, slippage: 0.01 }); console.log(`Swap confirmed: ${hash}`); ``` -------------------------------- ### Regenerate ABIs for Sugar SDK Source: https://github.com/velodrome-finance/sdk.js/blob/main/README.md Regenerates the Application Binary Interfaces (ABIs) for the Sugar SDK. This process requires an Etherscan API key and is performed from the `packages/sugar-sdk` directory. ```bash cd packages/sugar-sdk && npx @wagmi/cli generate YOUR_ETHERSCAN_KEY_HERE ``` -------------------------------- ### Custom SDK Configuration with Error Handling (TypeScript) Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Sets up an advanced Sugar SDK configuration with custom error handling, default token order overrides, and adjusted routing parameters. It integrates with wagmi's core configuration, allowing for custom transports and connectors, and attaches the Sugar-specific configurations to the wagmi config object. ```typescript import { getDefaultConfig, init, baseConfig, base, optimism } from "@dromos-labs/sdk.js"; import { createConfig, http, injected } from "@wagmi/core"; // Advanced configuration with custom error handler const customConfig = { ...baseConfig, onError: (error: unknown) => { console.error("Sugar SDK Error:", error); // Send to error tracking service }, // Override default token order for UI DEFAULT_TOKEN_ORDER: ["ETH", "USDC", "AERO", "VELO", "DAI"], // Adjust routing parameters MAX_HOPS: 2, POOLS_PAGE_SIZE: 200, }; // Create custom wagmi config const wagmiConfig = createConfig({ chains: [base, optimism], connectors: [injected()], transports: { [base.id]: http("https://mainnet.base.org"), [optimism.id]: http("https://mainnet.optimism.io"), }, }); // Attach Sugar config to wagmi config const config = init(wagmiConfig, customConfig); // Now config has both wagmi and Sugar capabilities ``` -------------------------------- ### Swap Transaction Output JSON (JSON) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/demo-node/README.md The JSON output structure generated by the swap script upon successful execution. It includes transaction details, token information, and confirmation status. ```json { "success": true, "txHash": "0x...", "chain": "base", "chainId": 8453, "account": "0x...", "fromToken": { "symbol": "USDC", "address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "decimals": 6 }, "toToken": { "symbol": "AERO", "address": "0x940181a94a35a4569e4529a3cdfb74e38fd98631", "decimals": 18 }, "amountIn": "1000000", "expectedAmountOut": "...", "amountOutFormatted": "...", "priceImpact": "...", "slippage": 0.01, "slippagePercent": 1, "waitedForReceipt": true, "unsignedTx": { "to": "0x...", "data": "0x...", "value": "0", "chainId": 8453 } } ``` -------------------------------- ### Import Supported Chain Objects (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Imports chain objects from the Sugar SDK, including optimism, base, and others. These can be used when defining chain configurations. ```typescript import { optimism, unichain, fraxtal, lisk, metalL2, soneium, swellchain, superseed, base, mode, celo, ink, } from "@dromos-labs/sdk.js"; ``` -------------------------------- ### Fetch Listed Tokens with Sugar SDK in Node.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/using-node.md Retrieves all listed tokens across the configured chains using the `getListedTokens` function. The returned tokens include details like symbol, name, decimals, chain ID, and USD price. Amounts are provided as bigints for precision. This function requires a pre-configured SDK `config` object. ```typescript import { getListedTokens } from "@dromos-labs/sdk.js"; const tokens = await getListedTokens({ config }); console.log(`Found ${tokens.length} tokens across all chains.`); const optimismTokens = tokens.filter((token) => token.chainId === 10); const usdc = tokens.find( (token) => token.symbol === "USDC" && token.chainId === 10 ); ``` -------------------------------- ### SugarWagmiConfig Type Definition (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Combines Wagmi Core configuration with Sugar configuration, providing a unified type for SDK configurations that integrate with Wagmi. ```typescript type SugarWagmiConfig = WagmiCoreConfig & { sugarConfig: Config; }; ``` -------------------------------- ### Swap Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md Executes a swap through the Universal Router or returns unsigned transaction data for custom signing. ```APIDOC ## POST /api/swap/execute ### Description Executes a swap through the Universal Router or returns unsigned transaction data for custom signing. ### Method POST ### Endpoint /api/swap/execute ### Parameters #### Request Body - **quote** (Quote) - Required - Quote returned by `getQuoteForSwap`. - **slippage** (number) - Optional - Decimal tolerance (default 0.005 = 0.5%). - **waitForReceipt** (boolean) - Optional - Await confirmation (default true when executing). - **unsignedTransactionOnly** (boolean) - Optional - Set to true to receive an `UnsignedSwapTransaction` instead of executing. - **account** (Address) - Required when `unsignedTransactionOnly` is true; address that will submit the transaction. ### Request Example (Execute Swap) ```json { "quote": { ... }, "slippage": 0.01, "waitForReceipt": true } ``` ### Request Example (Unsigned Transaction) ```json { "quote": { ... }, "unsignedTransactionOnly": true, "account": "0x..." } ``` ### Response #### Success Response (200) - **string** - Transaction hash when executing immediately. - **UnsignedSwapTransaction** (object) - Unsigned transaction data when requested. #### Response Example (Transaction Hash) ```json "0xabc123..." ``` #### Response Example (Unsigned Transaction) ```json { "to": "0x...", "data": "0x...", "value": "0", "from": "0x...", "gas": "100000" } ``` ``` -------------------------------- ### Request Unsigned Transaction for Swap with SDK.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md This snippet shows how to request an unsigned transaction for a swap operation using SDK.js. This is useful when you need to manually sign the transaction before submitting it. The `unsignedTransactionOnly` flag should be set to `true`, and the `account` address must be provided. The output is an unsigned transaction object that can be signed externally. ```typescript import { swap } from "@dromos-labs/sdk.js"; const unsignedTx = await swap({ config, quote, slippage: 0.01, unsignedTransactionOnly: true, account: "0x...", }); ``` -------------------------------- ### Fetch Swap Quote with getQuoteForSwap (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md Fetches the best available quote for a token swap using the Sugar SDK. It takes configuration, token details, and amount as input, and returns quote information or null if no route is found. Optional parameters control batch size and concurrency. ```typescript import { getQuoteForSwap } from "@dromos-labs/sdk.js"; const quote = await getQuoteForSwap({ config, fromToken, toToken, amountIn: 1_000_000n, batchSize: 50, concurrentLimit: 10, }); ``` -------------------------------- ### Execute Swap with swap Function (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md Executes a swap transaction using the provided quote and configuration. This function can either execute the transaction directly and return the hash, or return unsigned transaction data for custom signing. Optional slippage and receipt waiting parameters are available. ```typescript const transactionHash = await swap({ config, quote, slippage?: 0.01, waitForReceipt?: true, }); ``` ```typescript const unsignedTx = await swap({ config, quote, unsignedTransactionOnly: true, account: "0x..."; }); ``` -------------------------------- ### ChainConfig Type Definition (TypeScript) Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/config.md Defines the configuration structure for a specific blockchain network, including addresses for various tokens, contracts, and features like LP sugar and rewards. ```typescript type ChainConfig = { CHAIN: Chain; CONNECTOR_TOKENS: Address[]; STABLE_TOKEN: Address; DEFAULT_TOKENS: Address[]; WRAPPED_NATIVE_TOKEN?: Address; WETH_ADDRESS?: Address; UNSAFE_TOKENS?: Address[]; LP_SUGAR_ADDRESS: Address; REWARDS_SUGAR_ADDRESS: Address; ROUTER_ADDRESS: Address; PRICES_ADDRESS: Address; VOTER_ADDRESS: Address; QUOTER_ADDRESS: Address; UNIVERSAL_ROUTER_ADDRESS: Address; SLIPSTREAM_SUGAR_ADDRESS: Address; NFPM_ADDRESS: Address; VE_SUGAR_ADDRESS?: Address; RELAY_SUGAR_ADDRESS?: Address; }; ``` -------------------------------- ### Submit Signed Transaction with SDK.js Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/swaps.md This snippet demonstrates how to submit a pre-signed transaction using SDK.js. After obtaining an unsigned transaction and signing it externally, you can use this function to send the signed payload to the network. The `signedTransaction` parameter should be the hex-encoded string of your signed transaction. Setting `waitForReceipt` to `false` allows for asynchronous processing. ```typescript import { submitSignedTransaction } from "@dromos-labs/sdk.js"; const txHash = await submitSignedTransaction({ config, signedTransaction, // Hex string after you sign unsignedTx waitForReceipt: false, }); ``` -------------------------------- ### Fetch Listed Tokens Across Chains (TypeScript) Source: https://context7.com/velodrome-finance/sdk.js/llms.txt Retrieves a list of all tokens available across the configured blockchain networks using the Sugar SDK. This function requires an initialized SDK configuration and returns an array of token objects, each containing details like symbol, name, address, price, and user balance. The output can be filtered by chain ID or symbol. ```typescript import { getDefaultConfig, getListedTokens, optimism, base } from "@dromos-labs/sdk.js"; const config = getDefaultConfig({ chains: [ { chain: optimism, rpcUrl: process.env.OP_RPC }, { chain: base, rpcUrl: process.env.BASE_RPC } ] }); // Fetch all tokens from all configured chains const tokens = await getListedTokens({ config }); // Filter and display tokens console.log(`Found ${tokens.length} tokens`); const baseTokens = tokens.filter(t => t.chainId === base.id); console.log(`Base tokens: ${baseTokens.length}`); baseTokens.forEach(token => { console.log(`${token.symbol} (${token.name})`); console.log(` Address: ${token.address}`); console.log(` Price: $${token.price}`); console.log(` Balance: ${token.balance}`); console.log(` Decimals: ${token.decimals}`); console.log(` Chain ID: ${token.chainId}`); }); // Find specific token const usdc = tokens.find(t => t.symbol === "USDC" && t.chainId === base.id ); // Token type includes: // - address: Address // - symbol: string // - name: string // - decimals: number // - chainId: number // - price: string (USD price) // - balance: bigint (user's balance) // - wrappedAddress?: Address (for native tokens) ``` -------------------------------- ### Fetch Listed Tokens - TypeScript Source: https://github.com/velodrome-finance/sdk.js/blob/main/packages/docs/api/tokens.md Fetches all listed tokens across configured chains using the `getListedTokens` function. It requires a `SugarWagmiConfig` instance and returns a promise resolving to an array of `Token` objects. Note that balances are only populated if a wallet is connected. ```typescript import { getListedTokens } from "@dromos-labs/sdk.js"; const tokens = await getListedTokens({ config }); console.log(`Loaded ${tokens.length} tokens.`); const optimismTokens = tokens.filter((token) => token.chainId === 10); const usdc = tokens.find( (token) => token.symbol === "USDC" && token.chainId === 10 ); if (usdc) { const balance = Number(usdc.balance) / 10 ** usdc.decimals; console.log(`Balance: ${balance} ${usdc.symbol}`); } ```