Enso 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 35쪽 중 10쪽

}); const volumeData = await response.json(); console.log(`Volume data for chain ${chainId}:`, volumeData); return volumeData; } catch (error) { console.error(`Error fetching volume data for chain ${chainId}:`, error); throw error; } } // Get volume data for Ethereum getChainVolume(1); ``` ```bash cURL theme={null} curl -X GET \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ENSO_API_KEY" \ "https://api.enso.build/api/v1/volume/1" \ | jq ``` </CodeGroup> ## Position Information The Token API delivers data about DeFi assets including pricing, composition, and yield metrics. Filter tokens by protocol, chain, underlying assets, APY, or TVL to discover specific DeFi opportunities. ### Filter Supported Tokens Query tokens based on various criteria like protocol, underlying assets, or token type. This helps users discover specific DeFi opportunities. **API Reference:** [GET `/v1/tokens`](/api-reference/tokens/tokens) <CodeGroup> ```ts EnsoSDK theme={null} import { EnsoClient } from '@ensofinance/sdk'; // Initialize the client with your API key const enso = new EnsoClient({ apiKey: 'YOUR_API_KEY' // Replace with your actual API key }); // Get Aave V3 DeFi tokens on Ethereum mainnet (chainId 1) with USDT as underlying async function getAaveV3UsdtTokensOnEthereum() { try { const tokenData = await enso.getTokenData({ chainId: 1, // Ethereum mainnet protocolSlug: 'aave-v3', type: 'defi', underlyingTokens: '0xdAC17F958D2ee523a2206206994597C13D831ec7', // USDT includeMetadata: true }); console.log('Aave V3 DeFi tokens with USDT as underlying on Ethereum:', tokenData.data); return tokenData.data; } catch (error) { console.error('Error fetching tokens:', error); throw error; } } getAaveV3UsdtTokensOnEthereum(); ``` ```bash cURL theme={null} curl -X GET \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ENSO_API_KEY" \ "https://api.enso.build/api/v1/tokens?chainId=1&protocolSlug=aave-v3&type=defi&underlyingTokens=0xdAC17F958D2ee523a2206206994597C13D831ec7&includeMetadata=true" \ | jq ``` </CodeGroup> ### Get Protocol TVL and APY Data Access yield and total value locked (TVL) information for DeFi protocols. This data is crucial for comparing investment opportunities across the DeFi landscape. **API Reference:** [GET `/v1/tokens`](/api-reference/tokens/tokens) with APY filters <CodeGroup> ```ts EnsoSDK theme={null} import { EnsoClient } from '@ensofinance/sdk'; // Initialize the client with your API key const enso = new EnsoClient({ apiKey: 'YOUR_API_KEY' // Replace with your actual API key }); // Get tokens with APY over 5% for a specific protocol async function getHighYieldTokensForProtocol(protocolSlug: string, minApy: number = 5) { try { const tokenData = await enso.getTokenData({ chainId: 1, protocolSlug: protocolSlug, type: 'defi', apyFrom: minApy, includeMetadata: true }); console.log(`${protocolSlug} tokens with APY > ${minApy}%:`, tokenData.data); return tokenData.data; } catch (error) { console.error('Error fetching high-yield tokens:', error); throw error; } } getHighYieldTokensForProtocol('yearn'); ``` ```bash cURL theme={null} curl -X GET \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ENSO_API_KEY" \ "https://api.enso.build/api/v1/tokens?chainId=1&protocolSlug=yearn-v2&type=defi&apyFrom=5&includeMetadata=true" \ | jq ``` </CodeGroup> ### Get Token Prices Retrieve current token prices with confidence scores, supporting decision-making around token swaps and valuations. **API Reference:** [GET `/prices/token-price`](/api-reference/tokens/token-price) <CodeGroup> ```ts EnsoSDK theme={null} import { EnsoClient } from '@ensofinance/sdk'; // Initialize the client with your API key const enso = new EnsoClient({ apiKey: 'YOUR_API_KEY' // Replace with your actual API key }); // Get price data for a specific token async function getTokenPrice(chainId: number, tokenAddress: string) { try { const priceData = await enso.getPriceData({ chainId, address: tokenAddress }); console.log(`Price data for ${tokenAddress} on chain ${chainId}:`, priceData); return priceData; } catch (error) { console.error('Error fetching token price:', error); throw error; } } // Get price for WETH on Ethereum getTokenPrice(1, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'); ``` ```bash cURL theme={null} curl -X GET \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ENSO_API_KEY" \ "https://api.enso.build/api/v1/prices/1/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" \ | jq ``` </CodeGroup> I'll add the token information use cases with the specified layout and examples: ### Get Information for Several Tokens Retrieve detailed information about multiple tokens in a single request to support portfolio analysis or multi-token operations. **API Reference:** [GET `/v1/tokens`](/api-reference/tokens/tokens) <CodeGroup> ```ts EnsoSDK theme={null} // SDK Example const ensoClient = new EnsoClient({ apiKey: "your-api-key" }); const tokenData = await ensoClient.getTokenData({ chainId: 1, address: [ "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "0x6b175474e89094c44da98b954eedeac495271d0f" ], includeMetadata: true }); ``` ```bash cURL theme={null} curl -X GET \ 'https://api.enso.build/api/v1/tokens?chainId=1&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2&address=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&address=0x6b175474e89094c44da98b954eedeac495271d0f&includeMetadata=true' \ -H "Authorization: Bearer $ENSO_API_KEY" \ -H 'accept: application/json' ``` </CodeGroup> ### Fetch All Tokens from a Specific Protocol Get a comprehensive list of all tokens associated with a particular protocol to understand available investment options. **API Reference:** [GET `/v1/tokens`](/api-reference/tokens/tokens) <CodeGroup> ```ts EnsoSDK theme={null} // SDK Example const ensoClient = new EnsoClient({ apiKey: "your-api-key" }); const aaveTokens = await ensoClient.getTokenData({ chainId: 1, protocolSlug: "aave-v3", includeMetadata: true }); ``` ```bash cURL theme={null} curl -X GET \ 'https://api.enso.build/api/v1/tokens?chainId=1&protocolSlug=aave-v3&includeMetadata=true' \ -H "Authorization: Bearer $ENSO_API_KEY" \ -H 'accept: application/json' ``` </CodeGroup> ### Filter by Token Type and Minimum TVL Find specific token types with a minimum TVL (Total Value Locked) threshold to focus on well-established and liquid DeFi positions. **API Reference:** [GET `/v1/tokens`](/api-reference/tokens/tokens) <CodeGroup> ```ts EnsoSDK theme={null} // SDK Example const ensoClient = new EnsoClient({ apiKey: "your-api-key" }); const defiTokens = await ensoClient.getTokenData({ chainId: 1, type: "defi", tvl: 1000000, // $1M minimum TVL includeMetadata: true }); ``` ```bash cURL theme={null} curl -X GET \ 'https://api.enso.build/api/v1/tokens?chainId=1&type=defi&tvlFrom=1000000&includeMetadata=true' \ -H "Authorization: Bearer $ENSO_API_KEY" \ -H 'accept: application/json' ``` </CodeGroup> <div> <p>Updated </p> </div> # DeFi and Swap Routing Source: https://docs.enso.build/pages/build/get-started/route Find optimal paths for crosschain entering/exiting DeFi positions or swapping ERC20 tokens. The Route API is Enso's **crosschain automated pathfinding engine** that calculates optimal multi-step paths between any two DeFi positions - `tokenIn` and `tokenOut`. Whether you're swapping tokens, entering yield vaults, or moving assets across chains, the Route API handles the complex routing logic automatically. <Tip> **Would `route` do the job?** <br /> The `route` API might be the simpler way to route your assets. Before using the bundle API, check if `route` would work using [happypath](https://happypath.enso.build). </Tip> **Routing vs Bundling**: The Route API excels at single-path operations where you want Enso to determine the optimal route automatically. For custom multi-step workflows where you need precise control over each action, use the [Bundle API](/api-reference/defi-shortcuts/bundle-a-list-of-actions) instead. **When to use routing**: Token swaps with optimal pricing, vault entries/exits, position migrations between protocols, crosschain transfers, and any scenario where you want automated route optimization rather than manually specifying each step. <img /> <img /> ## Quick Start The `route` API produces a gas-optimized, atomic transaction between the two given positions, combining `swap`, `deposit`, and `redeem` operations. <Note> Use the [Bundle API](/pages/build/get-started/bundling-actions) if you need other [actions Enso supports](/pages/build/reference/actions), such as `harvest`, `borrow`, `repay`. </Note> ## Sample requests <Tabs> <Tab title="Token Swap"> ```typescript theme={null} const route = await ensoClient.getRouteData({ fromAddress: "0x...", chainId: 1, tokenIn: ["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"], // ETH tokenOut: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], // USDC amountIn: ["1000000000000000000"], // 1 ETH slippage: "50", // 0.5% routingStrategy: "delegate" }); await wallet.sendTransaction(route.tx); ``` </Tab> <Tab title="Vault Entry (Zap)"> ```typescript theme={null} const route = await ensoClient.getRouteData({ fromAddress: "0x...", chainId: 1, tokenIn: ["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"], // ETH tokenOut: ["0xa258c4606ca8206d8aa700ce2143d7db854d168c"], // yvWETH amountIn: ["1000000000000000000"], // 1 ETH slippage: "100", // 1% routingStrategy: "delegate" }); // ETH → WETH → Yearn vault automatically await wallet.sendTransaction(route.tx); ``` </Tab> <Tab title="Crosschain swap"> ```typescript theme={null} const route = await ensoClient.getRouteData({ fromAddress: "0x...", chainId: 1, // Ethereum destinationChainId: 8453, // Base tokenIn: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], // USDC Ethereum tokenOut: ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"], // USDC Base amountIn: ["1000000000"], // 1,000 USDC slippage: "300", // 3% (higher for crosschain) routingStrategy: "delegate" }); // Bridge USDC from Ethereum to Base await wallet.sendTransaction(route.tx); ``` </Tab> <Tab title="Crosschain Vault Zap"> ```typescript theme={null} const route = await ensoClient.getRouteData({ fromAddress: "0x...", chainId: 1, // Ethereum destinationChainId: 8453, // Base tokenIn: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], // USDC Ethereum tokenOut: ["0x04C0599Ae5A44757c0af6F9eC3b93da8976c150A"], // weETH vault on Base amountIn: ["1000000000"], // 1,000 USDC slippage: "500", // 5% (complex operation) routingStrategy: "delegate" }); // Bridge + vault entry in one transaction await wallet.sendTransaction(route.tx); ``` </Tab> </Tabs> <div> <a href="#1-simple-token-swap"> See complete examples with full setup and explanations → </a> </div> ## Core Concepts <CardGroup> <Card title="Input/Output Model" icon="right-left-large"> Specify any `tokenIn` and `tokenOut` - ERC20 tokens, LP tokens, vault shares, or yield positions. The Route API automatically finds the optimal path between any two DeFi positions across protocols and chains. </Card> <Card title="Response" icon="code" href="#examples"> Response contains a complete transaction object ready to sign (`tx`), `amountOut` (expected output), `gas` (estimated), and `route` (optimized path taken). </Card> <Card title="Slippage Control" icon="arrow-trend-down"> Set slippage in basis points: `"50"` = 0.5%, `"300"` = 3%. Higher slippage for complex routes. **Cannot use both `slippage` and `minAmountOut`** - choose one protection method. </Card> <Card title="Crosschain Operations" icon="bridge"> Add `destinationChainId` for crosschain routes. API automatically selects optimal bridges and calculates fees. </Card> </CardGroup> <Note> EVM → Solana routes end with token delivery on Solana. See [Solana routing](/pages/build/get-started/solana-routing) for the request requirements, a complete example, and delivery tracking. </Note> ## Control Crosschain Route Complexity For crosschain Route API requests, `crosschainRouteMode` controls where Enso may add same-chain routing around the bridge. It defaults to `"full"`; omit it to allow routing on both chains. | `crosschainRouteMode` | Allowed route shape | | - | - | | `"direct"` | Bridge the requested `tokenIn` directly into the requested `tokenOut`. | | `"source"` | Route on the source chain before bridging, then bridge directly into `tokenOut`. | | `"destination"` | Bridge `tokenIn` directly, then route on the destination chain. | | `"sourceOrDestination"` | Allow routing on the source or destination chain, but not both. | | `"full"` | Route before and after the bridge. This is the default. | Use a narrower mode when your product requires a specific crosschain route shape. This option applies only when `destinationChainId` is set. Solana destinations support source-side EVM composition only. See [Solana route modes](/pages/build/get-started/solana-routing#route-modes) for how each mode applies. ## Response Structure Use these fields to build the quote review screen: | Field | What it means | Show it as | | - | - | - | | `tx` | Complete transaction object ready for submission. Contains the correct `to`, `data`, `value`, and gas fields. | The transaction your wallet signs. Submit it as-is. | | `amountOut` | Simulated output amount from the selected route. | Expected output or estimated received amount. | | `minAmountOut` | Slippage-protected minimum output when available. | Minimum received amount. | | `gas` | Estimated gas usage from simulation. | Network cost estimate and transaction gas value. | | `priceImpact` | Estimated price impact for the route when available. | Price impact warning or route quality indicator. | | `route` | The optimization path Enso constructed. | Route details, protocols, or path disclosure. | | `preTransactions` | Transactions that may need to run before `tx`, including token approvals and protocol setup. Skip token approvals when the current allowance is sufficient. | Required setup transactions, in execution order. | | `metadata.bridgeFees` | Bridge and intent execution fees by protocol, component, source and destination chain, fee token, amount, and quote type. Amounts use the fee token's base unit. `deductedFromAmountOut` indicates whether the fee already reduced the quoted output. | Bridge fee breakdown. | Execute each required `preTransactions` entry before submitting `tx`. The `type` is `tokenApproval` for ordinary ERC-20 approvals or `requiredApproval` for protocol-specific setup. Submit each nested `tx` unchanged. Set `includeTransactionCost` to `true` to include `transactionCost` and `transactionCostUsd` in the response. It also adds `amountUsd` to each `metadata.bridgeFees` entry and the aggregate `metadata.bridgeFeeUsd`. The aggregate includes maximum fee reserves, is omitted when there are no fees, and is `null` when any non-zero fee cannot be priced. `transactionCost` is a point-in-time estimate in the source chain's native token smallest unit. `transactionCostUsd` is its decimal USD value. Either transaction cost field can be `null` when the source-chain fee estimate or native-token price is unavailable. The estimate covers mandatory source-chain execution fees. It excludes priority fees, `tx.value`, bridge fees, and destination-chain execution, so treat it as a lower bound rather than the final wallet fee. <Tip> Always use the complete `tx` object returned by the API, and use the `gas` value for your transaction. * The `to` address varies based on routing strategy, and other fields like `value` and `data` are precisely calculated for your specific route. * The `gas` value estimate comes from actual simulation and helps prevent out-of-gas transaction failures. </Tip> ## Examples The following examples progress from simple token swaps to complex crosschain vault interactions. Each example builds on concepts from previous ones, demonstrating how the Route API handles increasingly sophisticated DeFi operations automatically. ### 0. Install & Authenticate You can interact with the API using Enso SDK or directly via a REST API. You can explore Enso through [API Sandbox](/api-reference/). To install the SDK run the following command: ```bash theme={null} npm i @ensofinance/sdk pnpm i @ensofinance/sdk yarn add @ensofinance/sdk ``` To use the API, authenticate using the [API key](/pages/build/get-started/authentication). ### 1. Simple Token Swap Start with the most basic routing operation: swapping ETH for USDC on Ethereum mainnet. <CodeGroup> ```typescript SDK theme={null} import { EnsoClient } from '@ensofinance/sdk'; const ensoClient = new EnsoClient({ apiKey: 'your-api-key-here' }); const fromAddress = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; const receiver = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; const spender = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; // ETH → USDC swap with 0.5% slippage const swapRoute = await ensoClient.getRouteData({ fromAddress, receiver, spender, chainId: 1, amountIn: ["1000000000000000000"], // 1 ETH tokenIn: ["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"], // ETH tokenOut: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], // USDC slippage: "50", // 0.5% routingStrategy: "delegate" }); console.log('Expected USDC output:', swapRoute.amountOut); console.log('Estimated gas:', swapRoute.gas); console.log('Swap route complexity:', swapRoute.route.length, 'steps'); // Use route.tx to execute the transaction const txHash = await wallet.sendTransaction(swapRoute.tx); ``` ```bash cURL theme={null} curl --request POST \ --url https://api.enso.build/api/v1/shortcuts/route \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $ENSO_API_KEY" \ --data '{ "chainId": 1, "fromAddress": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "routingStrategy": "delegate", "receiver": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "spender": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "tokenIn": ["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"], "tokenOut": ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], "amountIn": ["1000000000000000000"], "slippage": "50" }' | jq ``` </CodeGroup> ### 2. Zap into Vault Enter a Yearn vault directly from ETH, automatically handling any intermediate swaps and vault deposits. <CodeGroup> ```typescript SDK theme={null} // ETH → yvWETH (Yearn WETH vault) with 1% slippage const vaultEntry = await ensoClient.getRouteData({ fromAddress, receiver, spender, chainId: 1, amountIn: ["1000000000000000000"], // 1 ETH tokenIn: ["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"], // ETH tokenOut: ["0xa258c4606ca8206d8aa700ce2143d7db854d168c"], // yvWETH slippage: "100", // 1% routingStrategy: "delegate" }); console.log('yvWETH shares received:', vaultEntry.amountOut); console.log('Route complexity:', vaultEntry.route.length, 'steps'); // Route typically: ETH → WETH → deposit to Yearn vault ``` ```bash cURL theme={null} # ETH → yvWETH (Yearn WETH vault) with 1% slippage curl --request POST \ --url https://api.enso.build/api/v1/shortcuts/route \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer $ENSO_API_KEY" \ --data '{ "chainId": 1, "fromAddress": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "routingStrategy": "delegate", "receiver": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "spender": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "tokenIn": ["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"], "tokenOut": ["0xa258c4606ca8206d8aa700ce2143d7db854d168c"], "amountIn": ["1000000000000000000"], "slippage": "100" }' | jq ``` </CodeGroup> **What's happening:** The router automatically wraps ETH to WETH, then deposits into the Y
프로젝트로 돌아가기