Enso 백서

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

}); ``` #### getBundleData(params: BundleParams, actions: BundleAction\[]) Constructs bundled transaction data for multiple DeFi operations in a single transaction. **First argument (`params`):** * `chainId` (number): Chain ID of the network to execute the transaction on * `fromAddress` (Address): Ethereum address of the wallet sending the transaction * `routingStrategy` (RoutingStrategy): Execution strategy * `receiver?` (Address): Default final-output receiver * `spender?` (Address): Account supplying input assets when supported * `refundReceiver?` (Address): Dust or applicable bridge-refund receiver * `ignoreAggregators?` (string\[]): Swap aggregators to ignore * `referralCode?` (string): Referral code included in the on-chain event **Second argument (`actions`):** ordered `BundleAction[]` request body. **Returns:** `Promise<BundleData>` ```typescript theme={null} const bundle = await enso.getBundleData( { chainId: 1, fromAddress: '0x123...', routingStrategy: 'delegate', }, [ { protocol: 'enso', action: 'route', args: { tokenIn: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', amountIn: '1000000000', receiver: '0x123...' } } ] ); ``` ### Data Retrieval Methods #### getBalances(params: BalanceParams) Retrieves token balances for a given wallet address. **Parameters:** * `chainId?` (number): Chain ID of the network to execute the transaction on * `eoaAddress` (Address): Address of the EOA to associate with the ensoWallet for balances * `useEoa?` (boolean): If true, returns balances for the provided eoaAddress instead of the associated ensoWallet **Returns:** `Promise<WalletBalance[]>` ```typescript theme={null} const balances = await enso.getBalances({ chainId: 1, eoaAddress: '0xYourWalletAddress', useEoa: true, }); ``` #### getTokenData(params: TokenParams) Fetches detailed information about tokens, including DeFi tokens and their underlying assets. **Parameters:** * `project?` (string): The overarching project or platform associated with the DeFi token * `protocolSlug?` (string): The specific standard integration or version of the DeFi project * `underlyingTokens?` (MultiAddress): Underlying tokens of defi token * `underlyingTokensExact?` (MultiAddress): Exact composition of underlying tokens * `primaryAddress?` (MultiAddress): Ethereum addresses for contract interaction * `address?` (MultiAddress): Ethereum addresses of the tokens * `chainId?` (number): Chain ID of the network of the token * `type?` (TokenType): Type of token ('defi' | 'base') * `apyFrom?` (Quantity): Only include tokens with APY over this value * `apyTo?` (Quantity): Only include tokens with APY below this value * `tvlFrom?` (Quantity): Only include tokens with TVL over this value * `tvlTo?` (Quantity): Only include tokens with TVL below this value * `page?` (number): Pagination page number (pages are of length 1000) * `cursor?` (number): Cursor for pagination * `includeMetadata?` (boolean): Whether to include token metadata * `name?` (string\[]): Names of the tokens * `symbol?` (string\[]): Symbols of the tokens **Returns:** `Promise<PaginatedTokenData>` ```typescript theme={null} const tokens = await enso.getTokenData({ chainId: 1, type: 'defi', includeMetadata: true, page: 1 }); ``` #### getPriceData(params: PriceParams) Gets the current price data for a specific token. **Parameters:** * `chainId` (number): Chain ID of the network to search for * `address` (Address): Address of the token to search for **Returns:** `Promise<PriceData>` ```typescript theme={null} const price = await enso.getPriceData({ chainId: 1, address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH }); ``` #### getMultiplePriceData(params: MultiPriceParams) Gets price data for multiple tokens. **Parameters:** * `chainId` (number): Chain ID of the network to search for * `addresses` (Address\[]): Addresses of tokens to check prices for **Returns:** `Promise<PriceData[]>` ```typescript theme={null} const prices = await enso.getMultiplePriceData({ chainId: 1, addresses: [ '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC ] }); ``` ### Protocol and Standard Methods #### getProtocolData(params?: ProtocolParams) Retrieves information about DeFi protocols supported by Enso. **Parameters:** * `chainId?` (number | string): Chain ID of the network to search for * `slug?` (string): Slug of the project to search for **Returns:** `Promise<ProtocolData[]>` ```typescript theme={null} // Get all protocols const allProtocols = await enso.getProtocolData(); // Get protocols for a specific chain const ethereumProtocols = await enso.getProtocolData({ chainId: 1 }); // Get a specific protocol const aaveProtocol = await enso.getProtocolData({ slug: 'aave-v3' }); ``` #### getStandards() Returns standards available for bundling with protocol information and supported actions. **Returns:** `Promise<StandardData[]>` ```typescript theme={null} const standards = await enso.getStandards(); ``` #### getStandardBySlug(slug: string) Returns a standard matching the given slug with supported actions and chains. **Parameters:** * `slug` (string): The protocol slug **Returns:** `Promise<StandardData[]>` ```typescript theme={null} const aaveStandard = await enso.getStandardBySlug('aave-v3'); ``` #### getActions() Returns all actions that can be bundled with the `/shortcuts/bundle` endpoint. **Returns:** `Promise<ActionData[]>` ```typescript theme={null} const actions = await enso.getActions(); ``` #### getActionsBySlug(slug: string) Gets actions for a specific protocol. **Parameters:** * `slug` (string): The protocol slug **Returns:** `Promise<ActionData[]>` ```typescript theme={null} const aaveActions = await enso.getActionsBySlug('aave-v3'); ``` ### Specialized Methods #### getRouteNonTokenized(params: RouteNonTokenizedParams) Gets execution data for best route to non-tokenized positions. **Parameters:** * `chainId` (number): Chain ID of the network to execute the transaction on * `fromAddress` (Address): Ethereum address of the wallet to send the transaction from * `routingStrategy` ('delegate' | 'delegate-legacy'): Routing strategy to use * `tokenIn` (Address\[]): Input tokens * `positionOut` (Address): Non-tokenized position to receive * `slippage?` (Quantity): Slippage in basis points * `amountIn` (Quantity\[]): Amount to send * `receiver` (Address): Receiver address * `spender?` (Address): Spender address * `referralCode?` (string): Referral code **Returns:** `Promise<RouteData>` ```typescript theme={null} const route = await enso.getRouteNonTokenized({ fromAddress: '0x123...', chainId: 1, routingStrategy: 'delegate', tokenIn: ['0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'], positionOut: '0xPositionAddress', amountIn: ['1000000000'], receiver: '0x123...', slippage: 50, }); ``` #### getIporShortcut(params, data: IporShortcutInputData) Returns a transaction for IPOR shortcut operations. **Parameters:** * `chainId?` (number): Chain ID (optional) * `fromAddress` (string): Ethereum address of the wallet * `data` (IporShortcutInputData): IPOR shortcut input data **Returns:** `Promise<IporShortcutData>` ```typescript theme={null} const iporShortcut = await enso.getIporShortcut( { chainId: 1, fromAddress: '0x123...' }, { amountIn: '1000000000000000000', tokenIn: '0xTokenAddress', tokenBToBuy: '0xTokenBAddress', percentageForTokenB: 5000, // 50% slippage: 50, simulate: true } ); ``` #### getNonTokenizedPositions(params?: NonTokenizedParams) Gets all non-tokenized positions with details. **Parameters:** * `project?` (string): The overarching project or platform * `protocolSlug?` (string): The specific standard integration * `chainId?` (number): Chain ID of the network * `destinationChainId?` (number): Destination chain ID for cross-chain bridging * `address?` (Address\[]): Ethereum addresses of positions * `primaryAddress?` (Address\[]): Ethereum addresses for contract interaction * `page?` (number): Pagination page number * `cursor?` (number): Cursor for pagination **Returns:** `Promise<PaginatedNonTokenizedPositionData>` ```typescript theme={null} const nonTokenizedPositions = await enso.getNonTokenizedPositions({ chainId: 1, project: 'aave' }); ``` ### Network and Utility Methods #### getNetworks(params?: NetworkParams) Returns networks supported by Enso. **Parameters:** * `name?` (string): Name of the network to search for * `chainId?` (string): Chain ID of the network to search for **Returns:** `Promise<ConnectedNetwork[]>` ```typescript theme={null} const networks = await enso.getNetworks(); const ethereum = await enso.getNetworks({ chainId: "1" }); ``` #### getProjects() Returns supported projects or platforms associated with available protocols. **Returns:** `Promise<Project[]>` ```typescript theme={null} const projects = await enso.getProjects(); ``` #### getProtocolsByProject(project: string) Returns all protocols available within the given project. **Parameters:** * `project` (string): The project name **Returns:** `Promise<ProtocolData[]>` ```typescript theme={null} const aaveProtocols = await enso.getProtocolsByProject('aave'); ``` #### getAggregators(chainId?: number) Fetches aggregators supported by Enso. **Parameters:** * `chainId?` (number): Chain ID to filter aggregators for **Returns:** `Promise<string[]>` ```typescript theme={null} const aggregators = await enso.getAggregators(1); ``` #### getVolume(chainId: number) Returns total USD and transactions volume for the given chainId. **Parameters:** * `chainId` (number): Chain ID to get volume for **Returns:** `Promise<unknown>` ```typescript theme={null} const volume = await enso.getVolume(1); ``` #### getAccountId() Gets the account ID associated with the API key. **Returns:** `Promise<string>` ```typescript theme={null} const accountId = await enso.getAccountId(); ``` ## Working with Large Numbers The SDK properly handles large numbers common in blockchain transactions: ```typescript theme={null} const wethAmount = "1000000000000000000"; // 1 WETH with 18 decimals const usdcAmount = "1000000"; // 1 USDC with 6 decimals ``` Always use base-unit strings for token amounts. Do not use JavaScript numbers. ## Bundle actions Start with the [Bundle API guide](/pages/build/get-started/bundling-actions), then use the [Bundle Actions Reference](/pages/build/reference/actions) for public composition actions. Query protocol metadata for current protocol-specific availability: ```typescript theme={null} // Get all available actions const actions = await enso.getActions(); // Get actions for a specific protocol const aaveActions = await enso.getActionsBySlug("aave-v3"); ``` Common bundle actions include: * **Route**: Token swaps and conversions * **Deposit**: Deposit tokens into DeFi protocols * **Redeem**: Withdraw tokens from DeFi protocols * **Approve**: Token approvals * **Borrow**: Borrow tokens from lending protocols * **Repay**: Repay loans to lending protocols * **Transfer**: Transfer tokens between addresses * **Bridge**: Cross-chain token transfers ## Error Handling The SDK includes proper error handling with custom error types: ```typescript theme={null} import { EnsoClient, EnsoApiError } from '@ensofinance/sdk'; try { const routeData = await enso.getRouteData(params); } catch (error) { if (error instanceof EnsoApiError) { console.error('API Error:', error.statusCode, error.responseData); } else { console.error('Request Error:', error.message); } } ``` ## Best Practices 1. **Use String Representations**: Always use string representations for token amounts to avoid precision issues with large numbers 2. **Handle Slippage**: Set appropriate slippage values (in basis points) to protect against price movements 3. **Gas Estimation**: Use the returned `gas` estimate to set appropriate gas limits 4. **Error Handling**: Implement proper error handling for network issues and API errors 5. **Rate Limiting**: Be mindful of API rate limits when making multiple requests ## Next Steps Explore these resources to fully leverage the Enso SDK: * [Routing Strategies](/pages/build/reference/routing-strategies) - Learn about the different routing options and when to use each one * [Bundle API](/pages/build/get-started/bundling-actions) - Compose, build, approve, and execute ordered actions * [Bundle Actions Reference](/pages/build/reference/actions) - Review public action inputs, outputs, and chaining rules * [Shortcuts](/pages/build/examples/shortcuts) - See practical examples of common DeFi operations implemented with the SDK * [Non-tokenized Positions](/pages/build/examples/route-nontokenized) - Discover how to interact with non-tokenized DeFi positions like Aave borrows or Liquity CDPs * [GitHub Repository](https://github.com/EnsoBuild/sdk-ts) - Access the source code, report issues, or contribute to the SDK * [Developer Chat](https://t.me/enso_shortcuts) - Join our Telegram group for technical support and discussions <div> <p>Updated </p> </div> # Swagger Source: https://docs.enso.build/pages/api-reference/swagger Swagger TODO # Custom Contract Calls Bundle Source: https://docs.enso.build/pages/build/examples/custom-call-bundle Bundle routing with non-standard ways to interact with protocols Enso supports When a standard `enso:route` isn't enough for protocols with unique function signatures (e.g., requiring a referral code as an argument), you can use the `/bundle` endpoint. By chaining actions like `enso:route` and `enso:call`, you can combine optimal routing with custom contract calls. ### Use Case: Swap and Deposit with a Custom Referral Code Let's explore a scenario where a user wants to swap `USDT` for `STAKED_HYPE`, and then deposit it for `LHYPE`, through a contract whose `deposit` function requires a custom `communityCode` argument. <Tabs> <Tab title="EOA signing"> When the transaction is from an EOA, the Enso Router contract executes the sequence. This requires explicit approvals for the router to operate on input tokens. #### Bundle Design In pseudo-code, the bundle looks as follows: ``` 0: enso.route(in: USDT, out: STAKED_HYPE, receiver: ENSO_ROUTER) 1: erc20.approve(STAKED_HYPE, HYPE_DEPOSITOR, amount: outputOfCallAt(1)) 2: enso.call( HYPE_DEPOSITOR.deposit(STAKED_HYPE, outputOf(1), 0, SENDER, "0x1234") ) ``` * **Setup: approve transaction**. The user approves the Enso Router to spend their input `USDT`, which is a required first step to grant the router permission for the swap. * **Action 0: `enso:route`**. The router swaps `USDT` for `STAKED_HYPE`. The `receiver` is critically set to the `ENSO_ROUTER` itself so it can hold the tokens for the next steps. * **Action 1: `erc20:approve`**. The Enso Router approves the final `HYPE_DEPOSITOR` contract, using `{ useOutputOfCallAt: 1 }` to dynamically set the approval amount to the exact output from the previous swap. * **Action 2: `enso:call`**. The router calls the final `deposit` function, passing the dynamic swap amount (again with `{ useOutputOfCallAt: 1 }`), the user's address as the recipient, and the required static `communityCode`. ```ts routeCustomCallEOA.ts theme={null} import { EnsoClient } from "@ensofinance/sdk"; const client = new EnsoClient({ apiKey: "YOUR_API_KEY", // Replace with your Enso API key }); // Define asset and contract addresses const USDT = "0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb"; const STAKED_HYPE = "0xffaa4a3d97fe9107cef8a3f48c069f577ff76cc1"; const HYPE_DEPOSITOR = "0x6e358dd1204c3fb1D24e569DF0899f48faBE5337"; const SENDER = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; // The user's EOA address const ENSO_ROUTER = "0xF75584eF6673aD213a685a1B58Cc0330B8eA22Cf"; // Enso's Router contract // Approve Enso router to use USDT const approval = await client.getApprovalData({ amount: USDT_AMOUNT, chainId: 999, fromAddress: SENDER, tokenAddress: USDT, }); // create the bundle const bundle = await client.getBundleData( { chainId: 999, fromAddress: SENDER, routingStrategy: "router", receiver: SENDER, }, [ { protocol: "enso", action: "route", args: { tokenIn: USDT, tokenOut: STAKED_HYPE, amountIn: USDT_AMOUNT, }, }, { protocol: "erc20", action: "approve", args: { amount: { useOutputOfCallAt: 0 }, spender: HYPE_DEPOSITOR, token: STAKED_HYPE, }, }, { protocol: "enso", action: "call", args: { tokenIn: STAKED_HYPE, tokenOut: LOOPED_HYPE, address: HYPE_DEPOSITOR, args: [ STAKED_HYPE, { useOutputOfCallAt: 0 }, 0, SENDER, "0x1234", ], method: "deposit", abi: "function deposit(address depositAsset, uint256 depositAmount, uint256 minimumMint, address to, bytes communityCode) external returns (uint256 shares)", }, }, ], ); await signEoa(approval.tx, approval.gas); await signEoa(bundle.tx, bundle.gas); console.log("Approval", {gas: approval.gas, tx: approval.tx}) console.log("Bundle", JSON.stringify(bundle, null, 2)); ``` </Tab> <Tab title="Smart wallet signing"> ### Smart Wallet Example (`routingStrategy: 'delegate'`) With a Smart Wallet, the wallet executes the bundle directly, simplifying the approval flow into fewer steps. #### Bundle Design In pseudo-code, we need to do the following: ``` 0: enso.route(in: USDT, out: STAKED_HYPE, receiver: SENDER) | 1: erc20.approve(STAKED_HYPE, HYPE_DEPOSITOR, amount: outputOfCallAt(0)) | 2: enso.call( HYPE_DEPOSITOR.deposit(STAKED_HYPE, outputOf(0), 0, SENDER, "0x1234") ) ``` * **Action 0: `enso:route`**. The Smart Wallet swaps `USDT` for `STAKED_HYPE` and receives the output tokens directly. * **Action 1: `erc20:approve`**. The Smart Wallet approves the final `HYPE_DEPOSITOR` contract, using `{ useOutputOfCallAt: 0 }` to dynamically approve the exact amount received from the swap. * **Action 2: `enso:call`**. The Smart Wallet calls the custom `deposit` function, passing the dynamic swap amount (again using `{ useOutputOfCallAt: 0 }`), the user's address as the recipient, and the required static `communityCode`. ```ts routeCustomCallSmartWallet.ts theme={null} import { EnsoClient } from "@ensofinance/sdk"; const client = new EnsoClient({ apiKey: "YOUR_API_KEY", // Replace with your Enso API key }); // Define asset and contract addresses const USDT = "0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb"; const STAKED_HYPE = "0xffaa4a3d97fe9107cef8a3f48c069f577ff76cc1"; const HYPE_DEPOSITOR = "0x6e358dd1204c3fb1D24e569DF0899f48faBE5337"; const SENDER = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; const bundle = await client.getBundleData( { chainId: 999, fromAddress: SENDER, routingStrategy: "delegate", receiver: SENDER, }, [ { protocol: "enso", action: "route", args: { tokenIn: USDT, tokenOut: STAKED_HYPE, amountIn: "100000000", receiver: SENDER, }, }, { protocol: "erc20", action: "approve", args: { token: STAKED_HYPE, spender: HYPE_DEPOSITOR, amount: { useOutputOfCallAt: 0 }, }, }, { protocol: "enso", action: "call", args: { address: HYPE_DEPOSITOR, method: "deposit", abi: "function deposit(address depositAsset, uint256 depositAmount, uint256 minimumMint, address to, bytes communityCode) external returns (uint256 shares)", args: [STAKED_HYPE, { useOutputOfCallAt: 0 }, 0, SENDER, "0x1234"], }, }, ] ); console.log(JSON.stringify(bundle, null, 2)); ``` </Tab> </Tabs> <div> <p>Updated </p> </div> # Request Tracking Source: https://docs.enso.build/pages/build/examples/request-referral Tag requests with a referral code to track usage and rewards. With `/bundle` and `/route` APIs you can tag transactions with a `referralCode`, allowing you to track usage and rewards associated with that code. Every transaction these APIs create will emit a `ShortcutExecuted` event with the referral code: ```solidity theme={null} ShortcutExecuted(accountId: bytes32, requestId: byte
프로젝트로 돌아가기