The Enso SDK provides a set of tools and methods to interact with the Enso API. It includes functionalities for token approvals, routing, quoting, and balance checking. The Route API is a highly-efficient DeFi aggregation and smart order routing REST API. With it, developers can easily tap into optimized routes for DeFi tokens/positions and multi-token swaps across various chains.

View on GitHub

Installation

Install the Enso SDK using your preferred package manager:

npm install @ensofinance/sdk

Quick Start

This example shows how to swap ETH directly to a Yearn vault position:

import { EnsoClient } from '@ensofinance/sdk';

const enso = new EnsoClient({
  apiKey: 'YOUR_API_KEY',
});

async function enterYearnVault() {
  // First, get the transaction data
  const routeData = await enso.getRouteData({
    fromAddress: '0xYourWalletAddress',
    receiver: '0xYourWalletAddress',
    spender: '0xYourWalletAddress',
    chainId: 1,
    amountIn: ['1000000000000000000'], // 1 ETH
    tokenIn: ['0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'], // ETH
    tokenOut: ['0xa258C4606Ca8206D8aA700cE2143D7db854D168c'], // yvWETH
    slippage: 50,
    routingStrategy: 'router',
  });
  
  // The routeData.tx object can now be sent using your preferred web3 library
  // Example with ethers.js:
  // const provider = new ethers.providers.Web3Provider(window.ethereum);
  // const signer = provider.getSigner();
  // const tx = await signer.sendTransaction(routeData.tx);
  // await tx.wait();
  
  console.log('Transaction data:', routeData.tx);
  console.log('Expected yvWETH amount:', routeData.amountOut);
}

enterYearnVault();

Core Concepts

The Enso SDK abstracts complex DeFi operations through several key components:

  1. EnsoClient: The main entry point for all SDK functionalities
  2. Routing Strategies: Different execution paths for transactions
  3. Bundle Actions: Compose multiple DeFi operations in a single transaction
  4. Approvals: Manage token allowances for DeFi interactions
  5. Token Data: Retrieve detailed information about tokens and protocols

Routing Strategies

There are 3 routing strategies available depending on your use case:

  • router - Uses a single contract which acts as a universal router
  • delegate - Returns calldata in the form of delegateCalls for smart accounts
  • delegate-legacy - Legacy version of delegate routing
  • router-legacy - Legacy version of router routing

Complete Methods Reference

Primary Methods

getRouteData(params: RouteParams)

Calculates the optimal route for token swaps or entering/exiting DeFi positions.

Parameters:

  • fromAddress (Address): Ethereum address of the wallet to send the transaction from
  • receiver? (Address): Ethereum address of the receiver of the tokenOut
  • spender? (Address): Ethereum address of the spender of the tokenIn
  • chainId (number): Chain ID of the network to execute the transaction on
  • destinationChainId? (number): Chain ID of the destination network for cross-chain bridging
  • amountIn (Quantity[]): Amount of tokenIn to swap in wei
  • slippage? (Quantity): Slippage in basis points (1/10000)
  • minAmountOut? (Quantity[]): Minimum amount out in wei
  • tokenIn (Address[]): Ethereum address of the token to swap from
  • tokenOut (Address[]): Ethereum address of the token to swap to
  • routingStrategy (RoutingStrategy): Routing strategy to use
  • fee? (Quantity[]): Fee in basis points for each amountIn value
  • feeReceiver? (Address): Address that will receive the collected fee
  • ignoreAggregators? (string[]): List of swap aggregators to ignore
  • ignoreStandards? (string[]): List of standards to ignore
  • toEoa? (boolean): Flag indicating if gained tokenOut should be sent to EOA
  • referralCode? (string): Referral code included in on-chain event

Returns: Promise<RouteData>

const routeData = await enso.getRouteData({
  fromAddress: '0xYourWalletAddress',
  receiver: '0xYourWalletAddress',
  spender: '0xYourWalletAddress',
  chainId: 1,
  amountIn: ['1000000000000000000'], // 1 ETH in wei
  tokenIn: ['0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'], // ETH
  tokenOut: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // DAI
  slippage: 50, // 0.5%
  routingStrategy: 'router',
});

getApprovalData(params: ApproveParams)

Generates transaction data for approving tokens to be spent by Enso contracts.

Parameters:

  • fromAddress (Address): Ethereum address of the wallet to send the transaction from
  • tokenAddress (Address): ERC20 token address of the token to approve
  • chainId (number): Chain ID of the network to execute the transaction on
  • amount (Quantity): Amount of tokens to approve in wei

Returns: Promise<ApproveData>

const approvalData = await enso.getApprovalData({
  fromAddress: '0xYourWalletAddress',
  tokenAddress: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH
  chainId: 1,
  amount: '1000000000000000000', // 1 WETH in wei
});

getBundleData(params: BundleParams, actions: BundleAction[])

Constructs bundled transaction data for multiple DeFi operations in a single transaction.

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 (RoutingStrategy): Routing strategy to use
  • receiver? (Address): Ethereum address of the receiver of the tokenOut
  • spender? (Address): Ethereum address of the spender of the tokenIn
  • ignoreAggregators? (string[]): List of swap aggregators to ignore
  • referralCode? (string): Referral code included in on-chain event
  • ignoreStandards? (string[]): List of standards to ignore
  • actions (BundleAction[]): Array of actions to bundle

Returns: Promise<BundleData>

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[]>

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>

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>

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[]>

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[]>

// 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[]>

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[]>

const aaveStandard = await enso.getStandardBySlug('aave-v3');

getActions()

Returns all actions that can be bundled with the /shortcuts/bundle endpoint.

Returns: Promise<ActionData[]>

const actions = await enso.getActions();

getActionsBySlug(slug: string)

Gets actions for a specific protocol.

Parameters:

  • slug (string): The protocol slug

Returns: Promise<ActionData[]>

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
  • fee? (Quantity[]): Fee in basis points
  • feeReceiver? (Address): Fee receiver address
  • amountIn (Quantity[]): Amount to send
  • receiver (Address): Receiver address
  • spender? (Address): Spender address
  • referralCode? (string): Referral code

Returns: Promise<RouteData>

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>

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>

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[]>

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[]>

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[]>

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[]>

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>

const volume = await enso.getVolume(1);

getAccountId()

Gets the account ID associated with the API key.

Returns: Promise<string>

const accountId = await enso.getAccountId();

Working with Large Numbers

The SDK properly handles large numbers common in blockchain transactions:

// Using string representation for large numbers (recommended)
const largeAmount = "1000000000000000000000000"; // 1 million tokens with 18 decimals

// You can also use JavaScript numbers for smaller values
const smallAmount = 1000000; // 1 USDC with 6 decimals

Bundle Actions

The Bundle API supports a variety of actions for interacting with DeFi protocols. For an up-to-date reference of all available actions and their parameters:

// 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:

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 - Learn about the different routing options and when to use each one
  • Available Actions for Bundle API - Explore all supported DeFi actions like swaps, deposits, borrows, and more
  • Shortcuts - See practical examples of common DeFi operations implemented with the SDK
  • Non-tokenized Positions - Discover how to interact with non-tokenized DeFi positions like Aave borrows or Liquity CDPs
  • GitHub Repository - Access the source code, report issues, or contribute to the SDK
  • Developer Chat - Join our Telegram group for technical support and discussions

Updated