### Get Started Source: https://docs.avnu.fi/llms Guides and overviews for getting started with Avnu.fi. ```APIDOC ## GET /get-started/first-swap ### Description Build a working token swap in 5 minutes. ### Method GET ### Endpoint /get-started/first-swap ### Parameters #### Query Parameters - **param1** (type) - Required/Optional - Description ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ## GET /get-started/overview ### Description Start building with avnu in minutes. ### Method GET ### Endpoint /get-started/overview ### Parameters #### Query Parameters - **param1** (type) - Required/Optional - Description ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Install avnu-sdk using npm Source: https://docs.avnu.fi/get-started/overview Installs the avnu SDK package using npm. This is the first step to integrating avnu's liquidity aggregation into your application. Ensure you have Node.js and npm installed. ```bash npm install @avnu/avnu-sdk ``` -------------------------------- ### Install avnu SDK with npm, yarn, or pnpm Source: https://docs.avnu.fi/get-started/first-swap Install the avnu SDK package using your preferred package manager. This is the first step to integrating avnu's token swapping capabilities into your project. ```bash npm install @avnu/avnu-sdk ``` ```bash yarn add @avnu/avnu-sdk ``` ```bash pnpm add @avnu/avnu-sdk ``` -------------------------------- ### Execute Token Swap with Avnu.fi SDK (TypeScript) Source: https://docs.avnu.fi/get-started/first-swap This example demonstrates how to fetch swap quotes and execute a swap using the Avnu.fi SDK. It requires setting up a Starknet provider and account, and uses the `getQuotes` and `executeSwap` functions. Dependencies include `starknet` and `@avnu/avnu-sdk`. ```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); ``` -------------------------------- ### Basic Swap Execution with Avnu SDK Source: https://docs.avnu.fi/docs/swap/execute-swap This example demonstrates how to execute a basic swap using the Avnu SDK. It involves first fetching quotes using `getQuotes` and then calling `executeSwap` with the obtained quote, slippage, and the Starknet account provider. Ensure necessary imports and setup for `provider` and `account` are done prior. ```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); ``` -------------------------------- ### Environment Variables for Avnu.fi SDK Source: https://docs.avnu.fi/get-started/first-swap This snippet shows the required environment variables for running the Avnu.fi SDK examples. It includes `ACCOUNT_ADDRESS` for the Starknet account and `PRIVATE_KEY` for authentication. These should be kept secure and not committed to version control. ```env ACCOUNT_ADDRESS=0x... PRIVATE_KEY=0x... ``` -------------------------------- ### Response Example (JSON) Source: https://docs.avnu.fi/llms-full Example JSON response structure for the exchange volumes endpoint. It includes trading volume in token amount and USD, the exchange name, and the start and end dates for the period. ```json [ { "value": 5234.567, "valueUsd": 2500000, "exchange": "Ekubo", "startDate": "2024-02-01", "endDate": "2024-02-14" }, { "value": 3789.123, "valueUsd": 1800000, "exchange": "JediSwap", "startDate": "2024-02-01", "endDate": "2024-02-14" } ] ``` -------------------------------- ### Execute Token Swap with Integration Fees (TypeScript) Source: https://docs.avnu.fi/get-started/first-swap This example shows how to execute a token swap while including integration fees. It utilizes the `integratorFees`, `integratorFeeRecipient`, and `integratorName` parameters in the `getQuotes` function. Ensure the `integratorFeeRecipient` is correctly set and the `integratorName` is provided. ```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); ``` -------------------------------- ### Execute Swap using TypeScript SDK and REST API Source: https://docs.avnu.fi/introduction Demonstrates how to get swap quotes and execute a swap using the Avnu TypeScript SDK. It also shows how to fetch swap quotes via the REST API. Requires the '@avnu/avnu-sdk' package for the SDK and 'ethers' for unit parsing. The API example uses curl. ```typescript import { getQuotes, executeSwap } from '@avnu/avnu-sdk'; import { parseUnits } from 'ethers'; // Get best quote const quotes = await getQuotes({ sellTokenAddress: usdcAddress, buyTokenAddress: strkAddress, sellAmount: parseUnits('1000', 6), // 1000 USDC takerAddress: account.address, }); // Execute swap const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.001, // 0.1% }); ``` ```bash curl -X POST "https://starknet.api.avnu.fi/v3/swap/quotes" \ -H "Content-Type: application/json" \ -d '{ "sellTokenAddress": "0x053c...", "buyTokenAddress": "0x04718...", "sellAmount": "1000000000", "takerAddress": "0x..." }' ``` -------------------------------- ### Avnu SDK: Complete Swap Example (TypeScript) Source: https://docs.avnu.fi/docs/swap Demonstrates a complete example of using the Avnu SDK to fetch solver-optimized quotes and execute a swap. It initializes the Starknet provider and account, defines token addresses, fetches quotes, logs route information, and executes the swap, waiting for transaction confirmation. Dependencies include 'starknet' and '@avnu/avnu-sdk'. ```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); ``` -------------------------------- ### Fetch TVL Data by Exchange (Python) Source: https://docs.avnu.fi/api/markets/tvl-feed This Python script uses the `requests` library to fetch historical TVL data. It defines the token address, calculates start and end dates, and sends a GET request to the API. The response is then parsed as JSON. Ensure the `requests` library is installed (`pip install requests`). ```python import requests from datetime import datetime, timedelta token_address = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7' end_date = datetime.now() start_date = end_date - timedelta(days=7) params = { 'startDate': start_date.isoformat() + 'Z', 'endDate': end_date.isoformat() + 'Z', 'resolution': '1D' } response = requests.get( f'https://starknet.impulse.avnu.fi/v3/tokens/{token_address}/exchange-tvl/line', params=params ) tvl_data = response.json() print(f"Fetched {len(tvl_data)} TVL data points") ``` -------------------------------- ### Fetch Historical Trading Volume Data (Python) Source: https://docs.avnu.fi/api/markets/volume-feed Example using Python with the requests library to retrieve historical trading volume data. It dynamically sets the start and end dates and makes a GET request to the API endpoint. ```python import requests from datetime import datetime, timedelta token_address = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7' end_date = datetime.now() start_date = end_date - timedelta(days=7) params = { 'startDate': start_date.isoformat() + 'Z', 'endDate': end_date.isoformat() + 'Z', 'resolution': '4H' } response = requests.get( f'https://starknet.impulse.avnu.fi/v3/tokens/{token_address}/exchange-volumes/line', params=params ) volume_data = response.json() print(f"Fetched {len(volume_data)} volume data points") ``` -------------------------------- ### SDK Integration Examples (TypeScript) Source: https://docs.avnu.fi/llms-full Presents two examples of using the avnu SDK: a simple integration for executing a swap directly and an advanced integration for composing swap calls with other operations. ```typescript // Simple integration const quotes = await getQuotes({ ... }); const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 100 // 1% }); // Advanced: compose with other operations const swapCalls = quoteToCalls(quote, slippage, account.address); const otherCalls = [...]; await account.execute([...swapCalls, ...otherCalls]); ``` -------------------------------- ### Prompting with Context7 for avnu SDK Source: https://docs.avnu.fi/llms-full Example of how to use Context7 to fetch avnu documentation for building a token swap. By adding 'use context7' to the prompt, the AI will access the latest avnu documentation. ```text Build a token swap using avnu SDK. use context7 ``` -------------------------------- ### Fetch Historical Trading Volume Data (cURL) Source: https://docs.avnu.fi/api/markets/volume-feed Example using cURL to retrieve historical trading volume data for a token. Requires token address, start date, end date, and resolution as query parameters. ```bash curl "https://starknet.impulse.avnu.fi/v3/tokens/0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7/exchange-volumes/line?startDate=2024-02-01T00:00:00Z&endDate=2024-02-14T00:00:00Z&resolution=1D" ``` -------------------------------- ### Fetch Token Exchange Volumes (cURL) Source: https://docs.avnu.fi/api/markets/volume-by-exchange Example using cURL to fetch trading volume distribution for a token across exchanges within a specified date range. Requires token address, start date, and end date. ```bash curl "https://starknet.impulse.avnu.fi/v3/tokens/0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7/exchange-volumes?startDate=2024-02-01&endDate=2024-02-14" ``` -------------------------------- ### Build Swap Calls using Python Source: https://docs.avnu.fi/api/swap/build-swap This Python example illustrates how to build swap transaction calls. It begins by fetching a quote via the `/quotes` endpoint and then uses the quote's ID to request build calls from the `/build` endpoint. The final step involves executing the transaction using a Starknet account object. ```python import requests from starknet_py.net.account.account import Account # Step 1: Get quote 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() quote = quotes[0] # Step 2: Get execution calls execute_response = requests.post( 'https://starknet.api.avnu.fi/swap/v3/build', json={ 'quoteId': quote['quoteId'], 'takerAddress': account.address, 'slippage': 0.01, 'includeApprove': True }, ) calls = execute_response.json()['calls'] # Step 3: Execute transaction tx = await account.execute(calls) print(f"Swap complete: {tx.transaction_hash}") ``` -------------------------------- ### AI Integration Example Source: https://docs.avnu.fi/llms Demonstrates how to leverage AI coding assistants with Avnu Developers documentation. This example is conceptual and would involve specific AI tool integrations. ```python # Conceptual example for AI integration # Replace with actual AI SDK calls def ask_avnu_ai(query): # Assume an AI model is available to process documentation queries response = ai_model.query("avnu_docs", query) return response user_question = "How do I execute a swap?" answer = ask_avnu_ai(user_question) print(answer) ``` -------------------------------- ### Get Transfer Volume Data (Python) Source: https://docs.avnu.fi/api/markets/transfer-volume Fetches historical token transfer volume data using Python's requests library. It dynamically sets the start and end dates and makes a GET request to the AVNU FI API, then calculates total and average volumes from the response. ```python import requests from datetime import datetime, timedelta token_address = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7' end_date = datetime.now() start_date = end_date - timedelta(days=7) params = { 'startDate': start_date.isoformat() + 'Z', 'endDate': end_date.isoformat() + 'Z', 'resolution': '1D' } response = requests.get( f'https://starknet.impulse.avnu.fi/v3/tokens/{token_address}/volumes/line', params=params ) volume_data = response.json() total = sum(d['valueUsd'] for d in volume_data) avg = total / len(volume_data) if volume_data else 0 print(f"Total volume: ${total:,.0f}") print(f"Average daily volume: ${avg:,.0f}") ``` -------------------------------- ### Get Trade Quotes with avnu-sdk (TypeScript) Source: https://docs.avnu.fi/get-started/overview Fetches optimal trade execution quotes from avnu's aggregated liquidity sources. Requires the SDK, token addresses, sell amount, and taker address. It utilizes ethers.js for unit parsing. ```typescript import { getQuotes } from '@avnu/avnu-sdk'; import { parseUnits } from 'ethers'; const quotes = await getQuotes({ sellTokenAddress: ethAddress, buyTokenAddress: strkAddress, sellAmount: parseUnits('1', 18), takerAddress: account.address, }); ``` -------------------------------- ### Initialize Starknet Provider and Account in TypeScript Source: https://docs.avnu.fi/get-started/first-swap Set up the Starknet provider and account using starknet.js or starknet-react. This involves configuring the RPC node URL and providing account credentials. Ensure private keys are not hardcoded in production environments. ```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(); ``` -------------------------------- ### Server-Side Proxy Example (Next.js) Source: https://docs.avnu.fi/llms-full This example shows how to set up a server-side proxy using Next.js to securely handle requests to the AVNU Paymaster API, protecting your API key. ```APIDOC ## POST /api/paymaster (Server-Side Proxy) ### Description This Next.js API route acts as a proxy to the AVNU Paymaster endpoint. It securely forwards requests, including your API key in the headers, preventing exposure in the frontend. ### Method POST ### Endpoint `/api/paymaster` ### Parameters #### Request Body - **(Any valid Paymaster request body)** - The payload sent to the AVNU Paymaster service. ### Request Example ```typescript // app/api/paymaster/route.ts export async function POST(request: Request) { const body = await request.json(); const response = await fetch('https://starknet.paymaster.avnu.fi', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-paymaster-api-key': process.env.AVNU_API_KEY!, }, body: JSON.stringify(body), }); return Response.json(await response.json()); } ``` ### Response #### Success Response (200) - **(AVNU Paymaster API Response)** - The response from the AVNU Paymaster service. #### Response Example ```json { "result": "..." } ``` ``` -------------------------------- ### Get Transfer Volume Data (cURL) Source: https://docs.avnu.fi/api/markets/transfer-volume Fetches historical transfer volume data for a specified token address and date range using cURL. Requires token address, start date, end date, and an optional resolution. ```bash curl "https://starknet.impulse.avnu.fi/v3/tokens/0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7/volumes/line?startDate=2024-02-01T00:00:00Z&endDate=2024-02-14T00:00:00Z&resolution=1D" ``` -------------------------------- ### Get Recurring Buy Orders Source: https://docs.avnu.fi/docs/dca/integration-guide Fetches a list of active recurring buy orders for a given trader address. Orders can be filtered by status and sorted. ```APIDOC ## GET /api/dca/orders ### Description Fetches a list of recurring buy orders for a specific trader, with filtering and sorting options. ### Method GET ### Endpoint /api/dca/orders ### Parameters #### Query Parameters - **traderAddress** (string) - Required - The address of the trader. - **status** (string) - Optional - Filter orders by status (e.g., `INDEXING`, `ACTIVE`, `CLOSED`). - **page** (integer) - Optional - The page number for pagination (defaults to 0). - **size** (integer) - Optional - The number of items per page (defaults to 20). - **sort** (string) - Optional - The sorting criteria (e.g., `timestamp,desc`). ### Request Example ```json { "traderAddress": "account.address", "status": "ACTIVE", "page": 0, "size": 20, "sort": "timestamp,desc" } ``` ### Response #### Success Response (200) - **content** (array) - An array of order objects. - **id** (string) - The order ID. - **amountSold** (string) - The amount of sell token sold. - **amountBought** (string) - The amount of buy token bought. - **orderAddress** (string) - The address of the order. - **timestamp** (string) - The timestamp of the order. #### Response Example ```json { "content": [ { "id": "order123", "amountSold": "100000000000000000", "amountBought": "50000000000000000", "orderAddress": "0x...", "timestamp": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Example: Fetch All Tokens using AVNU SDK (TypeScript) Source: https://docs.avnu.fi/llms-full This example demonstrates how to use the `fetchTokens` function from the `@avnu/avnu-sdk` to retrieve the first 100 tokens. It logs the total number of tokens and details for each token on the current page, including symbol, name, address, and tags. ```typescript import { fetchTokens } from '@avnu/avnu-sdk'; // Get first 100 tokens const result = await fetchTokens(); console.log(`Total tokens: ${result.totalElements}`); console.log(`Tokens on this page: ${result.content.length}`); result.content.forEach(token => { console.log(`${token.symbol}: ${token.name}`); console.log(` Address: ${token.address}`); console.log(` Tags: ${token.tags.join(', ')}`); }); ``` -------------------------------- ### Get Transfer Volume Data (API Endpoint) Source: https://docs.avnu.fi/llms-full API endpoint for retrieving historical transfer volume data for a token. Requires token address, start date, end date, and resolution. ```http GET https://starknet.impulse.avnu.fi/v3/tokens/{tokenAddress}/volumes/line Retrieve historical transfer volume data over time ``` -------------------------------- ### Fetch Token Market Data (Python) Source: https://docs.avnu.fi/api/markets/get-token-market-data Example of how to fetch token market data using Python. This script uses the 'requests' library to call the AVNU API and then prints relevant market statistics. ```python import requests token_address = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7' response = requests.get( f'https://starknet.impulse.avnu.fi/v3/tokens/{token_address}' ) token = response.json() print(f"{token['symbol']} Market Data:") print(f" Price: ${token['starknet']['usd']}") print(f" 24h Change: {token['starknet'].get('usdPriceChangePercentage24h', 0):.2f}%") print(f" Market Cap: ${token['global']['usdMarketCap']:,.0f}" if token.get('global') else " Market Cap: N/A") print(f" Starknet TVL: ${token['starknet']['usdTvl']:,.0f}") ``` -------------------------------- ### Prompting with Context7 for avnu Paymaster Source: https://docs.avnu.fi/llms-full Example of how to use Context7 to get information about integrating avnu paymaster for gasless transactions. The phrase 'use context7' instructs the AI to retrieve relevant documentation. ```text How do I integrate avnu paymaster for gasless transactions? use context7 ``` -------------------------------- ### Build Swap Calls using TypeScript Source: https://docs.avnu.fi/api/swap/build-swap This TypeScript example demonstrates the complete process of building swap calls. It first fetches a quote using the `/quotes` endpoint and then uses the obtained quoteId to request execution calls from the `/build` endpoint. Finally, it executes the transaction using an account object. ```typescript // Step 1: Get quote 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(); const quote = quotes[0]; // Step 2: Get execution calls const executeResponse = await fetch('https://starknet.api.avnu.fi/swap/v3/build', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ quoteId: quote.quoteId, takerAddress: account.address, slippage: 0.01, includeApprove: true }) }); const { calls } = await executeResponse.json(); // Step 3: Execute transaction const tx = await account.execute(calls); await account.waitForTransaction(tx.transaction_hash); console.log(`Swap complete: ${tx.transaction_hash}`); ``` -------------------------------- ### Get Token Information (Example Data) Source: https://docs.avnu.fi/llms-full This snippet represents the structure of data returned when fetching token information. It includes details like token address, symbol, decimals, and price in USD. ```json { "sellTokenAddress": "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "sellAmount": "0x2386f26fc10000", "sellAmountInUsd": 28.2265, "buyTokenAddress": "0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d", "buyAmount": "0xd005a71ea99678000", "buyAmountInUsd": 28.25618, "fee": { "feeToken": "0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d", "avnuFees": "0xda475abf000", "avnuFeesInUsd": 0.000002, "avnuFeesBps": "0xf", "integratorFees": "0x0", "integratorFeesInUsd": 0.0, "integratorFeesBps": "0x0" }, "chainId": "0x534e5f4d41494e", "blockNumber": "0x3ca1b4", "expiry": null, "routes": [ { "name": "Nostra", "address": "0x49ff5b3a7d38e2b50198f408fa8281635b5bc81ee49ab87ac36c8324c214427", "percent": 0.55, "sellTokenAddress": "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "buyTokenAddress": "0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d", "routes": [], "alternativeSwapCount": 0 }, { "name": "Ekubo", "address": "0x5dd3d2f4429af886cd1a3b08289dbcea99a294197e9eb43b0e0325b4b", "percent": 0.45, "sellTokenAddress": "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", "buyTokenAddress": "0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d", "routes": [], "alternativeSwapCount": 0 } ], "gasFees": "0x19b1b3cb5956130", "gasFeesInUsd": 0.013633, "priceImpact": 10.51, "sellTokenPriceInUsd": 2825.618, "buyTokenPriceInUsd": 0.117692, "estimatedSlippage": 0.00032 } ``` -------------------------------- ### Fetch Token Market Data (cURL) Source: https://docs.avnu.fi/api/markets/get-token-market-data Example of how to fetch token market data using cURL. This request targets a specific token address on the Starknet network. ```bash curl "https://starknet.impulse.avnu.fi/v3/tokens/0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7" ``` -------------------------------- ### Fetch Token Price Data (cURL) Source: https://docs.avnu.fi/llms-full Example using cURL to fetch historical token price data. Requires token contract address, start date, end date, and resolution. ```bash curl -X GET "https://starknet.impulse.avnu.fi/v3/tokens/0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7/prices/line?startDate=2024-02-01T00:00:00Z&endDate=2024-02-14T00:00:00Z&resolution=1D" ``` -------------------------------- ### Execute Swap with avnu-sdk (TypeScript) Source: https://docs.avnu.fi/get-started/overview Executes a previously obtained trade quote using the avnu SDK. Requires a provider, the selected quote, and a slippage tolerance. This function handles the on-chain transaction for the swap. ```typescript import { executeSwap } from '@avnu/avnu-sdk'; const result = await executeSwap({ provider: account, quote: quotes[0], slippage: 0.001 }); ``` -------------------------------- ### DCA Migration Example (v3 vs v4) Source: https://docs.avnu.fi/llms-full Demonstrates how to migrate DCA order creation and retrieval from v3 to v4. V4 simplifies the creation process and updates the paymaster handling. ```typescript import { executeCreateOrder, fetchGetOrders } from '@avnu/avnu-sdk'; // Get orders const orders = await fetchGetOrders({ traderAddress }); // Create order const response = await executeCreateOrder( account, order, { gasless: true, gasTokenAddress: '0x...' } ); ``` ```typescript import { executeCreateDca, getDcaOrders } from '@avnu/avnu-sdk'; // Get orders const orders = await getDcaOrders({ traderAddress }); // Create order const response = await executeCreateDca({ provider: account, order, // Paymaster now uses starknet.js PaymasterInterface }); ``` -------------------------------- ### Fetch TVL by Exchanges (TypeScript) Source: https://docs.avnu.fi/api/markets/tvl-by-exchange This TypeScript example shows how to fetch and display the current TVL distribution for a given token address. It calculates the total TVL and visualizes the distribution across exchanges. ```typescript // Get current TVL distribution for USDC const tokenAddress = '0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8'; const response = await fetch( `https://starknet.impulse.avnu.fi/v3/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()})`); }); ``` -------------------------------- ### Fetch and Process Token Market Data (TypeScript) Source: https://docs.avnu.fi/api/markets/get-market-data This TypeScript example shows how to fetch token market data from the AVNU API using the Fetch API. It then processes the response to display the total number of tokens found and lists the top 5 tokens by market capitalization, including their price and 24-hour percentage change. ```typescript const response = await fetch('https://starknet.impulse.avnu.fi/v3/tokens'); const tokens = await response.json(); console.log(`Found ${tokens.length} tokens`); // Display top 5 by market cap tokens .filter(t => t.global?.usdMarketCap) .sort((a, b) => (b.global?.usdMarketCap || 0) - (a.global?.usdMarketCap || 0)) .slice(0, 5) .forEach((token, i) => { const change = token.starknet.usdPriceChangePercentage24h?.toFixed(2) ?? 'N/A'; console.log(`${i + 1}. ${token.symbol}: $${token.starknet.usd} (${change}%)`); }); ```