### Installation and Setup Source: https://context7.com/avnu-labs/avnu-skill/llms.txt Install the avnu SDK and its dependencies. The SDK requires starknet.js as a peer dependency and optionally moment for DCA functionality. ```APIDOC ## Installation and Setup Install the avnu SDK and required dependencies. The SDK requires starknet.js as a peer dependency and optionally moment for DCA functionality. ```bash npm install @avnu/avnu-sdk starknet # For DCA functionality npm install moment ``` ```typescript import { Account, RpcProvider } from 'starknet'; import 'dotenv/config'; // Required environment variables // STARKNET_ACCOUNT_ADDRESS=0x... // STARKNET_PRIVATE_KEY=0x... // STARKNET_RPC_URL=https://rpc.starknet.lava.build (optional) const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL || 'https://rpc.starknet.lava.build', }); const account = new Account( provider, process.env.STARKNET_ACCOUNT_ADDRESS!, process.env.STARKNET_PRIVATE_KEY! ); // Common token addresses (mainnet) const TOKENS = { ETH: '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', STRK: '0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', USDC: '0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8', USDT: '0x068f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8', }; ``` ``` -------------------------------- ### Example .env.example Template Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Provides a template for the .env.example file, outlining required and optional environment variables for Starknet account and RPC configuration, including security warnings for sensitive keys. ```bash # Starknet Account Configuration # NEVER commit your private key! STARKNET_ACCOUNT_ADDRESS=0x... STARKNET_PRIVATE_KEY=0x... # RPC Configuration # Default: https://rpc.starknet.lava.build STARKNET_RPC_URL= # Network: mainnet or sepolia STARKNET_NETWORK=mainnet # Gasfree (Sponsored) Transactions # Get your key at: https://portal.avnu.fi # WARNING: Keep server-side only, never expose in frontend! AVNU_PAYMASTER_API_KEY= ``` -------------------------------- ### Setup Direct Account in TypeScript Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Demonstrates how to set up a Starknet Account object using environment variables for direct account access in TypeScript. It includes provider and account initialization. ```typescript import { Account, RpcProvider } from 'starknet'; import 'dotenv/config'; // Validate environment if (!process.env.STARKNET_ACCOUNT_ADDRESS) { throw new Error('STARKNET_ACCOUNT_ADDRESS is required'); } if (!process.env.STARKNET_PRIVATE_KEY) { throw new Error('STARKNET_PRIVATE_KEY is required'); } // Setup provider const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL || 'https://rpc.starknet.lava.build', }); // Setup account const account = new Account( provider, process.env.STARKNET_ACCOUNT_ADDRESS, process.env.STARKNET_PRIVATE_KEY ); ``` -------------------------------- ### Setup Wallet Account in TypeScript Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Illustrates how to connect to a Starknet wallet and create a WalletAccount object for frontend interactions. It assumes the use of a wallet SDK like 'get-starknet'. ```typescript import { WalletAccount, RpcProvider } from 'starknet'; const provider = new RpcProvider({ nodeUrl: 'https://rpc.starknet.lava.build', }); // Using get-starknet or wallet SDK async function connectWallet() { // Example with get-starknet const starknet = await connect(); if (starknet.isConnected) { const account = new WalletAccount( provider, starknet.account ); return account; } throw new Error('Wallet not connected'); } ``` -------------------------------- ### Install Avnu SDK and Starknet Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Installs the Avnu SDK and Starknet packages using npm, yarn, or pnpm. These are the core dependencies for interacting with the Avnu protocol. ```bash # npm npm install @avnu/avnu-sdk starknet # yarn yarn add @avnu/avnu-sdk starknet # pnpm pnpm add @avnu/avnu-sdk starknet ``` -------------------------------- ### AvnuOptions Interface Example Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Defines an example of the AvnuOptions interface in TypeScript, showing how to configure SDK options such as API base URLs, request cancellation signals, and public keys for response verification. ```typescript import { AvnuOptions } from '@avnu/avnu-sdk'; const options: AvnuOptions = { // Main API base URL baseUrl: 'https://starknet.api.avnu.fi', // Default for mainnet // DCA (Impulse) API base URL impulseBaseUrl: 'https://starknet.impulse.avnu.fi', // Default for mainnet // Request cancellation abortSignal: controller.signal, // Response signature verification (optional) avnuPublicKey: '0x...', }; ``` -------------------------------- ### Install Moment for DCA Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Installs the 'moment' package, which is required for DCA (Direct Contract Access) functionality within the Avnu SDK. ```bash npm install moment ``` -------------------------------- ### Compare Multiple Swap Quotes with Avnu SDK (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/swap-guide.md Illustrates how to fetch multiple swap quotes (using the `size` parameter) and then compare them. The example iterates through the quotes, displaying key metrics like the received amount, price impact, gas fees, and the DEX routes used, allowing users to select the most favorable option. ```typescript // Get multiple quotes const quotes = await getQuotes({ sellTokenAddress: ETH, buyTokenAddress: USDC, sellAmount: BigInt(10e18), size: 5, }); // Compare quotes quotes.forEach((quote, i) => { console.log(`Quote ${i + 1}:`); console.log(` Buy: ${quote.buyAmount} (${quote.buyAmountInUsd} USD)`); console.log(` Impact: ${(quote.priceImpact / 100).toFixed(2)}%`); // basis points to % console.log(` Gas: ${quote.gasFeesInUsd.toFixed(4)} USD`); console.log(` Routes: ${quote.routes.map(r => r.name).join(' + ')}`); }); // Best quote is always first, but sometimes: // - Quote 2 might have lower gas // - Quote 3 might have lower price impact ``` -------------------------------- ### Install Avnu SDK and Starknet Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/SKILL.md Installs the necessary Avnu SDK and Starknet packages using npm. This is the first step for integrating Avnu functionalities into your project. ```bash npm install @avnu/avnu-sdk starknet ``` -------------------------------- ### Getting an API Key Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/paymaster-guide.md Step-by-step instructions on how to obtain and configure an Avnu API key for using their services. ```APIDOC ## Getting an API Key ### Description Follow these steps to generate and set up your Avnu API key. This involves visiting the Avnu portal, connecting your wallet, creating a key, funding it, and configuring it in your environment variables. ### Method N/A (Procedural guide) ### Endpoint N/A ### Parameters N/A ### Request Example 1. Go to [portal.avnu.fi](https://portal.avnu.fi) 2. Connect using your starknet wallet 3. Create a new api key 4. Fund your key with some STRK on mainnet (free on Sepolia) 5. Add to your `.env` file (server-side only!): ```bash AVNU_PAYMASTER_API_KEY=your-api-key-here ``` ### Response N/A ``` -------------------------------- ### Install avnu SDK and Dependencies (Bash) Source: https://context7.com/avnu-labs/avnu-skill/llms.txt Installs the avnu SDK and its required peer dependency, starknet.js. The 'moment' package is optional and needed for DCA functionality. ```bash npm install @avnu/avnu-sdk starknet # For DCA functionality npm install moment ``` -------------------------------- ### Perform Gasless Swap using Avnu SDK (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/paymaster-guide.md Demonstrates how to execute a gasless swap using the Avnu SDK and StarkNet's paymaster functionality. This backend/script example shows setting up the paymaster with an API key, fetching quotes, and calling `executeSwap` with the 'sponsored' fee mode. ```typescript import { PaymasterRpc } from 'starknet'; import { executeSwap, getQuotes } from '@avnu/avnu-sdk'; const paymaster = new PaymasterRpc({ nodeUrl: 'https://starknet.paymaster.avnu.fi', headers: { 'x-paymaster-api-key': process.env.AVNU_PAYMASTER_API_KEY!, }, }); const quotes = await getQuotes({ sellTokenAddress: TOKENS.USDC, buyTokenAddress: TOKENS.ETH, sellAmount: BigInt(100e6), takerAddress: account.address, }); const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.01, paymaster: { active: true, provider: paymaster, params: { feeMode: { mode: 'sponsored' }, }, }, }); console.log('Tx Hash:', result.transactionHash); // User paid $0 in gas! ``` -------------------------------- ### Filter Tokens by Tags using Avnu SDK Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/tokens-prices.md Demonstrates how to filter tokens based on specific tags. It shows examples for fetching only 'Verified' tokens and fetching tokens that match multiple tags (using OR logic). ```typescript // Only verified tokens const verified = await fetchTokens({ tags: ['Verified'], }); // Multiple tags (OR logic) const safeTokens = await fetchTokens({ tags: ['Verified', 'Unruggable'], }); ``` -------------------------------- ### Gasfree with starknet.js Directly Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/paymaster-guide.md Demonstrates how to use the PaymasterRpc and quoteToCalls from Avnu SDK to build and execute a sponsored transaction directly. ```APIDOC ## Gasfree with starknet.js Directly ### Description This example shows how to set up the `PaymasterRpc` with your API key and use `quoteToCalls` to prepare transaction calls. It then demonstrates executing a transaction in 'sponsored' fee mode, where the dApp covers the gas costs. ### Method `POST` (Implicitly through `account.executePaymasterTransaction`) ### Endpoint `/` (Implicitly through `PaymasterRpc` and `account.executePaymasterTransaction`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed as arguments to functions) ### Request Example ```typescript import { PaymasterRpc, type PaymasterDetails } from 'starknet'; import { quoteToCalls } from '@avnu/avnu-sdk'; const paymaster = new PaymasterRpc({ nodeUrl: 'https://starknet.paymaster.avnu.fi', headers: { 'x-paymaster-api-key': process.env.AVNU_PAYMASTER_API_KEY!, }, }); // Build calls const { calls } = await quoteToCalls({ quote: quotes[0], takerAddress: account.address, slippage: 0.01, includeApprove: true, }); // Sponsored fee mode (no gasToken needed) const feeDetails: PaymasterDetails = { feeMode: { mode: 'sponsored' }, }; // Execute sponsored transaction const result = await account.executePaymasterTransaction(calls, feeDetails); const receipt = await account.waitForTransaction(result.transaction_hash); ``` ### Response #### Success Response (200) - `receipt` (object) - The transaction receipt after successful execution. #### Response Example ```json { "transaction_hash": "0x..." } ``` ``` -------------------------------- ### Initialize and Check Paymaster Availability (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/paymaster-guide.md Demonstrates how to initialize the PaymasterRpc from starknet.js and check its availability. This is a foundational step before interacting with other Paymaster functionalities. ```typescript import { PaymasterRpc } from 'starknet'; const paymaster = new PaymasterRpc({ nodeUrl: 'https://starknet.api.avnu.fi/paymaster/v1', }); // Check if paymaster is available const isAvailable = await paymaster.isAvailable(); console.log('Paymaster available:', isAvailable); // Get supported tokens const tokens = await paymaster.getSupportedTokens(); tokens.forEach(t => console.log(t.tokenAddress, t.priceInStrk)); ``` -------------------------------- ### Fetch Basic Token List with Avnu SDK Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/tokens-prices.md Retrieves a list of tokens and logs their symbol, address, decimals, tags, and daily volume. Requires the '@avnu/avnu-sdk' package. ```typescript import { fetchTokens } from '@avnu/avnu-sdk'; const page = await fetchTokens(); page.content.forEach(token => { console.log(`${token.symbol}: ${token.address}`); console.log(` Decimals: ${token.decimals}`); console.log(` Tags: ${token.tags.join(', ')}`); console.log(` Daily Volume: $${token.lastDailyVolumeUsd}`); }); ``` -------------------------------- ### Starknet .gitignore Configuration for Security Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Provides a sample .gitignore file to prevent sensitive files, such as environment variables and private keys, from being committed to version control. This is crucial for maintaining the security of your project. ```gitignore # Environment files .env .env.local .env.*.local # Never commit these *.pem *.key secrets/ ``` -------------------------------- ### Configure Environment Variables for Direct Account Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Sets up essential environment variables for direct account authentication, including the Starknet account address and private key. These are crucial for backend or script-based interactions. ```bash # .env STARKNET_ACCOUNT_ADDRESS=0x1234567890abcdef... STARKNET_PRIVATE_KEY=0xabcdef1234567890... ``` -------------------------------- ### Create Configured Avnu SDK Instance Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Demonstrates the creation of a reusable AvnuClient class in TypeScript that encapsulates SDK options and network configuration. It provides methods for fetching quotes and executing swaps. ```typescript import { getQuotes, executeSwap, AvnuOptions } from '@avnu/avnu-sdk'; class AvnuClient { private options: AvnuOptions; private account: Account; constructor(account: Account, network: 'mainnet' | 'sepolia' = 'mainnet') { this.account = account; this.options = { baseUrl: NETWORKS[network].baseUrl, impulseBaseUrl: NETWORKS[network].impulseBaseUrl, }; } async getQuotes(request: QuoteRequest) { return getQuotes(request, this.options); } async swap(request: QuoteRequest, slippage: number) { const quotes = await this.getQuotes(request); return executeSwap({ provider: this.account, quote: quotes[0], slippage, executeApprove: true, }); } } ``` -------------------------------- ### Setup Starknet Wallet Account (Frontend/dApps) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/SKILL.md Sets up a Starknet wallet account for frontend applications or dApps. This involves connecting to a user's wallet (like Argent or Braavos) through a wallet provider. ```typescript import { WalletAccount } from 'starknet'; // User connects their wallet (Argent, Braavos) const account = await WalletAccount.connect(provider, walletProvider); ``` -------------------------------- ### Get Token Prices API Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/tokens-prices.md Retrieves the current market prices for a list of tokens, including global and Starknet-specific prices. ```APIDOC ## GET /prices ### Description Fetches the current market prices for a given list of token addresses. Prices are provided from aggregated global sources and on-chain liquidity on Starknet. ### Method GET ### Endpoint /prices ### Parameters #### Query Parameters - **addresses** (string[]) - Required - An array of token contract addresses for which to fetch prices. ### Request Example ```typescript import { getPrices } from '@avnu/avnu-sdk'; const tokenAddresses = [ '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', // ETH '0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', // STRK '0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8', // USDC ]; const prices = await getPrices(tokenAddresses); prices.forEach(price => { console.log('Token Address:', price.address); console.log('Decimals:', price.decimals); if (price.globalMarket) { console.log('Global Price (USD):', price.globalMarket.usd); } if (price.starknetMarket) { console.log('Starknet Price (USD):', price.starknetMarket.usd); } }); ``` ### Response #### Success Response (200) - **address** (string) - The contract address of the token. - **decimals** (number) - The number of decimals for the token. - **globalMarket** (object | null) - An object containing the global market price in USD, or null if not available. - **usd** (number) - The price in USD from global market sources. - **starknetMarket** (object | null) - An object containing the Starknet market price in USD, or null if not available. - **usd** (number) - The price in USD from Starknet liquidity. #### Response Example ```json [ { "address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "decimals": 18, "globalMarket": { "usd": 3500.50 }, "starknetMarket": { "usd": 3499.75 } }, { "address": "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d", "decimals": 18, "globalMarket": { "usd": 1.50 }, "starknetMarket": { "usd": 1.48 } } ] ``` ``` -------------------------------- ### Setup Direct Starknet Account (Scripts/Backend) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/SKILL.md Configures a direct Starknet account for use in scripts or backend applications. It requires the Starknet RPC URL, account address, and private key, typically loaded from environment variables. ```typescript import { Account, RpcProvider } from 'starknet'; const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL || 'https://rpc.starknet.lava.build' }); const account = new Account( provider, process.env.STARKNET_ACCOUNT_ADDRESS!, process.env.STARKNET_PRIVATE_KEY! ); ``` -------------------------------- ### Get DCA Orders Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/dca-guide.md Fetches a list of DCA orders associated with a given trader address, with options to filter by status and paginate results. ```APIDOC ## GET /avnu-skill/dca/orders ### Description Retrieves a list of Dollar Cost Averaging (DCA) orders for a specified trader address. Supports filtering by order status and pagination. ### Method GET ### Endpoint /avnu-skill/dca/orders ### Parameters #### Query Parameters - **traderAddress** (string) - Required - The wallet address of the trader whose orders are to be fetched. - **status** (string) - Optional - Filters orders by their status. Possible values: `INDEXING`, `ACTIVE`, `CLOSED`. - **page** (integer) - Optional - The page number for pagination (defaults to 0). - **size** (integer) - Optional - The number of orders per page (defaults to 20). ### Response #### Success Response (200) - **totalElements** (integer) - The total number of orders matching the query. - **page** (integer) - The current page number. - **hasNext** (boolean) - Indicates if there are more pages of results. - **content** (array) - An array of DCA order objects. - **orderAddress** (string) - Unique order contract address. - **creatorAddress** (string) - Trader's wallet address. - **sellTokenAddress** (string) - Address of the token being sold. - **buyTokenAddress** (string) - Address of the token being bought. - **sellAmount** (string) - Total amount of sell token. - **sellAmountPerCycle** (string) - Amount of sell token per execution cycle. - **frequency** (number) - Execution interval in seconds. - **iterations** (number) - Total number of executions. - **amountSold** (string) - Amount of sell token already sold. - **amountBought** (string) - Amount of buy token already bought. - **executedTradesCount** (number) - Number of completed executions. - **startDate** (string) - ISO date string of the order start. - **endDate** (string) - ISO date string of the estimated order end. - **status** (string) - Current status of the order (`INDEXING`, `ACTIVE`, `CLOSED`). - **trades** (array) - History of executed trades. - **status** (string) - Status of the trade (`PENDING`, `SUCCEEDED`, `CANCELLED`). - **sellAmount** (string) - Amount of sell token used in the trade. - **buyAmount** (string) - Amount of buy token received in the trade. - **expectedTradeDate** (string) - Expected date of the trade. - **actualTradeDate** (string | null) - Actual date the trade occurred. - **txHash** (string | null) - Transaction hash of the trade. #### Response Example ```json { "totalElements": 5, "page": 0, "hasNext": false, "content": [ { "orderAddress": "0xorder1...", "creatorAddress": "0xtrader...", "sellTokenAddress": "0xusdc...", "buyTokenAddress": "0xeth...", "sellAmount": "100000000", "sellAmountPerCycle": "10000000", "frequency": 86400, "iterations": 10, "amountSold": "50000000", "amountBought": "15000000000000000", "executedTradesCount": 5, "startDate": "2023-10-27T10:00:00Z", "endDate": "2023-11-06T10:00:00Z", "status": "ACTIVE", "trades": [ { "status": "SUCCEEDED", "sellAmount": "10000000", "buyAmount": "3000000000000000", "expectedTradeDate": "2023-10-28T10:00:00Z", "actualTradeDate": "2023-10-28T10:01:05Z", "txHash": "0xtxhash1..." } ] } ] } ``` ``` -------------------------------- ### Initialize Starknet Account and Tokens (TypeScript) Source: https://context7.com/avnu-labs/avnu-skill/llms.txt Sets up a Starknet RPC provider and account using environment variables. Defines common token addresses for the Starknet mainnet. ```typescript import { Account, RpcProvider } from 'starknet'; import 'dotenv/config'; // Required environment variables // STARKNET_ACCOUNT_ADDRESS=0x... // STARKNET_PRIVATE_KEY=0x... // STARKNET_RPC_URL=https://rpc.starknet.lava.build (optional) const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL || 'https://rpc.starknet.lava.build', }); const account = new Account( provider, process.env.STARKNET_ACCOUNT_ADDRESS!, process.env.STARKNET_PRIVATE_KEY! ); // Common token addresses (mainnet) const TOKENS = { ETH: '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', STRK: '0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', USDC: '0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8', USDT: '0x068f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8', }; ``` -------------------------------- ### Initiate Unstake Operation (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/staking-guide.md Starts the unstaking process by locking tokens for a specified unbonding period. This is the first step in unstaking. The tokens are not immediately available and will enter a cooldown phase. ```typescript import { executeInitiateUnstake } from '@avnu/avnu-sdk'; const result = await executeInitiateUnstake({ provider: account, poolAddress: '0xpool...', amount: BigInt(50e18), // Unstake 50 STRK }); console.log('Unstake initiated:', result.transactionHash); console.log('Cooldown starts now - wait 21 days for STRK'); ``` -------------------------------- ### Configure Starknet RpcProvider with Custom Endpoints (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Demonstrates how to initialize the RpcProvider in Starknet using either an API key or custom headers for connecting to RPC endpoints. This is useful for integrating with services like Infura or custom RPC servers. ```typescript import { RpcProvider } from 'starknet'; // With API key const provider = new RpcProvider({ nodeUrl: `https://starknet-mainnet.infura.io/v3/${process.env.INFURA_KEY}`, }); // With custom headers const provider = new RpcProvider({ nodeUrl: 'https://your-rpc-endpoint.com', headers: { 'Authorization': `Bearer ${process.env.RPC_TOKEN}`, }, }); ``` -------------------------------- ### Get AVNU Staking Pool Information (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/staking-guide.md Retrieves general information about the AVNU staking pool, including total value locked, APY, commission rates, and the pool's address. This function is essential for understanding the overall health and parameters of the staking service. ```typescript import { getAvnuStakingInfo } from '@avnu/avnu-sdk'; const stakingInfo = await getAvnuStakingInfo(); console.log('Total Value Locked:', stakingInfo.totalStaked); console.log('APY:', stakingInfo.apy); console.log('Commission:', stakingInfo.commission); console.log('Pool Address:', stakingInfo.poolAddress); ``` -------------------------------- ### Create Gasless DCA Order with Paymaster (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/dca-guide.md This example demonstrates how to create a DCA order without requiring the user to pay gas fees directly, using a Paymaster. It involves configuring the `PaymasterRpc` and passing it along with the `executeCreateDca` function, specifying the fee mode and gas token. ```typescript import { PaymasterRpc } from 'starknet'; import { executeCreateDca } from '@avnu/avnu-sdk'; const paymaster = new PaymasterRpc({ nodeUrl: 'https://starknet.api.avnu.fi/paymaster/v1', }); const result = await executeCreateDca({ provider: account, order: dcaOrder, paymaster: { active: true, provider: paymaster, params: { feeMode: { mode: 'default', gasToken: USDC }, }, }, }); ``` -------------------------------- ### Get User Staking Position Details (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/staking-guide.md Fetches specific details about a user's staking position for a given token, including staked amount, pending rewards, unbonding amount, and claimable amounts. Requires the token address and the user's account address as input. ```typescript import { getUserStakingInfo } from '@avnu/avnu-sdk'; const userInfo = await getUserStakingInfo( TOKENS.STRK, // Token address account.address // User address ); console.log('Staked Amount:', userInfo.stakedAmount); console.log('Pending Rewards:', userInfo.pendingRewards); console.log('Unbonding Amount:', userInfo.unbondingAmount); console.log('Claimable Amount:', userInfo.claimableAmount); ``` -------------------------------- ### Avnu SDK Quote Response Structure and Route Analysis (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/swap-guide.md Defines the structure of a `Quote` object returned by the Avnu SDK, detailing fields like amounts, fees, gas, and routing information. It also includes an example of how to iterate through the `routes` array to analyze the DEX breakdown of a quote and identify common routing patterns. ```typescript interface Quote { quoteId: string; // Unique ID for building transaction sellTokenAddress: string; buyTokenAddress: string; sellAmount: bigint; // Input amount buyAmount: bigint; // Output amount (before fees) buyAmountWithoutFees: bigint; buyAmountInUsd: number; sellAmountInUsd: number; // Price analysis priceImpact: number; // In basis points (20 = 0.2%), negative = loss priceRatioUsd: number; // USD value ratio // Gas gasFees: bigint; // In FRI gasFeesInUsd: number; // Fees fee: { avnuFees: bigint; avnuFeesBps: number; integratorFees: bigint; integratorFeesBps: number; }; // Routing routes: Route[]; // DEX routing breakdown exactTokenTo: boolean; // true if exact output swap estimatedSlippage: number; // SDK-estimated slippage } interface Route { name: string; // DEX name (Jediswap, Ekubo, etc.) percent: number; // Percentage through this route routes: Route[]; // Nested sub-routes } const quote = quotes[0]; // Analyze routing quote.routes.forEach(route => { console.log(`${route.name}: ${route.percent * 100}%`); // Check for split routes if (route.routes.length > 0) { route.routes.forEach(sub => { console.log(` └─ ${sub.name}: ${sub.percent * 100}%`); }); } }); // Common route patterns: // - Single DEX: 100% through one source // - Split: 60% Jediswap, 40% Ekubo // - Multi-hop: ETH → USDC → STRK ``` -------------------------------- ### Handle Avnu Errors with TypeScript Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/error-handling.md A TypeScript function to categorize and provide user-friendly messages for various Avnu-related errors. It maps specific error strings to predefined error codes, messages, recoverability status, and suggestions. This function is crucial for providing clear feedback to users and guiding them on how to resolve issues. ```typescript interface ErrorResult { code: string; message: string; recoverable: boolean; suggestion: string; } function handleAvnuError(error: any): ErrorResult { const message = error.message || String(error); // Quote errors if (message.includes('INSUFFICIENT_LIQUIDITY')) { return { code: 'INSUFFICIENT_LIQUIDITY', message: 'No route found for this trade', recoverable: true, suggestion: 'Try reducing the amount or using a different token pair', }; } if (message.includes('QUOTE_EXPIRED')) { return { code: 'QUOTE_EXPIRED', message: 'Quote has expired', recoverable: true, suggestion: 'Refresh the quote and try again', }; } // Execution errors if (message.includes('SLIPPAGE_EXCEEDED') || message.includes('Insufficient tokens received')) { return { code: 'SLIPPAGE_EXCEEDED', message: 'Price moved too much during execution', recoverable: true, suggestion: 'Increase slippage tolerance or try again', }; } if (message.includes('u256_sub Overflow') || message.includes('INSUFFICIENT_BALANCE')) { return { code: 'INSUFFICIENT_BALANCE', message: 'Not enough tokens in wallet', recoverable: false, suggestion: 'Add more tokens to your wallet', }; } // Paymaster errors if (message.includes('PAYMASTER_REJECTED')) { return { code: 'PAYMASTER_REJECTED', message: 'Transaction not eligible for gas sponsorship', recoverable: true, suggestion: 'Try using regular gas or check eligibility', }; } // Network errors if (message.includes('timeout') || message.includes('fetch failed')) { return { code: 'NETWORK_ERROR', message: 'Network request failed', recoverable: true, suggestion: 'Check your internet connection and try again', }; } // Unknown error return { code: 'UNKNOWN_ERROR', message: message, recoverable: false, suggestion: 'Contact support if the issue persists', }; } // Usage try { await executeSwap({ ... }); } catch (error) { const result = handleAvnuError(error); console.log(`Error [${result.code}]: ${result.message}`); console.log(`Suggestion: ${result.suggestion}`); if (result.recoverable) { // Could retry or show retry button } } ``` -------------------------------- ### Estimate StarkNet Transaction Fees in TypeScript Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/paymaster-guide.md Demonstrates how to estimate transaction fees using StarkNet's `estimatePaymasterTransactionFee` method before execution. It shows how to set fee details, log the estimated cost to the user, and prompt for confirmation before calling `executePaymasterTransaction`. ```typescript const feeDetails: PaymasterDetails = { feeMode: { mode: 'default', gasToken: TOKENS.USDC }, }; const estimation = await account.estimatePaymasterTransactionFee(calls, feeDetails); // Show user the expected fee console.log('Gas fee:', estimation.suggested_max_fee_in_gas_token, 'USDC'); // Get user confirmation before executing const confirmed = await askUserConfirmation(estimation.suggested_max_fee_in_gas_token); if (confirmed) { await account.executePaymasterTransaction( calls, feeDetails, estimation.suggested_max_fee_in_gas_token ); } ``` -------------------------------- ### Fetch Verified Token by Symbol API Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/tokens-prices.md Retrieves the address of a verified token using its symbol. ```APIDOC ## GET /tokens/verified/{symbol} ### Description Fetches the contract address of a verified token using its symbol. This is useful for quickly getting the address of well-known tokens. ### Method GET ### Endpoint /tokens/verified/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The symbol of the verified token (e.g., 'ETH', 'USDC'). ### Request Example ```typescript import { fetchVerifiedTokenBySymbol } from '@avnu/avnu-sdk'; try { const eth = await fetchVerifiedTokenBySymbol('ETH'); const strk = await fetchVerifiedTokenBySymbol('STRK'); const usdc = await fetchVerifiedTokenBySymbol('USDC'); console.log('ETH Address:', eth.address); console.log('STRK Address:', strk.address); console.log('USDC Address:', usdc.address); } catch (error) { // Token not found or not verified console.error('Token not found or not verified'); } ``` ### Response #### Success Response (200) - **address** (string) - The contract address of the verified token. - **name** (string) - The full name of the token. - **symbol** (string) - The symbol of the token. - **decimals** (number) - The number of decimals for the token. - **logoUri** (string | null) - URL to the token's logo image. - **lastDailyVolumeUsd** (number) - The token's trading volume in USD over the last 24 hours. - **tags** (TokenTag[]) - An array of tags associated with the token. - **extensions** (object) - Additional metadata for the token. #### Error Response (404) - **message** (string) - "Token not found or not verified." #### Response Example ```json { "address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "name": "Ether", "symbol": "ETH", "decimals": 18, "logoUri": "https://...", "lastDailyVolumeUsd": 123456789.00, "tags": ["Verified"], "extensions": {} } ``` ``` -------------------------------- ### Fetch Token by Address API Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/tokens-prices.md Retrieves detailed information for a specific token using its contract address. ```APIDOC ## GET /tokens/{address} ### Description Fetches detailed information for a single token identified by its contract address. ### Method GET ### Endpoint /tokens/{address} ### Parameters #### Path Parameters - **address** (string) - Required - The contract address of the token. ### Request Example ```typescript import { fetchTokenByAddress } from '@avnu/avnu-sdk'; const ethAddress = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7'; const eth = await fetchTokenByAddress(ethAddress); console.log(eth.name); // "Ether" console.log(eth.symbol); // "ETH" console.log(eth.decimals); // 18 console.log(eth.tags); // ["Verified"] console.log(eth.logoUri); // URL to logo image ``` ### Response #### Success Response (200) - **address** (string) - The contract address of the token. - **name** (string) - The full name of the token. - **symbol** (string) - The symbol of the token. - **decimals** (number) - The number of decimals for the token. - **logoUri** (string | null) - URL to the token's logo image. - **lastDailyVolumeUsd** (number) - The token's trading volume in USD over the last 24 hours. - **tags** (TokenTag[]) - An array of tags associated with the token. - **extensions** (object) - Additional metadata for the token. #### Response Example ```json { "address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "name": "Ether", "symbol": "ETH", "decimals": 18, "logoUri": "https://...", "lastDailyVolumeUsd": 123456789.00, "tags": ["Verified"], "extensions": {} } ``` ``` -------------------------------- ### Gasfree Frontend Integration - Server Actions Source: https://context7.com/avnu-labs/avnu-skill/llms.txt This section details the server actions required for integrating gas-free transactions into your frontend dApp. It outlines a 3-phase pattern: build on server, sign on client, and execute on server, ensuring API key security. ```APIDOC ## POST /avnu-skill/paymaster/build ### Description Builds a paymaster transaction for sponsored fee execution. This action is intended to be run server-side to protect your API key. ### Method POST ### Endpoint `/avnu-skill/paymaster/build` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userAddress** (string) - Required - The address of the user initiating the transaction. - **calls** (array) - Required - An array of `Call` objects representing the transaction calls. ### Request Example ```json { "userAddress": "0x123...", "calls": [ { "to": "0x456...", "selector": "0xabc...", "calldata": [] } ] } ``` ### Response #### Success Response (200) - **typed_data** (object) - The typed data required for signing the transaction. - **transaction** (object) - The transaction details. #### Response Example ```json { "typed_data": { "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" } ], "Message": [ { "name": "transaction", "type": "Transaction" }, { "name": "metadata", "type": "Metadata" } ], "Transaction": [ { "name": "nonce", "type": "uint256" }, { "name": "sender", "type": " பாதுகாப்பு " }, { "name": "target", "type": " பாதுகாப்பு " }, { "name": "call_data", "type": " பாதுகாப்பு []" }, { "name": "max_fee", "type": "uint256" } ], "Metadata": [ { "name": "gas_limit", "type": "uint256" }, { "name": "gas_price", "type": "uint256" }, { "name": "paymaster_data", "type": " பாதுகாப்பு " }, { "name": "signature", "type": " பாதுகாப்பு []" } ] }, "primaryType": "Message", "domain": { "name": "AVNU Paymaster", "version": "1.0.0", "chainId": "0x530" }, "message": { "transaction": { "nonce": "0x0", "sender": "0x123...", "target": "0x722...", "call_data": [], "max_fee": "0x1" }, "metadata": { "gas_limit": "0x100000", "gas_price": "0x1", "paymaster_data": "0x", "signature": [] } } }, "transaction": { "nonce": "0x0", "sender": "0x123...", "target": "0x722...", "call_data": [], "max_fee": "0x1" } } ``` ## POST /avnu-skill/paymaster/execute ### Description Executes a signed paymaster transaction. This action is intended to be run server-side after the transaction has been signed by the user on the client. ### Method POST ### Endpoint `/avnu-skill/paymaster/execute` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userAddress** (string) - Required - The address of the user initiating the transaction. - **signedTransaction** (object) - Required - The signed transaction object obtained after client-side signing. - **typed_data** (object) - The typed data used for signing. - **signature** (array) - The signature of the transaction. ### Request Example ```json { "userAddress": "0x123...", "signedTransaction": { "typed_data": { ... }, "signature": ["0xabc..."] } } ``` ### Response #### Success Response (200) - **hash** (string) - The transaction hash of the executed transaction. #### Response Example ```json { "hash": "0xdef..." } ``` ``` -------------------------------- ### Secure Private Key Management in Starknet (TypeScript) Source: https://github.com/avnu-labs/avnu-skill/blob/main/skills/avnu/references/configuration.md Illustrates secure methods for managing private keys in Starknet applications. It strongly advises against hardcoding keys and recommends using environment variables or secret management services for production environments. ```typescript // NEVER do this const privateKey = '0x1234...'; // Hardcoded private key // ALWAYS use environment variables const privateKey = process.env.STARKNET_PRIVATE_KEY; // Validate before use if (!privateKey) { throw new Error('Private key not configured'); } // For production: Use secret managers // AWS Secrets Manager, HashiCorp Vault, etc. ```