### Initialize Starknet Provider and Account in TypeScript Source: https://context7_llms This TypeScript snippet demonstrates how to set up a Starknet provider and account using starknet.js. It includes examples for both direct provider/account setup and using hooks from starknet-react. Remember to handle private keys securely and avoid hardcoding them in production. ```typescript import { RpcProvider, Account } from 'starknet'; // Setup provider & account from starknet.js const provider = new RpcProvider({ nodeUrl: 'https://rpc.starknet.lava.build:443' }); const account = new Account( provider, 'YOUR_ACCOUNT_ADDRESS', 'YOUR_PRIVATE_KEY' ); // Or use hook from starknet-react // const { account } = useAccount(); ``` -------------------------------- ### Get Swap Quotes - Python Source: https://context7_llms Fetches optimized swap quotes from Avnu.fi across various Starknet liquidity sources using Python. This example shows how to set up query parameters and make a GET request. ```python import requests params = { 'sellTokenAddress': '0x049d...', 'buyTokenAddress': '0x053c...', 'sellAmount': '1000000000000000000', 'takerAddress': account.address } quote_response = requests.get( 'https://starknet.api.avnu.fi/swap/v3/quotes', params=params, ) quotes = quote_response.json() print(quotes); ``` -------------------------------- ### Prompting with Context7 Source: https://context7_llms Examples of how to use Context7 within prompts to get up-to-date avnu documentation. Simply include 'use context7' in your prompt. ```text Build a token swap using avnu SDK. use context7 ``` ```text How do I integrate avnu paymaster for gasless transactions? use context7 ``` -------------------------------- ### Get Swap Quotes Example (Python) Source: https://context7_llms Demonstrates how to fetch swap quotes from the Avnu.fi API using Python. It sends a GET request to the swap quotes endpoint and prints the received quotes. ```python import requests response = requests.get( 'https://starknet.api.avnu.fi/swap/v1/quotes', params=params, ) quotes = response.json() print('Quote:', quotes) ``` -------------------------------- ### Install AVNU SDK using npm, yarn, or pnpm Source: https://context7_llms This snippet shows how to install the AVNU SDK using different package managers. Ensure you have Node.js 22+ installed. The SDK is essential for interacting with the AVNU swap API. ```bash npm install @avnu/avnu-sdk ``` ```bash yarn add @avnu/avnu-sdk ``` ```bash pnpm add @avnu/avnu-sdk ``` -------------------------------- ### AVNU Fi Swap API Authentication Example Source: https://context7_llms Illustrates the authentication mechanism for the AVNU Fi Swap API, specifically for GET requests to the /swap/quotes endpoint. It shows the requirement for an 'x-api-key' header, which is optional but recommended for higher rate limits. ```bash GET /swap/quotes Headers: x-api-key: your-api-key # Optional, for higher rate limits ``` -------------------------------- ### Get Supported Liquidity Sources (Python) Source: https://context7_llms Demonstrates how to retrieve a list of all supported liquidity sources (DEXs) on Starknet via the Avnu.fi API using Python. It employs the requests library to make a GET request to the /swap/v3/sources endpoint. ```python import requests response = requests.get( 'https://starknet.api.avnu.fi/swap/v3/sources', ) sources = response.json() print(f"Total sources: {len(sources)}") ``` -------------------------------- ### Response Example for Building Swap Calls - JSON Source: https://context7_llms An example of a successful JSON response when building transaction calls for a swap. This structure includes the contract address, entrypoint, and calldata needed for execution. ```json { "calls": [ { "contractAddress": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "entrypoint": "approve", "calldata": ["0x123...", "1000000000000000000", "0"] }, { "contractAddress": "0x123abc...", "entrypoint": "swap", "calldata": ["0x049d...", "0x053c...", "1000000000000000000", "3150000000", "0"] } ] } ``` -------------------------------- ### Stake Tokens Example - TypeScript Source: https://context7_llms Demonstrates how to stake tokens using the Avnu Finance API with TypeScript. This example covers fetching available pools, selecting the best APY pool, and submitting a stake transaction. ```typescript import { Account } from 'starknet'; // 1. Get available pools const poolsRes = await fetch( 'https://starknet.api.avnu.fi/staking/v3' ); const pools = await poolsRes.json(); // Choose best APY pool for your token const bestPool = pools.sort((a, b) => b.apy - a.apy)[0]; // 2. Stake tokens const poolAddress = bestPool.poolAddress; const stakeRes = await fetch( `https://starknet.api.avnu.fi/staking/v3/pools/${poolAddress}/members/${account.address}/stake`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: '1000000000000000000' // Amount in token's decimals }) } ); const { calls } = await stakeRes.json(); // 3. Execute transaction const tx = await account.execute(calls); await account.waitForTransaction(tx.transaction_hash); console.log('Staked successfully!'); ``` -------------------------------- ### TypeScript Pagination Example Source: https://context7_llms Demonstrates how to paginate through token results using the `page` and `size` parameters in `fetchTokens`. This example fetches the second page of results, with 50 tokens per page, and displays the current page number and total pages. ```typescript import { fetchTokens } from '@avnu/avnu-sdk'; // Fetch second page with 50 tokens per page const page2 = await fetchTokens({ page: 1, // 0-indexed size: 50 }); console.log(`Page ${page2.number + 1} of ${page2.totalPages}`); console.log(`Showing ${page2.content.length} tokens`); ``` -------------------------------- ### AVNU Swap API Quote Request Examples Source: https://context7_llms Examples of how to request a swap quote from the AVNU API using different methods. These examples demonstrate the necessary parameters like token addresses and amounts for generating a quote. ```bash curl "https://starknet.api.avnu.fi/swap/v3/quotes?sellTokenAddress=0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7&buyTokenAddress=0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d&sellAmount=0x2386f26fc10000" ``` ```typescript const params = new URLSearchParams({ sellTokenAddress: '0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', buyTokenAddress: '0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', sellAmount: '0x2386f26fc10000' }); const response = await fetch(`https://starknet.api.avnu.fi/swap/v3/quotes?${params}`); const quotes = await response.json(); console.log('Quote:', quotes); ``` ```python import requests params = { 'sellTokenAddress': '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', 'buyTokenAddress': '0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', 'sellAmount': '0x2386f26fc10000' } response = requests.get( 'https://starknet.api.avnu.fi/swap/v3/quotes', ``` -------------------------------- ### Create DCA Order Request Examples Source: https://context7_llms Examples for creating a DCA order, demonstrating how to specify token addresses, amounts, and frequency. These examples cover different programming languages and tools for making the API request. ```bash curl -X POST "https://starknet.api.avnu.fi/dca/v3/orders" \ -H "Content-Type: application/json" \ -d '{ "traderAddress": "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "sellTokenAddress": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "sellAmount": "1000000000000000000", "sellAmountPerCycle": "100000000000000000", "buyTokenAddress": "0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8", "frequency": "P1D", "pricingStrategy": { "tokenToMinAmount": null, "tokenToMaxAmount": null } }' ``` ```typescript // Create a DCA order to buy $100 USDC daily with ETH const response = await fetch('https://starknet.api.avnu.fi/dca/v3/orders', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ traderAddress: account.address, sellTokenAddress: ETH_ADDRESS, sellAmount: ethers.parseEther("1"), // 1 ETH total sellAmountPerCycle: ethers.parseEther("0.1"), // 0.1 ETH per day buyTokenAddress: USDC_ADDRESS, frequency: "P1D", // Daily pricingStrategy: { tokenToMinAmount: null, // No minimum (market order) tokenToMaxAmount: null // No maximum } }) }); const { calls } = await response.json(); // Execute the calls to create the order await account.execute(calls); ``` ```python import requests from datetime import datetime # Create a weekly DCA order order_data = { 'traderAddress': account_address, 'sellTokenAddress': ETH_ADDRESS, 'sellAmount': str(10**18), # 1 ETH total 'sellAmountPerCycle': str(10**17 * 25 // 100), # 0.25 ETH per week 'buyTokenAddress': STRK_ADDRESS, 'frequency': 'P1W', # Weekly 'startDate': datetime.now().isoformat(), 'pricingStrategy': { 'tokenToMinAmount': null, # No minimum (market order) 'tokenToMaxAmount': null # No maximum } } response = requests.post( 'https://starknet.api.avnu.fi/dca/v3/orders', json=order_data, ) calls = response.json()['calls'] # Execute calls through your account ``` -------------------------------- ### TypeScript Search Tokens Example Source: https://context7_llms Illustrates how to search for tokens based on a query string using the `search` parameter in `fetchTokens`. This example finds tokens related to 'USDC' and limits the results to 10 per page. ```typescript import { fetchTokens } from '@avnu/avnu-sdk'; // Search for USDC-related tokens const usdcTokens = await fetchTokens({ search: 'USDC', size: 10 }); usdcTokens.content.forEach(token => { console.log(`${token.symbol} - ${token.name}`); }); ``` -------------------------------- ### TypeScript Multiple Filters and Sorting Example Source: https://context7_llms Shows how to apply multiple filters and perform custom sorting on token data. This example fetches verified tokens, filters them for those with CoinGecko data, and then sorts the results by daily trading volume. ```typescript import { fetchTokens } from '@avnu/avnu-sdk'; // Get verified tokens const tokens = await fetchTokens({ tags: ['Verified'], size: 100 }); // Filter tokens with CoinGecko data const withCoinGecko = tokens.content.filter( token => token.extensions?.coingeckoId ); // Sort by daily volume const sortedByVolume = tokens.content.sort( (a, b) => b.lastDailyVolumeUsd - a.lastDailyVolumeUsd ); console.log(`${withCoinGecko.length} tokens with CoinGecko data`); console.log(`Top token by volume: ${sortedByVolume[0]?.symbol}`); ``` -------------------------------- ### Claim Rewards Response Example Source: https://context7_llms Shows an example of a successful response when claiming staking rewards. It includes the chain ID and an array of transaction calls that need to be executed to complete the claim process. ```json { "chainId": "0x534e5f4d41494e", "calls": [ { "contractAddress": "0x123abc", "entrypoint": "claim_rewards", "calldata": [] } ] } ``` -------------------------------- ### Execute Stake Usage Example in TypeScript Source: https://context7_llms Provides a concrete example of using the `executeStake` function from the '@avnu/avnu-sdk' to deposit tokens into an avnu $STRK delegation pool. It includes necessary imports and shows how to specify the provider, pool address, and amount. ```typescript import { executeStake } from '@avnu/avnu-sdk'; import { parseUnits } from 'ethers'; const result = await executeStake({ provider: account, // Starknet Account poolAddress: '0x0362dc7da60bfddc8e3146028dfd94941c6e22403c98b5947104e637543b475d', // avnu $STRK delegation pool amount: parseUnits('100', 18), // Amount to stake (in wei) }); console.log('Transaction Hash:', result.transactionHash); ``` -------------------------------- ### Get Swap Quotes Example (TypeScript) Source: https://context7_llms Provides an example of how to retrieve swap quotes using the Avnu.fi API in TypeScript. It utilizes the fetch API to make a GET request and logs the JSON response. ```typescript async function getQuotes(params) { const response = await fetch( `https://starknet.api.avnu.fi/swap/v1/quotes?${new URLSearchParams(params)}`, ); const quotes = await response.json(); console.log('Quote:', quotes); } ``` -------------------------------- ### Complete Example for Token Swap on Starknet Source: https://context7_llms This TypeScript code demonstrates a full example of fetching quotes and executing a token swap using the Avnu SDK on Starknet. It requires setting up a Starknet RPC provider and account, then uses `getQuotes` to find swap options and `executeSwap` to perform the trade. It logs the transaction hash upon successful completion. ```typescript import { RpcProvider, Account } from 'starknet'; import { getQuotes, executeSwap } from '@avnu/avnu-sdk'; import { parseUnits, formatUnits } from 'ethers'; const ethAddress = "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"; const strkAddress = "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d"; async function main() { // Setup provider & account from starknet.js const provider = new RpcProvider({ nodeUrl: 'https://rpc.starknet.lava.build:443' }); const account = new Account( provider, process.env.ACCOUNT_ADDRESS!, process.env.PRIVATE_KEY! ); // Fetch quotes const quotes = await getQuotes({ sellTokenAddress: ethAddress, buyTokenAddress: strkAddress, sellAmount: parseUnits('0.001', 18), takerAddress: account.address, }); console.log(`Buying ${formatUnits(quotes[0].buyAmount, 18)} STRK`); // Execute swap const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.001, // 0.1% }); // Wait for confirmation await provider.waitForTransaction(result.transactionHash); console.log('✅ Done:', result.transactionHash); } main().catch(console.error); ``` -------------------------------- ### Execute Swap with Avnu SDK (TypeScript) Source: https://context7_llms Demonstrates a complete example of fetching optimized swap quotes using the Avnu SDK and executing the swap. It includes setting up the provider and account, fetching quotes with `getQuotes`, and executing the swap with `executeSwap`. Dependencies include the starknet, ethers, and @avnu/avnu-sdk libraries. ```typescript import { RpcProvider, Account } from 'starknet'; import { getQuotes, executeSwap } from '@avnu/avnu-sdk'; import { parseUnits } from 'ethers'; const provider = new RpcProvider({ nodeUrl: 'https://rpc.starknet.lava.build:443' }); const account = new Account( provider, process.env.ACCOUNT_ADDRESS!, process.env.PRIVATE_KEY! ); const ethAddress = "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"; const usdcAddress = "0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8"; // Fetch solver-optimized quotes const quotes = await getQuotes({ sellTokenAddress: ethAddress, buyTokenAddress: usdcAddress, sellAmount: parseUnits('1', 18), takerAddress: account.address, }); console.log('Solver route:'); quotes[0].routes.forEach(route => { console.log(` ${route.percent}% via ${route.name}`); }); // Execute with optimized routing const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.001 }); await provider.waitForTransaction(result.transactionHash); console.log('✅ Swap complete:', result.transactionHash); ``` -------------------------------- ### Get Swap Quotes - cURL Source: https://context7_llms Fetches optimized swap quotes from Avnu.fi across various Starknet liquidity sources. This cURL example shows how to send a GET request with query parameters to retrieve quote data. ```bash curl -X GET "https://starknet.api.avnu.fi/swap/v3/quotes?sellTokenAddress=0x049d...&buyTokenAddress=0x053c...&sellAmount=1000000000000000000&takerAddress=0x0123...abc" ``` -------------------------------- ### Install Avnu SDK using npm Source: https://context7_llms This bash command installs the Avnu SDK, a TypeScript/JavaScript library for integrating with Avnu Fi's liquidity aggregation services on Starknet. It is a prerequisite for using the SDK's functionalities like fetching quotes and executing swaps. ```bash npm install @avnu/avnu-sdk ``` -------------------------------- ### Execute Swap with Avnu SDK (TypeScript) Source: https://context7_llms Demonstrates how to execute a swap using the Avnu SDK in TypeScript. It includes steps for fetching quotes and then executing the swap with specified parameters like slippage. It assumes the provider and account setup are already done. ```typescript import { RpcProvider, Account } from 'starknet'; import { getQuotes, executeSwap } from '@avnu/avnu-sdk'; import { parseUnits } from 'ethers'; // ... setup provider and account ... // 1. Get quotes const quotes = await getQuotes({ sellTokenAddress: ETH_ADDRESS, buyTokenAddress: USDC_ADDRESS, sellAmount: parseUnits('1', 18), takerAddress: account.address, }); // 2. Execute swap const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.005, // 0.5% }); console.log('Transaction hash:', result.transactionHash); ``` ```typescript // Execute gasless swap const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.005, // 0.5% paymaster: { active: true, provider: paymasterProvider, // Your Paymaster instance params: {} // Paymaster params } }); ``` ```typescript // If token is already approved const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.005, // 0.5% executeApprove: false, }); ``` -------------------------------- ### Get Swap Quotes - TypeScript Source: https://context7_llms Fetches optimized swap quotes from Avnu.fi across various Starknet liquidity sources using TypeScript. This example demonstrates constructing URL parameters and making a fetch request. ```typescript const params = new URLSearchParams({ sellTokenAddress: '0x049d...', buyTokenAddress: '0x053c...', sellAmount: '1000000000000000000', takerAddress: account.address }); const quoteResponse = await fetch( `https://starknet.api.avnu.fi/swap/v3/quotes?${params}` ); const quotes = await quoteResponse.json(); console.log(quotes); ``` -------------------------------- ### Avnu SDK: Fetch Quotes and Execute Swaps (TypeScript) Source: https://context7_llms Demonstrates the simple integration flow using Avnu's SDK. It shows how to fetch optimized swap quotes and then execute a swap with automatic approvals, specifying the provider, quote, and slippage tolerance. ```typescript import { getQuotes, executeSwap } from "@avnu/avnu-sdk"; // Simple integration const quotes = await getQuotes({ /* ... request parameters ... */ }); const result = await executeSwap({ provider: account, // Assumes 'account' is your Starknet account object quote: quotes[0], // Selecting the first quote for execution slippage: 100 // Represents 1% slippage (value in wei/gwei, adjust as needed) }); console.log("Swap executed:", result); ``` -------------------------------- ### Fetch and Display Token TVL Distribution (TypeScript) Source: https://context7_llms This TypeScript example demonstrates how to make a GET request to the Avnu Finance API to retrieve the TVL for a given token, process the JSON response, and display the total TVL and its distribution across exchanges. It includes sorting and basic visualization. ```typescript // Get current TVL distribution for USDC const tokenAddress = '0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8'; const response = await fetch( `https://starknet.impulse.avnu.fi/v1/tokens/${tokenAddress}/exchange-tvl` ); const tvlData = await response.json(); // Display liquidity distribution const totalTvl = tvlData.reduce((sum, item) => sum + item.valueUsd, 0); console.log(`Total TVL: $${totalTvl.toLocaleString()}`); console.log(`Distributed across ${tvlData.length} exchanges:\n`); tvlData.sort((a, b) => b.valueUsd - a.valueUsd).forEach(item => { const share = (item.valueUsd / totalTvl) * 100; const bar = '█'.repeat(Math.floor(share / 2)); console.log(`${item.exchange.padEnd(15)} ${bar} ${share.toFixed(1)}% ($${item.valueUsd.toLocaleString()})`); }); ``` -------------------------------- ### Cancel DCA Order - TypeScript Example Source: https://context7_llms Demonstrates how to cancel an active DCA order using the AVNU Fi API with TypeScript. It constructs the request to the API, processes the response to get transaction calls, and then executes these calls using an account object. Remaining funds are automatically returned after cancellation. ```typescript const orderAddress = "0x0a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789"; const response = await fetch( `https://starknet.api.avnu.fi/dca/v3/orders/${orderAddress}/cancel`, { method: 'POST', } ); const { calls } = await response.json(); // Execute the cancellation const tx = await account.execute(calls); console.log(`Order cancelled: ${tx.transaction_hash}`); // Remaining funds are automatically returned to your wallet ``` -------------------------------- ### Fetch All Tokens Response Example Source: https://docs.avnu.fi/api/tokens This JSON object represents the response from the 'Get All Tokens' API endpoint. It contains a list of token objects, each with details such as name, address, symbol, decimals, logo URI, and associated tags (e.g., 'Verified', 'Community'). ```json { "content": [ { "name": "Ether", "address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "symbol": "ETH", "decimals": 18, "logoUri": "https://assets.avnu.fi/tokens/eth.svg", "lastDailyVolumeUsd": 12847392, "extensions": {}, "tags": ["Verified"] }, { "name": "USD Coin", "address": "0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8", "symbol": "USDC", "decimals": 6, "logoUri": "https://assets.avnu.fi/tokens/usdc.svg", "lastDailyVolumeUsd": 8234561, "extensions": {}, "tags": ["Verified"] } ], "size": 20, "number": 0, "totalElements": 156, "totalPages": 8 } ``` -------------------------------- ### Execute Token Swap with Integration Fees on Starknet Source: https://context7_llms This TypeScript example shows how to execute a token swap on Starknet while including integration fees. It uses the `getQuotes` function with additional parameters for `integratorFees`, `integratorFeeRecipient`, and `integratorName`, and then proceeds with `executeSwap`. It requires environment variables for account details. ```typescript import { RpcProvider, Account } from 'starknet'; import { getQuotes, executeSwap } from '@avnu/avnu-sdk'; import { parseUnits } from 'ethers'; const ethAddress = "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"; const strkAddress = "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d"; async function main() { const provider = new RpcProvider({ nodeUrl: 'https://rpc.starknet.lava.build:443' }); const account = new Account( provider, process.env.ACCOUNT_ADDRESS!, process.env.PRIVATE_KEY! ); // Fetch quotes with integration fees const quotes = await getQuotes({ sellTokenAddress: ethAddress, buyTokenAddress: strkAddress, sellAmount: parseUnits('0.001', 18), takerAddress: account.address, integratorFees: 10n, // 0.1% fee (10 bps) integratorFeeRecipient: '0xYOUR_FEE_RECIPIENT', integratorName: 'MyDApp', }); const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.01, // 1% }); await provider.waitForTransaction(result.transactionHash); console.log('✅ Swap complete:', result.transactionHash); } main().catch(console.error); ``` -------------------------------- ### Get Token Decimals - TypeScript Example Source: https://docs.avnu.fi/api/tokens This TypeScript function retrieves the number of decimal places for a given token address by querying the avnu Token List API. This information is crucial for performing accurate calculations involving token balances and amounts in DeFi applications. ```typescript // Get token decimals for calculations async function getTokenDecimals(address: string): Promise { const response = await fetch( `https://starknet.api.avnu.fi/v1/starknet/tokens/${address}` ); const token = await response.json(); return token.decimals; } ``` -------------------------------- ### Get Supported Liquidity Sources (cURL) Source: https://context7_llms Illustrates how to list all supported DEXs and liquidity sources on Starknet using the Avnu.fi API via cURL. This command fetches data from the /swap/v3/sources endpoint. ```bash curl "https://starknet.api.avnu.fi/swap/v3/sources" \ ``` -------------------------------- ### Fetch Token Info Response Example Source: https://docs.avnu.fi/api/tokens This JSON object represents the response from the 'Get Token Info' API endpoint for a specific token. It includes comprehensive details about the token, such as its name, contract address, symbol, decimal places, a URI for its logo, recent trading volume, and a list of associated tags. ```json { "name": "Ether", "address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "symbol": "ETH", "decimals": 18, "logoUri": "https://assets.avnu.fi/tokens/eth.svg", "lastDailyVolumeUsd": 12847392, "extensions": {}, "tags": ["Verified"] } ``` -------------------------------- ### Install Context7 for Claude Code Source: https://context7_llms Install the Context7 MCP server for use with Claude Code. This command fetches and installs the latest version of the context7-mcp package. ```bash claude mcp add context7 -- npx -y @upstash/context7-mcp@latest ``` -------------------------------- ### Get Supported Liquidity Sources (TypeScript) Source: https://context7_llms Shows how to obtain a list of all supported liquidity sources (DEXs) on Starknet using the Avnu.fi API with TypeScript. It uses the fetch API to call the /swap/v3/sources endpoint. ```typescript async function getSources() { const response = await fetch( 'https://starknet.api.avnu.fi/swap/v3/sources', ); const sources = await response.json(); return sources; } ``` -------------------------------- ### Execute Stake and Advanced Integration Example in TypeScript Source: https://context7_llms Demonstrates how to stake tokens using the `executeStake` function and how to build custom staking calls for advanced integrations, such as composing staking with swaps. This allows for flexible token deposits into staking pools. ```typescript // Simple integration const result = await executeStake({ provider: account, poolAddress: '0x362dc7da60bfddc8e3146028dfd94941c6e22403c98b5947104e637543b475d', amount: parseUnits('100', 18) }); // Advanced: compose with other operations const stakeCalls = stakeToCalls(poolAddress, amount); const swapCalls = quoteToCalls(quote, slippage, account.address); await account.execute([...swapCalls, ...stakeCalls]); ``` -------------------------------- ### Fetch and Analyze Token Price Data using TypeScript Source: https://context7_llms This TypeScript example fetches 30 days of daily price data for a given token address from the Avnu Finance API. It then calculates and logs basic price statistics such as average, maximum, and minimum prices. Dependencies include the native `fetch` API and `URLSearchParams`. ```typescript // Fetch 30 days of daily price data const tokenAddress = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7'; const endDate = new Date(); const startDate = new Date(); startDate.setDate(startDate.getDate() - 30); const params = new URLSearchParams({ startDate: startDate.toISOString(), endDate: endDate.toISOString(), resolution: '1D', in: 'USD' }); const response = await fetch( `https://starknet.impulse.avnu.fi/v1/tokens/${tokenAddress}/prices/line?${params}` ); const data = await response.json(); // Calculate price statistics const prices = data.map(d => d.value); const avgPrice = prices.reduce((a, b) => a + b) / prices.length; const maxPrice = Math.max(...prices); const minPrice = Math.min(...prices); console.log(`30-day stats: Avg: $${avgPrice}, High: $${maxPrice}, Low: $${minPrice}`); ``` -------------------------------- ### GET /swap/v3/quotes Source: https://context7_llms Retrieves quote information for a token swap. This endpoint allows users to get details about potential token exchanges, including amounts, fees, and routing information. ```APIDOC ## GET /swap/v3/quotes ### Description Retrieves quote information for a token swap. This endpoint allows users to get details about potential token exchanges, including amounts, fees, and routing information. ### Method GET ### Endpoint /swap/v3/quotes ### Query Parameters - **sellTokenAddress** (string) - Required - The address of the token to be sold. - **buyTokenAddress** (string) - Required - The address of the token to be purchased. - **sellAmount** (string) - Required - The amount of the sell token (in hex format). - **takerAddress** (string) - Optional - The address of the user initiating the swap. - **takerAmount** (string) - Optional - The exact amount of the token the taker wants to receive (in hex format). - **fee** (string) - Optional - The fee percentage to be applied to the swap. - **integratorFee** (string) - Optional - The integrator fee percentage to be applied. - **maxPriceImpact** (string) - Optional - The maximum acceptable price impact for the swap. - **chain_id** (string) - Optional - The chain ID for the transaction. - **exclude_protocols** (string) - Optional - A comma-separated list of protocols to exclude from routing. - **include_protocols** (string) - Optional - A comma-separated list of protocols to include in routing. ### Response #### Success Response (200) - **quoteId** (string) - Unique identifier for the quote. - **sellTokenAddress** (string) - Token address being sold. - **sellAmount** (string) - Amount of token to sell (hex format). - **sellAmountInUsd** (number) - USD value of sell amount. - **buyTokenAddress** (string) - Token address being purchased. - **buyAmount** (string) - Amount of token to receive (hex format). - **buyAmountInUsd** (number) - USD value of buy amount. - **fee** (object) - Fee breakdown for the swap. - **feeToken** (string) - Token address used for fees. - **avnuFees** (string) - Platform fees (hex format). - **avnuFeesInUsd** (number) - Platform fees in USD. - **avnuFeesBps** (string) - Platform fees in basis points. - **integratorFees** (string) - Integrator fees (hex format). - **integratorFeesInUsd** (number) - Integrator fees in USD. - **integratorFeesBps** (string) - Integrator fees in basis points. - **chainId** (string) - Network identifier. - **blockNumber** (string) - Block at which quote was generated (hex format). - **expiry** (number) - Unix timestamp when quote expires in seconds. - **routes** (array) - Swap routing paths with protocol details. - **name** (string) - DEX protocol identifier. - **address** (string) - Smart contract address. - **percent** (number) - Allocation percentage. - **sellTokenAddress** (string) - Input token for this route. - **buyTokenAddress** (string) - Output token for this route. - **routes** (array) - Nested routing steps. - **alternativeSwapCount** (integer) - Number of alternative swaps available. - **gasFees** (string) - Estimated gas cost in STRK (hex format). - **gasFeesInUsd** (number) - Gas fees converted to USD. - **priceImpact** (number) - Price impact in USD and in bps. - **sellTokenPriceInUsd** (number) - Current market price of sell token in USD. - **buyTokenPriceInUsd** (number) - Current market price of buy token in USD. - **estimatedSlippage** (number) - Projected slippage percentage. ### Request Example ```bash curl "https://starknet.api.avnu.fi/swap/v3/quotes?sellTokenAddress=0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7&buyTokenAddress=0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d&sellAmount=0x2386f26fc10000" ``` ```typescript const params = new URLSearchParams({ sellTokenAddress: '0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', buyTokenAddress: '0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', sellAmount: '0x2386f26fc10000' }); const response = await fetch(`https://starknet.api.avnu.fi/swap/v3/quotes?${params}`); const quotes = await response.json(); console.log('Quote:', quotes); ``` ```python import requests params = { 'sellTokenAddress': '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', 'buyTokenAddress': '0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d', 'sellAmount': '0x2386f26fc10000' } response = requests.get( 'https://starknet.api.avnu.fi/swap/v3/quotes', params=params ) quotes = response.json() print('Quote:', quotes) ``` ```