# 1inch Business Portal > This file provides a machine-readable index of 1inch Business Portal documentation > for AI agents, LLMs, and automation tools, following the llmstxt.org specification. > This file contains full inlined content for LLM consumption. Use this file for: Latest API versions, accurate endpoints, machine-readable integrations. - Supported chains: Ethereum, Solana, Base, Binance, zkSync, Gnosis, Optimism, Polygon, Linea, Sonic, Unichain, Arbitrum, Avalanche, Monad - Integration paths: REST APIs, SDKs, WebSockets, JSON-RPC, gRPC - MCP Server: https://api.1inch.com/mcp/protocol ## Overview https://business.1inch.com/portal/assets/docs-v2/overview.md Welcome to the official 1inch Business Portal documentation hub. Here you'll find comprehensive guides and references to help you integrate, build, and scale with 1inch APIs and protocols. ## What is 1inch Business Portal 1inch Business Portal is a SaaS Web3 infrastructure platform offering subscription-based access to the broader 1inch ecosystem, built on top of 1inch's battle-tested and widely adopted swap and execution technology, and designed for developers and businesses building and scaling on-chain applications. From early-stage startups to enterprises and institutions, 1inch Business Portal provides subscription-based access to the broader 1inch ecosystem, offering a scalable Web3 infrastructure platform built for high-throughput usage, production reliability, and long-term integrations. It supports mission-critical use cases across wallets, fintechs, trading platforms, and infrastructure providers operating under real-world load. ## Product Areas The 1inch Business Portal provides access to a set of core product areas across the broader 1inch ecosystem, enabling developers and businesses to build, operate, and scale on-chain applications using a unified Web3 infrastructure platform. ### Swap Execution, DEX Liquidity Aggregation & Orderbook Includes classic (pro-mode) swaps, intent-based swaps (Fusion), cross-chain swaps (Fusion+), orderbook functionality, and support for real-world assets (RWAs). This product area is designed for aggregating liquidity across decentralized exchanges (DEXs) and executing on-chain trades through both direct, transaction-based swaps and orderbook-driven trading workflows, alongside intent-driven execution models. ### Market & Trading Data Includes spot pricing, orderbook data, token metadata, token details, and market charts. These capabilities support pricing, discovery, analytics, and user-facing trading interfaces. ### Portfolio & Account Data Includes balance information and portfolio composition across supported networks. This product area enables portfolio tracking, asset monitoring, and account-level insights. ### Transactions & On-Chain Activity Includes transaction execution via a gateway, historical transaction data, and execution traces. These capabilities support monitoring, analytics, auditing, and operational workflows. ### Network & Infrastructure Data Includes gas price estimation, Web3 RPC access, and domain resolution. This product area provides production-ready blockchain connectivity for scalable and reliable on-chain interactions. ## Supported chains | Chain | Chain ID | | :---------------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | | Cronos | 25 | | Monad (RPC Nodes only ) | 143 | ## Developer Resources - [OpenAPI Specifications](/portal/documentation/apis): Interactive API references with try-it-out - [Available SDKs](/portal/documentation/sdks/available-sdks): TypeScript SDKs for swap, orderbook, and cross-chain - [1inch MCP Server](/portal/documentation/ai-integration/ecosystem): Connect your AI coding assistant to 1inch docs and APIs - [LLM-optimized documentation](/llms.txt): Machine-readable documentation index for AI agents and automation > For the canonical, machine-readable index of all APIs (recommended for AI agents and automation), see [llms.txt](/llms.txt). ## Integration support The documentation covers multiple product integration paths, including: - SDKs for faster, opinionated development - REST APIs for flexible backend integrations - WebSockets for real-time data and events (Swap API - for Intent and Cross Chain, Web3 RPC API) - JSON-RPC for direct blockchain interactions (Web3 RPC API) - gRPC for high-performance, low-latency use cases (Web3 RPC API on Solana) ## Quick links
View authentication requirements for all 1inch APIs and services.
Explore 13+ API products with rich documentation, examples, and OpenAPI specs--and experience them live by running API requests directly.
Explore official SDKs.
Connect AI coding assistants to 1inch documentation and SDK examples using Model Context Protocol.
Access resolver requirements, terms and onboarding flows.
Get answers to the most common questions about using 1inch.
## SDKs https://business.1inch.com/portal/assets/docs-v2/sdks/available-sdks.md This section provides an overview of the 1inch SDKs available for building, integrating, and extending swap functionality across different networks and execution models. The SDKs are grouped by purpose to help developers quickly identify the right tools for their use case--whether it's cross-chain swaps, intent-based trading, limit orders, protocol integrations, or low-level execution engines. ## Swap SDKs | Name | SDK Link | Supported Language | Examples | | :----------------- | :----------------------------------------- | :----------------- | :---------------------------------------------------- | | Cross Chain | https://github.com/1inch/cross-chain-sdk | TypeScript | https://github.com/1inch/cross-chain-resolver-example | | Intent Swap EVMs | https://github.com/1inch/fusion-sdk | TypeScript | https://github.com/1inch/fusion-resolver-example | | Intent Swap Solana | https://github.com/1inch/solana-fusion-sdk | TypeScript | | | Limit Order | https://github.com/1inch/limit-order-sdk | TypeScript | | ## Protocols | Name | SDK Link | Supported Language | Templates | | :------------ | :----------------------------------------------------------- | :----------------- | :----------------------------------------- | | Aqua Protocol | https://github.com/1inch/sdks/tree/master/typescript/aqua | TypeScript | https://github.com/1inch/aqua-app-template | | SWAP VM | https://github.com/1inch/sdks/tree/master/typescript/swap-vm | TypeScript | https://github.com/1inch/swap-vm-template | ## Utilities | Name | SDK Link | Supported Language | | :------------- | :-------------------------------------- | :----------------- | | Solidity Utils | https://github.com/1inch/solidity-utils | Solidity | ## AI & Automation For AI agents and LLM-based tools, a machine-readable documentation index is available at [`/llms.txt`](/llms.txt). ## Authentication https://business.1inch.com/portal/assets/docs-v2/apis/authentication.md The 1inch Business API supports two authentication methods: 1. **API keys** - Simple bearer tokens for direct integrations 2. **OAuth 2.1** - Standard protocol for user consent flows and server-to-server access Your credentials carry many privileges, so keep them secure. Do not share API keys or OAuth client secrets in publicly accessible areas such as GitHub or client-side code. --- ## API Keys You can view and manage your API keys under each of your [Applications](/applications). ### Usage - **Header**: `Authorization: Bearer {YOUR_API_KEY}` - **Query parameter**: `apiKey={YOUR_API_KEY}` ### REST API Call ```bash # Header authentication curl -X 'GET' \ 'https://api.1inch.com/swap/v5.2/1/tokens' \ -H 'accept: application/json' \ -H 'Authorization: Bearer YOUR_API_KEY' # Query parameter authentication curl -X 'GET' \ 'https://api.1inch.com/swap/v5.2/1/tokens?apiKey=YOUR_API_KEY' \ -H 'accept: application/json' ``` ### WebSocket ```bash # Header authentication wscat -c 'wss://api.1inch.com/web3/1' -H 'Authorization:Bearer YOUR_API_KEY' # Query parameter authentication wscat -c 'wss://api.1inch.com/web3/1?apiKey=YOUR_API_KEY' ``` ### Response Headers Every API response includes the following header: | Header | Description | | :------------- | :------------------------------------------------------------------------------------------------------ | | `X-Request-Id` | Unique request identifier. Save this value when troubleshooting -- it correlates with server-side logs. | **Tip:** When reporting an issue to support or using the MCP [`debug`](/portal/documentation/ai-integration/ecosystem#debug) tool, include the `X-Request-Id` from the failing response. It allows exact log lookup without time-range guessing. Note that logs are only available within the retention period defined by your subscription plan. --- ## OAuth 2.1 OAuth 2.1 provides an alternative to API keys, suitable for: - **Client Credentials** - Server-to-server integrations without user interaction - **Authorization Code + PKCE** - User-facing apps where the end user grants access OAuth access tokens are used the same way as API keys: `Authorization: Bearer {ACCESS_TOKEN}`. ### Obtaining OAuth Clients **Option A: Application Details (recommended)** 1. Go to [Applications](/applications) -> select an application -> **Details** 2. In the **OAuth Clients** section, click **Create OAuth client** 3. Choose grant type (Authorization Code or Client Credentials), set redirect URIs if needed, and create 4. Copy `client_id` and `client_secret` from the success dialog **Option B: Dynamic Client Registration (DCR)** Register a client via API: ```bash # Client Credentials - no application_id required curl -X POST 'https://api.1inch.com/oauth/register' \ -H 'Authorization: Bearer YOUR_PORTAL_ACCESS_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "client_name": "My Server Client", "redirect_uris": ["https://example.com"], "grant_types": ["client_credentials"] }' # Authorization Code - application_id required curl -X POST 'https://api.1inch.com/oauth/register' \ -H 'Authorization: Bearer YOUR_PORTAL_ACCESS_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "client_name": "My Web App Client", "redirect_uris": ["https://myapp.com/callback"], "grant_types": ["authorization_code", "refresh_token"], "application_id": "YOUR_APPLICATION_ID" }' ``` ### Discovery Fetch OAuth server metadata (RFC 8414). Replace the base URL with your auth server URL if it differs from the API gateway: ```bash curl 'https://api.1inch.com/.well-known/oauth-authorization-server' ``` Response includes `issuer`, `authorization_endpoint`, `token_endpoint`, `registration_endpoint`, `jwks_uri`, and supported grant types. Use these URLs for OAuth flows. ### Client Credentials Flow For server-to-server calls without user interaction: ```bash # 1. Exchange client credentials for access token curl -X POST 'https://api.1inch.com/oauth/token' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET' # 2. Use access_token in API calls curl -X 'GET' 'https://api.1inch.com/swap/v5.2/1/tokens' \ -H 'Authorization: Bearer ACCESS_TOKEN' ``` ### Authorization Code Flow (with PKCE) For user-facing apps where the end user grants access: ```bash # 1. Generate PKCE code_verifier and code_challenge (S256) # code_verifier = 32 random bytes, base64url # code_challenge = base64url(SHA256(code_verifier)) # 2. Redirect user to authorization endpoint # GET /oauth/authorize?response_type=code&client_id=...&redirect_uri=...&state=...&code_challenge=...&code_challenge_method=S256 # 3. User approves on consent page, gets redirected to redirect_uri?code=...&state=... # 4. Exchange authorization code for tokens curl -X POST 'https://api.1inch.com/oauth/token' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=authorization_code&code=AUTH_CODE&redirect_uri=...&code_verifier=...&client_id=...&client_secret=...' # 5. Use access_token; use refresh_token when access_token expires curl -X POST 'https://api.1inch.com/oauth/token' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=refresh_token&refresh_token=...&client_id=...&client_secret=...' ``` ### Supported Grant Types | Grant Type | Use Case | | -------------------- | ---------------------------- | | `client_credentials` | Server-to-server, no user | | `authorization_code` | User-facing apps with PKCE | | `refresh_token` | Refresh expired access token | ## Swap API https://business.1inch.com/portal/assets/docs-v2/apis/swap/swap.md 1inch Swap API product offers 3 different execution modes, designed to cover different liquidity sources and cross-chain requirements: - Intent Based Swaps - Classic Swaps - Cross Chain Swaps ## Supported Chains | Supported Chains | Chain ID | Classic SWAP | Intent based SWAP | Cross-chain SWAP | | :--------------- | :------- | :----------: | :---------------: | :--------------: | | Ethereum | 1 | [x] | [x] | [x] | | Solana | 501 | [ ] | [x] | [x] | | Base | 8453 | [x] | [x] | [x] | | Binance | 56 | [x] | [x] | [x] | | zkSync | 324 | [x] | [x] | [x] | | Gnosis | 100 | [x] | [x] | [x] | | Optimism | 10 | [x] | [x] | [x] | | Polygon | 137 | [x] | [x] | [x] | | Linea | 59144 | [x] | [x] | [x] | | Sonic | 146 | [x] | [x] | [x] | | Unichain | 130 | [x] | [x] | [x] | | Arbitrum | 42161 | [x] | [x] | [x] | | Avalanche | 43114 | [x] | [x] | [x] | ## Supported Features | Supported Features | Classic SWAP | Intent based SWAP | Cross-chain SWAP | | :----------------: | :----------: | :--------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------: | | Gasless | [ ] | [x] | [x] | | RWAs | [ ] | [x] | [ ] | | MEV Protection | [ ] | [x] | [x] | | SDKs | [ ] | [Intent EVM SDK](https://github.com/1inch/solana-fusion-sdk), [Intent Solana SDK](https://github.com/1inch/fusion-sdk) | [Cross-chain SDK](https://github.com/1inch/cross-chain-sdk) | | AI Integration | [x] | [x] | [x] | | Integrator Fee | [x] | [x] | [x] | **AI Integration** enables AI agents and coding assistants to discover, understand, and execute swaps through the [1inch MCP Server](../../ai-integration/ecosystem.md). Agents connected via the Model Context Protocol can search documentation, retrieve production-ready SDK examples, and build agentic swap workflows from intent submission to resolver execution, without manual research. **Integrator Fee** is a configurable fee that allows integration partners to earn a commission on transactions routed through the 1inch swap infrastructure. The integrator fee can be specified as a parameter in API requests or configured via the corresponding SDK implementations. ## Intent Based Swaps Gasless, MEV-resistant swaps executed through a competitive resolver network. Fusion mode allows users to submit swap intents that are filled by third-party resolvers. Orders are executed using a dynamic pricing mechanism that protects users from front-running and eliminates the need to pay gas fees directly. Best for: Gas-efficient swaps, MEV protection, large or price-sensitive trades. Learn more : [Intent Swap specs](./intent-swap/introduction.md) ## Classic Swaps Classic swaps provide maximum flexibility and control over swap parameters and execution behavior. This mode is equivalent to Pro mode in trading interfaces and is intended for advanced integrators who want full freedom of configuration. Best for: Advanced trading logic, fine-grained parameter control, immediate execution. Learn more : [Classic Swap specs](./classic-swap/introduction.md) ## Cross-Chain Swaps Seamless swaps across multiple blockchains with no bridging and fast execution time. Cross-chain swaps enable users to exchange assets between different networks through a unified API, abstracting away bridging complexity and cross-chain execution logic. Best for: Multi-chain applications, asset migration, Solana - EVMs cross-ecosystem liquidity access. Learn more : [Cross-chain Swap specs](./cross-chain-swap/introduction.md) https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/introduction.md # Introduction ## 1inch Fusion+ (intent-based atomic cross-chain swaps) The 1inch Fusion+ API is a powerful solution for secure and efficient cross-chain swaps in DeFi that uses a creative architecture of Dutch auctions and automated recovery, all without relying on a single centralized custodian. ### Key benefits - Intent-based trading: you can specify your trading intentions, which can then be fulfilled by both onchain and offchain liquidity. - Inherent MEV protection: by design, you cannot lose money to front-running or "sandwich attacks" on your orders. - Gas cost abstraction: you can swap without the need for a balance of native assets (like ETH) in your wallet, as the resolvers cover all gas costs. - Enhanced flexibility: you can set specific conditions for your trades, with the possibility of post-trade interactions, thereby providing greater control over the execution. - Native-coin support: swap directly from the native coin of any supported network (e.g., ETH, BNB, MATIC, AVAX, SOL) without manual wrapping and unwrapping. - no need for bridges or messaging protocols in transferring assets across networks. - Merged sources of liquidity as there are over 13 network available : 12 EVMs and Solana ## Supported Chains | Supported Chains | Chain ID | MEV | Gasless | | :--------------- | :------- | :-: | :-----: | | Ethereum | 1 | [x] | [x] | | Solana | 501 | [x] | [x] | | Base | 8453 | [x] | [x] | | Binance | 56 | [x] | [x] | | zkSync | 324 | [x] | [x] | | Gnosis | 100 | [x] | [x] | | Optimism | 10 | [x] | [x] | | Polygon | 137 | [x] | [x] | | Linea | 59144 | [x] | [x] | | Sonic | 146 | [x] | [x] | | Unichain | 130 | [x] | [x] | | Arbitrum | 42161 | [x] | [x] | | Avalanche | 43114 | [x] | [x] | :::info For a comprehensive technical overview, refer to the [1inch Fusion+ whitepaper](https://1inch.io/assets/1inch-fusion-plus.pdf). ::: ## Phases of a Fusion+ swap The process typically involves two main participants: the maker, who initiates the swap, and the resolver, who completes it; and has three phases. However, if any problems arise, there is an optional 4th _recovery phase_ that can be used as a last resort. ### Phase 1: Announcement The maker initiates the process by signing a 1inch Fusion+ order and broadcasting it to 1inch. This signals their intent to execute a cross-chain swap and sets the process in motion. The order is distributed to all resolvers, triggering a [Dutch auction](../intent-swap/introduction#dutch-auction-filling-rate). Resolvers compete by offering progressively better prices as the auction continues until a resolver locks in the order by initiating an escrow on the source chain. ### Phase 2: Deposit The winning resolver deposits the maker's assets into an escrow contract on the source chain, and then deposits the corresponding assets into an escrow on the destination chain. Both escrows are linked by a secret hash, ensuring that assets can only be unlocked once the swap is completed. A small safety deposit is also assigned to each escrow, incentivizing the resolver to successfuly complete the order. ### Phase 3: Withdrawal Once both escrows are verified by the relayer, the secret is revealed, allowing the resolver to unlock the assets on the destination chain for the maker. The resolver then uses the same secret to retrieve their newly acquired assets on the source chain, finalizing the swap. ### Finality Lock Configuration The current finality lock configuration determines the lock duration for cross-chain orders based on transaction volume. Below is a table showing the configuration values for each supported chain AS IS and TO BE states. | Chain ID | Chain Name | Low Volume (USD) | Medium Volume (USD) | High Volume (USD) | Low + Medium Volume Lock | High Volume Lock | | :------- | :--------- | :--------------- | :------------------ | :---------------- | :----------------------: | :--------------: | | 1 | Ethereum | < 100 | 100-100,000 | 100,000+ | 24s | 36s | | 10 | Optimism | < 1,000 | 1,000-100,000 | 100,000+ | 10s | 36s | | 56 | Binance | < 100 | 100-100,000 | 100,000+ | 4s | 12s | | 100 | Gnosis | < 100 | 100-100,000 | 100,000+ | 36s | 1m | | 130 | Unichain | < 100 | 100-100,000 | 100,000+ | 4s | 12s | | 137 | Polygon | < 100 | 100-100,000 | 100,000+ | 10s | 12s | | 146 | Sonic | < 100 | 100-100,000 | 100,000+ | 4s | 12s | | 324 | zkSync | < 1,000 | 1,000-100,000 | 100,000+ | 4s | 12s | | 42161 | Arbitrum | < 1,000 | 1,000-100,000 | 100,000+ | 10s | 36s | | 43114 | Avalanche | < 100 | 100-100,000 | 100,000+ | 4s | 12s | | 501 | Solana | < 100 | 100-100,000 | 100,000+ | 14s | 24s | | 8453 | Base | < 1,000 | 1,000-100,000 | 100,000+ | 4s | 12s | | 59144 | Linea | < 1,000 | 1,000-100,000 | 100,000+ | 4s | 12s | ### Optional phase: Recovery In the event of a failed swap (e.g., if a party becomes unresponsive), the protocol includes a recovery mechanism. After the timelock expires, any resolver or any participating entity can cancel the swap and return the assets to their original owners. The safety deposit in each escrow is transfered to any resolver who steps in to complete the swap during this phase. swap flow #### The partial fill feature When an order is 100% filled, a single secret is used to finalize the transaction between two parties. However, when an order is only partially filled by different resolvers, revealing the secret to the public could let others claim the remainder of the order without completing their part. To solve this, a Merkle tree of secrets is implemented for partial fills, which splits the order into equal parts and generates dedicated secrets for each portion of swap. For example, if an order is divided into four parts, the first secret is used for the first 25%, the second for 50%, and so on. If a participant fills a part of the order, the next participant uses the corresponding secret based on the current progress to continue filling the order. This ensures that each participant can only fill their portion without exposing the rest of the order. In the example image below, the 1st secret is used for the initial 0-20% fill, marking the first stage of the order. Secrets 2 and 3 are not used because the order skips directly from 20% to 80%, bypassing the ranges where these secrets would apply. The 4th secret is then used to fill the order from 20% to 80%, covering this larger portion. Finally, the 5th secret is used to complete the final 80-100% of the order, ensuring that the entire order is securely and progressively filled. partial fill ## API reference For detailed information about each endpoint, refer to the Fusion+ API [OpenAPI specs](./relayer/v1.2/submit/method/post). https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/quick-start/evm-to-evm.md ## Introduction This guide shows how to perform a cross-chain swap between two EVM chains using 1inch Fusion+. ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal). - Your wallet must have at least $1 of USDC on the source chain ## Integration Pattern 1. **Initialize SDK** - Create an SDK instance with your API key and blockchain provider 2. **Check Allowance** - Ensure the source token is approved for the Aggregation Router 3. **Fetch Quote** - Get cross-chain pricing for your swap 4. **Generate Secrets** - Create cryptographic secrets for escrow locking 5. **Place Order** - Submit the signed order with hashlock and secret hashes 6. **Monitor & Submit Secrets** - Poll for escrow deployment, then reveal secrets to finalize ## Interactive Code Example Explore the minimal quick-start implementation: For a more comprehensive example with balance checks and config-driven chain selection, see `src/swap-erc20-cross-chain.ts` in the same project. https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/quick-start/evm-to-solana.md ## Introduction This guide shows how to perform a cross-chain swap from an EVM chain to Solana using 1inch Fusion+. ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal). - Your wallet must have at least $5 worth of USDT (or the token you're swapping) on Ethereum - You need both an EVM wallet (source) and a Solana wallet address (destination) ## Key Differences from EVM-to-EVM - Uses `SolanaAddress` for the destination token and receiver address - Order is created with `quote.createEvmOrder()` and submitted via `sdk.submitOrder()` (two-step flow) - The destination chain ID is `NetworkEnum.SOLANA` (501) ## Interactive Code Example Explore the complete EVM-to-Solana implementation: https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/quick-start/solana-to-evm.md ## Introduction This guide shows how to perform a cross-chain swap from Solana to an EVM chain (e.g., Ethereum) using 1inch Fusion+. ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal). - Your wallet must have at least $5 worth of USDT on Solana (or the token you're swapping) - Your wallet must have sufficient SOL for transaction fees - You need both a Solana wallet (source) and an EVM wallet address (destination) ## Key Differences from EVM-to-EVM - Uses `SolanaAddress` for the source token and `EvmAddress` for the destination token - Order is created with `quote.createSolanaOrder()` and announced with `sdk.announceOrder()` - Requires building and submitting a Solana transaction via `SvmSrcEscrowFactory` to lock tokens in escrow - Uses `@solana/web3.js` and `@coral-xyz/anchor` for Solana transaction handling ## Integration Pattern 1. **Initialize SDK** -- Create an SDK instance with your API key 2. **Fetch Quote** -- Get cross-chain pricing from Solana to the destination EVM chain 3. **Generate Secrets** -- Create cryptographic secrets for escrow locking 4. **Create & Announce Order** -- Build the Solana order and announce it to the relayer 5. **Submit Solana Transaction** -- Deploy the source escrow and lock tokens on-chain 6. **Monitor & Submit Secrets** -- Poll for escrow deployment, then reveal secrets to finalize ## Interactive Code Example The EVM-to-EVM example demonstrates the core cross-chain flow. The Solana variant follows the same secret submission pattern but uses Solana-specific order creation and transaction handling: https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/sdk/overview.md The 1inch Cross-Chain Swap SDK (Fusion+) provides high-level functionality for performing atomic cross-chain swaps between EVM chains. Fusion+ enables swaps across different blockchains without bridges or messaging protocols. ## Key Benefits - **No bridges needed** -- Atomic swaps via escrow contracts on both chains - **MEV Protection** -- Dutch auction mechanism prevents front-running and sandwich attacks - **Gas cost abstraction** -- Resolvers pay gas fees on both source and destination chains - **Native token support** -- Swap directly from ETH, AVAX, BNB, etc. without wrapping - **13+ supported chains** -- Ethereum, Base, Arbitrum, Optimism, Polygon, BSC, Avalanche, and more ## How Cross-Chain Fusion+ Works 1. **Sign Order** -- The SDK generates a cross-chain order specifying source/destination tokens and chains 2. **Dutch Auction** -- Resolvers compete to fill your order at the best price 3. **Escrow Deployment** -- The winning resolver deploys escrow contracts on both chains 4. **Secret Reveal** -- You reveal cryptographic secrets to unlock escrows and finalize the swap 5. **Assets Delivered** -- Tokens arrive on the destination chain atomically ## Core Methods - **getQuote** -- Fetches cross-chain pricing, including auction parameters and secret counts - **placeOrder** -- Signs and submits a cross-chain order for ERC-20 tokens (all-in-one) - **createOrder** -- Generates an order struct for native token swaps (requires separate submission) - **submitNativeOrder** -- Submits a native token order to the relayer - **getOrderStatus** -- Checks order status (pending, executed, expired, refunded) - **getReadyToAcceptSecretFills** -- Checks if escrows are deployed and ready for secret submission - **submitSecret** -- Reveals a secret to unlock escrows and finalize the swap - **WebSocketApi** -- Real-time order status updates as an alternative to polling ## Integration Pattern A typical ERC-20 cross-chain swap follows this flow: 1. **Initialize SDK** -- Create an SDK instance with your API key and blockchain provider 2. **Check Allowance** -- Ensure the source token is approved for the Aggregation Router 3. **Fetch Quote** -- Get cross-chain pricing for your swap 4. **Generate Secrets** -- Create cryptographic secrets for escrow locking 5. **Place Order** -- Submit the signed order with hashlock and secret hashes 6. **Monitor & Submit Secrets** -- Poll for escrow deployment, then reveal secrets to finalize ## Interactive Code Example Explore the complete implementation -- this example demonstrates a cross-chain ERC-20 swap: https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/sdk/when-and-how-to-submit-secrets.md After placing a cross-chain order, the maker must monitor for escrow deployment and reveal cryptographic secrets to finalize the swap. This page explains the secret submission lifecycle. ## Secret Submission Flow 1. **Wait for escrow creation** -- After your order is matched, escrow contracts are deployed on both source and destination chains 2. **Check readiness** -- Use `getReadyToAcceptSecretFills(orderHash)` to verify both escrows are in place and finality locks have passed 3. **Submit secrets** -- Use `submitSecret(orderHash, secret)` to reveal each secret and unlock the escrows 4. **Verify completion** -- Use `getOrderStatus(orderHash)` to confirm the order is marked as `executed` ## Key Methods - **getReadyToAcceptSecretFills(orderHash)** -- Returns which fill indices are ready for secret submission. Poll this repeatedly after order placement. - **submitSecret(orderHash, secret)** -- Reveals a secret to unlock escrows. For multi-fill orders, submit secrets one at a time as each fill becomes ready. - **getOrderStatus(orderHash)** -- Returns the current order status (`pending`, `executed`, `expired`, `refunded`). - **getPublishedSecrets(orderHash)** -- Checks which secrets have already been revealed by other resolvers. ## Partial Fill Handling For large orders split across multiple resolvers, each fill gets its own secret. The `fills` array from `getReadyToAcceptSecretFills` tells you which indices need secrets. Track submitted indices to avoid duplicates. ## Interactive Code Example See the complete secret submission loop in context: https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/sdk/how-to-swap-native-tokens-cross-chain.md ## Introduction With Cross-Chain Swap, you can perform a gasless cross-chain swap from a chain's native token (like ETH on Base) to an asset on another chain. ## How does native cross-chain exchange work? For cross-chain orders involving a native token, a dedicated escrow contract is deployed on the source chain. This escrow serves as a temporary vault where the following sequence takes place: 1. **Deposit**: the user deposits the source chain's native coin into the escrow. Inside, the token is automatically wrapped into its canonical ERC-20 form (e.g., ETH -> WETH). 1. **Cross-chain execution**: when a resolver fills the order, it initiates a cross-chain message that pulls the wrapped asset from the source escrow, performs the swap via Cross-Chain Swap infrastructure, bridges the taker asset to the destination chain, and delivers it directly to the user's address on that chain. 1. **Refund**: if no resolver fills the order within the allowed timeframe, the escrow can be triggered to return the user's original native token on the source chain. This design ensures that users interact only with their native assets, while all wrapping, bridging, escrow management, and swap execution are seamlessly handled by Cross-Chain Swap infrastructure and its resolvers. In the section below, you'll find an interactive example of how to swap a native coin cross-chain. ## Interactive Example Explore the complete native token cross-chain swap implementation: ## Key Differences from ERC-20 Cross-Chain Swaps | Step | ERC-20 | Native Token | | -------------------- | ----------------------------- | ----------------------------------------------- | | Approval | Required (Aggregation Router) | Not needed | | Order creation | `sdk.placeOrder()` | `sdk.createOrder()` + `sdk.submitNativeOrder()` | | Escrow deployment | Handled by resolver | Must deploy via `NativeOrdersFactory` | | On-chain transaction | Not needed | Required to fund escrow | | Secret submission | Same for both | Same for both | https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/sdk/auction-calculator.md The `AuctionCalculator` class computes taker amounts and auction rate bumps from a limit order struct. This is useful for understanding how the Dutch auction mechanism determines pricing over time. ## Key Methods - **AuctionCalculator.fromLimitOrderV3Struct(order)** -- Creates a calculator instance from a `LimitOrderV3Struct` - **calcRateBump(blockTimestamp)** -- Returns the auction rate bump at a given timestamp (in basis points) - **calcAuctionTakingAmount(takingAmount, rateBump)** -- Returns the adjusted taker amount after applying the rate bump ## LimitOrderV3Struct Fields | Name | Type | Description | | ------------- | ------ | ----------------------------------------------------------------------- | | salt | string | Unique value to differentiate orders with identical parameters | | makerAsset | string | Token address the maker is selling | | takerAsset | string | Token address the maker is buying | | maker | string | Address of the order creator | | receiver | string | Address to receive taker asset (zero address = maker address) | | allowedSender | string | Restricts who can fill (zero address = anyone) | | makingAmount | string | Amount of maker asset | | takingAmount | string | Amount of taker asset | | offsets | string | Byte offsets for interaction parsing | | interactions | string | Encoded Fusion-specific data (auction points, resolvers, timing, flags) | https://business.1inch.com/portal/assets/docs-v2/apis/swap/cross-chain-swap/sdk/web-socket-api.md The WebSocket API enables real-time order tracking for cross-chain swaps. Instead of repeatedly polling the API for status updates, your application receives instant notifications when order events occur. ## Why Use WebSocket? For applications that need responsive user interfaces or automated trading systems, WebSocket provides significant advantages: - **Instant Updates** -- Receive order events within milliseconds instead of waiting for poll intervals - **Reduced API Load** -- A single persistent connection replaces hundreds of status requests - **Complete Event History** -- Track all state changes including partial fills, not just final status ## Order Events The WebSocket API notifies you of these order lifecycle events: - **order_created** -- Your order has been submitted and is visible to resolvers - **order_filled** -- The order was completely filled by a resolver - **order_filled_partially** -- Part of your order was filled (for large orders) - **order_invalid** -- The order became invalid due to cancellation, expiry, or insufficient balance ## Connection The WebSocket connects to: ``` wss://api.1inch.com/fusion-plus/ws ``` The SDK appends the version path automatically. ## Interactive Code Example https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/introduction.md ## 1inch intent-based swap (Fusion mode) 1inch Intent Swap API (Fusion mode) offers users a way to execute swaps without spending gas or risking being front-run. To the user, Fusion mode looks like a swap, but technically it is a limit order with a variable exchange rate filled by a third party called a resolver. An order's exchange rate decreases from the desired rate to the minimal return amount (Dutch auction) until it becomes profitable for resolvers to fill the order. Multiple resolvers compete for the order to ensure it is filled before the rate falls to the minimal return amount. Here are some examples of opportunities for resolvers to gain profit: - The Dutch auction constantly decreases the order rate. - Gas economy when filling matching orders. - Gas economy due to batch filling. For integrators and resolvers there is a [Fusion SDK](https://github.com/1inch/fusion-sdk) available to help with the integration. ## API reference For detailed information about each endpoint, refer to the [OPEN API specs section](./relayer/v2.0/1/order/submit/method/post). ## Supported Chains | Supported Chains | Chain ID | Ondo RWAs Support | xStocks RWAs Support | MEV | Gasless | | :--------------- | :------- | :---------------: | :------------------: | :-: | :-----: | | Ethereum | 1 | [x] | [x] | [x] | [x] | | Solana | 501 | [ ] | [ ] | [x] | [x] | | Base | 8453 | [ ] | [ ] | [x] | [x] | | Binance | 56 | [x] | [ ] | [x] | [x] | | zkSync | 324 | [ ] | [ ] | [x] | [x] | | Gnosis | 100 | [ ] | [ ] | [x] | [x] | | Optimism | 10 | [ ] | [ ] | [x] | [x] | | Polygon | 137 | [ ] | [ ] | [x] | [x] | | Linea | 59144 | [ ] | [ ] | [x] | [x] | | Sonic | 146 | [ ] | [ ] | [x] | [x] | | Unichain | 130 | [ ] | [ ] | [x] | [x] | | Arbitrum | 42161 | [ ] | [ ] | [x] | [x] | | Avalanche | 43114 | [ ] | [ ] | [x] | [x] | ## RWAs Support The 1inch Intent Swap API supports tokenized real-world assets (RWAs) from [Ondo](https://ondo.finance) and [xStocks](https://xstocks.fi). Trading availability and conditions, including market hours, may differ depending on the respective issuer. [Find out more](../real-world-assets-support.md). ## Dutch auction filling rate Each order starts with an auction timestamp, calculated as the order's signature timestamp plus a waiting period to account for different network speeds. Before the auction begins, an order can be filled at the maximum rate. After the auction starts, the filling rate gradually decreases. The filling rate depends on several factors, including swap volume, gas costs, and chosen preset (e.g., fast, fair, auction). To minimize price impact, the source token volume is divided into parts, creating multiple price points. This benefits users with better rates and allows resolvers to profit. The partial fill functionality optimizes efficiency by allowing large swaps to be executed at better rates. Different resolvers can fill different parts of the order, making it profitable at various points. The price curve is also dynamic, and adapts to gas market conditions to manage gas price volatility. This reduces the chance of order expiration and speeds up execution by 75%. If gas prices increase, the resolver might delay fulfillment, but if they decrease, the resolver benefits from lower costs. The adjusted price curve ensures users receive more tokens when base fees decline and corrects execution costs when they rise. We recommend resolvers split orders into 6-10 parts and check if at least one part can be filled. Below is a real-life example: auction curve https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/quick-start/quick-start-ethereum.md ## Introduction This guide shows how to use Intent Swap (Fusion mode) to perform a gasless swap from native ETH to USDC on Ethereum. You will use the 1inch Fusion SDK to fetch quotes, create orders, and submit them to the relayer network. Native token swaps require no approval--just deploy an escrow contract to lock your ETH. ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal). - Your wallet must have: - ETH on Ethereum ## Install Dependencies Install the Fusion SDK and ethers: ```bash npm install @1inch/fusion-sdk ethers dotenv ``` ## Set Up the Provider Create an ethers provider using the 1inch Web3 node and your API key. The provider is used for RPC calls and wallet signing. ```typescript import { ethers } from "ethers"; const rpcUrl = "https://api.1inch.com/web3/1"; const fetchReq = new ethers.FetchRequest(rpcUrl); fetchReq.setHeader("Authorization", `Bearer ${API_KEY}`); const provider = new ethers.JsonRpcProvider(fetchReq, 1, { staticNetwork: true }); const wallet = new ethers.Wallet(PRIVATE_KEY, provider); ``` ## Initialize the Fusion SDK Create a Fusion SDK instance with your API key and a blockchain provider connector. The connector bridges ethers to the SDK's expected interface. ```typescript import { FusionSDK, NetworkEnum, PrivateKeyProviderConnector } from "@1inch/fusion-sdk"; const sdk = new FusionSDK({ url: "https://api.1inch.com/fusion", network: NetworkEnum.ETHEREUM, blockchainProvider: new PrivateKeyProviderConnector(PRIVATE_KEY, { eth: { call: (tx) => provider.call(tx) }, extend() {} }), authKey: API_KEY }); ``` ## Get a Swap Quote Call `getQuote` with the native token sentinel address, destination token, amount, and wallet address. For native ETH, use the sentinel address `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. ```typescript const NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"; const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; const params = { fromTokenAddress: NATIVE, toTokenAddress: USDC, amount: "1000000000000000", // 0.001 ETH (18 decimals) walletAddress: wallet.address }; const quote = await sdk.getQuote(params); ``` ## Create and Submit the Order Create the order with `createOrder`, then submit it to the relayer with `submitNativeOrder` (not `submitOrder`). Native token orders use a different submission flow. ```typescript import { Address } from "@1inch/fusion-sdk"; const order = await sdk.createOrder(params); const makerAddress = new Address(wallet.address); const result = await sdk.submitNativeOrder(order.order, makerAddress, order.quoteId); console.log("Order submitted:", result.orderHash); ``` ## Deploy the Escrow Contract Native token swaps require an on-chain escrow to hold your ETH. Use `NativeOrdersFactory` to build the deployment transaction, then send it with your wallet. The escrow wraps ETH to WETH and locks it until the order is filled. ```typescript import { NativeOrdersFactory, NetworkEnum } from "@1inch/fusion-sdk"; const factory = NativeOrdersFactory.default(NetworkEnum.ETHEREUM); const call = factory.create(makerAddress, result.order); const tx = await wallet.sendTransaction({ to: call.to.toString(), data: call.data, value: call.value }); await tx.wait(); ``` ## Full Code Example Explore the complete quick-start implementation (~85 lines) in StackBlitz: For a more comprehensive example with order tracking and error handling, see `src/evm/swap-native.ts` in the same project. https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/quick-start/quick-start-solana.md ## Introduction This guide shows how to use Intent Swap (Fusion mode) to perform a gasless swap from native SOL to JUP on Solana. You will use the 1inch Solana Fusion SDK to create orders and build escrow transactions. Native SOL swaps require no approval--the escrow instruction locks your SOL on-chain until the order is filled. ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal/applications). - Your wallet must have: - SOL on Solana (swap amount plus ~0.01 SOL for transaction fees) ## Install Dependencies Install the Solana Fusion SDK, Solana web3.js, and supporting libraries: ```bash npm install @1inch/solana-fusion-sdk @solana/web3.js axios bs58 dotenv ``` ## Set Up the Connection Create a Solana connection using the 1inch Web3 node. Pass your API key in the `httpHeaders` for authenticated RPC access. ```typescript import { Connection } from "@solana/web3.js"; const rpcUrl = "https://api.1inch.com/web3/501"; const connection = new Connection(rpcUrl, { commitment: "confirmed", httpHeaders: { Authorization: `Bearer ${API_KEY}` }, wsEndpoint: `wss://api.1inch.com/web3/501?apiKey=${API_KEY}` }); ``` ## Create the Wallet Decode your private key (base58 or base64) and create a Keypair. The SDK supports both 32-byte seeds and 64-byte full keypairs. ```typescript import { Keypair } from "@solana/web3.js"; import bs58 from "bs58"; let secretKey: Uint8Array; try { secretKey = bs58.decode(PRIVATE_KEY); } catch { secretKey = Buffer.from(PRIVATE_KEY, "base64"); } let wallet: Keypair; if (secretKey.length === 32) { wallet = Keypair.fromSeed(secretKey); } else if (secretKey.length === 64) { wallet = Keypair.fromSecretKey(secretKey); } else { throw new Error(`Invalid private key length: ${secretKey.length} bytes (expected 32 or 64)`); } ``` ## Initialize the Fusion SDK Create the Solana Fusion SDK with an HTTP provider. The provider must implement `get` and `post` methods for API calls. ```typescript import { Sdk } from "@1inch/solana-fusion-sdk"; import axios from "axios"; const sdk = new Sdk( { async get(url: string, headers: Record): Promise { return (await axios.get(url, { headers })).data; }, async post(url: string, data: unknown, headers: Record): Promise { return (await axios.post(url, data, { headers })).data; } }, { baseUrl: "https://api.1inch.com/fusion", authKey: API_KEY, version: "v2.0" } ); ``` ## Create the Order Call `createOrder` with the source token (`Address.NATIVE` for SOL), destination token address, amount in lamports, and maker address. The SDK returns an order object used to build the escrow transaction. ```typescript import { Address } from "@1inch/solana-fusion-sdk"; import { LAMPORTS_PER_SOL } from "@solana/web3.js"; const JUP = "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"; const amount = BigInt(0.01 * LAMPORTS_PER_SOL); // 0.01 SOL const makerAddress = Address.fromPublicKey(wallet.publicKey); const order = await sdk.createOrder(Address.NATIVE, new Address(JUP), amount, makerAddress); ``` ## Build and Send the Escrow Transaction Use `FusionSwapContract` to create the escrow instruction, add it to a Solana transaction, sign with your wallet, and broadcast. The escrow locks your SOL until a resolver fills the order. ```typescript import { FusionSwapContract } from "@1inch/solana-fusion-sdk"; import { Transaction, PublicKey } from "@solana/web3.js"; const contract = FusionSwapContract.default(); const instruction = contract.create(order, { maker: makerAddress, srcTokenProgram: Address.TOKEN_PROGRAM_ID }); const tx = new Transaction().add({ programId: new PublicKey(instruction.programId.toBuffer()), keys: instruction.accounts.map((a) => ({ pubkey: new PublicKey(a.pubkey.toBuffer()), isSigner: a.isSigner, isWritable: a.isWritable })), data: Buffer.from(instruction.data) }); const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(); tx.recentBlockhash = blockhash; tx.lastValidBlockHeight = lastValidBlockHeight; tx.feePayer = wallet.publicKey; tx.sign(wallet); // skipPreflight: true -- 1inch Web3 can return "Invalid Request" on simulation // while the transaction still broadcasts and confirms on-chain const signature = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: true, maxRetries: 3 }); const confirmation = await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, "confirmed"); if (confirmation.value.err) { throw new Error(`Transaction failed: ${JSON.stringify(confirmation.value.err)}`); } ``` ## Full Code Example Explore the complete quick-start implementation (~120 lines) in StackBlitz: For a more comprehensive example with order tracking and error handling, see `src/solana/swap-sol-to-jup.ts` in the same project. https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/solana/overview.md The 1inch Solana Fusion SDK enables token swaps on Solana with ultra-fast transactions and minimal fees. Unlike EVM chains where orders are signed off-chain, Solana orders are placed directly on-chain through escrow contracts. ## Key Benefits - **Ultra-Fast Transactions** - Solana's ~400ms block times mean near-instant order confirmation - **Minimal Fees** - Transaction costs are typically under $0.01, with no additional 1inch fees - **Deep Liquidity** - Access swaps across over 1 million Solana-native tokens - **MEV Protection** - Built-in protection against front-running and sandwich attacks ## How Solana Fusion Works The swap process on Solana differs from EVM chains: 1. **Create Order** - The SDK generates a FusionOrder with optimal auction parameters 2. **Build Escrow Transaction** - A transaction is prepared to create an on-chain escrow holding your tokens 3. **Sign and Broadcast** - You sign and submit the transaction (paying ~$0.001 in fees) 4. **Resolver Fills Order** - Resolvers compete to fill your order at the best price 5. **Receive Tokens** - The destination token is delivered directly to your wallet ## Core Methods - **getQuote** - Fetches current pricing and auction parameters. Use this to display expected output amounts before users commit to a trade. - **createOrder** - Generates a FusionOrder struct with source/destination tokens, amounts, and Dutch auction parameters. This data is used to build the on-chain escrow transaction. - **getOrderStatus** - Checks whether an order is still active or has been filled/cancelled. Use this for polling-based status tracking. - **WebSocketApi** - Real-time order status updates as an alternative to polling. Subscribe to order events for instant notifications when your order is filled or cancelled. ## Integration Pattern A typical integration follows this flow: 1. **Initialize SDK** - Create an SDK instance with your API key 2. **Fetch Quote** - Show users the expected swap rate before they confirm 3. **Create Order** - Generate the order structure when user approves 4. **Build Transaction** - Use FusionSwapContract to create the escrow instruction 5. **Submit & Track** - Broadcast the transaction and monitor for completion ## Interactive Code Example Explore the complete implementation -- this example demonstrates swapping SOL to JUP: https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/solana/filling-and-canceling-solana-fusion-order.md Fusion orders on Solana have a defined lifecycle that includes filling by resolvers and cancellation options. Understanding this lifecycle helps you build robust applications that handle all possible order outcomes. ## Order Lifecycle After an escrow is created on-chain, the order enters the active state where: 1. **Resolvers Monitor** - Professional market makers watch for profitable orders to fill 2. **Dutch Auction** - The offered price decreases over time, incentivizing quick fills 3. **Fill or Expire** - Either a resolver fills the order, or it expires after the deadline ## Cancellation Options Orders can be cancelled in two scenarios: - **Maker Cancellation** - As the order creator (maker), you can cancel your own order at any time before it's filled. This returns your tokens from the escrow back to your wallet. - **Resolver Cancellation** - After an order expires, resolvers can trigger cancellation to clean up the escrow. For this service, resolvers earn a small cancellation premium (paid in lamports) as defined in the order parameters. ## Interactive Code Example Explore the complete implementation -- this example demonstrates how to cancel an existing order: https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/solana/web-socket-api.md The WebSocket API provides real-time order tracking on Solana. For applications that need instant feedback on order status, WebSocket eliminates the latency and overhead of polling. ## Why Use WebSocket on Solana? Solana's fast block times (~400ms) make real-time tracking particularly valuable: - **Instant Notifications** - Know immediately when your order is filled - **Transaction Details** - Each event includes the Solana transaction signature for verification - **Efficient Monitoring** - Track multiple orders with a single connection ## Order Events The Solana WebSocket API provides three event types: ### create Emitted when your escrow transaction is confirmed on-chain. Includes the transaction signature and slot number. ### fill Emitted when a resolver fills your order. Contains the resolver's address and the amounts exchanged. ### cancel Emitted when an order is cancelled, either by the maker or by a resolver cleaning up an expired order. ## Interactive Code Example Explore the complete implementation -- this example demonstrates creating an order and tracking it via WebSocket events: https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/evms/overview.md The 1inch Intent Swap SDK provides high-level functionality to work with Fusion mode on EVM-compatible chains. Fusion enables gasless swaps where resolvers compete to fill your order at the best price through a Dutch auction mechanism. ## Key Benefits - **Gasless Swaps** - Resolvers pay gas fees on your behalf, so you never need ETH for transaction costs - **MEV Protection** - Dutch auction mechanism protects against front-running and sandwich attacks - **Multi-Chain Support** - Works across Ethereum, Base, Polygon, Arbitrum, Optimism, Avalanche, BNB Chain, and more - **No Wrapping Required** - Swap native tokens (ETH, MATIC, etc.) directly without wrapping to WETH first ## How EVM Fusion Works 1. **Create Order** - The SDK generates a FusionOrder with optimal Dutch auction parameters 2. **Sign Order** - You sign the order off-chain using EIP-712 typed data (no gas required) 3. **Submit to Relayer** - The signed order is submitted to the 1inch resolver network 4. **Resolver Fills** - Resolvers compete to fill your order, driving you toward the best execution price 5. **Receive Tokens** - The destination token is delivered directly to your wallet ## Core Methods - **getQuote** - Fetches current pricing and auction parameters. Use this to display expected output amounts before users commit to a trade. - **createOrder** - Generates a FusionOrder struct with source/destination tokens, amounts, and Dutch auction parameters. Returns an order ready for signing. - **submitOrder** - Submits a signed order to the 1inch relayer network. The relayer broadcasts your order to resolvers who compete to fill it. - **getOrderStatus** - Checks whether an order is pending, filled, or cancelled. Use this for polling-based status tracking. - **WebSocketApi** - Real-time order status updates as an alternative to polling. Subscribe to order events for instant notifications when your order is filled or cancelled. ## Integration Pattern A typical integration follows this flow: 1. **Initialize SDK** - Create an SDK instance with your API key and wallet/signer 2. **Fetch Quote** - Show users the expected swap rate before they confirm 3. **Create Order** - Generate the order structure when user approves 4. **Submit Order** - Send the signed order to the relayer network 5. **Track Status** - Monitor completion via polling (`getOrderStatus`) or WebSocket subscription ## Interactive Code Example Explore the complete implementation -- this example demonstrates swapping ERC-20 tokens: https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/evms/swapping-a-native-token-to-ERC-20.md With Intent Swap, you can swap a chain's native token (like ETH on Ethereum) to any ERC-20 token. This is ideal for users who hold only native tokens and want to acquire other assets without first wrapping them manually. ## How It Works Native token swaps require an additional on-chain step compared to ERC-20 swaps: 1. **Create Order** - The SDK generates a FusionOrder with optimal auction parameters 2. **Submit to Relayer** - Use `submitNativeOrder()` to register the order with the resolver network 3. **Deploy Escrow** - Use `NativeOrdersFactory` to deploy an escrow contract that holds your native token 4. **Automatic Wrapping** - The escrow wraps your native token (e.g., ETH -> WETH) and locks it 5. **Order Execution** - Resolvers compete to fill your order at the best price 6. **Direct Delivery** - The destination token is transferred directly to your wallet If no resolver fills the order before expiry, the escrow returns your native token. ## Key Differences from ERC-20 Swaps - **No approval needed** - Native tokens don't require ERC-20 approval - **Escrow deployment required** - You must send a transaction to deploy the escrow contract - **Small gas cost** - The escrow deployment costs a small amount of gas (~0.001 ETH) ## Interactive Code Example Explore the complete implementation -- this example demonstrates swapping native ETH for USDC on Ethereum mainnet: https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/evms/swapping-with-permit2.md Permit2 is Uniswap's universal token approval system that enables gasless approvals after a one-time setup. Instead of approving each protocol separately, you approve Permit2 once and then use off-chain signatures for all subsequent token transfers. ## Why Use Permit2? - **Cost Savings** - After the initial approval, no gas is required for future approvals - **Better Security** - Permits are time-limited and can specify exact amounts - **Improved UX** - Users sign a message instead of submitting a transaction ## How It Works 1. **One-Time Setup** - Approve your tokens to the Permit2 contract (can be max amount) 2. **Get Quote** - Request a quote with `isPermit2: true` flag 3. **Create Order** - The SDK generates a Permit2 signature bundled with your order 4. **Submit** - The relayer verifies the signature and executes the swap ## Interactive Code Example Explore the complete implementation -- this example demonstrates swapping USDC to WETH using Permit2: https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/sdk/evms/websocket-api.md The WebSocket API enables real-time order tracking for production applications. Instead of repeatedly polling the API for status updates, your application receives instant notifications when order events occur. ## Why Use WebSocket? For applications that need responsive user interfaces or automated trading systems, WebSocket provides significant advantages: - **Instant Updates** - Receive order events within milliseconds instead of waiting for poll intervals - **Reduced API Load** - A single persistent connection replaces hundreds of status requests - **Complete Event History** - Track all state changes including partial fills, not just final status ## Order Events The WebSocket API notifies you of these order lifecycle events: - **order_created** - Your order has been submitted and is visible to resolvers - **order_filled** - The order was completely filled by a resolver - **order_filled_partially** - Part of your order was filled (for large orders) - **order_invalid** - The order became invalid due to cancellation, expiry, or insufficient balance ## Interactive Code Example Explore the complete implementation -- this example demonstrates creating a swap order and tracking its progress via WebSocket events: https://business.1inch.com/portal/assets/docs-v2/apis/swap/classic-swap/introduction.md The 1inch classic swap API (Pathfinder v6.1) is a cutting-edge discovery and routing algorithm that offers asset exchanges at the best rates on the market. Pathfinder finds the most efficient paths for a token swap and is able to split between different protocols and even different market depths within one protocol in the shortest possible time. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Eficiency The latest version (V 6.1) of Pathfinder algorithm pushes DeFi trading forward by unlocking smarter, more efficient swaps, and bringing a number of concrete advantages to 1inch Swap users: - Maximized returns: multiple swap paths are combined to secure the best rates, delivering more value from every trade. - Superior liquidity efficiency: by splitting volumes into finer chunks and blending paths, Pathfinder taps into pools more effectively, skimming the cream from concentrated liquidity for optimal exchanges. - Unrivaled access: the new Pathfinder facilitates a deeper dive into diverse liquidity pools, distributing volume to capture better rates where it matters most. - Gas efficiency: by merging paths to achieve better gas cost efficiency, every swap becomes more cost-effective. ## Before V 6.1 old routing ## After V 6.1 new pathfinder routing ## API reference For detailed information about each endpoint, refer to the classic swap API [OpenAPI specs](./methods/v6.1/1/quote/method/get). ## Quickstart In order to quickly understand how to make an exchange using the protocol, we suggest you use the [Quickstart guide](./quick-start.md). :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: https://business.1inch.com/portal/assets/docs-v2/apis/swap/classic-swap/quick-start.md Let's go over an example of how to perform a token swap using the **1inch Classic Swap API**. --- ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal). - Your wallet must have: - USDC (or the token you're swapping) on Base - ETH on Base to pay gas fees ## Typescript Program 1. Loads configuration variables (private key, wallet address, RPC URL, and 1inch Business Portal API key) from the environment or a local `.env` file 2. Connects to the Base chain using viem 3. Checks the allowance of the token being swapped and increases the approval if necessary 4. Uses the `/swap` endpoint to construct the swap transaction 5. It signs and broadcasts the transaction ### Dependencies - node v18.17.1 - npm v10.9.2 ```bash npm install dotenv ethers ``` ### Example ```typescript import dotenv from "dotenv"; import { Wallet, JsonRpcProvider, Contract } from "ethers"; dotenv.config(); const requiredEnvVars = ["PRIVATE_KEY", "API_KEY", "RPC_URL"]; for (const key of requiredEnvVars) { if (!process.env[key]) { console.error(`Missing required environment variable: ${key}`); process.exit(1); } } const AGGREGATION_ROUTER_V6 = "0x111111125421ca6dc452d289314280a0f8842a65"; const usdcBase = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; const wethBase = "0x4200000000000000000000000000000000000006"; const BASE_CHAIN_ID = 8453; const baseUrl = `https://api.1inch.com/swap/v6.1/${BASE_CHAIN_ID}`; const config = { aggregationRouter: AGGREGATION_ROUTER_V6, privateKey: process.env.PRIVATE_KEY!, apiKey: process.env.API_KEY!, rpcUrl: process.env.RPC_URL!, srcTokenAddress: usdcBase, dstTokenAddress: wethBase, amountToSwap: "100000", slippage: 1 // 1% }; const erc20ABI = [ { constant: true, inputs: [ { name: "owner", type: "address" }, { name: "spender", type: "address" } ], name: "allowance", outputs: [{ name: "", type: "uint256" }], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { name: "spender", type: "address" }, { name: "amount", type: "uint256" } ], name: "approve", outputs: [{ name: "", type: "bool" }], payable: false, stateMutability: "nonpayable", type: "function" } ]; type TransactionPayload = { to: string; data: string; value: bigint; }; type TxResponse = { tx: TransactionPayload; }; const provider = new JsonRpcProvider(config.rpcUrl); const wallet = new Wallet(config.privateKey, provider); function buildQueryURL(path: string, params: Record): string { const url = new URL(baseUrl + path); url.search = new URLSearchParams(params).toString(); return url.toString(); } async function call1inchAPI(endpointPath: string, queryParams: Record): Promise { const url = buildQueryURL(endpointPath, queryParams); const response = await fetch(url, { method: "GET", headers: { Accept: "application/json", Authorization: `Bearer ${config.apiKey}` } }); if (!response.ok) { const body = await response.text(); throw new Error(`1inch API returned status ${response.status}: ${body}`); } return (await response.json()) as T; } async function signAndSendTransaction(tx: TransactionPayload): Promise { try { const txResponse = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: tx.value }); return txResponse.hash; } catch (err) { console.error("Transaction signing or broadcasting failed"); console.error("Transaction data:", tx); throw err; } } async function checkAllowance(tokenAddress: string, spenderAddress: string): Promise { console.log("Checking token allowance..."); const tokenContract = new Contract(tokenAddress, erc20ABI, provider); const allowance = await tokenContract.allowance(wallet.address, spenderAddress); console.log("Allowance:", allowance.toString()); return allowance; } async function approveIfNeeded(tokenAddress: string, spenderAddress: string, requiredAmount: bigint): Promise { const allowance = await checkAllowance(tokenAddress, spenderAddress); if (allowance >= requiredAmount) { console.log("Allowance is sufficient for the swap."); return; } console.log("Insufficient allowance. Approving exact amount needed..."); const tokenContract = new Contract(tokenAddress, erc20ABI, wallet); const tx = await tokenContract.approve(spenderAddress, requiredAmount); console.log("Approval transaction sent. Hash:", tx.hash); console.log("Waiting for confirmation..."); await tx.wait(); console.log("Approval confirmed!"); } async function performSwap(): Promise { const swapParams = { src: config.srcTokenAddress, dst: config.dstTokenAddress, amount: config.amountToSwap, from: wallet.address.toLowerCase(), slippage: config.slippage.toString(), disableEstimate: "false", allowPartialFill: "false" }; console.log("Fetching swap transaction..."); const swapTx = await call1inchAPI("/swap", swapParams); console.log("Swap transaction:", swapTx.tx); const txHash = await signAndSendTransaction(swapTx.tx); console.log("Swap transaction sent. Hash:", txHash); } async function main() { try { await approveIfNeeded(config.srcTokenAddress, config.aggregationRouter, BigInt(config.amountToSwap)); await performSwap(); } catch (err) { console.error("Error:", (err as any)?.response?.data || err); } } main().catch((err) => { console.error("Unhandled error in main:", err); process.exit(1); }); ``` ## Go Program Uses the [official 1inch Go SDK](https://github.com/1inch/1inch-sdk-go/) to perform a token swap on the Base chain: 1. Loads configuration variables (private key, RPC URL, and 1inch Business Portal API key) from the environment 2. Connects to the Base chain using the SDK 3. Uses the `GetApproveAllowance` function in the SDK to call the `/approve/allowance` REST endpoint to check if your wallet has granted the proper USDC allowance to the 1inch router 4. If the allowance is **insufficient**, it uses the `GetApproveTransaction` function in the SDK to call the `/approve/transaction` REST endpoint to construct and send an approval transaction 5. Then, it uses the `GetSwap` function in the SDK to call the `/swap` REST endpoint to construct the swap transaction 6. It signs and broadcasts these transactions using the SDK client ### Dependencies - go v1.24.5 ```bash go get github.com/1inch/1inch-sdk-go/sdk-clients/aggregation go get github.com/ethereum/go-ethereum ``` ### Code ```go package main import ( "context" "fmt" "log" "math/big" "os" "time" "github.com/1inch/1inch-sdk-go/constants" "github.com/1inch/1inch-sdk-go/sdk-clients/aggregation" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" ) var ( privateKey = os.Getenv("PRIVATE_KEY") nodeUrl = os.Getenv("RPC_URL") devPortalToken = os.Getenv("DEV_PORTAL_API_KEY") ) const ( UsdcBase = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" WethBase = "0x4200000000000000000000000000000000000006" amountUsdc = "100000" // 0.1 USDC (6 decimals) ) func main() { config, err := aggregation.NewConfiguration(aggregation.ConfigurationParams{ NodeUrl: nodeUrl, PrivateKey: privateKey, ChainId: constants.BaseChainId, ApiUrl: "https://api.1inch.com", ApiKey: devPortalToken, }) if err != nil { log.Fatalf("Failed to create configuration: %v\n", err) } client, err := aggregation.NewClient(config) if err != nil { log.Fatalf("Failed to create client: %v\n", err) } ctx := context.Background() walletAddr := client.Wallet.Address().Hex() // Step 1: Check Allowance allowanceData, err := client.GetApproveAllowance(ctx, aggregation.GetAllowanceParams{ TokenAddress: UsdcBase, WalletAddress: walletAddr, }) if err != nil { log.Fatalf("Failed to get allowance: %v\n", err) } allowance := new(big.Int) allowance.SetString(allowanceData.Allowance, 10) amountToSwap := new(big.Int) amountToSwap.SetString(amountUsdc, 10) // Step 2: Approve if needed if allowance.Cmp(amountToSwap) < 0 { fmt.Println("Insufficient allowance. Approving...") approveData, err := client.GetApproveTransaction(ctx, aggregation.GetApproveParams{ TokenAddress: UsdcBase, Amount: amountUsdc, }) if err != nil { log.Fatalf("Failed to get approve data: %v\n", err) } data, err := hexutil.Decode(approveData.Data) if err != nil { log.Fatalf("Failed to decode approve data: %v\n", err) } to := common.HexToAddress(approveData.To) tx, err := client.TxBuilder.New().SetData(data).SetTo(&to).Build(ctx) if err != nil { log.Fatalf("Failed to build approve transaction: %v\n", err) } signedTx, err := client.Wallet.Sign(tx) if err != nil { log.Fatalf("Failed to sign approve transaction: %v\n", err) } err = client.Wallet.BroadcastTransaction(ctx, signedTx) if err != nil { log.Fatalf("Failed to broadcast approve transaction: %v\n", err) } fmt.Printf("Approve transaction sent: https://basescan.org/tx/%s\n", signedTx.Hash().Hex()) // Wait for approval to be mined for { receipt, _ := client.Wallet.TransactionReceipt(ctx, signedTx.Hash()) if receipt != nil { fmt.Println("Approve transaction confirmed.") break } time.Sleep(2 * time.Second) } } else { fmt.Println("Sufficient allowance already present.") } // Step 3: Perform Swap swapData, err := client.GetSwap(ctx, aggregation.GetSwapParams{ Src: UsdcBase, Dst: WethBase, Amount: amountUsdc, From: walletAddr, Slippage: 1, // 1% slippage }) if err != nil { log.Fatalf("Failed to get swap data: %v\n", err) } tx, err := client.TxBuilder.New(). SetData(swapData.TxNormalized.Data). SetTo(&swapData.TxNormalized.To). SetGas(swapData.TxNormalized.Gas). SetValue(swapData.TxNormalized.Value). Build(ctx) if err != nil { log.Fatalf("Failed to build transaction: %v\n", err) } signedTx, err := client.Wallet.Sign(tx) if err != nil { log.Fatalf("Failed to sign transaction: %v\n", err) } err = client.Wallet.BroadcastTransaction(ctx, signedTx) if err != nil { log.Fatalf("Failed to broadcast transaction: %v\n", err) } fmt.Printf("Swap transaction sent: https://basescan.org/tx/%s\n", signedTx.Hash().Hex()) // Wait for swap transaction to be mined for { receipt, _ := client.Wallet.TransactionReceipt(ctx, signedTx.Hash()) if receipt != nil { fmt.Println("Swap transaction confirmed!") break } time.Sleep(2 * time.Second) } } ``` https://business.1inch.com/portal/assets/docs-v2/apis/swap/real-world-assets-support.md ## What are RWAs? Real-world assets are tokenized representations of traditional financial instruments made accessible on-chain. In the case of Ondo-backed and xStocks assets, the tokens are designed to follow the total economic performance of the underlying instrument, aiming to mirror its value behavior rather than operate as derivatives. By bringing these instruments to blockchain ecosystems, RWAs allow users and developers to interact with traditional market exposures without directly accessing traditional brokerage or settlement infrastructure. ## Why can RWAs be useful? - _Expanded exposure set_: RWAs introduce equity, fixed-income, and commodity-linked exposures alongside crypto assets. - _Portfolio diversification_: RWAs can complement crypto-native assets with different risk and return characteristics. - _Composable on-chain usage_: once tokenized, RWAs can be integrated into smart contracts, intent-based execution, and automated strategies. ## How do RWAs work in 1inch? 1inch supports RWAs through its _Intent Swap API_ (Fusion mode), providing gasless and MEV-protected execution. Supported RWA tokens may be included in swap intents with outcome constraints, and are fulfilled by competing resolvers subject to market and eligibility conditions. This integration is powered through collaboration with [Ondo Finance](https://ondo.finance/) and [xStocks](https://xstocks.fi/), which helps ensure reliable pricing and smooth handling of RWA-linked tokens within the execution process. ## xStocks access and trading conditions ### Supported networks - Ethereum ### Geographic availability and time of operation xStocks RWAs are available for trading 24/7 and provide continuous access without time or geographic restrictions. ### Supported pairs and minimum order size Trading is currently supported exclusively in USDC <-> xStocks pairs. Note that orders below $20 are not filled. ## Ondo access and trading conditions ### Supported networks - Ethereum - BNB Smart Chain ### Geographic availability RWAs are available in most regions, subject to regulatory and eligibility restrictions. They are not available to users located in: - Afghanistan - Algeria - Belarus - Canada - China (excluding Hong Kong) - Crimea, Donetsk People's Republic (DNR), Luhansk People's Republic (LNR), Kherson and Zaporizhzhia regions (Ukraine), the city of Sevastopol - Cuba - Democratic Republic of Korea - European Economic Area - Eritrea - Iran - Libya - Myanmar - Morocco - Nepal - Russia - Singapore - Somalia - South Sudan - Sudan - Syria - Switzerland - United States, or any of its states, possessions, territories, or federal districts - United Kingdom - Venezuela ### Time of operation Primary pricing and liquidity for RWAs follow traditional market hours and are generally available 24 hours a day, 5 days a week, to stay aligned with underlying markets. :::info Outside of market hours (e.g., weekends or holidays), secondary transfers may still occur, but pricing may be wider or less representative due to underlying markets being closed. ::: ### Quick FAQ - **Which RWA tokens are available via the Intent Swap API?** Only whitelisted, issuer-approved RWA tokens that meet 1inch's technical, liquidity, and compliance integration criteria are exposed. - **What token standards are supported?** Currently, ERC-20 tokens are supported for RWA swaps via the 1inch Intent Swap API. - **Does 1inch perform KYC or AML on users before purchasing the RWAs?** No. 1inch does not perform KYC/AML. Compliance requirements are enforced by the RWA issuer at the token or contract level. - **What is the integrator responsible for?** Integrators are responsible for: user eligibility checks, UI/UX warnings, and regulatory disclosures and jurisdictional compliance. --- ## Legal disclaimer _Information relating to real-world assets backed by Ondo Finance (Ondo) and Backed Finance AG (xStocks), including their structure, backing, regulatory positioning, eligibility, and availability, is provided by Ondo, xStocks, or with reference thereto. Developers and users should review own terms of Ondo and/or xStocks, disclosures, and documentation and monitor updates provided directly by Ondo and/or xStocks._ _1inch does not issue, sponsor, endorse, manage, or provide investment advice in relation to any RWA or underlying asset. 1inch acts solely as an infrastructure and technology provider, enabling access to supported tokens via its APIs, where available._ _This material is provided for informational purposes only and does not constitute investment advice, an offer, solicitation, or recommendation to acquire or dispose of any asset._ _Availability of RWAs may vary by jurisdiction, eligibility criteria, network, market conditions, and third-party restrictions, and may change over time._ _Nothing in this material modifies, supplements, or overrides any representations, warranties, obligations, or disclaimers set forth in any agreement between you and 1inch (or its affiliates), which shall govern in the event of any inconsistency._ ## Orderbook API https://business.1inch.com/portal/assets/docs-v2/apis/orderbook/introduction.md 1inch Orderbook API is using the 1inch [Limit Order Protocol](https://github.com/1inch/limit-order-protocol), which is a set of smart contracts that can work on any EVM-based blockchains. Key features of the protocol are extreme flexibility and high gas efficiency. ## Orderbook An orderbook is a trading mechanism where users create fixed-price orders for tokens, specifying both the execution price and an expiration condition that limits how long the order remains valid. For example, you can put up 2 WBTC tokens for sale at the price of 82,415 DAI tokens valid for 7 days. The 1inch Limit Orders Protocol provides a rich set of tools for flexible and professional trade management: - Partial fill Orders can be filled in multiple steps without requiring full execution at once. - Predicates Conditional execution logic (e.g. price bounds, time constraints, external state checks). - Single cancellation Cancel a specific order by its unique hash. - Batch (bunch) cancellation Invalidate multiple orders efficiently in a single action. - Fullness check Ensure the order is filled exactly as specified, preventing over- or under-fills when required. - Validation Custom on-chain validation logic to control whether an order can be executed. To enable efficient market making, RFQ orders are used, benefiting from a special optimization that avoids high gas costs during execution. ## Limit order execution ### 1. Order placement Users place limit orders. Each order is cryptographically signed and remains off-chain until executed. ### 2. Order discovery Anyone can fetch these signed orders using the [1inch Orderbook API](./methods) to execute trades by submitting them on-chain. ### 3. Order execution To execute an order, the signed order is submitted to the smart contract's `fillOrder` method. See the latest contract addresses in [Limit Order SDK](https://github.com/1inch/limit-order-sdk/blob/master/src/constants.ts). :::info Both the buyer and seller must approve the 1inch Limit Order Protocol to transfer their tokens. ::: ## Supported tokens standards - ERC-20 - ERC-721 - ERC-1155 Other token standards can be supported via external extensions. :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## More resources - To quickly understand how to create, sign, and submit a limit order, see the [Quickstart guide](./quick-start.md). - For detailed information about each endpoint, refer to the [Orderbook API Swagger section](./methods). - Try directly at [1inch dApp](https://1inch.com/pro?mode=limit&pair=1:0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48). - Explore the [Limit Order Protocol](https://github.com/1inch/limit-order-protocol/). - For integration purposes, check out [Limit Order SDK](./limit-order-sdk/introduction.md). https://business.1inch.com/portal/assets/docs-v2/apis/orderbook/quick-start.md ## Introduction This guide shows how to create and submit a Limit Order v4 using the [@1inch/limit-order-sdk](https://github.com/1inch/limit-order-sdk) on Ethereum. ## Before You Start - You must have a valid **1inch API Key**. You can get one from the [1inch Business](https://business.1inch.com/portal). - Your wallet must have: - USDC on Ethereum (for the maker asset) - ETH for the token approval transaction ## Integration Pattern 1. **Approve Tokens** - Grant the Limit Order Protocol contract permission to spend your tokens 2. **Initialize SDK** - Create an SDK instance with your API key and network 3. **Configure Traits** - Set expiration and nonce via `MakerTraits` 4. **Create Order** - Build a properly formatted order with the SDK 5. **Sign Order** - Sign with EIP-712 typed data (no gas required) 6. **Submit Order** - Send the signed order to the 1inch Orderbook API ## Interactive Code Example Explore the minimal quick-start implementation (~90 lines): For a more comprehensive example with provider-agnostic design and balance checks, see `src/create-limit-order.ts` in the same project. https://business.1inch.com/portal/assets/docs-v2/apis/orderbook/sdk/introduction.md The [limit-order-sdk](https://github.com/1inch/limit-order-sdk) is a TypeScript library developed by 1inch that enables developers to build, sign, and manage off-chain limit orders, fully compatible with the 1inch Limit Order Protocol. ## Key Benefits - **Gasless Order Creation** - Sign orders off-chain with EIP-712, only pay gas for token approval - **Orderbook Discovery** - Submit signed orders to the 1inch Orderbook for resolvers to fill - **Multi-Token Support** - Trade ERC-20, ERC-721, and ERC-1155 tokens - **Permit Support** - Use permits for gasless approvals ## How It Works 1. **Approve Tokens** - Grant the Limit Order Protocol contract permission to spend your tokens (one-time gas cost) 2. **Create Order** - Use the SDK to build a properly formatted order with assets, amounts, and expiration 3. **Sign Order** - Sign the order off-chain using EIP-712 typed data (no gas required) 4. **Submit to Orderbook** - Send the signed order to the 1inch Orderbook API (free) 5. **Resolver Fills** - Resolvers discover and fill your order on-chain ## Interactive Code Example Explore the complete implementation -- this example demonstrates creating, signing, and submitting a limit order: ## Advanced usage In addition to publishing limit orders to the 1inch Orderbook, the Limit Order SDK can also be used for more advanced and customized workflows that operate independently of the Orderbook API. To learn more about this use case, see [Advanced usage for custom protocol integration](./advanced-usage.md). https://business.1inch.com/portal/assets/docs-v2/apis/orderbook/sdk/querying-the-orderbook.md The Limit Order SDK provides a built-in `Api` class for querying orders from the 1inch Orderbook. You can retrieve orders by hash, by maker address, or browse all active orders with pagination support. ## Prerequisites You need: - A 1inch API key (get one at [1inch Business](https://business.1inch.com/portal)) - The `@1inch/limit-order-sdk` package installed No wallet or private key is required for read-only queries. ## Setting up the API client ```javascript import { Api, FetchProviderConnector, CursorPager } from "@1inch/limit-order-sdk"; const api = new Api({ networkId: 1, // Ethereum mainnet authKey: "your-api-key", httpConnector: new FetchProviderConnector() }); ``` ## Query by order hash If you have an order hash from a previous submission, you can retrieve its full details: ```javascript const order = await api.getOrderByHash(orderHash); console.log("Maker Asset:", order.data.makerAsset); console.log("Taker Asset:", order.data.takerAsset); console.log("Making Amount:", order.data.makingAmount); console.log("Taking Amount:", order.data.takingAmount); ``` ## Query by maker address To retrieve all orders created by a specific wallet address, use `getOrdersByMaker` with pagination: ```javascript const response = await api.getOrdersByMaker(makerAddress, { pager: new CursorPager({ limit: 10 }), statuses: [1] // 1 = active orders only }); for (const order of response.items) { console.log("Maker Asset:", order.data.makerAsset); console.log("Taking Amount:", order.data.takingAmount); } ``` ### Status codes | Status | Meaning | | ------ | --------- | | 1 | Active | | 2 | Filled | | 3 | Expired | | 4 | Cancelled | ## Query all active orders To browse the full orderbook, use `getAllOrders` with pagination: ```javascript const response = await api.getAllOrders({ pager: new CursorPager({ limit: 5 }), statuses: [1] }); console.log(`Found ${response.items.length} active orders`); ``` ## Full working example https://business.1inch.com/portal/assets/docs-v2/apis/orderbook/sdk/advanced-usage.md The [limit-order-sdk](https://github.com/1inch/limit-order-sdk) can be used not only to integrate with the 1inch Orderbook, but also as a toolkit for building custom trading infrastructure based on the 1inch Limit Order Protocol. This approach is intended for teams who want full control over how orders are constructed, signed, and filled--independently of the public 1inch backend. With this scenario, you can benefit from using the following advanced features: - Manually construct limit and RFQ orders - Asset evaluation helpers - Custom execution predicates ## Difference between Orderbook API and custom protocol | Feature | Orderbook API | Custom Protocol Integration | | :------------------ | :-------------------------- | :-------------------------- | | Limit orders | [x] Supported | [x] Supported | | `permit` field | [x] Supported | [x] Supported | | RFQ orders | [ ] Not supported | [x] Fully supported | | Custom predicates | [ ] Ignored | [x] Executed on-chain | | `interaction` field | [ ] Not accepted | [x] Fully usable | | Fee customization | [ ] Fixed (protocol default) | [x] Fully configurable | ## About RFQ orders A Request for Quotation (RFQ) is a business process where a trader requests a price quote from a supplier for the purchase of specific tokens. RFQ orders are gas-optimized and purpose-built for the needs of professional market makers. They offer lightweight execution with specific constraints: - Supports expiration time - Can be canceled by order ID - Fillable only once - Allows partial fill (only once) These characteristics make RFQ orders ideal for real-time, short-lived liquidity provisioning. ## Start your custom integration Explore internals and primitives in the Limit Order SDK repository: - [Limit order](https://github.com/1inch/limit-order-sdk/blob/master/src/limit-order/) - [RFQ order](https://github.com/1inch/limit-order-sdk/tree/master/src/rfq-order) ## History API https://business.1inch.com/portal/assets/docs-v2/apis/history/introduction.md History API allows you to access accurate transaction history data across several major networks. With it, you can get such information as: - Transaction type, hash, status, fee, timestamps - Participants addresses - Token transfers, and more ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Use cases The History API can be applied across various industries and scenarios that require access to accurate on-chain transaction data. Below are some common use cases: ### Compliance and auditing The History API enables companies to access transaction details, including participants, amounts, and timestamps, helping them meet auditing requirements and adhere to Anti-Money Laundering (AML) regulations. ### Portfolio management Investors and portfolio managers can use the History API to analyze transaction histories across multiple blockchain networks. It helps track token movements, swaps, staking activities, and liquidity provisions, allowing your users to generate reports and optimize investment strategies. ### DeFi protocol analytics Decentralized Finance (DeFi) protocols rely on transaction data to monitor user behavior, liquidity, and protocol usage. The History API provides detailed information on liquidity additions, removals, borrowing, lending, and staking activities, making it essential for DeFi analytics platforms. ### NFT marketplaces NFT marketplaces can integrate the History API to display detailed transaction histories for NFTs, including purchases, bids, sales, and transfers. This enables buyers and sellers to review historical data before making decisions. ### Security and risk management Security platforms can use the History API to track transaction histories and identify suspicious activities, such as unauthorized approvals or large token transfers. The API's detailed breakdown of transaction types helps detect patterns indicative of potential security threats, protecting users from fraud and malicious actions. ### Enterprise resource management Enterprises engaging in blockchain transactions can integrate the History API to manage internal operations and resources more effectively. It helps track employee or system-triggered transactions, manage smart contract interactions, and ensure transparency in decentralized workflows. ### Tax reporting Individuals and businesses dealing with cryptocurrencies must track all transactions for accurate tax reporting. The History API allows users to retrieve transaction histories to calculate gains, losses, and taxable events such as token swaps and sales. :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## Transaction types We define the following transaction types: | Transaction type | Description | | --------------------- | -------------------------------------------------------------------------------------------------------------------- | | `Unknown` | A transaction type that hasn't been identified or categorized. | | `Approve` | Granting permission for a smart contract to spend your tokens. | | `Wrap` | Converting a cryptocurrency into its wrapped version. | | `Unwrap` | Converting a wrapped token back to its original cryptocurrency. | | `Swap` | Exchanging one type of token for another. | | `Transfer` | Sending tokens from one address to another. | | `LimitOrderFill` | Executing a limit order by buying or selling tokens at the specified price or better. | | `LimitOrderCancel` | Canceling an existing limit order that is expired or hasn't been filled fully. | | `LimitOrderCancelAll` | Canceling an active limit order. | | `AddLiquidity` | Providing tokens to a liquidity pool to facilitate trading and earn rewards. | | `RemoveLiquidity` | Withdrawing tokens from a liquidity pool. | | `Borrow` | Taking out a loan in the form of tokens from a lending protocol. | | `Repay` | Returning borrowed tokens to a lending protocol. | | `Stake` | Locking tokens in a protocol to earn rewards or participate in governance. | | `Unstake` | Withdrawing staked tokens from a protocol. | | `Vote` | Casting a vote on a proposal in a decentralized governance system. | | `DelegateVotePower` | Assigning your voting power to another address to vote on your behalf. | | `UnDelegateVotePower` | Revoking the assignment of your voting power from a delegate. | | `DiscardVote` | Invalidating or withdrawing a previously cast vote. | | `Claim` | Retrieving rewards or tokens that are due to you. | | `Action` | Performing a specific function or task within a smart contract. | | `Bridge` | Transferring tokens across different blockchains. | | `BuyNft` | Purchasing an NFT from the marketplace. | | `BidNft` | Placing a bid on an NFT in an auction. | | `OfferSellNft` | Making an offer to sell an NFT you own. | | `Burn` | Permanently removing tokens from circulation. | | `WrappedTx` | A [Gnosis Safe](https://app.safe.global/welcome) transaction which can include one or more multisigned transactions. | | `RegisterENSDomain` | Registering a human-readable name on the Ethereum Name Service (ENS) to associate with your address. | | `Revoke` | Withdrawing previously granted permissions or approvals. | | `CreateSafe` | Creating a multisig Gnosis Safe Wallet. | | `AddOwner` | Adding a new owner to a multisig Gnosis Safe Wallet. | | `MultiStage` | A transaction that involves multiple steps or stages, often used in complex operations. | ## Supported networks - [Ethereum Mainnet](https://ethereum.org/) - [Arbitrum](https://arbitrum.io/) - [Avalanche](https://www.avax.network/) - [BNB Chain](https://www.binance.com/en/support/announcement/854415cf3d214371a7b60cf01ead0918) - [Gnosis](https://www.xdaichain.com/) - [Sonic](https://www.soniclabs.com/) - [Optimism](https://www.optimism.io/) - [Polygon](https://polygon.technology/) - [zkSync Era](https://docs.zksync.io/build) - [Base](https://docs.base.org/) - [Unichain](https://www.unichain.org/) ## Quickstart To start using History API swiftly, refer to the [Quickstart guide](./quick-start). ## API reference For detailed information about each endpoint, refer to the History API [Open API section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/history/quick-start.md This guide will walk you through on how you can seamlessly retrieve and display wallet transactions by using the wallet history API. ## Prerequisites - Node.js and npm installed - Basic knowledge of JavaScript, React, and Express.js ## Step-by-step guide ### Step 1: Initialization 1. Create a new directory for the project: ```bash mkdir wallet-history && cd wallet-history ``` 2. Initialize a new Node.js project: ```bash npm init -y ``` 3. Install Express, CORS, and Axios: ```bash npm install express cors axios ``` 4. Install dotenv: ```bash npm install dotenv ``` Then create a new file called .env and add your api key: ```bash API_KEY=YOUR_1INCH_API_KEY ``` 5. Create a new file `api.js` and set up a basic Express server by pasting into it the following: ```javascript // Import required packages const express = require("express"); const axios = require("axios"); const dotenv = require("dotenv"); const cors = require("cors"); const path = require("path"); // Initialize the app and load environment variables from .env dotenv.config({ path: path.resolve(__dirname, ".env") }); const app = express(); // Enable CORS for all routes app.use(cors()); const BASE_URL = "https://api.1inch.com/history/v2.0/history"; // Endpoint to fetch wallet transaction history app.get("/api/:address/history", async (req, res) => { const address = req.params.address; const limit = req.query.limit || 10; try { const constructedUrl = `${BASE_URL}/${address}/events?chainId=${1}&limit=${limit}`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` // Use API key from .env } }); // Send the response data back to the client res.json(response.data); } catch (error) { console.error("Error fetching wallet transactions:", error); res.status(500).json({ error: "An error occurred while fetching data" }); } }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); ``` 1. Add an endpoint to fetch wallet transactions and don't forget to replace API_KEY with your 1inch Business API key: ```javascript const BASE_URL = "https://api.1inch.com/history/v2.0/history"; app.get("/api/:address/history", async (req, res) => { const address = req.params.address; const limit = req.query.limit || 10; try { const constructedUrl = `${BASE_URL}/${address}/events?chainId=${1}&limit=${limit}`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); // Send the data from the API back to the client res.json(response.data.items); } catch (error) { console.error("Axios Error: ", error.response); res.status(500).json({ error: "Failed to fetch wallet transactions" }); } }); ``` ### Step 2: Setting up React frontend 1. Create a new React application: ```bash npx create-react-app client ``` 2. Navigate to the React application directory: ```bash cd client ``` 3. Create a `History.js` component inside the `src` directory with the following content: ```javascript import React, { useState, useEffect } from "react"; const History = ({ address }) => { const [transactions, setTransactions] = useState([]); const [isLoading, setLoading] = useState(false); useEffect(() => { const fetchData = async () => { setLoading(true); const response = await fetch(`http://localhost:5001/api/${address}/history`); if (!response.ok) { console.log("Fetch history error", response); return; } const transactions = await response.json(); setTransactions(transactions); setLoading(false); }; if (isLoading) { return; } fetchData(); }, [address]); if (isLoading) { return
Loading...
; } return ( ); }; export default History; ``` 4. Import and use `History` in `src/App.js`: ```javascript import React, { useState } from "react"; import "./App.css"; import History from "./History"; function App() { const [inputValue, setSearchTerm] = useState(""); const [address, setAddress] = useState(); const handleChange = (event) => { setSearchTerm(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); setAddress(inputValue); }; return (
{address &&

Ethereum history of {address}

} {address && }
); } export default App; ``` ### Step 3: Running the project 1. Start the Express server: ```bash node api.js ``` 2. In a new terminal, navigate to the client directory and start the React app: ```bash cd client ``` Now, you can view your wallet transaction history at http://localhost:3000. Described above is a basic setup and you can expand upon this by adding more features, error handling, and styling to get to production.
## Traces API https://business.1inch.com/portal/assets/docs-v2/apis/traces/introduction.md The 1inch Trace API provides comprehensive, step-by-step data on every operation within on-chain transactions. This empowers developers and analysts to gain precise insights into transaction behavior. This API supports many networks ensuring compatibility across diverse ecosystems. With fast and organized transaction traces, you can debug, audit, and optimize with ease, whether you're working on smart contracts or analyzing historical transaction data. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## What are transaction traces? A transaction trace is essentially a step-by-step representation of every operation that occurs during the execution of a transaction on the blockchain. For Ethereum, these operations can be quite varied, from basic transfers of ETH to complex contract interactions. ## Why are transaction traces useful? - **Debugging smart contracts**: developers can use transaction traces to troubleshoot their smart contracts, especially when something goes wrong. They can identify which specific step of the contract resulted in an error. - **Optimization**: developers can analyze how gas is consumed during different operations in the transaction. This helps in optimizing smart contracts to be more gas efficient. - **Security audits**: transaction traces can be instrumental in security audits. They allow auditors to see the exact flow of operations, ensuring that the contract behaves as expected. - **Understanding contract behavior**: for those trying to understand how a particular smart contract operates, tracing provides a clear breakdown of its inner workings. - **Historical analysis**: for platforms or researchers analyzing blockchain data, transaction traces offer rich insights into the actual execution of historical transactions. :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## API reference For detailed information about each endpoint, refer to the Traces API [Swagger section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/traces/quick-start.md ## 1inch Transaction Traces API: 1inch's Transaction Traces API provides users with an efficient way to access transaction traces for different chains. ### 1. Check Synced Interval: Before fetching any transaction traces, it's useful to know the synced interval. It gives the range of block numbers that have been synced and are available for query. **Endpoint**: ```text GET /v1.0/chain/{chain}/synced-interval ``` **Parameters**: - `chain` (required): Chain ID. For Ethereum mainnet, it would be `1`. **Sample Request**: ```text https://api.1inch.com/traces/v1.0/chain/1/synced-interval ``` ### 2. Get Block Trace by Number: To retrieve the transaction traces of all transactions in a specific block. **Endpoint**: ```text GET /v1.0/chain/{chain}/block-trace/{blockNumber} ``` **Parameters**: - `chain` (required): Chain ID. - `blockNumber` (required): The block number you wish to retrieve traces from. **Sample Request**: ```text https://api.1inch.com/traces/v1.0/chain/1/block-trace/15000000 ``` ### 3. Get Block Trace by Transaction Hash: If you are specifically interested in the trace of a particular transaction within a block, you can fetch it using the transaction hash. **Endpoint**: ```text GET /v1.0/chain/{chain}/block-trace/{blockNumber}/tx-hash/{txHash} ``` **Parameters**: - `chain` (required): Chain ID. - `blockNumber` (required): The block number containing the transaction. - `txHash` (required): The hash of the specific transaction you want to trace. **Sample Request**: ```text https://api.1inch.com/traces/v1.0/chain/1/block-trace/17378177/tx-hash/0x16897e492b2e023d8f07be9e925f2c15a91000ef11a01fc71e70f75050f1e03c ``` ### Prerequisites: - Node.js and npm installed. - A text editor or IDE. - API key for the Transaction Traces API. ### Steps: 1. **Initialize a New Node.js Project**: ```bash mkdir traces_api_tutorial cd traces_api_tutorial npm init -y ``` 2. **Install the Required Packages**: We'll be using `axios` to make the HTTP requests: ```bash npm install axios ``` 3. **Set Up Your API Key**: For the sake of security, store your API key in a `.env` file: ```bash echo "API_KEY=YOUR-API-KEY" > .env ``` Then, install `dotenv` to use this file: ```bash npm install dotenv ``` 4. **Write the Code**: Create a new file named `index.js` and add the following: ```javascript require("dotenv").config(); const axios = require("axios"); const BASE_URL = "https://api.1inch.com/traces/v1.0/chain"; async function getSyncedInterval(chain) { const url = `${BASE_URL}/${chain}/synced-interval`; const response = await axios.get(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); return response.data; } async function getBlockTraceByNumber(chain, blockNumber) { const url = `${BASE_URL}/${chain}/block-trace/${blockNumber}`; const response = await axios.get(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); return response.data; } async function getBlockTraceByNumberAndTxHash(chain, blockNumber, txHash) { const url = `${BASE_URL}/${chain}/block-trace/${blockNumber}/tx-hash/${txHash}`; const response = await axios.get(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); return response.data; } function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } (async function () { try { const chain = 1; // Example chain const blockNumber = 15000000; // Example block number const txHash = "0x16897e492b2e023d8f07be9e925f2c15a91000ef11a01fc71e70f75050f1e03c"; // Example transaction hash const syncedInterval = await getSyncedInterval(chain); console.log("Synced Interval:", syncedInterval); await sleep(1000); // Sleep for 1 second to avoid rate limit const blockTrace = await getBlockTraceByNumber(chain, blockNumber); console.log("Block Trace:", blockTrace); await sleep(1000); // Sleep for 1 second to avoid rate limit const txTrace = await getBlockTraceByNumberAndTxHash(chain, blockNumber, txHash); console.log("Transaction Trace:", txTrace); } catch (error) { console.error("Error fetching data:", error.response ? error.response.data : error.message); } })(); ``` 5. **Run Your Script**: ```bash node index.js ``` Transaction traces are a powerful tool for anyone interacting with or developing on the blockchain. They provide invaluable insights into the workings of smart contracts, helping improve efficiency, security, and understanding. With 1inch's Transaction Traces API, accessing these insights becomes a seamless process, enabling deeper interaction with blockchain data. With the steps above, you'll be able to interact with the Transaction Traces API using Node.js. Make sure you replace `'API-KEY'` in the `.env` file with your actual API key. ## Portfolio API https://business.1inch.com/portal/assets/docs-v2/apis/portfolio/introduction.md The 1inch Portfolio API aggregates and presents detailed information for web3 assets across multiple wallets and chains. By leveraging this API, you can gain a holistic view into any crypto portfolio and track performance metrics. This allows you or your users to make informed investment decisions without the hassle of juggling multiple platforms. ## Key features - **Multi-wallet support**: add and monitor multiple wallets to get a complete picture of your crypto holdings across various addresses. - **Multi-chain integration**: view assets and transactions across multiple supported blockchains on a single screen. - **Detailed analytics**: access advanced DeFi analytics, including metrics from top protocols like Uniswap, Curve, Aave, and more. - **Profit and loss tracking**: calculate and track your portfolio's profit and loss and return on investment across different protocols and tokens. - **Current value monitoring**: obtain real-time data on the current value of your assets, organized by chains and addresses. - **Comprehensive protocol data**: get detailed information on supported protocols, including underlying tokens, APR, unclaimed fees, and more. - **Investment opportunity discovery**: identify and explore new investment opportunities based on any given portfolio's performance and market trends. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Getting started To begin using the 1inch Portfolio API, generate an API key and set up your development environment. Then you check out the [Quickstart guide](./quick-start), or dive right into any of the endpoints listed below. :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## Core Concepts | Term | Meaning | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Address** | Wallet address. EVM chains use `0x...` format, Solana uses base58. | | **Chain ID** | Numeric blockchain identifier. `1` = Ethereum mainnet, `137` = Polygon, etc. See [supported chains](./methods/portfolio/v5.0/general/supported_chains/method/get). | | **Timerange** | Period for historical calculations. Values: `1day`, `1week`, `1month`, `1year`, `3years`. Counted backwards from current time. | | **Snapshot** | Point-in-time view of assets. By default returns current state; optional `timestamp` parameter returns historical state. | | **Metrics** | Aggregated historical data for a timerange: profit/loss, ROI, volume of inflows and outflows, etc. | | **Protocol** | DeFi application where user has positions (Aave, Uniswap, Compound, etc.). See [supported protocols](./methods/portfolio/v5.0/general/supported_protocols/method/get). Does not include simple token holdings. | | **Native token** | Chain's base currency (ETH on Ethereum, MATIC on Polygon). Represented as `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` in API responses. | ## API reference For detailed information about each endpoint, refer to the Portfolio API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/portfolio/quick-start.md Base URL (unified gateway at `https://api.1inch.com`): `https://api.1inch.com/portfolio/portfolio/v5.0` The OpenAPI paths for the Portfolio service are `/portfolio/v5.0/...`. On the unified gateway, use an extra `/portfolio` segment so requests are routed correctly (the gateway strips the first `/portfolio` before forwarding). The same applies to the MCP `product_api` tool: use paths starting with `/portfolio/portfolio/v5.0`. Portfolio API provides real-time and historical data about wallet holdings across multiple blockchains. Track token balances, DeFi positions, profit and loss, and portfolio value over time. This guide covers the most common use cases to get you started quickly. For full API reference, see the [Open API specifications](./methods). ## Response Format All endpoints return responses wrapped in an envelope: ```json { "result": { ... }, "meta": { ... } } ``` Your data is always in `result`. The `meta` field contains optional metadata (pagination, warnings, etc.). ## Multiple Wallets Pass multiple `addresses` parameters to aggregate data across wallets: ```bash ?addresses=0xabc...&addresses=0xdef...&addresses=0x123... ``` The API will return combined results. Individual wallet breakdowns are available in `by_address` field where supported. ## Getting Started ### 1. Get Total Portfolio Value Returns USD value of all assets (tokens + DeFi positions) broken down by category, chain, and protocol. ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/general/current_value?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` Response: ```json { "result": { "total": 12543.87, "by_category": [ { "category_id": "tokens", "category_name": "Tokens", "value_usd": 8234.12 }, { "category_id": "protocols", "category_name": "Protocols", "value_usd": 3106.3 }, { "category_id": "native", "category_name": "Native", "value_usd": 1203.45 } ], "by_chain": [ { "chain_id": 1, "chain_name": "Ethereum", "value_usd": 9500.0 }, { "chain_id": 137, "chain_name": "Polygon", "value_usd": 3043.87 } ], "by_protocol_group": [{ "protocol_group_id": "aave", "protocol_group_name": "Aave", "value_usd": 2500.0 }] } } ``` **Notes:** - `tokens` = ERC-20 tokens and SPL tokens - `native` = ETH, MATIC, BNB, etc. - `protocols` = value locked in DeFi (lending, LPs, staking, etc.) ### 2. Get Profit and Loss Returns realized + unrealized PnL for a given timerange, grouped by chain. ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/general/profit_and_loss?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75&timerange=1year' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` Response: ```json { "result": [ { "chain_id": 1, "abs_profit_usd": 2341.56 }, { "chain_id": 137, "abs_profit_usd": -128.3 }, { "chain_id": null, "abs_profit_usd": 2213.26 } ] } ``` **Notes:** - `chain_id: null` = aggregated total across all chains - Negative values indicate a loss ### 3. Get Token Holdings and DeFi Positions **Token balances:** ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/tokens/snapshot?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` **DeFi positions:** ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/protocols/snapshot?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` **Notes:** - Add `chain_id` parameter to filter by specific chain - Add `timestamp` (unix seconds) to get historical snapshot ### 4. Get Token and Protocol Metrics Returns PnL, ROI, inflows/outflows for each token or protocol position. **Token metrics:** ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/tokens/metrics?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75&timerange=1year' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` **Protocol metrics:** ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/protocols/metrics?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75&timerange=1year' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` **Notes:** - Returns a list of metrics per token/protocol position - Each item includes `profit_abs_usd`, `roi`, `inflow_usd`, `outflow_usd`, etc. ### 5. Get Single Token Details Returns detailed analytics for a specific token: average buy price, inflows, outflows, PnL. ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/tokens/additional/details?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75&chain_id=1&contract_address=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&timerange=1year' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` Response: ```json { "result": { "chain": 1, "contract_address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "symbol": "USDC", "name": "USD Coin", "amount": 5000.0, "price_to_usd": 1.0, "value_usd": 5000.0, "abs_profit_usd": 127.45, "roi": 0.026, "average_price_usd": 0.998, "average_price_usd_period": 0.999, "value_inflow_usd": 4800.0, "value_outflow_usd": 320.0, "value_inflow_usd_period": 2400.0, "value_outflow_usd_period": 150.0 } } ``` **Notes:** - `average_price_usd` = all-time average purchase price - `average_price_usd_period` = average price within requested timerange - `roi` = return on investment as decimal (0.026 = 2.6%) - `*_period` fields = values calculated only for the requested timerange ### 6. Get Portfolio Value Chart Returns time series data for plotting portfolio value over time. ```bash curl 'https://api.1inch.com/portfolio/portfolio/v5.0/general/chart?addresses=0xd470055c6189b921c4d44b3d277ad868f79c0f75&timerange=1month' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` Response: ```json { "result": [ { "timestamp": 1704067200, "value_usd": 10234.50 }, { "timestamp": 1704153600, "value_usd": 10456.78 }, ... ] } ``` **Notes:** - Timestamps are Unix epoch seconds (UTC) - Data points interval: 5min for `1day`, 30min for `1week`, 2h for `1month`, daily for `1year`, weekly for `3years` ## Common Use Cases | Use case | Endpoint | Required parameters | | ------------------------- | --------------------------------- | ------------------------------------------- | | Portfolio total value | `/general/current_value` | `addresses` | | PnL by chain | `/general/profit_and_loss` | `addresses`, `timerange` | | Token balances | `/tokens/snapshot` | `addresses` | | DeFi positions | `/protocols/snapshot` | `addresses` | | Token metrics | `/tokens/metrics` | `addresses`, `timerange` | | Protocol metrics | `/protocols/metrics` | `addresses`, `timerange` | | Single token analytics | `/tokens/additional/details` | `addresses`, `chain_id`, `contract_address` | | Token transaction history | `/tokens/additional/transactions` | `addresses`, `chain_id`, `contract_address` | | Portfolio value chart | `/general/chart` | `addresses`, `timerange` | | Single token chart | `/tokens/additional/charts` | `addresses`, `chain_id`, `contract_address` | ## Balance API https://business.1inch.com/portal/assets/docs-v2/apis/balance/introduction.md The 1inch Balance API provides real-time, accurate information about token balances and allowances across multiple chains. This API is essential for applications that need to track or display the assets held in web3 wallets and offers a simple integration into wallets, exchanges, and other dApps. By leveraging the Balance API, you can ensure that your users always have up-to-date details on their token holdings, allowances, and more. ## Supported Chains The 1inch Balance API supports a broad range of chains: | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the 1inch Balance API? The 1inch Balance API offers several significant benefits: - **Wide selection of tokens**: supports any token on the most popular blockchain networks. - **Fast response time**: with response times under 400 ms, the Balance API is among the fastest on the market, providing nearly instant access to wallet balances and allowances. ## Integration possibilities The 1inch Balance API can be integrated into a variety of applications, making it versatile for many web3 use cases. It is especially useful in: - Wallets - Portfolio and token trackers - Exchanges and meta-aggregators - Majority of web3 applications :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## API reference For detailed information about each endpoint, refer to the Balance API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/balance/quick-start.md ## Building a Token Balance Checker using 1inch Balance API In this tutorial, we will create a simple Python script to check the token balances of a given wallet address using the 1inch Balance API. We'll use the popular `requests` library to make API calls. ### Prerequisites: 1. Python (3.6 or higher) installed on your machine. 2. `requests` library. Install it using `pip install requests`. ### Step 1: Understanding the API Before we begin, let's briefly understand the 1inch Balance API endpoint we'll be using: - **Endpoint**: `https://api.1inch.com/balance` - **Method**: `GET` - **Parameters**: - `walletAddress`: The Ethereum wallet address for which we want to fetch token balances. ### Step 2: Implementing the Token Balance Checker Create a new Python file named `token_balance_checker.py` and write the following code: ```python # token_balance_checker.py import requests def get_token_balances(wallet_address): endpoint = f'https://api.1inch.com/balance/v1.2/1/balances/{wallet_address}' response = requests.get(endpoint, headers={'Authorization': f'Bearer YOUR-API-KEY'}) if response.status_code == 200: return response.json() else: print(f"Failed to fetch token balances. Error code: {response.status_code}") return None def main(): # Replace '0xYourWalletAddress' with the Ethereum wallet address you want to check wallet_address = '0xYourWalletAddress' token_balances = get_token_balances(wallet_address) if token_balances: print(f"Token balances for wallet address {wallet_address}:") for token, balance in token_balances.items(): print(f"{token}: {balance}") else: print("Token balance fetch failed. Please check your wallet address.") if __name__ == '__main__': main() ``` ### Step 3: Running the Token Balance Checker Save the script and run it using the command: ```bash python token_balance_checker.py ``` Replace `'0xYourWalletAddress'` in the script with the Ethereum wallet address you want to check. The script will then fetch and display the token balances for that wallet address. That's it! You have now built a simple Token Balance Checker using the 1inch Balance API. You can further expand this project to include more functionality, such as calculating the total value of tokens based on token prices, filtering out zero-balance tokens, and more. Remember to handle errors and implement security measures, such as input validation and user authentication, when building real-world applications. ## Gas Price API https://business.1inch.com/portal/assets/docs-v2/apis/gas-price/introduction.md The 1inch Gas Price API provides real-time, accurate gas price data across various blockchains, enabling developers and users to make informed decisions on transaction costs. With ultimate interoperability, the API allows seamless integration into applications that require up-to-date gas prices. ## Supported Chains The Gas Price API provides support for the following chains: | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the Gas Price API? The Gas Price API offers several key benefits: - **Up-to-date information**: provides the most current gas price data on various blockchains for your users. - **Fast response**: With a response time of less than 200 ms, the Gas Price API is one of the fastest solutions available. ## Integration possibilities The Gas Price API can be integrated into various applications, such as: - Wallets - Exchanges and meta-aggregators - Portfolio trackers - Trading and arbitrage bots Any user interface that needs to display gas prices can benefit from integrating the Gas Price API. :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: :::tip For the canonical, machine-readable index of API versions (recommended for AI agents and automation), see [llms.txt](/llms.txt). ::: ## API reference For detailed information about each endpoint, refer to the Gas Price API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/gas-price/quick-start.md # Gas Price API Tutorial Here we're going to run through a full stack tutorial on the Gas Price API As a background here is an short brief into the three parameters we will be getting as a response `baseFee`, `maxPriorityFeePerGas`, and `maxFeePerGas`. 1. **Base Fee**: - Introduced by EIP-1559, the base fee is an amount of ether that is burned (removed from circulation) for every transaction or smart contract execution. - The base fee is adjusted by the protocol with every block. Its purpose is to ensure that the Ethereum block (space for transactions) is neither too full nor too empty. If a block is more than 50% full, the base fee increases. If it's less than 50% full, the base fee decreases. - The base fee is burned, meaning it's not given to the miners but removed from the total ether supply. 2. **Max Priority Fee Per Gas** (often called Tip): - While the base fee is burned, miners still need an incentive to include your transaction in the block, especially when the network is busy. - This is where the "max priority fee" comes in. It's a tip that goes directly to the miner. If you provide a higher tip, miners are more likely to prioritize your transaction. - Unlike the base fee, the priority fee isn't algorithmically adjusted. It's set by the sender, and it represents how much they're willing to pay to prioritize their transaction. 3. **Max Fee Per Gas**: - This is the total maximum amount (in wei, the smallest unit of ether) a user is willing to pay per unit of gas. - It includes both the base fee and the priority fee (tip). - When a transaction is mined, the difference between the max fee per gas and the actual cost (base fee + tip) is refunded to the user. For more info on these fees and how they're calculated you can read this article [here](https://ethereum.org/en/developers/docs/gas/). To kick off the tutorial we're going to set up the backend with express js for the web server, and axios as an HTTP client to get the information. ## Backend 1. **Setup** ```bash mkdir gas-price-app cd gas-price-app npm init -y npm install express axios ``` 1. **server.js** ```javascript const express = require("express"); const axios = require("axios"); const path = require("path"); const app = express(); const PORT = 3000; // Serve static files from the React frontend app -> coming in the next part app.use(express.static(path.join(__dirname, "client/build"))); // Get the front end file by going to the root domain app.get("/", (req, res) => { res.sendFile(path.join(__dirname + "/client/build/index.html")); }); app.get("/gas-price", async (req, res) => { try { const response = await axios.get(""); res.json(response.data); } catch (error) { res.status(500).json({ message: "Error fetching gas prices" }); } }); app.listen(PORT, () => { console.log(`Server running on :${PORT}`); }); ``` ## Frontend For the frontend, we'll use React and we'll also install the HTTP client axios to get the endpoint we just created: 1. **Setup** ```bash npx create-react-app client cd client npm install axios, react ``` 2. **App.js** Replace the contents of `src/App.js` with: ```jsx import React, { useState, useEffect } from "react"; import axios from "axios"; function App() { const [gasPrice, setGasPrice] = useState({}); useEffect(() => { const fetchGasPrice = async () => { const response = await axios.get("/gas-price"); setGasPrice(response.data); }; fetchGasPrice(); }, []); return (

Ethereum Gas Prices

Base Fee: {gasPrice.baseFee}
{gasPrice.low && ( <>
Low: {gasPrice.low.maxPriorityFeePerGas}
Medium: {gasPrice.medium.maxPriorityFeePerGas}
High: {gasPrice.high.maxPriorityFeePerGas}
Instant: {gasPrice.instant.maxPriorityFeePerGas}
)}
); } export default App; ``` 3. Add proxy to `client/package.json`: ```json "proxy": "" ``` 4. Run both the backend and frontend: - In the `gas-price-app` directory, run: ```bash node server.js ``` - In the `gas-price-app/client` directory, run: ```bash npm run build npm start ``` When you navigate to `http://localhost:3000`, the frontend should now display the gas prices fetched from the 1inch API through our backend server. And that's it! With just a few lines of code, you've created a full stack application that displays Ethereum gas prices from the 1inch API.
## Spot Price API https://business.1inch.com/portal/assets/docs-v2/apis/spot-price/introduction.md The Spot Price API provides real-time token price data across multiple blockchains. This provides your users with accurate pricing information in a given chain's native currency. Whether you're building a new dApp, financial platform, or web3-based tool, this API ensures you have up-to-date and reliable price information when you need it. This API is an essential tool for wallets, exchanges, portfolio trackers, and any application that requires real-time data. ## Supported Chains The Spot Price API supports a wide range of chains: | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the Spot Price API? The Spot Price API offers several key advantages: - **Wide selection of tokens**: supports any token across the most popular blockchain networks. - **Fastest response time**: with a response time under 300 ms, the Spot Price API is one of the fastest solutions on the market. ## Integration possibilities The Spot Price API can be integrated into a wide range of applications, making it a versatile tool for different use cases. It is particularly useful in: - Wallets - Portfolio and token trackers - Exchanges and meta-aggregators :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## API reference For detailed information about each endpoint, refer to the Spot Price API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/spot-price/quick-start.md ## Getting Started the 1inch Spot Price API The 1inch Spot Price API allows you to retrieve on-chain prices of tradable tokens on the Ethereum network. All prices are presented in the native currency WEI. In this tutorial, we will cover how to interact with the API to get token prices using various endpoints. ### Prerequisites Before you begin, make sure you have the following: 1. A code editor to write and run the code (e.g., Visual Studio Code, PyCharm). 2. Python installed on your system. 3. Basic knowledge of Python programming and REST APIs. ### Step 1: Import Required Libraries To start, create a new Python script (e.g., `token_prices.py`) and import the necessary libraries, If you don't have requests make sure you install it by running `pip install requests` ```python import requests ``` ### Step 2: Get Prices for Whitelisted Tokens The first endpoint allows you to get prices for whitelisted tokens. These tokens are pre-defined and can be accessed without specifying any parameters. Let's implement a function to fetch these prices: Replace your API key with the one found [here](/applications) ```python def get_whitelisted_token_prices(): url = "https://api.1inch.com/price/v1.1/1" response = requests.get(url, headers={'Authorization': f'Bearer YOUR_API_KEY'}) if response.status_code == 200: prices = response.json() print("Prices for whitelisted tokens:") for token_address, price in prices.items(): print(f"{token_address}: {price}") else: print("Failed to fetch token prices.") ``` ### Step 3: Get Prices for Requested Tokens The second endpoint allows you to request prices for specific tokens. To do this, you need to pass an array of token addresses in the request body. Let's implement a function to get prices for requested tokens: ```python def get_requested_token_prices(tokens): url = "https://api.1inch.com/price/v1.1/1" payload = { "tokens": tokens } response = requests.post(url, headers={'Authorization': f'Bearer YOUR_API_KEY'}, json=payload) if response.status_code == 200: prices = response.json() print("Prices for requested tokens:") for token_address, price in prices.items(): print(f"{token_address}: {price}") else: print("Failed to fetch token prices.") ``` ### Step 4: Get Prices for Multiple Addresses The third endpoint allows you to get prices for multiple tokens at once. You need to pass multiple token addresses separated by commas in the URL. Let's implement a function to fetch prices for multiple addresses: ```python def get_prices_for_addresses(addresses): url = f"https://api.1inch.com/price/v1.1/1/{','.join(addresses)}" response = requests.get(url, headers={'Authorization': f'Bearer YOUR_API_KEY'}) if response.status_code == 200: prices = response.json() print("Prices for requested tokens:") for token_address, price in prices.items(): print(f"{token_address}: {price}") else: print("Failed to fetch token prices.") ``` ### Step 5: Test the Functions Now that we have implemented the functions, let's test them by calling each one: ```python if __name__ == "__main__": # Test get_whitelisted_token_prices get_whitelisted_token_prices() # Test get_requested_token_prices tokens_to_request = ["0x111111111117dc0aa78b770fa6a738034120c302"] get_requested_token_prices(tokens_to_request) # Test get_prices_for_addresses addresses_to_fetch = ["0x111111111117dc0aa78b770fa6a738034120c302", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"] get_prices_for_addresses(addresses_to_fetch) ``` ### Step 6: Run the Script Save the script and run it using Python. You should see the prices for whitelisted tokens, prices for the requested tokens, and prices for the specified addresses displayed in the console. That's it! You have successfully used the 1inch Spot Price API to fetch on-chain token prices in Python. You can further integrate this functionality into your applications to get real-time token prices and make informed decisions while trading. ## Full script Here you can find the full script with consideration of the default RPS limit ```python import requests import time def get_whitelisted_token_prices(): url = "https://api.1inch.com/price/v1.1/1" response = requests.get(url, headers={'Authorization': f'Bearer YOUR_API_KEY'}) if response.status_code == 200: prices = response.json() print("Prices for whitelisted tokens:") for token_address, price in prices.items(): print(f"{token_address}: {price}") else: print("Failed to fetch token prices.") def get_requested_token_prices(tokens): url = "https://api.1inch.com/price/v1.1/1" payload = { "tokens": tokens } response = requests.post(url, headers={'Authorization': f'Bearer YOUR_API_KEY'}, json=payload) if response.status_code == 200: prices = response.json() print("Prices for requested tokens:") for token_address, price in prices.items(): print(f"{token_address}: {price}") else: print("Failed to fetch token prices.") def get_prices_for_addresses(addresses): url = f"https://api.1inch.com/price/v1.1/1/{','.join(addresses)}" response = requests.get(url, headers={'Authorization': f'Bearer YOUR_API_KEY'}) if response.status_code == 200: prices = response.json() print("Prices for requested tokens:") for token_address, price in prices.items(): print(f"{token_address}: {price}") else: print("Failed to fetch token prices.") if __name__ == "__main__": # Test get_whitelisted_token_prices get_whitelisted_token_prices() # sleep one second because of RPS limit time.sleep(1) # Test get_requested_token_prices tokens_to_request = ["0x111111111117dc0aa78b770fa6a738034120c302"] get_requested_token_prices(tokens_to_request) # sleep one second because of RPS limit time.sleep(1) # Test get_prices_for_addresses addresses_to_fetch = ["0x111111111117dc0aa78b770fa6a738034120c302", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"] get_prices_for_addresses(addresses_to_fetch) ``` https://business.1inch.com/portal/assets/docs-v2/apis/spot-price/oracle-deployment-guide.md This section provides a comprehensive guide on deploying an oracle, including the nuances of script parameters and additional setup steps. Follow these steps to ensure accurate and reliable oracle deployment for price data retrieval. ### Step 1: Surveying DEX Liquidity 1. **Identify DEXes with Sufficient Liquidity:** Begin by surveying the network for Decentralized Exchanges (DEXes) that offer sufficient liquidity. This ensures the oracle can retrieve reliable and accurate price data. ### Step 2: Selection of DEXes 2. **Select Supported DEXes:** Choose DEXes that are supported by `SpotPriceAggregator` or are forks of supported protocols. Supported DEXes can be found in the `contracts/oracles/` directory of the project. ### Step 3: Network Configuration 3. **Configure the Network Settings:** - Skip this step if your network is supported. This can be checked by observing whether the network is mentioned (registered or not) during a test run, visible in the console output. This verification can be done also by reviewing the `registerAll` method in the [`Networks` class](https://github.com/1inch/solidity-utils/blob/master/hardhat-setup/networks.ts#L108-L128). If your network is listed there, it's considered supported, and no further action is required for registration in this step. - Update the [Hardhat settings file](https://github.com/1inch/spot-price-aggregator/blob/master/hardhat.config.js) to configure the network. - Utilize the `Networks` class from [solidity-utils](https://github.com/1inch/solidity-utils/blob/master/hardhat-setup/networks.ts) for network registration. - Example configuration snippet: ```javascript ... const { Networks } = require('@1inch/solidity-utils/hardhat-setup'); const net = new Networks(true, 'mainnet', true); net.register(your_network_name, networkId, process.env.YOURNETWORK_RPC_URL, process.env.YOURNETWORK_PRIVATE_KEY, etherscan_network_name, process.env.YOURNETWORK_ETHERSCAN_KEY); const networks = net.networks; const etherscan = net.etherscan; ... ``` ### Step 4: Environment Variables 4. **Set Environment Variables:** Define necessary environment variables in the `.env` file located at the project root. Include variables such as `YOURNETWORK_RPC_URL`, `YOURNETWORK_PRIVATE_KEY`, and `YOURNETWORK_ETHERSCAN_KEY` with appropriate values: - `YOURNETWORK_RPC_URL`: The RPC URL for accessing your network's node. This URL can support the HTTP header 'auth-key'. To use this header, append the header value to the URL using the `|` symbol. For example: `http://localhost:8545|HeaderValue`. This format allows you to authenticate requests to your node. - `YOURNETWORK_PRIVATE_KEY`: Your account's private key, which should be entered without the `0x` prefix. This key is used for deploying contracts and executing transactions on the network. - `YOURNETWORK_ETHERSCAN_KEY`: The API key for an Etherscan-like blockchain explorer that supports your network. This key is necessary for verifying and publishing your contract's source code. Ensure you register for an API key with a compatible explorer service for your network. ### Step 5: Deploying Oracles 5. **Deploy Oracles:** - Use the deploy script located at `deploy/commands/simple-deploy.js`. You can find a description of the script and how to use it in the [scripts description](https://github.com/1inch/spot-price-aggregator/blob/master/deploy/README.md). - Configure the `PARAMS` object for each protocol you wish to deploy an oracle for. The parameters include: - **contractName**: Name of the contract from the `contracts/oracles/` directory. - **args**: Arguments required by the contract (See contract's constructor). - **deploymentName**: A name for your deployment, which will be used to create a file in the `deployments/` directory. - Ensure the `skip` [flag](https://github.com/1inch/spot-price-aggregator/blob/master/deploy/commands/simple-deploy.js#L25) is set to `false` to proceed with deployment. - Example command for deployment: `yarn && yarn deploy `. ### Step 6: Deploying Wrappers 6. **Deploy Wrappers:** - Follow similar steps as step 5 to deploy necessary wrappers and `MultiWrapper`. You can find different wrappers in the `contracts/wrappers/` directory. After `MultiWrapper` is deployed, it will be possible to edit these lists of wrappers. ### Step 7: Deploying OffchainOracle 7. **Deploy OffchainOracle:** - Follow similar steps as step 5 to deploy the `OffchainOracle`. Make sure to include the deployed oracles (from step 5), `MultiWrapper` with wrappers (from step 6) and specifying the tokens you wish to use as connectors for price discovery. After `OffchainOracle` is deployed, it will be possible to edit these lists of oracles and connectors. ## Token API https://business.1inch.com/portal/assets/docs-v2/apis/tokens/introduction.md The Token API retrieves comprehensive token information and allows users to search for token data using a token's name, address, or symbol. This feature ensures that your application or platform can access precise token details across various blockchain networks. Whether you're developing a new dApp, a data aggregation tool, or a financial platform, the Token API provides up-to-date and essential token information whenever required. This API is indispensable for wallets, explorers, portfolio trackers, and any application that needs reliable token data. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the Token API? The Token API offers several key advantages: - **Extensive token search capabilities**: supports searches by token name, address, or symbol, covering a broad range of tokens across popular blockchain networks. - **Reliable data accuracy**: ensures accurate and up-to-date token information to support a seamless user experience. - **High availability**: designed for robustness, the Token API performs efficiently, even under heavy query loads. ## Integration possibilities The Token API can be integrated into a variety of applications, making it a flexible solution for diverse use cases. It is especially beneficial for: - Price trackers - Block explorers - Wallets - Portfolio and token trackers - Exchanges and meta-aggregators :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## API reference For detailed information about each endpoint, refer to the Token API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/tokens/quick-start.md In this tutorial, we will walk you through the process of using the 1inch Token API with Python and the `requests` library. We'll cover how to search for tokens, get detailed information about individual tokens, and obtain a list of supported tokens from the 1inch API. Now, let's get started! ## Step 1: Prerequisites ### Python Make sure you have Python installed on your system. If you don't, follow the [official instructions](https://www.python.org/). ### Requests library This script uses the `requests` library to make HTTP requests to the 1inch Token API. Install it by running: ```bash pip install requests ``` ### Set up environment variables To securely manage your API key, store it as an environment variable. For macOS: 1. Open the Terminal. 1. Add `API_KEY` variable to your shell configuration file. Replace `your_api_key` with your DevPortal API key: ```bash export API_KEY=your_api_key ``` 1. Save and reload your configuration file: ```bash source ~/.zshrc # For zsh (default for macOS) ``` ### Prepare for rate limits The script includes mechanisms to handle API rate limits. It introduces small delays between API calls using the time library. You don't need to install `time`, as it's part of Python's standard library. The `time.sleep(1)` function pauses the script for one second between calls, ensuring compliance with API restrictions. ### Organize imports Now, the opening part of your script should look something like this: ```python import requests # For making API requests import time # For introducing delays between requests (to respect API rate limits) import os # For accessing environment variables ``` ## Step 2: Define the API base URL and headers Next, we'll define the base URL and headers for the 1inch Token API. We'll use this URL to construct our API requests. Additionally, we make sure `API_KEY` is retrieved from the environment variable. ```python API_KEY = os.getenv("API_KEY") BASE_URL = "https://api.1inch.com/token" HEADERS = { "Authorization": f"Bearer {API_KEY}", "accept": "application/json" } ``` ## Step 3: Search for tokens To search for tokens, we'll use the `/v1.4/{chain_id}/search` endpoint. We'll provide a query in the name, symbol, or description of the token to search for matches. ```python def search_tokens(query, chain_id, limit=10, ignore_listed="false"): endpoint = f"{BASE_URL}/v1.4/{chain_id}/search" params = { "query": query, "limit": limit, "ignore_listed": ignore_listed } response = requests.get(endpoint, headers=HEADERS, params=params) if response.status_code == 200: return response.json() else: print(f"Failed to search tokens. Status code: {response.status_code}") return None ``` ## Step 4: Get detailed information about specific tokens To get detailed information about specific tokens, we'll use the `/v1.4/{chain_id}/custom/{addresses}` endpoint. We'll provide a list of token addresses for which we want to obtain information. ```python def get_tokens_info(chain_id, addresses): endpoint = f"{BASE_URL}/v1.4/{chain_id}/custom/{','.join(addresses)}" response = requests.get(endpoint, headers=HEADERS ) if response.status_code == 200: return response.json() else: print(f"Failed to get tokens info. Status code: {response.status_code}") return None ``` ## Step 5: Get all tokens info To get information about all tokens supported by 1inch on a specific network, we'll use the `/v1.4/{chain_id}` endpoint. ```python def get_all_tokens_info(chain_id, provider="1inch"): endpoint = f"{BASE_URL}/v1.4/{chain_id}" params = { "provider": provider, } response = requests.get(endpoint, headers=HEADERS, params=params) if response.status_code == 200: return response.json() else: print(f"Failed to get all tokens info. Status code: {response.status_code}") return None ``` ## Step 6: Get 1inch token list To get the list of 1inch tokens, we'll use the `/v1.4/{chain_id}/token-list` endpoint. ```python def get_1inch_token_list(chain_id, provider="1inch"): endpoint = f"{BASE_URL}/v1.4/{chain_id}/token-list" params = { "provider": provider, } response = requests.get(endpoint, headers=HEADERS, params=params) if response.status_code == 200: return response.json() else: print(f"Failed to get 1inch token list. Status code: {response.status_code}") return None ``` ## Step 7: Putting it all together Now, let's put it all together and use the functions to interact with the 1inch Token API. ```python if __name__ == "__main__": # Step 3: Search for tokens search_query = "1inch" chain_id = 1 # Replace with the chain ID you want to search on search_results = search_tokens(search_query, chain_id) print("Search Results:") print(search_results) # sleep one second because of RPS limit time.sleep(1) # Step 4: Get detailed information about specific tokens token_addresses = ["0x111111111117dc0aa78b770fa6a738034120c302"] # Replace with token addresses you want to query tokens_info = get_tokens_info(chain_id, token_addresses) print("Tokens Info:") print(tokens_info) # sleep one second because of RPS limit time.sleep(1) # Step 5: Get information about all tokens on a token list all_tokens_info = get_all_tokens_info(chain_id) print("All Tokens Info:") print(all_tokens_info) # sleep one second because of RPS limit time.sleep(1) # Step 6: Get 1inch token list token_list = get_1inch_token_list(chain_id) print("1inch Token List:") print(token_list) ``` That's it! You've successfully used the 1inch Token API with Python and the `requests` library to search for tokens, get detailed token information, and obtain a list of supported tokens from 1inch. Happy coding! ## Full script Below you can find the full script with consideration of the default RPS limit: ```python import requests import time import os API_KEY = os.getenv("API_KEY") BASE_URL = "https://api.1inch.com/token" HEADERS = { "Authorization": f"Bearer {API_KEY}", "accept": "application/json" } # for a list of providers check https://tokenlists.org/ def search_tokens(query, chain_id, limit=10, ignore_listed="false"): endpoint = f"{BASE_URL}/v1.4/{chain_id}/search" params = { "query": query, "limit": limit, "ignore_listed": ignore_listed } response = requests.get(endpoint, headers=HEADERS, params=params) if response.status_code == 200: return response.json() else: print(f"Failed to search tokens. Status code: {response.status_code}") return None def get_tokens_info(chain_id, addresses): endpoint = f"{BASE_URL}/v1.4/{chain_id}/custom/{','.join(addresses)}" response = requests.get(endpoint, headers=HEADERS ) if response.status_code == 200: return response.json() else: print(f"Failed to get tokens info. Status code: {response.status_code}") return None def get_all_tokens_info(chain_id, provider="1inch"): endpoint = f"{BASE_URL}/v1.4/{chain_id}" params = { "provider": provider, } response = requests.get(endpoint, headers=HEADERS, params=params) if response.status_code == 200: return response.json() else: print(f"Failed to get all tokens info. Status code: {response.status_code}") return None def get_1inch_token_list(chain_id, provider="1inch"): endpoint = f"{BASE_URL}/v1.4/{chain_id}/token-list" params = { "provider": provider, } response = requests.get(endpoint, headers=HEADERS, params=params) if response.status_code == 200: return response.json() else: print(f"Failed to get 1inch token list. Status code: {response.status_code}") return None if __name__ == "__main__": # Step 3: Search for tokens search_query = "1inch" chain_id = 1 # Replace with the chain ID you want to search on search_results = search_tokens(search_query, chain_id) print("Search Results:") print(search_results) # sleep one second because of RPS limit time.sleep(1) # Step 4: Get detailed information about specific tokens token_addresses = ["0x111111111117dc0aa78b770fa6a738034120c302"] # Replace with token addresses you want to query tokens_info = get_tokens_info(chain_id, token_addresses) print("Tokens Info:") print(tokens_info) # sleep one second because of RPS limit time.sleep(1) # Step 5: Get information about all tokens on a token list all_tokens_info = get_all_tokens_info(chain_id) print("All Tokens Info:") print(all_tokens_info) # sleep one second because of RPS limit time.sleep(1) # Step 6: Get 1inch token list token_list = get_1inch_token_list(chain_id) print("1inch Token List:") print(token_list) ``` ## NFT API https://business.1inch.com/portal/assets/docs-v2/apis/nft/introduction.md Get expanded data on users' NFTs. The NFT API is designed to meet the needs of NFT platform developers and provides direct streamlined access to on-chain vital NFT data. With a simple GET request, retrieve comprehensive information about any NFT--whether it's pixel art, a meme, or a unique collectible. Using just an NFT owner's address, developers can access detailed attributes of their assets, including image URLs, descriptions, associated contract details, and links to platforms like OpenSea. Queries can be customized with parameters like 'limit' and 'offset' to fit a variety of use cases, from lightweight data visualization to in-depth analytics. As NFTs continue to gain prominence as digital art, collectibles, and even financial assets, having an efficient way to interact with and retrieve data about them is crucial. Whether you're building an NFT marketplace, a personal collection tracker, or a digital art gallery, our NFT API is the ideal foundation to start. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Base | 8453 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the NFT API? The NFT API offers several key advantages: - **Comprehensive NFT data**: retrieve a wide array of NFT attributes, including image URLs, descriptions, metadata, and contract details, all from a single API. - **Efficient querying**: customize requests with parameters like `limit` and `offset` to ensure seamless data retrieval, whether for simple lists or complex analyses. - **Cross-platform compatibility**: direct links to platforms like OpenSea make it easy to integrate NFT data across different marketplaces and applications. - **Optimized for large datasets**: designed to handle significant query volumes, ensuring stable performance even for high-traffic applications. ## Integration possibilities The NFT API can be integrated into various applications, making it highly versatile for different NFT-centric use cases. It is especially valuable for: - NFT marketplaces - Personal NFT collection trackers - Digital art galleries and virtual galleries - Wallets with NFT support - DeFi platforms leveraging NFTs as collateral - NFT data aggregators and analytics platforms :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## API reference For detailed information about each endpoint, refer to the NFT API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/nft/quick-start.md ## Getting Started with the NFT API with React and Node.js The 'List NFTs' API demo will walk you through on how users can seamlessly retrieve and display a curated selection of non-fungible tokens (NFTs) from a specified collection or platform. ### Prerequisites: 1. Node.js and npm installed. 2. Basic knowledge of JavaScript, React, and Express.js. ### Steps: ### 1. Setting Up Node Backend 1.1. Create a new directory for the project: ```bash mkdir nft-collection && cd nft-collection ``` 1.2. Initialize a new Node.js project: ```bash npm init -y ``` 1.3. Install Express and Axios: ```bash npm install express axios ``` 1.4. Create a new file `api.js` and set up a basic Express server: ```javascript const express = require("express"); const axios = require("axios"); const cors = require("cors"); const path = require("path"); const app = express(); const PORT = 5000; const BASE_URL = "https://api.1inch.com/nft/v2/byaddress"; app.use(cors()); // To handle CORS issues when making requests to the front end // Serve static files from the React app app.use(express.static(path.join(__dirname, "nft-collection/build"))); // We will route all other requests to the nft-collection build app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "nft-collection/build", "index.html")); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ``` 1.5. Add an endpoint to fetch NFTs (replace `API_KEY`): ```javascript const BASE_URL = "https://api.1inch.com/nft/v2/byaddress"; app.get("/fetchNfts", async (req, res) => { const address = req.query.address || "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; const limit = req.query.limit || 50; const offset = req.query.offset || 0; const chainIds = req.query.chainIds || 1; try { const constructedUrl = `${BASE_URL}?address=${address}&chainIds=${chainIds}&limit=${limit}&offset=${offset}`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); // Send the data from the API back to the client res.json(response.data); } catch (error) { console.error("Axios Error: ", error.response); res.status(500).json({ error: "Failed to fetch NFTs" }); } }); ``` ### 2. Setting Up React Frontend 2.1. Create a new React app: ```bash npx create-react-app client ``` 2.2. Navigate to the React app directory: ```bash cd client ``` 2.3. Install Axios: ```bash npm install axios ``` 2.4. Create a component `NFTList.js` inside the `src` directory: ```jsx import React, { useState, useEffect } from "react"; import { fetchNFTs } from "./api"; const NFTList = ({ address }) => { const [nfts, setNfts] = useState([]); useEffect(() => { const fetchData = async () => { try { const response = await fetchNFTs(address); setNfts(response.data.assets); } catch (error) { console.error("Error fetching NFTs:", error); } }; fetchData(); }, [address]); return (
{nfts.map((nft) => (
{nft.name}

{nft.name}

{nft.description}

))}
); }; export default NFTList; ``` 2.5. Import and use `NFTList` in `src/App.js`: ```jsx import React from "react"; import "./App.css"; import NFTList from "./NFTList"; function App() { return (

My NFT Collection

); } export default App; ``` ### 3. Running the Project 3.1. Start the Express server: ```bash node api.js ``` 3.2. In a new terminal, navigate to the `client` directory and start the React app: ```bash cd client npm start ``` Now, you can view your NFT collection visualization at `http://localhost:3000`. That's it! This is a basic setup and you can expand upon this by adding more features, error handling, and styling to get to production.
## Transaction Gateway API https://business.1inch.com/portal/assets/docs-v2/apis/transaction/introduction.md The Transaction Gateway API provides reliable on-chain transaction broadcasting, supporting both public and private modes. This enables developers to choose the most appropriate broadcasting method for their use case, whether for general public transactions or for sensitive, protected transactions in a private mempool. Ideal for applications focused on security and efficiency, the Transaction Gateway API is a powerful tool for wallets, exchanges, and virtually any on-chain application. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the Transaction Gateway API? The Transaction Gateway API offers several key advantages: - **Private broadcasting**: provides a secure way to broadcast transactions to a private mempool, offering protection against front-running and ensuring increased transaction privacy. - **Flexible broadcasting modes**: supports both public and private transaction broadcasting, allowing users to choose the method that best fits their needs. - **Reliable performance**: ensures robust transaction delivery, even under high-volume scenarios, making it suitable for fast-paced trading environments. ## Integration possibilities The Transaction Gateway API can be integrated into a wide range of applications, including: - Wallets - Exchanges and meta-aggregators - Traders and arbitrage bots - DeFi platforms and lending protocols - NFT marketplaces - Payment processors and merchant tools :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## API reference For detailed information about each endpoint, refer to the Transaction Gateway API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/transaction/quick-start.md ## How to Use the 1inch Transaction Gateway API with Python and Request In this tutorial, we will guide you through the process of using the 1inch Transaction Gateway API with Python and the `requests` library. The Transaction Gateway API allows you to broadcast public and private transactions on the Ethereum network using raw transaction data. Before we begin, ensure you have Python installed on your system. If you don't have the `requests` library installed, you can install it using `pip` by running the following command: ```bash pip install requests ``` Now, let's get started with step-by-step instructions! ### Step 1: Import the `requests` Library First, we need to import the `requests` library, which allows us to make HTTP requests to the 1inch Transaction Gateway API. ```python import requests ``` ### Step 2: Define the API Base URL Next, we'll define the base URL for the 1inch Transaction Gateway API. We'll use this URL to construct our API requests. ```python base_url = "https://api.1inch.com/tx-gateway/v1.1/1" headers = { "Authorization": "Bearer [YOUR_API_KEY]", "accept": "application/json" } ``` ### Step 3: Broadcast Public Transaction To broadcast a public transaction, we'll use the `/broadcast` endpoint. We'll provide the raw transaction data as the request body. ```python def broadcast_public_transaction(raw_transaction): endpoint = "/broadcast" data = { "rawTransaction": raw_transaction } response = requests.post(base_url + endpoint, headers=headers, json=data) if response.status_code == 200: return response.json()["transactionHash"] else: print(f"Failed to broadcast public transaction. Status code: {response.status_code}") return None ``` ### Step 4: Broadcast Private Transaction To broadcast a private transaction, we'll use the `/flashbots` endpoint. Again, we'll provide the raw transaction data as the request body. ```python def broadcast_private_transaction(raw_transaction): endpoint = "/flashbots" data = { "rawTransaction": raw_transaction } response = requests.post(base_url + endpoint, headers=headers, json=data) if response.status_code == 200: return response.json()["transactionHash"] else: print(f"Failed to broadcast private transaction. Status code: {response.status_code}") return None ``` ### Step 5: Broadcast a Raw Transaction via RPC If you prefer to broadcast a raw transaction via RPC, we'll use the `/rpc` endpoint. Similar to the previous steps, we'll provide the JSON-RPC request as the request body. ```python def broadcast_raw_transaction_via_rpc(json_rpc_request): endpoint = "/rpc" data = json_rpc_request response = requests.post(base_url + endpoint, headers=headers, json=data) if response.status_code == 200: return response.json()["result"] else: print(f"Failed to broadcast transaction via RPC. Status code: {response.status_code}") return None ``` ### Step 6: Putting It All Together Now, let's put everything together and use the functions to broadcast transactions on the Ethereum network. ```python if __name__ == "__main__": # Replace with the raw transaction data you want to broadcast raw_transaction_data = "0xf86..." # Step 3: Broadcast public transaction transaction_hash_public = broadcast_public_transaction(raw_transaction_data) print("Transaction Hash (Public):", transaction_hash_public) # Step 4: Broadcast private transaction transaction_hash_private = broadcast_private_transaction(raw_transaction_data) print("Transaction Hash (Private):", transaction_hash_private) # Step 5: Broadcast transaction via RPC # Replace with the JSON-RPC request you want to use json_rpc_request_data = { "jsonrpc": "2.0", "id": "string", "method": "eth_sendRawTransaction", "params": [raw_transaction_data] } transaction_hash_rpc = broadcast_raw_transaction_via_rpc(json_rpc_request_data) print("Transaction Hash (RPC):", transaction_hash_rpc) ``` That's it! You have successfully used the 1inch Transaction Gateway API with Python and the `requests` library to broadcast public and private transactions, as well as transactions via RPC on the Ethereum network. Happy coding! ## Full Script Here you can find the full script with consideration of the default RPS limit ```python import requests import time base_url = "https://api.1inch.com/tx-gateway/v1.1/1" headers = { "Authorization": "Bearer [YOUR_API_KEY]", "accept": "application/json" } def broadcast_public_transaction(raw_transaction): endpoint = "/broadcast" data = { "rawTransaction": raw_transaction } response = requests.post(base_url + endpoint, headers=headers, json=data) if response.status_code == 200: return response.json()["transactionHash"] else: print(f"Failed to broadcast public transaction. Status code: {response.status_code}") return None def broadcast_private_transaction(raw_transaction): endpoint = "/flashbots" data = { "rawTransaction": raw_transaction } response = requests.post(base_url + endpoint, headers=headers, json=data) if response.status_code == 200: return response.json()["transactionHash"] else: print(f"Failed to broadcast private transaction. Status code: {response.status_code}") return None def broadcast_raw_transaction_via_rpc(json_rpc_request): endpoint = "/rpc" data = json_rpc_request response = requests.post(base_url + endpoint, headers=headers, json=data) if response.status_code == 200: print(response.json()) return response.json()["result"] else: print(f"Failed to broadcast transaction via RPC. Status code: {response.status_code}") return None if __name__ == "__main__": # Replace with the raw transaction data you want to broadcast raw_transaction_data = "0xf86..." # Step 3: Broadcast public transaction transaction_hash_public = broadcast_public_transaction(raw_transaction_data) print("Transaction Hash (Public):", transaction_hash_public) # sleep one second because of RPS limit time.sleep(1) # Step 4: Broadcast private transaction transaction_hash_private = broadcast_private_transaction(raw_transaction_data) print("Transaction Hash (Private):", transaction_hash_private) # sleep one second because of RPS limit time.sleep(1) # Step 5: Broadcast transaction via RPC # Replace with the JSON-RPC request you want to use json_rpc_request_data = { "jsonrpc": "2.0", "id": "string", "method": "eth_sendRawTransaction", "params": [raw_transaction_data] } transaction_hash_rpc = broadcast_raw_transaction_via_rpc(json_rpc_request_data) print("Transaction Hash (RPC):", transaction_hash_rpc) ``` ## Charts API https://business.1inch.com/portal/assets/docs-v2/apis/charts/introduction.md The 1inch Charts API is designed to provide easy retrieval and display of chart data for onchain assets, including ERC20 tokens, NFTs, and more. It fetches and visualizes historical market data, giving you the tools needed to make data-driven decisions. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Base | 8453 | | Binance | 56 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | ## Key features - **Retrieval of chart data**: enables fetching of historical and real-time chart data. - **Versatile data types**: supports data for ERC20 token pairs, NFTs, and more. - **Easy integration**: designed to be easily integrated into backend systems (Node.js) and frontend applications (React). - **Support for multiple networks**: currently available on Ethereum, Binance Smart Chain, and Polygon. ## Use cases in dApps ### NFT marketplaces - **Price history charts:** display historical price trends for NFTs - **Volume charts:** show trading volume over time, gain insight into the sentiment and liquidity of specific NFTs. ### Decentralized exchanges (DEXes) - **Token price charts:** provide users with historical and real-time price charts for any supported ERC20 token. - **Trading volume charts:** visualize trading volumes to help users understand market activity. ### Portfolio management tools - **Asset performance tracking:** allow users to track the historical performance of their assets--ideal for wallet applications as well! - **Portfolio analysis:** provide insights into the value changes and trends in a user's portfolio over time. ### Yield farming platforms - **Yield tracking:** show historical yields of multiple farming positions to help users make informed decisions. - **APY trends:** visualize the APY trends of an individual farm to help users assess its performance. ### DeFi analytics - **Market analysis:** provide comprehensive market analysis tools for users to study trends and make data-driven decisions. - **Liquidity pool charts:** show data for various liquidity pools, including volume, fees, and pool composition. :::info If you are an enterprise with significant API request volumes, [**complete this application**](/get-enterprise) to get in touch with us to explore Enterprise options tailored to your needs. ::: ## API reference For detailed information about each endpoint, refer to the Charts API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/charts/quick-start.md This guide will help you set up a project to retrieve and display chart data using the 1inch Charts API. You'll create a Node.js backend to handle API requests and serve data, and a React frontend to display this data in a user-friendly way. Once finished, you'll have built a simple yet powerful NFT collection viewer that you can expand upon and customize! ## Prerequisites - You'll need Node.js and npm installed. - Basic knowledge of JavaScript, React, and Express.js. ## Step 1: Set Up the Node Backend This backend will handle API requests, fetch data from the Charts API, and serve your frontend React application. ### 1.1. Create a new project directory ```bash mkdir nft-collection && cd nft-collection ``` ### 1.2. Initialize a new Node.js project This will create the `package.json' file. ```bash npm init -y ``` ### 1.3. Install necessary packages - **Express:** A web framework for Node.js, used to build the backend server. - **Axios:** A HTTP client, used to make API requests. - **CORS:** Middleware to handle Cross-Origin Resource Sharing, essential when the frontend and backend are on different ports. - **Path:** A Node.js module for working with file and directory paths. ```bash npm install express axios cors path ``` ### 1.4. Set up a basic Express server Create a file named `api.js` and add the following code. This will initialize an Express server to handle API requests and serve the React app (see Step 2 below). ```javascript const express = require("express"); const axios = require("axios"); const cors = require("cors"); const path = require("path"); const app = express(); const PORT = 3000; const BASE_URL = "https://api.1inch.com/charts/v1/..."; app.use(cors()); // Handle CORS issues // Serves static files from the React app app.use(express.static(path.join(__dirname, "client/build"))); // Endpoint to fetch chart data app.get("/charts", async (req, res) => { try { const response = await axios.get(BASE_URL, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); res.send(response.data); } catch (error) { console.error("Error fetching charts data:", error); res.status(500).json({ error: "Failed to fetch charts data" }); } }); // Serve the React app for other routes app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "client/build", "index.html")); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ``` ## Step 2: Setting Up React Frontend The frontend will display the data fetched from the backend API. ### 2.1. Create a new React app This creates a new React application for your frontend code. ```bash npx create-react-app client ``` ### 2.2. Navigate to the React app directory ```bash cd client ``` ### 2.3. Install Axios This will be used to make HTTP requests from the React app to the backend. ```bash npm install axios ``` ### 2.4. Create an NFT list component This component will handle fetching and displaying NFT data. Create a file with this directory and name: `src/NFTList.js`. Then add the following code: ```javascript import React, { useState, useEffect } from "react"; import axios from "axios"; const NFTList = ({ address }) => { // Initialize state to store NFT data const [nfts, setNfts] = useState([]); useEffect(() => { // Fetch NFT data from the server const fetchData = async () => { try { // Fetch NFTs for the given address const response = await axios.get(`/fetchNfts?address=${address}`); // Update the state with the fetched NFT data setNfts(response.data.assets); } catch (error) { console.error("Error fetching NFTs:", error); } }; fetchData(); }, [address]); // Refetch if the address changes return (
{/* Render the list of NFTs */} {nfts.map((nft) => (
{nft.name}

{nft.name}

{nft.description}

))}
); }; export default NFTList; ``` ### 2.5. Update the main App component Integrate the NFT list component into the main application. Add this to `src/App.js`: ```javascript import React from "react"; import "./App.css"; import NFTList from "./NFTList"; function App() { return (

My NFT Collection

); } export default App; ``` ## Step 3: Running the Project ### 3.1. Start the Express server ```bash node api.js ``` ### 3.2. Start the React app Navigate to the client directory and run the React development server: ```bash cd client npm start ``` You should now have a functional application for viewing NFT collections! While primitive, this framework can easily be built upon with features such as web3 wallet connections, auction mechanics, and more.
## Domains API https://business.1inch.com/portal/assets/docs-v2/apis/domains/introduction.md The Domains API enables seamless interaction with blockchain-based domain services, providing tools to resolve and retrieve domain information for addresses, as well as access provider data. Whether you're building a wallet, an identity service, or any web3 application, the Domains API offers essential functionality to enhance user experiences with blockchain domains. ## Supported Chains | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Polygon | 137 | ## Use cases The Domains API can be applied for the following use cases: - **Wallets and identity applications**: enable users to interact with human-readable domain names instead of long blockchain addresses. - **Batch domain resolution**: efficiently resolve multiple addresses to domains for applications handling large datasets. - **Provider information**: integrate provider avatars and branding for enhanced visual experiences. ## Quickstart To start using Domains API swiftly, refer to the [Quickstart guide](./quick-start). ## API reference For detailed information about each endpoint, refer to the Domains API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/domains/quick-start.md --- sidebar_position: 2 --- # Quickstart guide ## Introduction This guide will walk you through retrieving data from providers such as ENS, LENS, and UD using the Domains API. ## Prerequisites - Node.js and npm installed on your machine - Basic knowledge of JavaScript, React, and Express.js ## Step-by-step guide ### Step 1: Initialization 1. Create a new directory for your project: ```bash mkdir domains && cd domains ``` 2. Initialize a new Node.js project: ```bash npm init -y ``` 3. Install Express, CORS, and Axios: ```bash npm install express cors axios ``` 4. Install dotenv for securely storing environment variables: ```bash npm install dotenv ``` Then create a new file called `.env` and add your DevPortal API key to it: ```bash API_KEY=YOUR_1INCH_API_KEY ``` ### Step 2: Import required libraries 1. Create a new file named `api.js` in your project directory. 1. Add the following code to import necessary packages and initialize your Express application: ```javascript const express = require("express"); const axios = require("axios"); const dotenv = require("dotenv"); const cors = require("cors"); const path = require("path"); // Load environment variables dotenv.config({ path: path.resolve(__dirname, ".env") }); const app = express(); app.use(cors()); ``` ### Step 3: Define API endpoints Add the following code to define your API endpoints: - Retrieve domain information ```javascript const BASE_URL = "https://api.1inch.com/domains/v2.0"; app.get("/api/:domain/info", async (req, res) => { const domain = req.params.domain; try { const constructedUrl = `${BASE_URL}/${domain}/lookup`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); res.json(response.data); } catch (error) { res.status(500).json({ error: "API error" }); } }); ``` - Reverse lookup for a domain: ```javascript app.get("/api/:domain/reverseinfo", async (req, res) => { const domain = req.params.domain; try { const constructedUrl = `${BASE_URL}/${domain}/reverse-lookup`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); res.json(response.data); } catch (error) { res.status(500).json({ error: "API error" }); } }); ``` - Retrieve provider data with avatars: ```javascript app.get("/api/:domain/get-providers-data-with-avatar", async (req, res) => { const domain = req.params.domain; try { const constructedUrl = `${BASE_URL}/get-providers-data-with-avatar`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); res.json(response.data); } catch (error) { res.status(500).json({ error: "API error" }); } }); ``` ### Step 4: Start the server 1. Add the following code to start your Express server and save the file: ```javascript const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); ``` 1. Run the server by using in your Terminal: ```bash node api.js ``` ## Response models The API returns structured JSON responses, which you can use to integrate with your application. - Response model: Provider data with avatar ```json { "result": { "protocol": "string", "domain": "string", "address": "string", "avatar": {} } } ``` - Response model: Domain or address information ```json { "result": { "protocol": "string", "address": "string", "checkUrl": "string" } } ``` ## Token Details API https://business.1inch.com/portal/assets/docs-v2/apis/token-details/introduction.md The Token Details API is a versatile set of endpoints designed to provide developers with in-depth insights about tokens and native tokens. This API empowers developers to access critical token data, historical price trends, and market performance metrics, streamlining the integration of token-related functionality into applications. Whether you're building a DeFi application, analytics dashboard, or wallet service, the Token Details API provides the tools you need to deliver a rich, data-driven user experience. ## Supported Chains The Token Details API provides support for the following chains: | Supported Chains | Chain ID | | :--------------- | :------- | | Ethereum | 1 | | Solana | 501 | | Base | 8453 | | Binance | 56 | | zkSync | 324 | | Gnosis | 100 | | Optimism | 10 | | Polygon | 137 | | Linea | 59144 | | Sonic | 146 | | Unichain | 130 | | Arbitrum | 42161 | | Avalanche | 43114 | ## Why use the Token Details API? Token data and price history are essential for applications in the DeFi ecosystem to deliver accurate and insightful functionality. The Token Details API simplifies this by providing: - Comprehensive token metadata and performance metrics. - Historical price data to support analytics and trend visualization. - Reduced development effort by offering ready-to-use endpoints for token-related data. ## Use cases The Token Details API can be leveraged for a variety of use cases, including: - **DeFi dashboards**: display token details and price trends on analytics platforms. - **Wallet applications**: show detailed token information, including links to explorers and social media. - **Market analytics**: visualize historical price trends and analyze market performance. - **Token research**: provide links to white papers, research materials, and source code for deeper insights. - **Portfolio tracking**: enable users to monitor token performance and price changes. - **Custom charts**: create visualizations of historical token price movements. - **Token listings**: dynamically display token details, including descriptions and market data. ## Quickstart To start using Token Details API swiftly, refer to the [Quickstart guide](./quick-start). ## API reference For detailed information about each endpoint, refer to the Token Details API [OpenAPI section](./methods). https://business.1inch.com/portal/assets/docs-v2/apis/token-details/quick-start.md The Token Details API demo will walk you through how users can seamlessly retrieve and display token price changes from the past week. ## Prerequisites - Node.js and npm installed - Basic knowledge of JavaScript, React, and Express.js ### Set up environment variables To securely manage your API key, store it as an environment variable. For macOS: 1. Open the Terminal. 1. Add `API_KEY` variable to your shell configuration file. Replace `your_api_key` with your DevPortal API key: ```bash export API_KEY=your_api_key ``` 1. Save and reload your configuration file: ```bash source ~/.zshrc # For zsh (default for macOS) ``` ## Step 1: Initialization 1. Create a new directory for the project: ```bash mkdir token-details && cd token-details ``` 1. Initialize a new Node.js project: ```bash npm init -y ``` 1. Install Express, CORS, and Axios: ```bash npm install express cors axios ``` 1. Create a new file `api.js` and set up a basic Express server by pasting into it the following: ```javascript const express = require("express"); const axios = require("axios"); const cors = require("cors"); const path = require("path"); const app = express(); const PORT = 5001; app.use(cors()); // To handle CORS issues when making requests to the front end // Serve static files from the React app app.use(express.static(path.join(__dirname, "client/build"))); // Add endpoint handler here // We will route all other requests to the client build app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "client/build", "index.html")); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ``` 1. Add an endpoint to fetch token prices: ```javascript const BASE_URL = "https://api.1inch.com/token-details/v1.0/charts/interval"; const CHAIN_ID = 1; // Eth app.get("/api/:tokeAddress/prices/:interval", async (req, res) => { const { tokeAddress, interval } = req.params; try { const constructedUrl = `${BASE_URL}/${CHAIN_ID}/${tokeAddress}?interval=${interval}`; const response = await axios.get(constructedUrl, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); // Send the data from the API back to the client res.json(response.data.d); } catch (error) { console.error("Axios Error: ", error.response); res.status(500).json({ error: "Failed to fetch token price by interval" }); } }); ``` ## Step 2: Setting up React frontend 1. Create a new React application: ```bash npx create-react-app client ``` 2. Navigate to the React application directory and install React Charts: ```bash cd client npm i react-charts ``` 3. Create a component `TokenPrice.js` inside the `src` directory with the following content: ```javascript import React, { useState, useEffect } from "react"; import { Chart } from "react-charts"; const TokenPrice = ({ address, interval }) => { const [tokenPrices, setTokenPrices] = useState([]); const [isLoading, setLoading] = useState(false); const primaryAxis = React.useMemo(() => ({ getValue: (datum) => datum.date }), []); const secondaryAxes = React.useMemo(() => [{ getValue: (datum) => datum.price }], []); useEffect(() => { const fetchData = async () => { setLoading(true); const response = await fetch(`http://localhost:5001/api/${address}/prices/${interval}`); if (!response.ok) { console.log("Fetch token prices error", response); return; } const prices = await response.json(); setTokenPrices(prices); setLoading(false); }; if (isLoading) { return; } fetchData(); }, [address, interval]); if (isLoading) { return
Loading...
; } if (tokenPrices.length === 0) { return
No data available
; } return ( ({ date: new Date(d.t * 1000), price: d.v })) } ], primaryAxis, secondaryAxes }} /> ); }; export default TokenPrice; ``` 4. Import and use `TokenPrice` in `src/App.js`: ```javascript import "./App.css"; import TokenPrice from "./TokenPrice"; function App() { return (

Token Price

); } export default App; ``` ## Step 3: Running the project 1. Start the Express server: ```bash node api.js ``` 2. In a new terminal, navigate to the client directory and start the React app: ```bash cd client npm start ``` Now, you can view your 1inch token price over last week at http://localhost:3000. Described above is a basic setup and you can expand upon this by adding more features, error handling, and styling to get to production.
## Web3 RPC API https://business.1inch.com/portal/assets/docs-v2/apis/web3/overview.md The Web3 RPC API provides you with an easy way to maintain a constant, secure connection to the blockchain. These nodes provide reliable, real-time data access and interaction capabilities for executing transactions, monitoring block events, and querying network data efficiently. ## Supported features | Supported Chains | Chain ID | JSON-RPC | Websockets/Subscriptions | gRPC | full-node | archive-node | | :--------------- | :------- | :------: | :----------------------: | :--: | :-------: | :----------: | | Ethereum | 1 | [x] | [x] | [ ] | [x] | [x] | | Solana | 501 | [x] | [x] | [x] | [x] | [x] | | Base | 8453 | [x] | [x] | [ ] | [x] | [x] | | Binance | 56 | [x] | [x] | [ ] | [x] | [x] | | Monad | 143 | [x] | [x] | [ ] | [x] | [x] | | zkSync | 324 | [x] | [x] | [ ] | [x] | [x] | | Gnosis | 100 | [x] | [x] | [ ] | [x] | [x] | | Optimism | 10 | [x] | [x] | [ ] | [x] | [x] | | Polygon | 137 | [x] | [x] | [ ] | [x] | [x] | | Linea | 59144 | [x] | [x] | [ ] | [x] | [x] | | Sonic | 146 | [x] | [x] | [ ] | [x] | [x] | | Unichain | 130 | [x] | [x] | [ ] | [x] | [x] | | Arbitrum | 42161 | [x] | [x] | [ ] | [x] | [x] | | Avalanche | 43114 | [x] | [x] | [ ] | [x] | [x] | | Cronos | 25 | [x] | [x] | [ ] | [x] | [x] | ## Supported API Interaction Methods - **JSON-RPC** -- Standard request-response protocol used for blockchain node interactions. - **WebSockets (Subscriptions)** -- Persistent, event-driven connections for receiving real-time updates. - **gRPC (Solana only)** -- High-performance, streaming-capable remote procedure calls for low-latency and real-time interactions on the Solana blockchain. :::info Solana gRPC Support For real-time Solana blockchain data streaming, check out our [Solana gRPC](./solana/solana-grpc.md) documentation using the Yellowstone protocol. ::: ## Getting Started Select a chain from the navigation to view available JSON-RPC methods for that network. Each chain has its own set of methods that can be called using JSON-RPC requests. ## Authentication For authentication details, see the [Authentication documentation](../authentication.md). ## Base URL The base URL for all Web3 RPC requests is:`https://api.1inch.com/web3/{chainId}` Where `{chainId}` is the chain ID of the network you want to interact with. ## Benefits - **Maximal uptime**: we have developed the most advanced internal systems for node health check/load balancing, which enable us to offer the maximum possible uptime. - **High load resistance**: thanks to our significant expertise, we can support high network load without sacrificing uptime. - **Support for multiple chains**: the Web3 RPC API supports different EVM networks, allowing you to interact with various blockchains through a single provider. - **Seamless integration**: easily integrate with your existing web3 projects using standard Web3 libraries. - **Included in all plans**: the Web3 RPC API, is included in all plans - **Full and archive node support**: choose between low-latency full nodes for real-time execution and archive nodes with complete historical blockchain state for analytics, auditing, and backtesting. :::info Enhanced API services are available as part of our paid plans. They are designed for enterprises with high-demand blockchain interactions or substantial operational scale, ensuring superior performance in terms of connectivity, throughput, and response times. ::: ## Example Here's a simple example using viem to make a JSON-RPC call: ```typescript import { createPublicClient, http } from "viem"; import { mainnet } from "viem/chains"; const client = createPublicClient({ chain: mainnet, transport: http("https://api.1inch.com/web3/1", { fetchOptions: { headers: { Authorization: `Bearer ${process.env.API_KEY}` } } }) }); // Get the current block number const blockNumber = await client.getBlockNumber(); console.log("Current block number:", blockNumber); ``` ## Potential use cases - **Decentralized applications (dApps)**: ensure your dApp has a stable and secure connection to the blockchain for tasks like reading smart contract data, sending transactions, and querying blockchain state. - **Decentralized exchanges (DEXes)**: maintain high uptime and reliable data feeds for trading operations, ensuring users can trade assets seamlessly. - **Trading bots**: achieve fast and reliable access to blockchain data to make timely trading decisions and execute trades. - **Wallets**: provide users with real-time balance updates, transaction statuses, and other important blockchain data. - **Analytics platforms**: collect and analyze blockchain data for insights and trends without worrying about node maintenance. ## API Reference For detailed information about each endpoint, refer to the Web3 RPC API [section](./ethereum/methods). https://business.1inch.com/portal/assets/docs-v2/apis/web3/solana/solana-grpc.md Yellowstone gRPC enables real-time Solana blockchain data streaming through gRPC interfaces. Stream accounts, transactions, blocks, and slots with low latency and efficient bidirectional communication. ## Getting Started ### Endpoint - `api.1inch.com:443` ### Authentication All requests must include an API key in the authorization header: ```bash Authorization: Bearer YOUR_API_KEY ``` Get your API key [here](/applications). ## Protocol Reference The protocol uses Protocol Buffers. View the [geyser.proto definition](https://github.com/rpcpool/yellowstone-grpc/blob/master/yellowstone-grpc-proto/proto/geyser.proto) for complete specifications. **Key Methods:** - `Subscribe` - Bidirectional stream for real-time updates - `GetLatestBlockhash`, `GetBlockHeight`, `GetSlot` - `IsBlockhashValid`, `Ping`, `GetVersion` ### Setup Download [geyser.proto](https://github.com/rpcpool/yellowstone-grpc/blob/master/yellowstone-grpc-proto/proto/geyser.proto) and [solana-storage.proto](https://github.com/rpcpool/yellowstone-grpc/blob/master/yellowstone-grpc-proto/proto/solana-storage.proto) to your project. ## Typescript Usage Examples #### Install dependencies ```bash npm install @grpc/grpc-js @grpc/proto-loader ``` ### Example 1: Simple GetSlot call ```typescript import * as grpc from "@grpc/grpc-js"; import * as protoLoader from "@grpc/proto-loader"; // Load proto file const packageDefinition = protoLoader.loadSync("path/to/geyser.proto", { longs: String // Convert uint64 to strings for easier handling }); const geyserProto = grpc.loadPackageDefinition(packageDefinition).geyser; // Create client with TLS const client = new geyserProto.Geyser("api.1inch.com:443", grpc.credentials.createSsl()); // Set authorization metadata const metadata = new grpc.Metadata(); metadata.add("authorization", "Bearer YOUR_API_KEY"); // Call GetSlot client.getSlot({}, metadata, (err, response) => { if (err) { console.error("Error:", err); return; } console.log("Current slot:", response.slot); }); ``` ### Example 2: Subscribe to account updates ```typescript import * as grpc from "@grpc/grpc-js"; import * as protoLoader from "@grpc/proto-loader"; const packageDefinition = protoLoader.loadSync("path/to/geyser.proto", { longs: String }); const geyserProto = grpc.loadPackageDefinition(packageDefinition).geyser; const client = new geyserProto.Geyser("api.1inch.com:443", grpc.credentials.createSsl()); const metadata = new grpc.Metadata(); metadata.add("authorization", "Bearer YOUR_API_KEY"); // Create bidirectional stream const stream = client.subscribe(metadata); // Send subscription request stream.write({ accounts: { client: { account: ["ACCOUNT_PUBKEY_HERE"], owner: [], filters: [] } } }); // Handle updates stream.on("data", (data) => { if (data.account) { console.log("Account update:", { slot: data.account.slot, lamports: data.account.account.lamports }); } }); stream.on("error", (err) => console.error("Error:", err)); stream.on("end", () => console.log("Stream ended")); ``` ## Go Usage Examples ### Install dependencies ```bash go get google.golang.org/grpc google.golang.org/grpc/credentials # generate bindings protoc --go_out=. --go-grpc_out=. geyser.proto ``` ### Example 1: Simple GetSlot call ```go package main import ( "context" "crypto/tls" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" pb "your/proto/package" // Generated from geyser.proto ) func main() { // Connect with TLS creds := credentials.NewTLS(&tls.Config{ ServerName: "api.1inch.com", }) conn, err := grpc.Dial("api.1inch.com:443", grpc.WithTransportCredentials(creds)) if err != nil { log.Fatal(err) } defer conn.Close() client := pb.NewGeyserClient(conn) // Add authorization ctx := metadata.AppendToOutgoingContext( context.Background(), "authorization", "Bearer YOUR_API_KEY", ) // Call GetSlot resp, err := client.GetSlot(ctx, &pb.GetSlotRequest{}) if err != nil { log.Fatal(err) } log.Printf("Current slot: %d", resp.Slot) } ``` ### Example 2: Subscribe to account updates ```go package main import ( "context" "crypto/tls" "fmt" "io" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" pb "your/proto/package" ) func main() { creds := credentials.NewTLS(&tls.Config{ ServerName: "api.1inch.com", }) conn, err := grpc.Dial("api.1inch.com:443", grpc.WithTransportCredentials(creds)) if err != nil { log.Fatal(err) } defer conn.Close() client := pb.NewGeyserClient(conn) ctx := metadata.AppendToOutgoingContext( context.Background(), "authorization", "Bearer YOUR_API_KEY", ) stream, err := client.Subscribe(ctx) if err != nil { log.Fatal(err) } // Send subscription request err = stream.Send(&pb.SubscribeRequest{ Accounts: map[string]*pb.SubscribeRequestFilterAccounts{ "client": { Account: []string{"ACCOUNT_PUBKEY_HERE"}, Owner: []string{}, Filters: []*pb.SubscribeRequestFilterAccountsFilter{}, }, }, }) if err != nil { log.Fatal(err) } // Receive updates for { update, err := stream.Recv() if err == io.EOF { break } if err != nil { log.Fatal(err) } if account := update.GetAccount(); account != nil { fmt.Printf("Account update: slot=%d, lamports=%d\n", account.Slot, account.Account.Lamports) } } } ``` ## Additional Resources - [Yellowstone gRPC GitHub Repository](https://github.com/rpcpool/yellowstone-grpc) - [Protocol Buffer Definition (geyser.proto)](https://github.com/rpcpool/yellowstone-grpc/blob/master/yellowstone-grpc-proto/proto/geyser.proto) - [Solana Geyser Plugins Documentation](https://docs.solana.com/developing/plugins/geyser-plugins) - [gRPC Documentation](https://grpc.io/docs/) ## Resolvers https://business.1inch.com/portal/assets/docs-v2/resolvers/introduction.md Welcome to the onboarding guide for becoming a Resolver in the 1inch ecosystem. This document outlines the self-service onboarding process and helpful resources for resolving **Intent-based Orders** (Fusion and Cross-chain/Fusion+ Orders) and **Limit Orders** . ## Self-Service Onboarding ### Step 1: Login/Register Visit the [1inch Business Portal login page](https://business.1inch.com/portal/login) and select the preferred registration method. On the first onboarding screen, select your business segment(s) from the available options (multi-select): Resolver and other applicable segments. ### Step 2: Set your entity type and accept the terms Select your entity type and confirm that you've read, understood, and accepted the [Terms of Use of the Business Portal](portal/assets/legal-docs/terms_of_service_public_api_20260218.pdf) and the [1inch Network Terms of Use for Resolvers](/portal/assets/legal-docs/resolvers/terms-of_use_resolvers_20251124.pdf) ### Step 3: Provide Resolver Information 1. Provide the following resolver details: - **Resolver name** (required) - **Logo** (optional) -- URL to your logo in SVG format. The URL must point to a valid image file. - **Contract Address** for each protocol where resolving is intended | Protocol | Configuration | | :------------------- | :-------------------------- | | **Limit Order (LO)** | Chains + contract addresses | | **Intent** | Chains + contract addresses | | **Cross Chain** | Chains + contract addresses | Contract address validation: - Every contract address you add is automatically scanned across all chains before you proceed. - The UI indicates if a contract address is blacklisted (flagged as positive). ### Step 4: Perform KYC/KYB Complete the verification process based on your selection in Step 2. If you face any difficulties with KYB, please reach out to compliance@1inch.com. ### Step 5: Complete Compliance Survey Complete the compliance survey for resolvers. This step is mandatory and no whitelisting will be enabled until the verification and survey have been completed. ### Step 6: NFT Minting and Confirmation Once **both** of the following are complete: - KYC/KYB approval - Compliance survey completion Your Access NFT(s) will be minted, granting access to Order fulfillment. **Email notifications:** - A single confirmation email is sent after all NFTs are minted. - If any contract address becomes blacklisted during this step, you will receive a notification email (content to be provided). --- # Protocol-Specific Onboarding From here, the next steps are determined by the protocol you choose to integrate with. Please follow the corresponding subsection. ## Intent-Based Orders ### Request Off-Chain Auction Access [optional for Fusion Orders] Resolvers may apply for off-chain auction access to Fusion Orders before the Dutch Auction phase begins. To request access: 1. Provide your API endpoint developed in accordance with the Exclusive Resolver API script example and related technical documentation. 2. Submit the request via the dedicated support communication channel created during onboarding. 3. Upon review and approval by the technical team, your Resolver will be integrated into the Exclusive Resolver API and granted off-chain auction access to Fusion Orders before the Dutch Auction phase begins. Participation in the Exclusive Resolver API requires ongoing compliance with the Service Level Agreement (SLA) as detailed in Annex A of the Resolver Terms of Use. [Exclusive Resolver API Documentation](./exclusive-resolver-api) ### Follow Quickstart Guidelines #### Intent - Fusion SDK: https://github.com/1inch/cross-chain-swap/tree/ef6956a527528ff6c842dbdcbbd00a812436cd1f - Fusion Resolver Example: https://github.com/1inch/fusion-resolver-example - Fusion API Docs: https://github.com/1inch/fusion-resolver-example #### Cross-chain - Cross-chain SDK: https://github.com/1inch/fusion-sdk - Cross-chain Resolver Example: https://github.com/1inch/fusion-resolver-example - Cross-chain API Docs: https://github.com/1inch/cross-chain-swap/tree/ef6956a527528ff6c842dbdcbbd00a812436cd1f :::info Governance-Dependent Functionality The whitelisting, farming, and any Unicorn Power-based exclusivity or eligibility mechanisms are currently disabled for Fusion Orders as per 1IP-89 and shall apply only if and when enabled through a governance vote or a decision originating therefrom. Until such activation occurs, these features remain unavailable, and Intent Order Resolvers are not required to perform any related actions. ::: ## Limit Orders ### Choose Your Strategy #### Option 1: Unicorn Power (UP) Enabled Stake and delegate 1INCH tokens to accumulate Unicorn Power (UP). To qualify for the whitelist and become eligible to execute Limit Orders, your resolver must hold at least 5% of the total UP across all whitelisted resolvers. Complete the steps from the [Unicorn Power setup](../limit-order/unicorn-power-setup.md): **Fees** **50% fee discount** on Limit Orders. ! Requires at least 5% UP: - 1 bps for stable/pegged pairs - 25 bps for non-stable pairs #### Option 2: No Unicorn Power (UP) - Limit Orders (standard fee applies). Farming and 5% UP are not required. **Fees** - 2 bps for stable/pegged pairs - 50 bps for non-stable pairs :::info No further steps required. ::: ### Follow Quickstart Guidelines - Limit Order SDK: https://github.com/1inch/limit-order-sdk/tree/master - Limit Order Resolver Example: https://github.com/1inch/limit-order-sdk/blob/master/tests/extensions/fee-taker/fee-taker.spec.ts - Limit Order API Docs: https://business.1inch.com/portal/documentation/apis/orderbook/introduction https://business.1inch.com/portal/assets/docs-v2/resolvers/terms-of-use.md ## Terms of Use for Resolvers: The document defines eligibility, obligations, and compliance requirements for approved resolvers. Explore the [document](/portal/assets/legal-docs/resolvers/terms-of_use_resolvers_20251124.pdf) ## Exclusive Resolver API Terms: The document contains technical specifications and access details for eligble resolvers to the exlusive resolver endpoint. Explore the [document](/documentation/resolvers/exclusive-resolver-terms) https://business.1inch.com/portal/assets/docs-v2/resolvers/limit-order/quick-start-for-limit-order.md ## Kick off integration Once verified, it's time to integrate. The following resources will help you start fast: - [Limit Order Protocol Extension FeeTaker](https://github.com/1inch/limit-order-protocol/blob/master/contracts/extensions/FeeTaker.sol) - [Limit Order SDK](https://github.com/1inch/limit-order-sdk) - [Example for order submission (line 24)](https://github.com/1inch/limit-order-sdk/blob/master/src/sdk/sdk.ts#L24) - [`makingAmount` and `takingAmount` calculation (lines 78-108)](https://github.com/1inch/limit-order-sdk/blob/master/src/limit-order/limit-order-with-fee.ts#L78-L108) - In case you have chosen the staking strategy, make sure to pass the taker address to apply the Intent Swaps whitelist discount (Top 10, 5% UP). If you need further assistance, reach out to our support team: support@1inch.com. A dedicated support communication channel will be established. ## Active order discovery 1. Use the Orderbook API endpoint to fetch active orders: [GET /v4.1/1/all](/documentation/apis/orderbook/methods/v4.1/1/all/method/get). 2. Apply one of the statuses for filtering: - `status=1`: Order can be filled for the full `remainingMakerAmount` - `status=2`: Orders with insufficient approval or balance for the full remaining amount https://business.1inch.com/portal/assets/docs-v2/resolvers/limit-order/contracts-interaction.md ## Deployed contracts | Name | Contract | Address | | -------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------- | | Staking v2 | st1inch | [0x9A0C8Ff858d273f57072D714bca7411D717501D7](https://etherscan.io/address/0x9A0C8Ff858d273f57072D714bca7411D717501D7) | | Staking farm | StakingFarmingPod | [0x1A87c0F9CCA2f0926A155640e8958a8A6B0260bE](https://etherscan.io/address/0x1A87c0F9CCA2f0926A155640e8958a8A6B0260bE) | | Settlement | Settlement | [0xA88800CD213dA5Ae406ce248380802BD53b47647](https://etherscan.io/address/0xA88800CD213dA5Ae406ce248380802BD53b47647) | | Delegation pod | PowerPod | [0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947](https://etherscan.io/address/0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947) | | Resolver information | ResolverMetadata | [0xBF4543819ECede56220bcB1e8C1BBa9Ef290a58a](https://etherscan.io/address/0xBF4543819ECede56220bcB1e8C1BBa9Ef290a58a) | | Whitelist | WhitelistRegistry | [0xF55684BC536487394B423e70567413faB8e45E26](https://etherscan.io/address/0xF55684BC536487394B423e70567413faB8e45E26) | | Whitelist info | WhitelistHelper | [0xF779bdde38C39138Dcaf1514B8a6b8a6C165642D](https://etherscan.io/address/0xF779bdde38C39138Dcaf1514B8a6b8a6C165642D) | ## Stake 1INCH (relevant only for UP optional strategy) | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ---------------- | -------------------------------------------------------------------------- | | Contract | st1inch.sol | | Contract address | 0x9A0C8Ff858d273f57072D714bca7411D717501D7 | | Methods | Staking | - deposit(uint256 amount, uint256 duration) - depositWithPermit(uint256 amount, uint256 duration, bytes calldata permit) - depositFor(address account, uint256 amount, uint256 duration) - depositForWithPermit(address account, uint256 amount, uint256 duration, bytes calldata permit) | | Description | Stakes 1inch to get staking power according to the lock time | ```javascript //Deposits 100 1inch with 1 day lock await st1inch.deposit(ether("100"), time.duration.days("1")); ``` ## Register delegation pod (relevant only for UP optional strategy) | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ---------------- | -------------------------------------------------------------------------- | | Contract | PowerPod.sol | | Contract address | 0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947 | | Methods | addPod(address pod) | | Description | Register pod usage for the tx sender. Needed for: | - Resolvers to enable resolver's and delegated staking power usage for whitelisting - Stakers to enable unicorn power delegation | ```javascript // register `delegation` pod usage a `resolver` await st1inch.connect(resolver).addPod(delegation.address); ``` ## Register delegation share token (relevant only for UP optional strategy) | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ---------------- | ----------------------------------------------------------------------------------------- | | Contract | PowerPod.sol | | Contract address | 0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947 | | Methods | register(string memory name, string memory symbol, uint256 maxUserFarms) | | Description | Creates a resolvers share token to count delegated staked power shares and accrue rewards | ```javascript // Register resolver's token with name 'resolver token share' and symbol 'RTS' await delegation.register("resolver token share", "RTS"); ``` ## Delegate resolver's staking power to self (relevant only for UP optional strategy) | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ---------------- | -------------------------------------------------------------------------- | | Contract | PowerPod.sol | | Contract address | 0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947 | | Methods | delegate(address delegatee) | | Description | delegate(address delegatee) | ```javascript // Delegates all staking power to self await delegation.connect(resolver).delegate(resolver.address); ``` ## Whitelist resolver | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ---------------- | --------------------------------------------------------------------------------------------------------------- | | Contract | WhitelistRegistry.sol | | Contract address | 0xF55684BC536487394B423e70567413faB8e45E26 | | Methods | register() | | Description | Checks if sender is eligible to be whitelisted and put it into the whitelist sorted by staking power descending | ```javascript // Try to put the sender to the whitelist await whitelist.connect(resolver).register(); ``` ## FeeBank | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ------------------------- | -------------------------------------------------------------------------- | | Contract | FeeBank.sol | | Contract address | 0xa0844e046a5B7Db55Bb8DcdFfbF0bBF9c6dc6546 | | Methods | | - deposit(uint256 amount) | - depositFor(address account, uint256 amount) - depositWithPermit(uint256 amount, bytes calldata permit) - depositForWithPermit | | Description | Deposits 1INCH for fee deduction when filling orders | ```javascript // Deposit fees to fee bank await feeBank.connect(resolver).deposit(amount); ``` ## Resolving ```solidity struct Order { uint256 salt; address makerAsset; address takerAsset; address maker; address receiver; address allowedSender; // equals to Zero address on public orders uint256 makingAmount; uint256 takingAmount; uint256 offsets; // bytes makerAssetData; // bytes takerAssetData; // bytes getMakingAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount) // bytes getTakingAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount) // bytes predicate; // this.staticcall(bytes) => (bool) // bytes permit; // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2)) // bytes preInteraction; // bytes postInteraction; bytes interactions; // concat(makerAssetData, takerAssetData, getMakingAmount, getTakingAmount, predicate, permit, preIntercation, postInteraction) } ``` | Repository | [limit-order-settlement](https://github.com/1inch/limit-order-settlement/) | | ---------------- | -------------------------------------------------------------------------- | | Contract | Settlement.sol | | Contract address | 0xA88800CD213dA5Ae406ce248380802BD53b47647 | | Methods | .settleOrders(bytes calldata data) | | Description | Settles an order | https://business.1inch.com/portal/assets/docs-v2/resolvers/limit-order/resolver-farming-guide.md ## Overview As a resolver, offering farm incentives to delegators can help increase your Unicorn Power balance and consequently, your probability of filling orders. Upon registering as a resolver, the farm contract is automatically deployed. You can fetch the farm by interacting with the `dst1inch` contract's ABI. Note that you can reward delegators with any ERC-20 token, not only tokens from the incentive program. --- ### How to Fetch a Farm with the `dst1inch` Contract 1. Go to the "Read Contract" section of the [`dst1inch` contract](https://etherscan.io/token/0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947#readContract#F6) on Etherscan. Under the `defaultFarms` method, enter your resolver address within the 'address' parameter and send the call.

resolver-farming

1. Click on the returned farm contract address and navigate to the 'Write Contract' section of the returned contract page. This is your newly generated farm distribution address.

resolver-farming

3. Call the `setDistributor` method using the address that will be managing and distributing rewards.

resolver-farming

4. On the same contract, call `addRewardsToken` with the desired token address that will be distributed to your delegators.

resolver-farming

5. Lastly, on the same contract, call `startFarming`, entering the `rewardsToken` address, amount, and period (both amount and period are uint256). Once called, your farm will have started, and rewards will begin to be distributed to your delegators.

resolver-farming

--- ### How to Replenish Farming Token Balance (Optional) To replenish the token balance of your farm rewards, call `addRewardsToken` and `startFarming` to the farm contract as done in the initial setup. --- ### Example ABI Interaction :::info The example script below reads ABI definitions for both the [dst1inch](https://etherscan.io/token/0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947#code) and [multiFarmingPod](https://etherscan.io/address/0x1583C1dBe20625d0B752d472E845FbA96D096829#code) contracts. You will need to create two new files and add the ABI definitions which can be found at these URLS: - [`dst1inchABI.json`](https://api.etherscan.io/api?module=contract&action=getabi&address=0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947&apikey=YourApiKeyToken) - [`abi.json`](https://api.etherscan.io/api?module=contract&action=getabi&address=0x1583C1dBe20625d0B752d472E845FbA96D096829&apikey=YourApiKeyToken) Don't forget to replace 'YourApiKeyToken' with your actual Etherscan API key at the end of each linked URL above! ::: ```javascript require("dotenv").config(); //for accessing sensitive information such as private keys, API keys, etc. const { Web3 } = require("web3"); const web3 = new Web3(`Your_ethereum_RPC`); const fs = require("fs"); const dst1inchABI = JSON.parse(fs.readFileSync("dst1inchABI.json", "utf8")); const farmABI = JSON.parse(fs.readFileSync("abi.json", "utf8")); const erc20Abi = [ // ERC20 ABI fragment (for contract approval) { constant: false, inputs: [ { name: "spender", type: "address" }, { name: "value", type: "uint256" } ], name: "approve", outputs: [ { name: "", type: "bool" } ], payable: false, stateMutability: "nonpayable", type: "function" } ]; const dst1inch = "0xAccfAc2339e16DC80c50d2fa81b5c2B049B4f947"; const dst1inchContract = new web3.eth.Contract(dst1inchABI, dst1inch); const account = "YOUR_REGISTERED_ADDRESS"; const privateKey = "YOUR_PRIVATE_KEY"; async function distributeFarmingRewards(resolverAddress, newDistributor, rewardsToken, amount, period) { try { // Call defaultFarms with your resolver address const farmAddress = await dst1inchContract.methods.defaultFarms(resolverAddress).call(); console.log(`Farm address: ${farmAddress}`); const farmContract = new web3.eth.Contract(farmABI, farmAddress); const tokenContract = new web3.eth.Contract(erc20Abi, rewardsToken); // Call setDistributor on the returned farm address const setDistributorTx = { from: resolverAddress, to: farmAddress, data: farmContract.methods.setDistributor(newDistributor).encodeABI() }; const setDistributorSignedTx = await web3.eth.accounts.signTransaction(setDistributorTx, privateKey); await web3.eth.sendSignedTransaction(setDistributorSignedTx.rawTransaction); console.log("Distributor set successfully"); // Approve the farm contract to spend the tokens const approveTx = { from: newDistributor, to: rewardsToken, data: tokenContract.methods.approve(farmAddress, amount).encodeABI() }; const approveSignedTx = await web3.eth.accounts.signTransaction(approveTx, privateKey); await web3.eth.sendSignedTransaction(approveSignedTx.rawTransaction); console.log("Approval transaction confirmed"); // Call addRewardsToken with the address of distribution token const addRewardsTokenTx = { from: newDistributor, to: farmAddress, data: farmContract.methods.addRewardsToken(rewardsToken).encodeABI() }; const addRewardsTokenSignedTx = await web3.eth.accounts.signTransaction(addRewardsTokenTx, privateKey); await web3.eth.sendSignedTransaction(addRewardsTokenSignedTx.rawTransaction); console.log("Rewards token added successfully"); // Call startFarming(address rewardsToken, uint256 amount, uint256 period) const startFarmingTx = { from: newDistributor, to: farmAddress, data: farmContract.methods.startFarming(rewardsToken, amount, period).encodeABI() }; const startFarmingSignedTx = await web3.eth.accounts.signTransaction(startFarmingTx, privateKey); await web3.eth.sendSignedTransaction(startFarmingSignedTx.rawTransaction); console.log("Farming started successfully"); } catch (error) { console.error("Error distributing farming rewards:", error); } } const resolverAddress = account; const newDistributor = account; // you can use any address as the distributor const rewardsToken = "0xRewardsTokenAddress"; const amount = web3.utils.toWei("Amount", "Token Name"); // Amount of rewards tokens const period = 3600; // Period in seconds distributeFarmingRewards(resolverAddress, newDistributor, rewardsToken, amount, period) .then(() => console.log("Farming rewards distributed successfully")) .catch((error) => console.error("Error distributing farming rewards:", error)); ``` Have questions? Reach out to us in the live support chat! https://business.1inch.com/portal/assets/docs-v2/resolvers/limit-order/unicorn-power-setup.md These steps initialize Unicorn Power farming: 1. Approve staking 1INCH for 1inch contract. 2. Stake 1INCH to gain Unicorn Power. 3. Add a delegation pod to enable power delegation. 4. Register yourself to be a resolver. 5. (Optional) Change the default farm to a new farm. 6. Delegate available Unicorn Power to yourself. 7. Register a resolver at the whitelist. 8. Set up a worker to settle orders. ## Setup script example ```javascript const { ether, time } = require("@1inch/solidity-utils"); const { ethers } = require("hardhat"); // Setup environment const inch = await ethers.getContractAt("IERC20", "0x111111111117dc0aa78b770fa6a738034120c302"); const st1inch = await ethers.getContractAt("IERC20", "0x9a0c8ff858d273f57072d714bca7411d717501d7"); const powerPod = await ethers.getContractAt("IERC20", "0xaccfac2339e16dc80c50d2fa81b5c2b049b4f947"); const whitelist = await ethers.getContractAt("WhitelistRegistry", "0xF55684BC536487394B423e70567413faB8e45E26"); const stakeAmount = ether("1000000"); const lockTime = time.duration.years("2"); const myShareToken = { name: "MyShareTokenName", symbol: "MST" }; const worker = "..."; // Address of wallet which send transaction const [resolver] = await ethers.getSigners(); // Ethers setup script // approve 1inch staking await await inch.connect(resolver).approve(st1inch.address, stakeAmount); // stake 1inch token await (await st1inch.connect(resolver).deposit(stakeAmount, lockTime)).wait(); // add delegation pod to // 1. make it possible for any user to delegate staking power to // the resolver's account // 2. make it possible for a resolver to allocate its staking power for itself await (await st1inch.connect(resolver).addPod(powerPod.address)).wait(); // register resolver's delegation token to count stakers' shares and rewards await ( await powerPod.connect(resolver).functions["register(string,string)"](myShareToken.name, myShareToken.symbol) ).wait(); // Delegate staked power to self await (await powerPod.connect(resolver).delegate(resolver.address)).wait(); // Whitelist resolver (there should be enough unicorn power to be in top 10) await (await whitelist.connect(resolver).register()).wait(); // Add worker address from which order settlement will be executed await (await whitelist.connect(resolver).promote(1, worker)).wait(); ``` https://business.1inch.com/portal/assets/docs-v2/resolvers/intent/evm.md ## Kick off integration Once verified, it's time to integrate. Start exploring [Swap APIs technical documentation](/documentation/apis/swap/intent-swap/introduction) to learn more about Intent Swaps. ## Testing Complete your resolver technical deployment and validate it in a test environment. For testing, create and fulfill your own Intent Swaps orders using [1inch Fusion Resolver Example on GitHub](https://github.com/1inch/fusion-resolver-example). https://business.1inch.com/portal/assets/docs-v2/resolvers/intent/solana.md ## Read the docs Once verified, it's time to integrate. The following resources will help you start fast: - [Solana Intent Swaps SDK](https://github.com/1inch/solana-fusion-sdk) - [Intent Swaps API documentation](/documentation/apis/swap/intent-swap/introduction). When using the OpenAPI specs, make sure you select Solana in the network selector to get the correct information. - [Example integration tests demonstrating order creation, fill, and cancellation flows on Solana using the Bankrun simulator](https://github.com/1inch/solana-fusion-sdk/blob/master/tests/fusion-order.spec.ts). - [Core method building the fill transaction instruction](https://github.com/1inch/solana-fusion-sdk/blob/master/src/contracts/fusion-swap-contract.ts#L135), including resolver whitelist check and required account layout. ## Retrieve active orders Use the Intent Swap API endpoint to fetch active orders: [GET /v2.0/1/order/active](/documentation/apis/swap/intent-swap/orders/v2.0/1/order/active/method/get). ## Calculate current price Calculate the current price, using the [Dutch auction parameters](https://github.com/1inch/solana-fusion-sdk/blob/master/src/amount-calculator/auction-calculator/README.md). ## Execute order on-chain Use the SDK method [`FusionSwapContract.fill()`](https://github.com/1inch/solana-fusion-sdk/blob/master/src/contracts/fusion-swap-contract.ts#L135) to build and send the on-chain fill instruction. This call constructs the full transaction, including the resolver's whitelist verification and all required token and escrow accounts. ## Execution tips - The `fill` instruction does not support post-actions. You must send the taker token before receiving the maker token. - Solana has strict limits on transaction size. If you need extra actions, use batching tools (for example, Jito) to send several transactions together. - In most cases, you can execute everything from a regular wallet (EOA) without writing your own program. https://business.1inch.com/portal/assets/docs-v2/resolvers/cross-chain/cross-chain-test-examples.md This section provides a practical, end-to-end overview of working with the **1inch Cross-Chain Swaps** infrastructure from a resolver perspective. The guide focuses on **three main test scenarios**, each demonstrating a critical part of the resolver workflow: 1. **Basic Cross-Chain Order Execution** Demonstrates setting up the environment, initializing chains and wallets, deploying escrows, and completing a single-fill swap. 2. **Partial Fills (Multi-Secret Orders)** Shows how to construct multi-fill orders using Merkle-based hash-locks and execute partial fills while maintaining correct resolver logic. 3. **Order Cancellation Flow** Covers creating a cancelable order, interacting with the corresponding hash-lock, and validating the resolver and user withdrawals. Together, these examples walk you through key implementation steps such as environment initialization, escrow deployment on source and destination chains, event handling, secret management, and balance validation. They are designed to help you confidently validate your resolver integration and ensure compatibility with the latest **Cross-Chain SDK** and **Resolver API** requirements. ## Test 1: Basic cross-chain order ### Initialization Set up the environment including initializing chains, wallets, and contracts. ```javascript import 'dotenv/config' import {expect, jest} from '@jest/globals' import {createServer, CreateServerReturnType} from 'prool' import {anvil} from 'prool/instances' import Sdk from '@1inch/cross-chain-sdk' import { computeAddress, ContractFactory, JsonRpcProvider, MaxUint256, parseEther, parseUnits, randomBytes, Wallet as SignerWallet } from 'ethers' import {uint8ArrayToHex, UINT_40_MAX} from '@1inch/byte-utils' import assert from 'node:assert' import {ChainConfig, config} from './config' import {Wallet} from './wallet' import {Resolver} from './resolver' import {EscrowFactory} from './escrow-factory' import factoryContract from '../dist/contracts/TestEscrowFactory.sol/TestEscrowFactory.json' import resolverContract from '../dist/contracts/Resolver.sol/Resolver.json' const {Address} = Sdk jest.setTimeout(1000 * 60) // Private keys for testing (NEVER EXPOSE YOUR REAL PRIVATE KEY) const userPk = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d' const resolverPk = '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a' describe('Resolving example', () => { const srcChainId = config.chain.source.chainId const dstChainId = config.chain.destination.chainId // Define chain-related data type Chain = { node?: CreateServerReturnType | undefined provider: JsonRpcProvider escrowFactory: string resolver: string } // Variables for chain and wallet data let src: Chain let dst: Chain let srcChainUser: Wallet let dstChainUser: Wallet let srcChainResolver: Wallet let dstChainResolver: Wallet let srcFactory: EscrowFactory let dstFactory: EscrowFactory let srcResolverContract: Wallet let dstResolverContract: Wallet let srcTimestamp: bigint // Store the current timestamp // Utility to increase time on both chains async function increaseTime(t: number): Promise { await Promise.all([src, dst].map((chain) => chain.provider.send('evm_increaseTime', [t]))) } // Setup before running tests beforeAll(async () => { // Initialize chains ;[src, dst] = await Promise.all([initChain(config.chain.source), initChain(config.chain.destination)]) // Initialize wallets srcChainUser = new Wallet(userPk, src.provider) dstChainUser = new Wallet(userPk, dst.provider) srcChainResolver = new Wallet(resolverPk, src.provider) dstChainResolver = new Wallet(resolverPk, dst.provider) // Initialize factory contracts srcFactory = new EscrowFactory(src.provider, src.escrowFactory) dstFactory = new EscrowFactory(dst.provider, dst.escrowFactory) // Top up user account and approve tokens await srcChainUser.topUpFromDonor( config.chain.source.tokens.USDC.address, config.chain.source.tokens.USDC.donor, parseUnits('1000', 6) ) await srcChainUser.approveToken( config.chain.source.tokens.USDC.address, config.chain.source.limitOrderProtocol, MaxUint256 ) // Initialize resolver contracts and top up balances srcResolverContract = await Wallet.fromAddress(src.resolver, src.provider) dstResolverContract = await Wallet.fromAddress(dst.resolver, dst.provider) await dstResolverContract.topUpFromDonor( config.chain.destination.tokens.USDC.address, config.chain.destination.tokens.USDC.donor, parseUnits('2000', 6) ) await dstChainResolver.transfer(dst.resolver, parseEther('1')) await dstResolverContract.unlimitedApprove(config.chain.destination.tokens.USDC.address, dst.escrowFactory) // Store the current timestamp from the source chain srcTimestamp = BigInt((await src.provider.getBlock('latest'))!.timestamp) }) // Retrieve balances for maker and resolver on both chains async function getBalances( srcToken: string, dstToken: string ): Promise<{src: {user: bigint; resolver: bigint}; dst: {user: bigint; resolver: bigint}}> { return { src: { user: await srcChainUser.tokenBalance(srcToken), resolver: await srcResolverContract.tokenBalance(srcToken) }, dst: { user: await dstChainUser.tokenBalance(dstToken), resolver: await dstResolverContract.tokenBalance(dstToken) } } } ``` --- ### Fetching orders Fetch existing orders via 1inch Cross-Chain Websocket API. ```javascript // Test suite for filling an order describe('Fill', () => { // Swapping USDC between Ethereum and BSC it('should swap Ethereum USDC -> Bsc USDC. Single fill only', async () => { const initialBalances = await getBalances( config.chain.source.tokens.USDC.address, config.chain.destination.tokens.USDC.address ) // Create a cross-chain order const secret = uint8ArrayToHex(randomBytes(32)) const order = Sdk.CrossChainOrder.new( new Address(src.escrowFactory), { salt: Sdk.randBigInt(1000n), maker: new Address(await srcChainUser.getAddress()), makingAmount: parseUnits('100', 6), takingAmount: parseUnits('99', 6), makerAsset: new Address(config.chain.source.tokens.USDC.address), takerAsset: new Address(config.chain.destination.tokens.USDC.address) }, { hashLock: Sdk.HashLock.forSingleFill(secret), timeLocks: Sdk.TimeLocks.new({ srcWithdrawal: 10n, srcPublicWithdrawal: 120n, srcCancellation: 121n, srcPublicCancellation: 122n, dstWithdrawal: 10n, dstPublicWithdrawal: 100n, dstCancellation: 101n }), srcChainId, dstChainId, srcSafetyDeposit: parseEther('0.001'), dstSafetyDeposit: parseEther('0.001') }, { auction: new Sdk.AuctionDetails({ initialRateBump: 0, points: [], duration: 120n, startTime: srcTimestamp }), whitelist: [ { address: new Address(src.resolver), allowFrom: 0n } ], resolvingStartTime: 0n }, { nonce: Sdk.randBigInt(UINT_40_MAX), allowPartialFills: false, allowMultipleFills: false } ) // Sign the order and calculate its hash const signature = await srcChainUser.signOrder(srcChainId, order); const orderHash = order.getOrderHash(srcChainId); ``` --- ### Escrow creation and deposit Create and deposit assets into source and destination chain escrows. ```javascript // Initialize resolver contract and log the order fill process const resolverContract = new Resolver(src.resolver, dst.resolver); console.log(`[${srcChainId}]`, `Filling order ${orderHash}`); // Fill the order on the source chain const fillAmount = order.makingAmount; const { txHash: orderFillHash, blockHash: srcDeployBlock } = await srcChainResolver.send( resolverContract.deploySrc( srcChainId, order, signature, Sdk.TakerTraits.default() .setExtension(order.extension) .setAmountMode(Sdk.AmountMode.maker) .setAmountThreshold(order.takingAmount), fillAmount ) ); console.log(`[${srcChainId}]`, `Order ${orderHash} filled for ${fillAmount} in tx ${orderFillHash}`); // Handle event and deposit on the destination chain const srcEscrowEvent = await srcFactory.getSrcDeployEvent(srcDeployBlock); const dstImmutables = srcEscrowEvent[0] .withComplement(srcEscrowEvent[1]) .withTaker(new Address(resolverContract.dstAddress)); console.log(`[${dstChainId}]`, `Depositing ${dstImmutables.amount} for order ${orderHash}`); const { txHash: dstDepositHash, blockTimestamp: dstDeployedAt } = await dstChainResolver.send( resolverContract.deployDst(dstImmutables) ); console.log(`[${dstChainId}]`, `Created dst deposit for order ${orderHash} in tx ${dstDepositHash}`); // Retrieve and calculate escrow contract addresses const ESCROW_SRC_IMPLEMENTATION = await srcFactory.getSourceImpl(); const ESCROW_DST_IMPLEMENTATION = await dstFactory.getDestinationImpl(); const srcEscrowAddress = new Sdk.EscrowFactory(new Address(src.escrowFactory)).getSrcEscrowAddress( srcEscrowEvent[0], ESCROW_SRC_IMPLEMENTATION ); const dstEscrowAddress = new Sdk.EscrowFactory(new Address(dst.escrowFactory)).getDstEscrowAddress( srcEscrowEvent[0], srcEscrowEvent[1], dstDeployedAt, new Address(resolverContract.dstAddress), ESCROW_DST_IMPLEMENTATION ); ``` --- ### Escrow verification and withdrawals Withdraw funds from the escrow after relayer validation ```javascript await increaseTime(11); // User shares secret after validation of dst escrow deployment console.log(`[${dstChainId}]`, `Withdrawing funds for user from ${dstEscrowAddress}`); await dstChainResolver.send( resolverContract.withdraw("dst", dstEscrowAddress, secret, dstImmutables.withDeployedAt(dstDeployedAt)) ); console.log(`[${srcChainId}]`, `Withdrawing funds for resolver from ${srcEscrowAddress}`); const { txHash: resolverWithdrawHash } = await srcChainResolver.send( resolverContract.withdraw("src", srcEscrowAddress, secret, srcEscrowEvent[0]) ); console.log( `[${srcChainId}]`, `Withdrew funds for resolver from ${srcEscrowAddress} to ${src.resolver} in tx ${resolverWithdrawHash}` ); const resultBalances = await getBalances( config.chain.source.tokens.USDC.address, config.chain.destination.tokens.USDC.address ); // User transferred funds to resolver on source chain expect(initialBalances.src.user - resultBalances.src.user).toBe(order.makingAmount); expect(resultBalances.src.resolver - initialBalances.src.resolver).toBe(order.makingAmount); // Resolver transferred funds to user on destination chain expect(resultBalances.dst.user - initialBalances.dst.user).toBe(order.takingAmount); expect(initialBalances.dst.resolver - resultBalances.dst.resolver).toBe(order.takingAmount); ``` --- ## Test 2: Partial fill order Create an order with multiple secrets, then execute those fills using each correct secret. ### Creating the order ```javascript it("should swap Ethereum USDC -> Bsc USDC. Multiple fills. Fill 100%", async () => { const initialBalances = await getBalances( config.chain.source.tokens.USDC.address, config.chain.destination.tokens.USDC.address ); // User creates order with 11 secrets (10 parts) // note: use a cryptographically secure random number for real-life scenarios const secrets = Array.from({ length: 11 }).map(() => uint8ArrayToHex(randomBytes(32))); const secretHashes = secrets.map((s) => Sdk.HashLock.hashSecret(s)); const leaves = Sdk.HashLock.getMerkleLeaves(secrets); const order = Sdk.CrossChainOrder.new( new Address(src.escrowFactory), { salt: Sdk.randBigInt(1000n), maker: new Address(await srcChainUser.getAddress()), makingAmount: parseUnits("100", 6), takingAmount: parseUnits("99", 6), makerAsset: new Address(config.chain.source.tokens.USDC.address), takerAsset: new Address(config.chain.destination.tokens.USDC.address) }, { hashLock: Sdk.HashLock.forMultipleFills(leaves), timeLocks: Sdk.TimeLocks.new({ srcWithdrawal: 10n, // 10s finality lock for test srcPublicWithdrawal: 120n, // 2m for private withdrawal srcCancellation: 121n, // 1sec public withdrawal srcPublicCancellation: 122n, // 1sec private cancellation dstWithdrawal: 10n, // 10s finality lock for test dstPublicWithdrawal: 100n, // 100sec private withdrawal dstCancellation: 101n // 1sec public withdrawal }), srcChainId, dstChainId, srcSafetyDeposit: parseEther("0.001"), dstSafetyDeposit: parseEther("0.001") }, { auction: new Sdk.AuctionDetails({ initialRateBump: 0, points: [], duration: 120n, startTime: srcTimestamp }), whitelist: [ { address: new Address(src.resolver), allowFrom: 0n } ], resolvingStartTime: 0n }, { nonce: Sdk.randBigInt(UINT_40_MAX), allowPartialFills: true, allowMultipleFills: true } ); const signature = await srcChainUser.signOrder(srcChainId, order); const orderHash = order.getOrderHash(srcChainId); ``` ### Filling the order ```javascript // Resolver fills order const resolverContract = new Resolver(src.resolver, dst.resolver); console.log(`[${srcChainId}]`, `Filling order ${orderHash}`); const fillAmount = order.makingAmount; const idx = secrets.length - 1; // last index to fulfill const { txHash: orderFillHash, blockHash: srcDeployBlock } = await srcChainResolver.send( resolverContract.deploySrc( srcChainId, order, signature, Sdk.TakerTraits.default() .setExtension(order.extension) .setInteraction( new Sdk.EscrowFactory(new Address(src.escrowFactory)).getMultipleFillInteraction( Sdk.HashLock.getProof(leaves, idx), idx, secretHashes[idx] ) ) .setAmountMode(Sdk.AmountMode.maker) .setAmountThreshold(order.takingAmount), fillAmount, Sdk.HashLock.fromString(secretHashes[idx]) ) ); console.log(`[${srcChainId}]`, `Order ${orderHash} filled for ${fillAmount} in tx ${orderFillHash}`); const srcEscrowEvent = await srcFactory.getSrcDeployEvent(srcDeployBlock); const dstImmutables = srcEscrowEvent[0] .withComplement(srcEscrowEvent[1]) .withTaker(new Address(resolverContract.dstAddress)); console.log(`[${dstChainId}]`, `Depositing ${dstImmutables.amount} for order ${orderHash}`); const { txHash: dstDepositHash, blockTimestamp: dstDeployedAt } = await dstChainResolver.send( resolverContract.deployDst(dstImmutables) ); console.log(`[${dstChainId}]`, `Created dst deposit for order ${orderHash} in tx ${dstDepositHash}`); const secret = secrets[idx]; const ESCROW_SRC_IMPLEMENTATION = await srcFactory.getSourceImpl(); const ESCROW_DST_IMPLEMENTATION = await dstFactory.getDestinationImpl(); const srcEscrowAddress = new Sdk.EscrowFactory(new Address(src.escrowFactory)).getSrcEscrowAddress( srcEscrowEvent[0], ESCROW_SRC_IMPLEMENTATION ); const dstEscrowAddress = new Sdk.EscrowFactory(new Address(dst.escrowFactory)).getDstEscrowAddress( srcEscrowEvent[0], srcEscrowEvent[1], dstDeployedAt, new Address(resolverContract.dstAddress), ESCROW_DST_IMPLEMENTATION ); await increaseTime(11); // finality lock passed // User shares secret after validation of dst escrow deployment console.log(`[${dstChainId}]`, `Withdrawing funds for user from ${dstEscrowAddress}`); await dstChainResolver.send( resolverContract.withdraw("dst", dstEscrowAddress, secret, dstImmutables.withDeployedAt(dstDeployedAt)) ); console.log(`[${srcChainId}]`, `Withdrawing funds for resolver from ${srcEscrowAddress}`); const { txHash: resolverWithdrawHash } = await srcChainResolver.send( resolverContract.withdraw("src", srcEscrowAddress, secret, srcEscrowEvent[0]) ); console.log( `[${srcChainId}]`, `Withdrew funds for resolver from ${srcEscrowAddress} to ${src.resolver} in tx ${resolverWithdrawHash}` ); const resultBalances = await getBalances( config.chain.source.tokens.USDC.address, config.chain.destination.tokens.USDC.address ); // User transferred funds to resolver on the source chain expect(initialBalances.src.user - resultBalances.src.user).toBe(order.makingAmount); expect(resultBalances.src.resolver - initialBalances.src.resolver).toBe(order.makingAmount); // Resolver transferred funds to user on destination chain expect(resultBalances.dst.user - initialBalances.dst.user).toBe(order.takingAmount); expect(initialBalances.dst.resolver - resultBalances.dst.resolver).toBe(order.takingAmount); }); ``` --- ## Test 3: Order cancellation Cancel an order by creating a new order with a hash lock and managing the withdrawal process. ```javascript // ---- Order cancellation ---- describe('Cancel', () => { it('should cancel swap Ethereum USDC -> Bsc USDC', async () => { const initialBalances = await getBalances( config.chain.source.tokens.USDC.address, config.chain.destination.tokens.USDC.address ) // User creates order // note: use a cryptographically secure random number for real-life scenarios const hashLock = Sdk.HashLock.forSingleFill(uint8ArrayToHex(randomBytes(32))) const order = Sdk.CrossChainOrder.new( new Address(src.escrowFactory), { salt: Sdk.randBigInt(1000n), maker: new Address(await srcChainUser.getAddress()), makingAmount: parseUnits('100', 6), takingAmount: parseUnits('99', 6), makerAsset: new Address(config.chain.source.tokens.USDC.address), takerAsset: new Address(config.chain.destination.tokens.USDC.address) }, { hashLock, timeLocks: Sdk.TimeLocks.new({ srcWithdrawal: 0n, // no finality lock for test srcPublicWithdrawal: ``` https://business.1inch.com/portal/assets/docs-v2/resolvers/exclusive-resolver-terms.md The Exclusive Resolver API is a new feature available for resolvers within the 1inch Fusion mode. This API allows a 1inch Fusion resolver to be chosen as an exclusive filler at the beginning of the auction. By providing a quote, a resolver commits to executing the order as soon as the user submits it to the 1inch Relayer API. The order must be executed before the end of the exclusivity period. The executed order's maker amount must match the amount provided by the resolver's API for a specific `initialRateBump` **Performance metrics:** - **Maximum response time (including network):** 500ms - **SLA:** 90%. Calculated from: _Number of executed exclusive orders / Total resolver's exclusive orders x 100%_. Only orders submitted by the user before the exclusivity period ends are counted.

### **API Endpoint:** `POST /quote` Returns a list of resolver's quotes, sorted by the maker's amount (descending), along with the corresponding taker amount rate bump from the minimal return amount. ### Body - `makerAsset`: the address of the token that the user is selling. - `takerAsset`: the address of the token that the user is buying. - `makerAmount`: the amount of the `makerAsset` that the user is selling. - `minTakerAmount`: the minimum amount of the `takerAsset` that the user expects to receive. - `makerAddress`: the wallet address of the user requesting a quote. - `quoteId`: a unique ID of the quote. - `gasBumpEstimate` _(New!)_: estimated gas cost adjustment based on order fill through the 1inch router. - `gasPriceEstimate` _(New!)_: estimated gas price for executing the order. These new fields allow resolvers to fine-tune their quotes more precisely based on gas costs. ### Response - `grid`: an array containing details of proposed price improvements (max items: 50): - `makerAmount`: partial or full fill amount. - `initialRateBump`: rate bump at the beginning of the Dutch auction. - **Min**: 0 - **Max**: 16777215 - **10000000** -> **100%** ### Example **Request:** ```text POST /quote ``` **Body:** ```json { "chainId": 1, "makerAsset": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "takerAsset": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "makerAmount": "1000000000000000000", "minTakerAmount": "2400000000", "makerAddress": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "quoteId": "cf872857-c456-4f4f-aff0-84f7bebb7df2", "gasBumpEstimate": "50000", "gasPriceEstimate": "30000000000" } ``` **Response (HTTP code: 200):** ```json { "grid": [ { "makerAmount": "1000000000000000000", // 1 ETH (100%) "initialRateBump": 10000 // improve minTakerAmount by 0.1% }, { "makerAmount": "500000000000000000", // 0.5 ETH (50%) "initialRateBump": 100000 // improve minTakerAmount by 1% }, { "makerAmount": "100000000000000000", // 0.1 ETH (10%) "initialRateBump": 1000000 // improve minTakerAmount by 10% } ] } ``` ## Errors Use these error codes in API response in case: - **_400 Bad Request_**: - Token pair is not supported. - Cannot provide a quote for specified `makerAmount` / `minTakerAmount` / `makerAddress`. - **_500 Internal Server Error_**: - Unexpected error on the server. # Useful tips and formulas ## Calculate: "**How much does the user receive at the start of the auction?**" ```text takerAmount = minTakerAmount * (initialRateBump + 10000000) / 10000000 ``` ## Calculate: "**What initial rate bump is needed for a specific `takerAmount`?**" ```text initialRateBump = (takerAmount * 10000000 / minTakerAmount) - 10000000 ``` ## **Understanding `gasBumpEstimate` and `gasPriceEstimate`** - `gasBumpEstimate`: this value is calculated based on the estimated gas cost required to fill an order via the 1inch router. If you anticipate that your execution will be more gas-efficient, you can adjust your `initialRateBump` accordingly to reflect this advantage. - Detailed calculation: [Fusion SDK Gas Bump Calculation](https://github.com/1inch/fusion-sdk/blob/8452c43be3edfccf181e5c1003ffb55c6b32b2dc/src/auction-calculator/auction-calculator.ts#L90) - `gasPriceEstimate`: this estimate provides an expected gas price for executing the transaction, helping to determine the most optimal bid pricing strategy. - Detailed calculation: [Fusion SDK Gas Estimate Calculation](https://github.com/1inch/fusion-sdk/blob/8452c43be3edfccf181e5c1003ffb55c6b32b2dc/src/auction-calculator/auction-calculator.ts#L76) Additionally, for reference, you can check the related contract logic used in gas calculations: [Limit Order Settlement Contract Code](https://github.com/1inch/limit-order-settlement/blob/2eef6f86bf0142024f9a8bf054a0256b41d8362a/contracts/extensions/BaseExtension.sol#L140) ## **How to determine if my resolver is selected for exclusive execution?** To check whether your resolver is selected for exclusive execution, follow steps below. 1. Import the necessary modules from the 1inch Fusion SDK: ```typescript import { Extension, FusionOrder, now } from "@1inch/fusion-sdk"; import { Address } from "@1inch/fusion-sdk"; ``` 1. Create an object containing the details of the Fusion order: ```typescript const orderData = { ... } ``` 1. Provide the encoded order extension data ```typescript const ext = "0x..."; // Example encoded order extension ``` 4. Decode and process the Fusion order ```typescript const fusionOrder = FusionOrder.fromDataAndExtension(orderData, Extension.decode(ext)); ``` 5. Check if the resolver is exclusive. Define the resolver's promotee address and check whether it has exclusive execution rights using the updated Fusion SDK logic: ```typescript const resolverPromoteeAddress = Address.ZERO_ADDRESS; const isExclusive = fusionOrder.isExclusiveResolver(resolverPromoteeAddress); const isExclusivePeriod = fusionOrder.isExclusivityPeriod(now()); ``` 6. Interpret the results - `isExclusive` -> Returns `true` if the resolver is selected for exclusive execution. - `isExclusivePeriod` -> Returns `true` if the exclusivity period is still active. For further details, refer to the relevant Fusion SDK implementation: - [Fusion Order Exclusive Resolver Check](https://github.com/1inch/fusion-sdk/blob/5b112ec34fc12e61c496cbe54cc93987accfce4b/src/fusion-order/fusion-order.ts#L302) - [Fusion Order Exclusivity Period Check](https://github.com/1inch/fusion-sdk/blob/5b112ec34fc12e61c496cbe54cc93987accfce4b/src/fusion-order/fusion-order.ts#L588)
## FAQ https://business.1inch.com/portal/assets/docs-v2/faq/api-error-messages-explained.md If you're encountering issues with our API, this guide will help you understand some common error messages and their meanings. _Please note: This list is not comprehensive. Other errors involving the dynamics of generic EVM transaction estimations might require deeper investigation._ :::tip Save the `X-Request-Id` header Every API response includes an `X-Request-Id` header. When you encounter an error, save this value -- it uniquely identifies your request in server logs. You can share it with support or use the [MCP `debug` tool](/portal/documentation/ai-integration/ecosystem#debug) to pull matching log lines for your organization. ::: ## General Errors - **400 - Bad Request:** This indicates an incorrect parameter. Ensure that all required parameters are correctly set. - **403 - Forbidden:** This indicates that the origin address is a banned or restricted address (see [terms and conditions](/assets/legal-docs/terms_of_service_public_api_20260218.pdf)) - **403 - Unauthorized:** Your API key is missing or incomplete. Please double check that correct key was entered and try again. - **429 - Rate Limit:** You've made too many requests to the API within a 1 second time period. Reduce your requests per second (RPS) to stay below the free 1rps limit. If higher limits are required, please fill out the 1inch Network Enterprise API application. - **503 - Banned IP:** The IP address you're using to access the API is banned. Please ensure you're adhering to 1inch Network's terms of use. - **The API isn't behaving as expected:** In certain cases you may be passing in a parameter supported by the API but the wrong type or expected value. For example `disableEstimate=true` will work but `disableEstimate=True` will not. All parameters are CAsE SenSiTive. This is especially apparent when stringifying boolean values in python. ## Specific Errors - **Cannot sync token:** The token either doesn't exist on the blockchain or isn't a valid token. Also, double check that you are using the correct chainID in relation to the token used. - **Amount is not set:** The 'amount' field hasn't been specified. - **_Please note:_** All token amounts must be in the correct decimal format! The decimal format can be found by looking up the token contract on the block explorer. - **Example:** If the [source token is DAI](https://etherscan.io/token/0x6b175474e89094c44da98b954eedeac495271d0f), and you are sending 1 DAI, the amount with 18 decimals would be `1000000000000000000`. Token Decimals - **Src is not set:** The 'src' (source token contract) field is missing. - **Dst is not set:** The 'dst' (destination token contract) field is missing. - **Insufficient liquidity:** The aggregator can't find a route for the swap due to low liquidity. ## Swap-specific Errors - **Not enough src balance:** This means your source token balance is insufficient. It provides the required amount and your current balance. - **Not enough Allowance:** You haven't granted the necessary token allowance to the 1inch router. It'll indicate the amount, current allowance, and the spender address, e.g., "Spender: 0x1111111254eeb25477b68fb85ed929f73a960582". - **Insufficient liquidity:** As mentioned earlier, the aggregator couldn't route the swap. :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: https://business.1inch.com/portal/assets/docs-v2/faq/api-troubleshooting.md ## What is the rate limit? As of August 2023, all free public API usage has been reduced to 1 requests per second (rps). :::info For workloads that require higher RPS, expanded quotas, or sustained performance, explore the available paid plans on the [**pricing page**](/pricing). For organizations with significant trading volumes or advanced requirements, [**complete this application**](/get-enterprise) to explore tailored Enterprise options. ::: ## "Insufficient Liquidity" error This error can occur for a number of reasons: - The liquidity pool has not been queried - make sure one of the aggregated sources has at least 10k of a connector token listed below. - If you're getting a quote, please make sure to take into account the decimals of the token. Do not include decimal places in the "from token amount". The API returns the number of decimal places the token supports when calling /quote or /swap - There's an error in the server and is unable to find a path, this may require contacting the 1inch support team for more investigation. ## "Cannot Estimate" This error occurs when the eth_estimateGas RPC call throws an error. There are many reasons why this can throw an error, and they all tend to mean the transaction is guaranteed to fail. This is a protection, so a transaction is broadcast that's going to fail. To find the precise error, disableEstimate=true can be used in the query and an eth_estimateGas RPC call can be done locally. The transaction can also be simulated with a platform like tenderly or blocknative for a better look at the transaction trace. Some common reasons why a transaction may fail: - A token has a fee on transfer or swap and the slippage tolerance needs to be increased - A token has a fee on transfer _and_ the fee and referrer parameter is set causing the transaction to always fail - The rate has expired and changed in the latest block. ## Troubleshooting insufficient allowance / balance In the case of one of these errors, you may not have a[ token approval](https://help.1inch.io/en/articles/6147312-token-approvals) or you're missing the token balance. To do a token approval, you can use the API to approve the token to the 1inch router. Insufficient Allowance --- ## What are the "parts" parameters? The parts parameters is comprised of 3 things - mainRouteParts - virtualParts - parts Each of these has their own unique meaning. The main route parts denotes the initial split and can be seen on the UI. In this example it's the 70%/30% split Parts Parameter The parts parameter is how many individual blocks there can be. In the picture above we can see 4 blocks with the top being the first main route part with 2 parts to it and the bottom one being the second main route part with 2 parts in it. The virtual parts is the splits _inside_ of a part. We can see in the first main route part above, in the first block there are 2 virtual parts splitting the USDC between hashflow and uniswap. In the second main route part we can see three virtual parts in the first block, a hashflow route with 2 different rates and one to uniswap. ## What is the "Complexity level?" Complexity level is how many steps a swap can go through, below are the levels and what it means for the swap. Each level adds to the previous level. - **Complexity level 0:** the source token can be wrapped or unwrapped and swapped through one liquidity pool per main route part. - **Complexity level 1:** the source token can be wrapped or unwrapped and swapped through two liquidity pools. This means there can be up to one connector token in each main route part. - **Complexity level 2 (Default):** the source token can be wrapped or unwrapped and swapped through three liquidity pools. This means there can be up to two connector tokens in each main route part. - **Complexity level 3:** the source token can be wrapped or unwrapped and swapped through four liquidity pools. This means there can be up to three connector tokens in each main route part. ## How can I limit the liquidity sources in the query? To limit the liquidity sources to a query, you can manually enter the pool-contacts that you to use using the "protocols" parameter. All other liquidity sources will be excluded by default. ### Still have questions? Feel free to reach out to us in the live support chat! :::tip Debugging with `X-Request-Id` Every API response includes an `X-Request-Id` header that uniquely identifies your request. When contacting support, include this value for faster investigation. If you use the [1inch MCP Server](/portal/documentation/ai-integration/ecosystem), the `debug` tool can look up production logs by this request id. ::: https://business.1inch.com/portal/assets/docs-v2/faq/cors-error-faq.md When integrating the 1inch API in your dApp, you might experience an issue with CORS (Cross-Origin Resource Sharing). It can be confusing, especially when your API calls are successful via tools like [Curl](https://curl.se/) or [Postman](https://www.postman.com/), but fail when made from your custom dApp's UI. ## This article covers: [What is CORS?](#what-is-cors) [Why am I facing this issue?](#why-am-i-facing-this-issue) [How can I resolve CORS errors when calling the 1inch API?](#how-can-i-resolve-cors-errors-when-calling-the-1inch-api) [Can I call functions without a server and still avoid CORS errors?](#can-i-call-functions-without-a-server-and-still-avoid-cors-errors) ### What is CORS? Cross-Origin Resource Sharing (CORS) is a common security protocol implemented by most browsers to help prevent security risks with cross-origin requests. Essentially, a cross-origin request is when a web page from one domain tries to access resources, like data or images etc., from a different domain. For example, say you're browsing "[coindesk.com](https://www.coindesk.com/)" and it has a ETH/BTC ticker widget that pulls price data from "[tradingview.com](https://www.tradingview.com/)". When the "coindesk.com" domain tries to fetch the price data from the "tradingview.com" domain, it's making a cross-origin request. Browsers prevent HTTP requests to a different domain than the one hosting the web page, in order to protect users against cross-site security threats. This can be really helpful in blocking things like [request forgery](https://owasp.org/www-community/attacks/csrf), malicious [script inclusion](https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/11-Client_Side_Testing/13-Testing_for_Cross_Site_Script_Inclusion). ### Why am I facing this issue? When the CORS protocol blocks your requests, it's a signal that the 1inch API hasn't granted explicit permissions to your domain. For 1inch integrations, this usually happens when trying to call the 1inch API from you're dApp's front-end. When sending a request through a frontend, the API key is embedded within the client-side code or headers, making it accessible to anyone who inspects the webpage's source or monitors its network traffic. This makes it so a malicious actor could easily extract and use your exposed key for their own benefit (or even to get around their own rate limits)! ### How can I resolve CORS errors when calling the 1inch API? The most common solution is to run your request through some type of middleware or proxy server. This additional component makes the call, receives the response, adds necessary headers, and then forwards it to your application. Then the browser will see the request as originating from the same domain, avoiding any CORS triggers. You can use your own custom proxy or a turnkey proxy server like [Lambda / AWS](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-integrations.html). Please note: Make sure that your API key and headers are entered correctly! ### Can I call functions without a server and still avoid CORS errors? Since non-server functions are still called on the front-end, your request will still likely be blocked. https://business.1inch.com/portal/assets/docs-v2/faq/how-to-read-tx-input-data.md In this article, we'll learn how to read and decode the raw calldata that's passed to Ethereum smart contracts. The calldata contains the function signature and arguments passed to the function. We can start with something simple like ```text 0xb7760c8f000000000000000000000000000000000000000000000000000000004d866d9200000000000000000000000068b3465833fb72a70ecdf485e0e4c7bd8665fc45; ``` To start, we need to extract the function signature from the first four bytes of the calldata. These four bytes represent the function selector, which uniquely identifies each function in the contract. We can use a web3 library to extract the function selector and match it to the corresponding function in the contract. If you don't have this, you can just use a tool like https://4byte.directory/ to look up the function selector. Once we have the function selector, we can use the function signature to determine the number and type of arguments that are passed to the function. For example, the function signature for the transfer function in the ERC20 standard is 0xa9059cbb, which corresponds to the function transfer(address to, uint256 value). The first argument is an address, which is 20 bytes long, and the second argument is a uint256, which is 32 bytes long. We can use this information to extract the arguments from the calldata. ```text // transfer(uint256 amount, address to) 0xb7760c8f // arguments 000000000000000000000000000000000000000000000000000000004d866d9200000000000000000000000068b3465833fb72a70ecdf485e0e4c7bd8665fc45 ``` Now that the function selector and arguments are separated, the arguments can be decoded. In their most basic form, every argument is padded to 32 bytes. This is because the calldata is stored in 32 byte slots. We can use this information to extract the arguments from the calldata. ```text // uint256 amount 000000000000000000000000000000000000000000000000000000004d866d92 // address to 00000000000000000000000068b3465833fb72a70ecdf485e0e4c7bd8665fc45 ``` This is a lot more readable now. The amount is `0x4d866d92` and the address is `0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45` ##Dynamic variables Transaction data containing information that is not a fixed size is much harder to decode. These types would be something like a string or bytes. To show how complicated strings can be, consider the following example of "hello world" encoded as a parameter. ```text 0x 0000000000000000000000000000000000000000000000000000000000000020 000000000000000000000000000000000000000000000000000000000000000c 48656c6c6f20576f726c64210000000000000000000000000000000000000000 ``` The first 32 bytes represent the offset to the string. The second 32 bytes represent the length of the string. The remaining bytes represent the string itself. The string is padded to 32 bytes, so the remaining bytes are 0s. This is a basic outline of decoding transaction data by hand. There are many more edge cases and complications that can arise, but this should give you a good idea of how to decode transaction data. If you want to learn more about reading transaction input data, we recommend reading [this article](https://degatchi.com/articles/reading-raw-evm-calldata/). https://business.1inch.com/portal/assets/docs-v2/faq/infrastructure-fee.md Infrastructure fees apply to Swap API transactions. These fees are deducted from the destination amount of each completed Network Request and are distinct from subscription fees. They help maintain and scale the infrastructure that powers the APIs--ensuring reliability, performance, and operational continuity. Following infrastructure fees apply by plan: | Plan | Fees for stable coins | Fees for non-stable coins | | :------- | --------------------: | ------------------------: | | Dev | 10 bps | 30 bps | | Startup | 7 bps | 20 bps | | Pro | 4 bps | 10 bps | | Business | 2 bps | 5 bps | All 1inch interfaces or channels (dApp, Wallet and others using the API) may incur infrastructure fees in the following ranges: 0-5 bps for stable pairs and 0-30 bps for non-stable pairs. ## Support https://business.1inch.com/portal/support/article/8422842 If you're encountering issues with our API, this guide will help you understand some common error messages and their meanings. General Errors 400 - Bad Request: This indicates an incorrect parameter. Ensure that all required parameters are correctly set. 429 - Rate Limit: You've made too many requests to the API within a 1-second time period. Reduce your requests per second (RPS) to stay below the free 1 RPS limit . If higher limits are required, check out the current 1inch Business Plans . 503 - Banned IP: The IP address you're using to access the API is banned. Please ensure you're adhering to 1inch terms of use . Specific Errors Cannot sync token: The token either doesn't exist on the blockchain or isn't a valid token. Also, double check that you are using the correct chainID in relation to the token used. Amount is not set: The 'amount' field hasn't been specified. ***Please note: All token amounts must be in the correct decimal format! The decimal format can be found by looking up the token contract on the block explorer. Example: If the source token is DAI, and you are sending 1 DAI, the amount with 18 decimals would be 1000000000000000000. https://etherscan.io/token/0x6b175474e89094c44da98b954eedeac495271d0f Src is not set: The 'src' (source token contract) field is missing. Dst is not set: The 'dst' (destination token contract) field is missing. Insufficient liquidity: The aggregator can't find a route for the swap due to low liquidity. Swap-specific Errors 400 - Bad Request : This will be similar to the general 400 error; however, these error messages will also specify a missing parameter or more details of the problem. Not enough src balance: This means your source token balance is insufficient. It provides the required amount and your current balance. Not enough Allowance: You haven't granted the necessary token allowance to the 1inch router. It'll indicate the amount, current allowance, and the spender address, e.g., "Spender: 0x1111111254eeb25477b68fb85ed929f73a960582". Insufficient liquidity: As mentioned earlier, the aggregator couldn't route the swap. *** Please note: This list is not comprehensive. Other errors involving the dynamics of generic EVM transaction estimations might require deeper investigation. Questions, comments, concerns? Feel free to reach out to our support team by clicking the live chat below. https://business.1inch.com/portal/support/article/8186441 Currently, 1inch Business only supports English; however, keep an eye out for more languages to come! https://business.1inch.com/portal/support/article/9821013 At 1inch, we're constantly working to improve platform security and build a compliant reputation within the overarching web3 ecosystem. In line with this commitment, when creating a brand new 1inch Business account, all users must pass a standard Know Your Customer (KYC) verification process. This is a prerequisite for accessing and building with all 1inch public APIs. It involves a simple and quick process that consists of both liveness and ID verification. This step is in accordance with Section 8 of 1inch Business Terms of Service . The KYC process is designed to be straightforward, taking just a few minutes to be fulfilled. FAQ How can I return to my verification session before the assessment is finalized? If you had to interrupt your verification session, you can resume it by logging in to 1inch Business, going to the Dashboard , and clicking Proceed to Verification on the banner at the top of the page. How do I know the status of my verification? Throughout the process, emails will be sent to the address that was entered when creating 1inch Business account, updating you on the current status. What should I do if there is an issue with my verification process? 1inch Business verification processes are conducted through our trusted third-party provider, Sumsub. While most users complete these checks smoothly, there may be instances where: Documents are not accepted due to inconsistencies. Live photo uploads encounter errors. Issues arise with document clarity or completeness. If you experience any challenges during the verification process, reach out directly to Sumsubs' support team for prompt assistance. https://business.1inch.com/portal/support/article/8186430 To delete your 1inch Business account: In the top-right corner of any page, click the windows logo and select Profile . Navigate to Delete tab. Select Delete account . Read the disclaimer and confirm the account deletion on the following screen. Deleting your account will permanently remove all related data (API keys, settings, and history). Any applications using this API key will no longer be able to access 1inch APIs. Questions, comments, concerns? Feel free to reach out to us in the live support chat! https://business.1inch.com/portal/support/article/11581772 Keeping your billing address up to date ensures smooth invoicing and compliance with financial regulations. You can add or update your billing address at any time directly through your 1inch Business account. The updated billing information takes effect immediately and does not require additional approval. Steps to add or update your billing address Log in to your 1inch Business account. In the top-right corner, click the windows icon, then select to Profile > Billing information . Select your entity type: Corporate Individual Fill in the fields shown. Click Save to apply the changes. Note that all fields must be completed. The only exception is the Organization URL field, which is optional for corporate entities . https://business.1inch.com/portal/support/article/8186443 To change 1inch Business theme: Click the windows icon in the upper-right corner of any page. In the menu opened, select from light, automatic, or dark theme. Questions, comments, concerns? Feel free to reach out in the live support chat! https://business.1inch.com/portal/support/article/8186455 If you need to regenerate an API key for any reason (whether it be for security reasons or staff changes, etc.), it is quite easy! To get started, navigate to click Applications at the top of the page. Next, click the application key for which you want to regenerate, and click Regenerate on the following screen. Lastly, click Regenerate again to confirm the action on the following screen. Once a key is regenerated, the old one will be permanently disabled. After confirming, your old API key will be replaced with a new one that can be used immediately. Questions, comments, concerns? Feel free to reach out in the live support chat! https://business.1inch.com/portal/support/article/8186424 To change or modify your 1inch Business profile settings, click the windows icon in the upper-right corner of the page and select Profile . From here, you will be able to change all of the details within your profile. Once you are finished updating the information, click Save to apply the changes. Questions, comments, concerns? Feel free to reach out in our Live Support Chat! https://business.1inch.com/portal/support/article/9549117 Different user roles define the actions users can perform within 1inch Business. This guide will help you understand the various roles and the permissions they come with. User roles We have four main user roles: Owner , Admin , Developer , and Finance . Each role has specific permissions to help you perform your tasks efficiently. Here's a quick overview of what each role can do: Owner: full access to everything (applications, organizations, billing, payments, subscriptions), only one Owner per organization Admin: can manage applications and organizations and view subscriptions Developer: can manage applications and view organizations, payments, and subscriptions Finance: can manage billing and payments and view applications, organizations, and subscriptions By assigning the appropriate roles, you can ensure each user has the correct level of access to perform their tasks efficiently. Remember, there is only one Owner per account who holds the legal responsibility for the organization. Owner Note: There is only one Owner per organization, and the Owner is the legal entity responsible for the organization. The Owner has the most comprehensive access, allowing full control over all aspects of the portal. What can owners do? Modify applications and their keys View, modify, and delete organizations Update billing information Process payments Update subscriptions Admin Admins have broad access but with some limitations compared to Owners. What can admins do? View and modify applications and their keys View and modify organization details Check subscription details Developer Developers focus on managing applications and keys, with some read-only access to other areas. What can developers do? View and modify applications and their keys Check organization details Check payment details Check subscription details Finance Finance users handle billing and payments, with some additional read-only access. What can finance do? Update billing information Process payments Check application details Check organization details Check subscription details Number of users per account The maximum number of users per account tier is as follows: Dev -- 1 user Start-up -- 2 users Professional -- 3 users Business -- 5 users Enterprise -- 20 users How to add a new user to your account Important note: To add a user to an organization, they must first be removed from any existing organization. For example, the user must delete their current account before being assigned to a new organization. Go to your main account dashboard, and click the profile icon in the upper-right corner of the page. Then click Settings . Within User management , click Invite . In the window opened, enter the new user's email and select one of the roles. Currently, the roles of Admin , Developer , or Finance can be selected. Click Invite user to send them the invitation to join. Questions, Comments, Concerns? Feel free to reach out to us in the live support chat! https://business.1inch.com/portal/support/article/12132359 What's new 1inch has upgraded its Intent Swap API to support tokenized real-world assets (RWAs). With this update, RWAs are now accessible via the 1inch dApp and Wallet (outside of the US and other restricted regions). RWAs are also available to partners through the Intent Swap API on 1inch Business. One of the first partners to expand its integration is Trust Wallet , bringing RWA access to its community. Why it matters Liquidity has been one of the biggest hurdles for RWA adoption. The upgraded Intent Swap API addresses this by leveraging 1inch's leading aggregation technology, making RWA swaps as easy and efficient as crypto swaps. This milestone was achieved in partnership with Ondo Finance , a leader in tokenized real-world assets. Ondo recently announced the launch of Ondo Global Markets , which provides non-US investors seamless access to over 100 tokenized assets on Ethereum, with plans to expand to more than 1,000 by the end of the year. How it works Resolvers : 1inch routes trades through resolvers to execute orders quickly and securely. Aggregation : users get access to tokenized assets with efficient pricing and liquidity. Ecosystem access : all Intent Swap API integrators can now enable RWAs for their eligible users. Things to know Normally, Ondo GM tokens are tradable 24/5 in line with U.S. market hours (Sunday 8 pm ET-Friday 8 pm ET) The only supported pairs are USDC/USDon <> Ondo_RWA RWA access is jurisdiction-restricted . Not available for users in the United States, the United Kingdom, and other restricted regions . Token availability depends on issuer classification, local regulations, and risk filters. https://business.1inch.com/portal/support/article/8186363 To apply for the 1inch enterprise API with increased requests per second, you should apply at https://business.1inch.com/landing Sign up for an account and use the "Get Enterprise" button on your dashboard. Once your information has been submitted, we will review the application in the order that it was received. https://business.1inch.com/portal/support/article/8186392 How can I increase my requests per second (rps)? To increase your requests per second, please fill out the enterprise application form here . https://business.1inch.com/portal/support/article/8432805 This article covers: What is CORS? Why am I facing this issue? How can I resolve CORS errors when calling 1inch Business? Can I call functions without a server and still avoid CORS errors? When integrating 1inch Business in your dApp, you might experience an issue with CORS (Cross-Origin Resource Sharing). It can be confusing, especially when your API calls are successful via tools like Curl or Postman , but fail when made from your custom dApp's UI. What is CORS? Cross-Origin Resource Sharing (CORS) is a common security protocol implemented by most browsers to help prevent security risks with cross-origin requests. Essentially, a cross-origin request is when a web page from one domain tries to access resources, like data or images etc., from a different domain. For example , s ay you're browsing coindesk.com and it has a ETH/BTC ticker widget that pulls price data from " tradingview.com ". When the "coindesk.com" domain tries to fetch the price data from the "tradingview.com" domain, it's making a cross-origin request. Browsers prevent HTTP requests to a different domain than the one hosting the web page, in order to protect users against cross-site security threats. This can be really helpful in blocking things like request forgery , malicious script inclusion . Why am I facing this issue? When the CORS protocol blocks your requests, it's a signal that 1inch Business hasn't granted explicit permissions to your domain. For 1inch integrations, this usually happens when trying to call the 1inch API from you're dApp's front-end. When sending a request through a frontend, the API key is embedded within the client-side code or headers, making it accessible to anyone who inspects the webpage's source or monitors its network traffic. This makes it so a malicious actor could easily extract and use your exposed key for their own benefit (or even to get around their own rate limits)! How can I resolve CORS errors when calling the 1inch API? The most common solution is to run your request through some type of middleware or proxy server . This additional component makes the call, receives the response, adds necessary headers, and then forwards it to your application. Then the browser will see the request as originating from the same domain, avoiding any CORS triggers. You can use your own custom proxy or a turnkey proxy server like Lambda / AWS . Please note: Make sure that your API key and headers are entered correctly! Can I call functions without a server and still avoid CORS errors? Since non-server functions are still called on the front-end, your request will still likely be blocked. Need higher rate limits? Request an enterprise endpoint. https://business.1inch.com/portal/support/article/12867971 Before you start, make sure you are logged in to your 1inch Business account and have the Owner role . Upgrading your subscription Navigate to the 1inch Business pricing page . In the comparison table, select Get under the plan you want to upgrade to. In the next screen, review your purchase and check the details for the selected subscription. Any unused calls from your current billing period are automatically applied as a discount toward the new subscription when upgrading from a paid plan. Once ready, select Confirm . Add or review your billing address details and accept the Commercial API Terms of Use. Once ready, select Subscribe . Connect your wallet and make a payment for your new subscription. Once the payment is finalized, your new subscription is ready to be used. Downgrading your subscription Navigate to the 1inch Business pricing page . In the comparison table, select Downgrade to under the plan of your choice. In the next screen, review your purchase and check the details for the selected subscription. Your current subscription stays active until the end of your current billing period (monthly or yearly). No refunds are issued for the remaining time. Once ready, select Confirm . In the pop-up, review the warning and select Downgrade subscription . Add or review your billing address details and accept the Commercial API Terms of Use. Once ready, select Subscribe . A downgrade takes effect at the start of your next billing cycle, and a new invoice will be sent to you 4 days prior to that. If the request is submitted less than 4 days before renewal, the invoice for the upcoming cycle is generated immediately. For the downgraded plan to become active, the invoice for the new plan must be created and paid. Otherwise, the account will be automatically moved to the Dev (Free) Plan. Cancelling an active, downgrading, or upgrading subscription If you have changed your mind, you can cancel: Active subscription Upgrade request Downgrade request To cancel: In the upper-right corner of the page, click the windows icon and select Subscription . In the list, select the subscription you want to cancel (upgrade and downgrade requests are in Pending status). Under the subscription summary, select Cancel subscription . In the pop-up, review the warning and select Cancel subscription . When cancelling an active subscription, it remains active until the end of the current billing period. No refunds are issued for the remaining time of the active period. https://business.1inch.com/portal/support/article/11703585 Introduction The 1inch custom plan configurator is a flexible tool designed for users who want to build a subscription plan tailored to their specific business needs and use cases. It provides the freedom to select the APIs you require, set custom rate limits for Requests Per Second (RPS) and Requests Per Month (RPM), and choose your preferred payment cycle. The configurator is available to anyone with an account in 1inch Business and completed KYC/KYB verification . If this verification hasn't been completed yet, users can easily start the process directly from the configurator page without interrupting their session. With the custom plan, you can: Choose which APIs to include in your plan. Define custom RPS and RPM limits for each API. Select your payment cycle. Add additional users. Manage API keys. Add applications that will use the selected APIs. How to create a custom plan While logged in to your 1inch Business account, go to the custom plan configurator . Click + next to the APIs you want to customize for your plan. For each added API, select the desired RPM and RPS limits. From Pre-payment period , select how often you would like to pay for the plan. Review your choice and click Continue to proceed. In the next screen, customize the number of Users , Applications , and API keys if necessary. Click Continue to proceed. If your KYC/KYB verification is not finished yet, you'll have to complete it before moving on to the payment. Review your billing information, agree to the terms of use, and click Continue . Review your purchase and click Confirm and Pay to finalize the payment through your wallet of choice. If you haven't connected a wallet yet, click Connect wallet and follow the on-screen instructions. After your payment is successfully processed, your custom plan will become active. The start date of your new billing cycle will be set based on the date your invoice was paid. If you had any unused limits remaining from your previous paid plan, the value of those unused limits will be deducted from the first payment for your custom plan. https://business.1inch.com/portal/support/article/10214433 The API top-up feature allows you to independently increase your monthly API call quota without the need to upgrade your subscription. This self-service capability allows you to efficiently respond to increased demand, ensuring operational continuity and flexibility. The top-up feature is especially useful during periods of unexpected demand or for handling special projects that require additional API capacity. Top-up details You can top up your current subscription plan with increments of 100,000 additional API calls. Additional calls are strictly available for the current billing cycle and provide a temporary enhancement to meet your immediate requirements. Note that any unused calls from the top-up do not carry over into the next month. The top-up feature also provides flexibility in specifying the type of 1inch API that needs additional capacity. You can allocate the top-up to specific APIs based on your project requirements, ensuring that resources are directed where they are most needed. The API top-up feature exclusively increases the number of API calls available. The rate of requests per second (RPS) remains unchanged and continues to align with the limits defined by your current subscription plan. If an increase in RPS is required, consider upgrading to a higher-tier plan. Steps to top up your account with additional requests Step 1: Fill in your basket Navigate to the main dashboard of your 1inch Business account. Under Requests usage, click Top up . From the drop-down, select the product to which you want to allocate additional requests and specify the amount. If you need several products to be topped up, click Add product and repeat the step for each product. Click Confirm to proceed. Step 2: Complete KYC or KYB verification (optional) At this stage, KYC/KYB completion may be required. This is a one-time action, and you won't have to verify your identity with each subsequent top-up. The verification is conducted by the third-party service, Sumsub. To learn more about the process, see Registration / KYC requirement . To start the process, click Proceed to Verification . Follow the on-screen instructions to complete your verification. Step 3: Confirm billing details If you previously entered your billing information, it will be auto-filled. However, the fields are still editable. If you edit your billing details in this step, they will be automatically updated throughout 1inch Business after you proceed to the next step. If some or all of your billing information is missing, add it manually. Review your billing details and ensure you have filled in all mandatory fields. Accept the terms of usage and click Confirm to proceed. Step 4: Make a payment Confirm the payment and proceed using your wallet. If you haven't connected a wallet before, you will be prompted to connect one at this stage. Follow the on-screen instructions to connect your crypto wallet and proceed with the payment. Once your wallet is connected, select the currency and network for your payment. Review the payment details and click Send to finalize the payment. https://business.1inch.com/portal/support/article/9037727 If you've completed a new plan purchase or your renewal is due, there are two ways to get the invoice: For every payment that is due, we dispatch the corresponding invoice directly to your billing email address. This document is provided as a PDF attachment for your convenience. In your 1inch Business account, navigate to Subscription > Invoices and download the invoice you require in PDF format. Questions, comments, concerns? Feel free to reach out in the live support chat! https://business.1inch.com/portal/support/article/9389950 To ensure seamless management of your subscription, it's important to use the designated 1inch Business payment system when settling your bill. Steps to complete an invoice payment 1. Log in to your 1inch Business account. 2. On the payment awaiting banner, click Proceed with payment . 3. Connect your wallet via 1inch Business wallet connect plugin and follow the on-screen instructions to complete the payment. 4. Review the amount, then click Confirm and Pay . Once the transaction succeeds on-chain, your payment will be complete. Any payments made outside of 1inch Business payment plugin will not be automatically recognized and associated with your account. This might lead to delays in the activation or renewal of your plan, so it's highly recommended that you process your payments through 1inch Business only. Payments FAQ When is the invoice for subscription renewal issued? The invoice is issued 4 days before the start of your new subscription cycle. Will paying the renewal invoice earlier change the renewal date of my subscription cycle? No, paying the invoice earlier does not alter the renewal date of your subscription cycle. When will all plan features activate for my renewed subscription? All plan features will activate on the scheduled start date of the cycle. Unless the payment has been made outside 1inch Business payment plugin. If you encounter any issues or have questions regarding the payment process, contact our Support Team for assistance through the live support chat. We're here to help ensure that your experience is smooth and hassle-free. https://business.1inch.com/portal/support/article/8703748 Pricing and upgrades for 1inch Business subscription plans When you create an account yourself in 1inch Business, it's automatically assigned the Dev plan , which is free of charge and comes with limits of 1 Request Per Second (RPS) and a total of 100,000 monthly calls . Higher rate limits are available at the following predefined paid plans: Start-Up: 10 RPS within 1,000,000 monthly calls Professional: 20 RPS within 3,000,000 monthly calls Business: 40 RPS within 7,000,000 monthly calls These base limits for the Dev plan--and for any predefined subscription plans--apply specifically to the set of swap APIs : Classic Swap , Intent Swap , Cross-Chain Swap , and the Orderbook API . In addition to the Swap APIs, there are other useful APIs available for all paid plans . These additional APIs have their own limits of 1 RPS and 100,000 monthly calls and include: History API Traces API Portfolio API Balance API Gas Price API Spot Price API Token API NFT API Transaction Gateway API Web3 RPC API Charts API Domains API Token Details API If the predefined plans don't meet your needs in terms of request limits per second or month--or if you'd like more flexibility in accessing additional APIs--you can create a Custom plan tailored to your requirements . With a Custom plan, you can choose which APIs to include, define your preferred rate limits, select your payment cycle, and adjust other parameters to fit your specific use case. For details, see How to customize your subscription plan . Projects that reach a swap volume of US$10 million through 1inch Business will automatically be upgraded to a Custom plan, requiring communication with the 1inch representative. This plan typically includes a revenue share agreement based on the swap volume. The same condition is extended to entities requiring increased requests per second (RPS) for all other APIs (excluding the 1inch swap APIs). If neither the predefined nor custom plans fully meet your requirements--particularly if you expect high traffic volumes and need significantly higher rate limits-- submit a request for an Enterprise plan . The 1inch Team will be happy to help design a solution tailored to your specific needs. For a successful upgrade to the Enterprise, the following steps need to be fulfilled: Confirmation of the package and billing cycle. KYC/KYB verification, depending on your entity type. Filling in the billing information and accepting the terms of use. Payment of the total due using USDC cryptocurrency on the Ethereum network. Questions, comments, concerns? Feel free to reach out to us in the Live Support Chat! https://business.1inch.com/portal/support/article/12398075 How are API plans priced for usage spikes and overages? API plans are not billed dynamically for short usage spikes. Each plan has fixed request limits (RPS and RPM). If you exceed those limits, requests are blocked with a 429 response rather than incurring overage charges. To handle higher or spiky workloads, you can move to a higher tier, customize your plan , or negotiate enterprise terms . Can I have separate rate limits per product or API keys? Standard plans apply limits broadly. However, you can use the Custom plan configurator to set the RPS and call limits for each type of API. API keys share the RPS and call limits across the account. Do paid tiers include historical data retention (API calls and statistics)? Yes. All paid plans of 1inch API include at least 30 days of data retention, while higher tiers may extend this to 90 days, depending on the package. Does 1inch provide extended data retention for Enterprise plan? Yes. Enterprise plans provide extended statistics retention for up to 180 days. This allows deeper insights into historical API usage and performance monitoring. You can explore this feature in the statistics section of the portal. Is SSO (Single Sign-On) available in 1inch API plans? Yes, with the Enterprise plan, SSO can be negotiated and configured based on the SAML provider used. How are quotas and billing managed across teams and projects? Billing and quotas are tied to your subscription plan in 1inch Business. Each plan defines limits, such as Requests Per Second (RPS) and Requests Per Month (RPM), which are reset monthly. You can choose between monthly or annual billing intervals or even negotiate it with your sales associate, depending on your needs. If you occasionally exceed your quota, you can purchase top-ups for extra requests beyond your plan's limits. Where can I find the security audits done by 1inch? Security is a top priority at 1inch. Every major protocol upgrade and smart contract deployment undergoes independent audits by established blockchain security firms. All completed audit reports are published on the official 1inch GitHub repository for audits . Does the enterprise plan include dedicated support? Every enterprise customer is assigned a dedicated relationship manager who guides them through the entire enterprise lifecycle. The onboarding and support process is fully tailored to a customer's specific needs, ensuring personalized assistance and long-term partnership. https://business.1inch.com/portal/support/article/12351066 What is Ethereum and why build on Ethereum Mainnet? Ethereum Mainnet is the primary public Ethereum production blockchain where ETH and tokens carry real economic value, where real assets are traded, and smart contracts run with full decentralization and security. Building on Mainnet gives access to the largest liquidity, most users, and a mature ecosystem--which is critical for many DeFi use cases. What is the Ethereum JSON-RPC, and which methods do dApps use most? The Ethereum JSON-RPC is a standard protocol that lets dApps and wallets interact with Ethereum nodes to read blockchain state (balances, blocks, logs) or send transactions. Common methods include eth_call , eth_getBalance , eth_getTransactionReceipt , eth_estimateGas , eth_getLogs , and block-query methods (e.g., eth_blockNumber , eth_getBlockByNumber ). Do 1inch endpoints on Ethereum support WebSocket RPC? 1inch offers Web3 RPC API endpoints over HTTP for major EVM chains, as well as WebSocket support for all existing Web3 RPC methods. Is the archive state (including eth_getLogs) available on Ethereum via 1inch? Yes. The 1inch Web3 RPC API offers access to historical data (logs, past blocks, events), which lets you query older state and past logs via methods like eth_getLogs . How do I estimate gas on Ethereum via API? You can use the 1inch Gas Price API, which provides up-to-date gas price data for various blockchains, including Ethereum. How to avoid RPC rate limits on high-throughput Ethereum apps? To avoid rate limits, you can: Use 1inch Business plan configurator to configure and customize the RPS and Web3 calls based on your needs, rather than public or shared endpoints. Use WebSockets. https://business.1inch.com/portal/support/article/12380488 How are API plans priced for usage spikes and overages? API plans are not billed dynamically for short usage spikes. Each plan has fixed request limits per second and per minute (RPS and RPM). If you exceed those limits, requests are blocked with a 429 response rather than incurring overage charges. To handle higher or spiky workloads, you can upgrade, customize your plan, or negotiate enterprise terms. Where can I check API status and uptime? For uptime or incident updates, contact 1inch Support. Can I have separate rate limits per product or API keys? Standard plans apply limits broadly. But you can use the custom plan configurator and set the RPS and calls limit at the API Product level. The API keys share the RPS and call limits across the account. Do paid tiers include historical data retention (API calls and statistics)? Yes, all 1inch Business paid plans include a minimum data retention of 30 days, with some tiers offering up to 90 days of retention depending on the package selected. What happens when I upgrade to a higher plan? The upgrade takes effect immediately after you pay the invoice. Any unused calls or credits from your current billing period are automatically applied as a discount toward the new plan, and you only pay the difference. What happens when I downgrade my plan? Downgrades take effect at the start of your next billing cycle. No refunds or unused quota transfers are provided when moving to a lower plan. I submitted a downgrade right before renewal. What happens? The downgrade will still take effect at the end of your current billing cycle. However, if you submit it less than 4 days before renewal, the invoice for the next cycle is generated immediately. What if my renewal payment has already been processed? If the renewal has already gone through, your downgrade will apply after one more billing cycle: a month or a year, depending on your subscription. How do I activate my downgraded plan? To activate your downgraded plan, you must create and pay the invoice for it. If payment isn't completed, your account will be switched to the Dev (Free) Plan. I changed my mind--can I undo the downgrade? Sure! You can cancel your downgrade request anytime before the next billing cycle begins. What happens when I cancel my subscription? Your subscription stays active until the end of your current billing period (monthly or yearly). No refunds are issued for the remaining time--you'll keep access until the period ends. ## AI Integration https://business.1inch.com/portal/assets/docs-v2/ai-integration/ecosystem.md 1inch provides two complementary AI integration methods: the **MCP Server** -- a live protocol your AI assistant uses to execute swaps, place limit orders, query APIs, and access documentation -- and **AI Skills** -- reusable instruction packages that teach agents the setup patterns. Both are free to connect, work together, and share the same [authentication](#authentication). ## MCP Server The 1inch MCP Server is an **AI-native integration**: your editor or CLI agent speaks to 1inch over the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) so it can execute token swaps, place limit orders, query portfolio and price data, and pull documentation -- all through natural conversation. **Cost and access:** There is **no separate charge** to connect to the MCP server. **Swap**, **Orderbook**, **Business API access**, and the **`debug`** tool use the same authentication and API entitlements as the rest of the 1inch Business / developer stack (standard API terms apply to those calls). Documentation search, the example catalog, and example source work **without authentication**, so you can start exploring immediately. The server is hosted at `https://api.1inch.com/mcp/protocol` For setup instructions per client, see [Supported Clients](supported-clients.md). :::tip For AI agents and automation that don't use MCP, see our [LLM-optimized documentation](/llms.txt) -- a machine-readable index of all APIs following the [llmstxt.org](https://llmstxt.org) specification. ::: ### MCP Server capabilities The MCP server exposes **seven tools**. The first three are public; the rest require [authentication](#authentication). | Tool | Auth | Description | | :-------------- | :------- | :--------------------------------------------------------------------------------------------- | | `swap` | Required | Build quotes and execution steps for classic (Pro), intent (Fusion), and cross-chain swaps | | `orderbook` | Required | Build, sign, submit, list, and cancel limit orders via the 1inch Orderbook API | | `product_api` | Required | Call 1inch Business product APIs (Portfolio, Spot Price, Token, Gas Price, Web3 RPC, and more) | | `debug` | Required | Debug production issues: look up request logs by correlation id or time window | | `search` | Public | Search documentation and API reference | | `list_examples` | Public | List available SDK code examples | | `get_example` | Public | Retrieve full example source (TypeScript, Go, Python, etc.) | Full parameter reference: [Available tools](#available-tools). ## AI Skills The **1inch AI Skill** is a reusable instruction package that teaches AI agents how to connect to and use the 1inch MCP server -- the production URL, available tools, authentication setup, and client configuration patterns. Install it once and your agent knows the setup automatically. ```bash npx skills add 1inch/1inch-ai ``` Source and full details: [github.com/1inch/1inch-ai](https://github.com/1inch/1inch-ai) Use both together: the skill teaches your agent _how_ to connect; MCP provides the _live connection_. ## Authentication The public tools (`search`, `list_examples`, `get_example`) work **without authentication**. The execution tools (`swap`, `orderbook`, `product_api`, `debug`) require authentication via either an API key or OAuth. ### API key Pass your 1inch API key via the `Authorization: Bearer ` header. Get a key from the [1inch Business Portal](https://business.1inch.com/portal). How to set the header depends on your MCP client -- see the [Authentication setup](supported-clients.md#authentication-setup) section in Supported Clients for client-specific configuration. ### OAuth When you call an authenticated tool without an API key, MCP clients that support OAuth will automatically prompt you to log in via the 1inch Business Portal. After authentication, all tools become available for the duration of your session. For all supported OAuth flows including `client_credentials` for server-to-server use, see [OAuth 2.1](/documentation/apis/authentication#oauth-21). ## Agentic use "Agentic" here means your **client runs a tool loop**: the model decides which MCP tools to call, uses the results, and may call again until the task is done. You describe the outcome; the agent plans steps. ### Typical tool chains | Goal | How the agent usually proceeds | | :------------------------ | :--------------------------------------------------------------------------------------------------------------- | | Swap or quote exploration | Swap tool for quotes / steps; combine with doc search for mode differences (classic vs Fusion vs cross-chain) | | Place a limit order | Orderbook tool to build the order server-side -> sign the returned typed data -> submit back via orderbook | | Operational checks | Business API tool for token metadata, gas, spot price, portfolio P&L, etc., then map results back into your code | | Debug production issues | **`debug`** with a request id from API responses or a time window to retrieve logs for your account | | New feature in your repo | Documentation search -> example catalog -> example source -> apply or refactor code in your project | | Correct API usage | Search docs for parameters and errors -> cross-check with an example -> suggest headers, chains, and payloads | You do not need to name each tool: a capable client exposes them to the model; prompts like "swap 100 USDC to ETH on Base" or "find the official swap example" are enough. ### Prompt patterns that work well for agents - **Direct execution:** "Swap 100 USDC to ETH on Base from my wallet 0x1234..." - **Multi-step flows:** "Place a limit order to sell 1000 USDC for 1000 USDT on Ethereum, expiring in 1 hour." - **Outcome first:** "Implement ERC-20 -> USDC swap on Base in TypeScript; use 1inch MCP for docs and examples, then wire it into `src/swap.ts`." - **Operational queries:** "What's my portfolio P&L on Ethereum?" or "What's the current gas price on Base?" - **Verify against examples:** "Fetch the closest SDK example from MCP, then diff our `quote()` call against it." ### MCP vs `llms.txt` for agents | | MCP | [`/llms.txt`](/llms.txt) | | :--------------------- | :---------------------------------------------------------------------- | :----------------------------------------------------- | | **Best for** | Agentic execution (swaps, orders, APIs) + interactive coding assistants | Bulk context, custom RAG, CI jobs, clients without MCP | | **Freshness** | Live API access + server-side search (periodically indexed) | Snapshot index you fetch and chunk yourself | | **Authenticated APIs** | Yes -- swaps, orderbook, portfolio, gas, spot price, debugging, and more | No -- static links and summaries only | Use both if you split work: e.g. `llms.txt` in a pipeline for broad grounding, MCP in the IDE for grounded examples and tool-backed answers. ### Limits and responsibility - **Sessions:** See [Too many sessions (429)](supported-clients.md#troubleshooting)--each client window may count as a session; agents should avoid spawning unbounded parallel MCP connections. - **Approvals:** Your client may ask you to approve tool calls, especially OAuth or API writes. The MCP server does not bypass your org's access rules. - **Secrets:** Pass API keys or headers only as documented for your client (e.g. `supergateway` `--header`); never commit credentials. ## Available tools The 1inch MCP Server provides seven tools. Four execution tools require [authentication](#authentication); three public tools work without it. ### Authenticated tools (API key or OAuth) These tools require [authentication](#authentication). You can authenticate via an API key header or OAuth -- see [Authentication setup](supported-clients.md#authentication-setup) for client-specific configuration. #### swap Execute token swaps via 1inch. The server automatically finds the best rate across all available routes, handles token resolution, allowance checks, and transaction building -- the agent only signs transactions where required. Supports same-chain and cross-chain swaps. | Parameter | Type | Required | Description | | :-------------- | :------ | :------- | :-------------------------------------------------------------- | | `src` | string | Yes | Source token (symbol or address) | | `dst` | string | Yes | Destination token (symbol or address) | | `amount` | string | Yes | Amount in smallest units | | `chain` | number | Yes | Chain ID | | `from` | string | Yes | Sender wallet address | | `quoteOnly` | boolean | No | If true, returns quotes without building a transaction | | `preferredType` | string | No | `"classic"`, `"fusion"`, or `"crosschain"` (omit to auto-route) | | `dstChain` | number | No | Destination chain ID (triggers cross-chain mode) | | `slippage` | number | No | Slippage tolerance in percent (default 0.5) | | `signedOrder` | string | No | Submit a previously signed Fusion/cross-chain order | | `orderHash` | string | No | Order hash for submission | **Typical flow:** 1. Call `swap` with source/destination tokens and amount -- the server finds the best rate automatically 2. Sign the returned transaction (`eth_sendTransaction`) or typed data (`eth_signTypedData_v4`) 3. For Fusion/cross-chain: call `swap` again with the `signedOrder` to submit #### orderbook Manage limit orders via the 1inch Orderbook API (v4.1). The server builds orders server-side using the Limit Order SDK -- no SDK installation needed on the client. **Actions:** | Action | Description | | :------- | :----------------------------------------------------------------------- | | `build` | Server-side order construction. Returns EIP-712 typed data for signing | | `create` | Submit a signed order to the orderbook | | `list` | Query orders by maker address, order hash, or browse all with pagination | | `cancel` | Load order state and return on-chain cancellation guidance | **Build parameters:** | Parameter | Type | Required | Description | | :------------------ | :----- | :------- | :----------------------------------- | | `action` | string | Yes | `"build"` | | `chain` | number | Yes | Chain ID | | `makerAsset` | string | Yes | Token to sell (symbol or address) | | `takerAsset` | string | Yes | Token to receive (symbol or address) | | `makingAmount` | string | Yes | Amount to sell (smallest units) | | `takingAmount` | string | Yes | Amount to receive (smallest units) | | `maker` | string | Yes | Maker wallet address | | `expirationSeconds` | number | No | Expiration in seconds (default 600) | **Typical flow:** 1. Call `orderbook` with `action: "build"` and your order parameters 2. Approve the maker asset for the Limit Order Protocol contract (address provided in the response) 3. Sign the returned `typedData` with `eth_signTypedData_v4` 4. Call `orderbook` with `action: "create"`, passing `orderHash`, `signature`, and `orderData` from the build response #### product_api Call any 1inch Business product API endpoint using your authenticated session. This single tool provides access to **all** 1inch APIs: Portfolio, Spot Price, Token, Gas Price, Web3 RPC, Balance, NFT, Charts, Transaction Gateway, and every other endpoint available in the 1inch Business platform. For **Portfolio v5.0** through this gateway, use paths starting with `/portfolio/portfolio/v5.0/...` (the first `/portfolio` segment is stripped when routing to the Portfolio service). | Parameter | Type | Required | Description | | :-------- | :----- | :------- | :---------------------------------------------------------------- | | `method` | string | No | `"GET"` or `"POST"` (default `"GET"`) | | `path` | string | Yes | API path (e.g. `/portfolio/portfolio/v5.0/general/current_value`) | | `query` | object | No | Query parameters as key-value pairs | | `body` | object | No | Request body for POST requests | #### `debug` Debug production issues by looking up request logs. Provide a correlation id (`x-request-id` from any API response) to trace a specific request, or specify a time window to retrieve all logs for your account. | Parameter | Type | Required | Description | | :---------- | :----- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `requestId` | string | No\* | `x-request-id` (or correlation id) from API responses. When set, searches logs for this value; optional `startTime` / `endTime` narrow the window (defaults to the last 24 hours ending at `endTime` or now). | | `startTime` | string | No\* | RFC3339 start of the query window (required with `endTime` when `requestId` is omitted). | | `endTime` | string | No | RFC3339 end of the query window. | | `logLevel` | string | No | Filter by log level: `"info"`, `"warn"`, or `"error"`. Omit to return all levels. Only applies to time-window mode (ignored when `requestId` is set). | | `limit` | number | No | Max log lines (1-100, default 50). | \*Provide **`requestId`**, or both **`startTime`** and **`endTime`**, to list all logs in that window (when `requestId` is omitted). **Log retention:** The time window you can query depends on the log retention period of your subscription plan. **Response shape:** The tool returns JSON with `mode` (`request_id` or `logs`), `timeRange` (`start` / `end` in RFC3339), `count`, and `logs` (array of entries). Each entry includes timestamp, message, and optional level and HTTP status code. ### Public tools (no authentication required) #### search Search across all 1inch documentation, API references, and SDK guides. Returns matching results with titles, snippets, and links. | Parameter | Type | Required | Description | | :------------- | :------ | :------- | :------------------------------------ | | `query` | string | Yes | Search query | | `limit` | number | No | Results per page (1-100) | | `page` | number | No | Page number (1-based) | | `include_body` | boolean | No | Include full document body in results | #### list_examples List all available SDK code examples. Returns example names that can be used with the `get_example` tool. No parameters required. Currently available examples: - **@1inch-examples/intent-swap** -- Intent/Fusion swaps for EVM and Solana - **@1inch-examples/limit-order** -- Limit orders for EVM chains - **@1inch-examples/cross-chain-swap** -- Cross-chain swaps (Fusion+) #### get_example Retrieve the full source code of an SDK example. | Parameter | Type | Required | Description | | :-------- | :----- | :------- | :----------------------------------------- | | `name` | string | Yes | Example name from `list_examples` | | `file` | string | No | Specific file path (omit to get all files) | ## What you can do Once connected, you work through natural conversation. Your AI assistant calls the right tools behind the scenes. ### Execute token swaps Describe the swap you want ("swap 100 USDC to ETH on Base"), and the assistant automatically finds the best rate across all available routes, handles token resolution, allowance checks, and transaction building. You only need to sign the transaction. Supports same-chain swaps (classic and Fusion) and cross-chain swaps. ### Place limit orders Create limit orders without installing any SDK. Tell your AI "place a limit order to sell 100 USDC for 100 USDT on Ethereum", and the server builds the order server-side, returns the data for you to sign, and submits it to the orderbook. ### Query any 1inch API The `product_api` tool gives your AI access to **all 1inch Business product APIs** -- Portfolio, Spot Price, Token, Gas Price, Web3 RPC, Balance, NFT, Charts, Transaction Gateway, and more. Ask "what's my portfolio value on Ethereum?" or "what's the current gas price on Base?" -- every API endpoint available in the 1inch Business platform is accessible through this single tool. ### Debug production issues Use **`debug`** to trace a request by `x-request-id` or to list logs in a time range. Paste the correlation id from a failed API response and ask the assistant to pull the matching log lines. ### Search documentation and browse SDK examples Ask any question about 1inch APIs, supported chains, error codes, or integration patterns. Your AI searches across all documentation, API references, and SDK guides -- no manual browsing required. You can also pull complete, working code examples directly into your conversation in TypeScript, Go, or Python. :::info The examples are provided in TypeScript -- but your AI assistant can translate them into any language. Just ask for "the swap example in Java" or "convert this to Rust" and it will adapt the code for you. ::: ## Example prompts The following examples show the kinds of questions and requests that work well with the 1inch MCP Server and AI Skills. Use them as starting points and adapt to your specific use case. ### Executing swaps > "Swap 1000 USDC to ETH on Ethereum from my wallet 0x1234..." > "Find the best rate for swapping 0.5 ETH to USDT on Arbitrum." > "Swap 100 USDC from Base to Polygon." The assistant calls the swap tool, automatically finds the best rate and route, and returns the transaction or typed data for you to sign. ### Managing limit orders > "Place a limit order to sell 1000 USDC for 1000 USDT on Ethereum, expiring in 1 hour." > "List my active limit orders on Ethereum for wallet 0x1234..." > "Check the status of order 0xabc..." The assistant builds orders server-side, guides you through signing, and submits to the orderbook. ### Querying portfolio and token data > "What's my portfolio P&L on Ethereum for wallet 0x1234...?" > "What's the current price of 1INCH in USD?" > "What's the gas price on Base right now?" The assistant calls the appropriate product API endpoint and returns the data directly. ### Debugging with production logs > "Here's my x-request-id from a 500 response -- pull the server logs." > "List logs between 2026-01-15T00:00:00Z and 2026-01-15T23:59:59Z." The assistant calls **`debug`** with your request id or time window and returns the matching log entries. ### Debugging and troubleshooting > "My swap transaction is returning a 400 error. What are the common causes?" > "I'm getting CORS errors when calling the 1inch API from my frontend. How do I fix this?" > "The approval transaction succeeded but the swap still fails with 'insufficient allowance'. What should I check?" The assistant searches the FAQ and API documentation for known issues and solutions specific to your error. ### Starting a new integration > "I'm building a swap feature on Base. Show me a complete TypeScript example for swapping ERC-20 tokens using the 1inch API." > "I need to integrate 1inch swaps into my Go backend service. Show me how to use the Go SDK." > "How do I call the 1inch swap API from Python?" The assistant retrieves the relevant SDK example with full source code -- including wallet setup, token approval, swap execution, and error handling -- in the language you need, ready for you to adapt. ### Getting code for specific scenarios > "Show me how to swap native ETH to USDC on Base, including gas estimation." > "Get the Solana swap implementation with proper error handling." > "How do I check and set token allowance before executing a swap in Go?" > "Show me how to set up a viem provider configured for 1inch on Arbitrum." > "Show me a working cross-chain swap example between Ethereum and Base." The assistant retrieves the matching documentation and example files in your language, and highlights the relevant sections for your scenario. ### Understanding APIs and parameters > "What authentication method does the 1inch API use? Show me the header format." > "What parameters does the swap endpoint accept, and which ones are required?" > "What chains and chain IDs does 1inch support?" > "How does the orderbook API work for limit orders?" The assistant searches the API reference and returns the specific details you need, with links to the full documentation for deeper reading. ### Prompting tips To get the most out of the MCP Server: - **Just say what you want done.** "Swap 100 USDC to ETH on Base" or "place a limit order for 1000 USDT on Ethereum" -- the assistant handles the rest. - **Mention your chain.** Saying "on Base", "on Arbitrum", or "cross-chain from Ethereum to Polygon" helps the assistant pick the right route immediately. - **Combine execution with research.** The assistant maintains context, so you can ask "what's the best rate for this swap?" then follow up with "now execute it" and "show me how to handle the error I got" -- all in the same session. - **Ask about trade-offs.** Questions like "What's the best way to handle large swaps?" or "When should I use limit orders instead of swaps?" get you a tailored recommendation backed by the documentation. - **Ask for examples when building features.** When you need working code, ask for an SDK example -- the examples are tested, complete implementations that give the AI better context to help you. - **Iterate on the code.** Once the assistant retrieves an example, ask follow-up questions: "Now adapt this for USDT instead of USDC" or "Add retry logic for failed transactions." ## Legal Disclaimer Use of the 1inch MCP Server is subject to the [1inch Business Portal Terms of Service](/portal/assets/legal-docs/terms_of_service_public_api_20260218.pdf) and the applicable [Software Legal Notice](/portal/assets/legal-docs/software_policy_20260218.pdf). Users are responsible for ensuring compliance with applicable regulations. https://business.1inch.com/portal/assets/docs-v2/ai-integration/supported-clients.md The 1inch [MCP Server](ecosystem.md) and [AI Skills](ecosystem.md#ai-skills) work with a wide range of AI coding assistants. This page covers setup instructions, authentication configuration, and troubleshooting for each supported client. ## Supported clients | Client | MCP Setup | AI Skills | | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------- | :--------------------------------- | | Claude Desktop | [Instructions](#claude-desktop) | [Install](#ai-skills-installation) | | Claude Code | [Instructions](#claude-code) | [Install](#ai-skills-installation) | | OpenAI Codex | [Instructions](#openai-codex) | [Install](#ai-skills-installation) | | Gemini CLI | [Instructions](#gemini-cli) | [Install](#ai-skills-installation) | | Cursor | [Instructions](#cursor) | [Install](#ai-skills-installation) | | Windsurf | [Instructions](#windsurf) | [Install](#ai-skills-installation) | | VS Code (Copilot) | [Instructions](#vs-code-copilot) | [Install](#ai-skills-installation) | | JetBrains IDEs | [Instructions](#jetbrains-ides) | [Install](#ai-skills-installation) | The following clients are also MCP-compatible and can connect using the [generic setup](#other-mcp-clients) below: - **Continue** -- open-source AI assistant for VS Code and JetBrains - **Zed** -- AI-native code editor - **Amazon Q Developer** -- AWS AI coding assistant MCP is an open standard with rapidly growing adoption. Any MCP-compatible client can connect to the 1inch MCP Server. ## MCP Server setup ### Claude Code Claude Code supports HTTP MCP servers natively: ```bash claude mcp add \ --transport http \ --scope user \ 1inch-business \ https://api.1inch.com/mcp/protocol ``` ### OpenAI Codex Codex supports MCP servers in both the CLI and the VS Code extension: ```bash codex --mcp-server "https://api.1inch.com/mcp/protocol" ``` For the VS Code extension, add the server in the Codex MCP settings panel with the same URL. ### Gemini CLI Gemini CLI supports HTTP MCP servers natively: ```bash gemini mcp add \ --transport http \ 1inch-business \ https://api.1inch.com/mcp/protocol ``` ### Claude Desktop Claude Desktop communicates via stdio, so you use [`supergateway`](https://www.npmjs.com/package/supergateway) to bridge to the HTTP server. This requires Node.js 18+. Add the following to your configuration file: - **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json` - **Windows:** `%APPDATA%\Claude\claude_desktop_config.json` ```json { "mcpServers": { "1inch-business": { "command": "/absolute/path/to/node/bin/npx", "args": [ "-y", "supergateway", "--streamableHttp", "https://api.1inch.com/mcp/protocol", "--outputTransport", "stdio" ], "env": { "PATH": "/absolute/path/to/node/bin:/usr/bin:/bin" } } } } ``` Replace `/absolute/path/to/node/bin` with the path to your Node.js installation (e.g., `/usr/local/bin` or the output of `dirname $(which node)`). :::info The `command` and `PATH` fields require absolute paths because AI clients do not inherit your shell's PATH. Using `npx -y` ensures the latest version of `supergateway` is downloaded automatically. ::: ### Cursor Create or edit `.cursor/mcp.json` in your project root: ```json { "mcpServers": { "1inch-business": { "url": "https://api.1inch.com/mcp/protocol" } } } ``` ### Windsurf Create or edit `~/.codeium/windsurf/mcp_config.json`: ```json { "mcpServers": { "1inch-business": { "serverUrl": "https://api.1inch.com/mcp/protocol" } } } ``` ### VS Code (Copilot) Create or edit `.vscode/mcp.json` in your project root: ```json { "servers": { "1inch-business": { "type": "http", "url": "https://api.1inch.com/mcp/protocol" } } } ``` :::info VS Code also supports configuring MCP servers through `settings.json` under the `"mcp"` key. See the [VS Code MCP documentation](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) for additional options. ::: ### JetBrains IDEs IntelliJ IDEA, WebStorm, PyCharm, and other JetBrains IDEs support MCP through the AI Assistant (2025.1+). 1. Open **Settings** -> **Tools** -> **AI Assistant** -> **Model Context Protocol (MCP)** 2. Click **Add**, select **HTTP**, and paste the following JSON snippet: ```json { "mcpServers": { "1inch-business": { "url": "https://api.1inch.com/mcp/protocol" } } } ``` The 1inch MCP tools will be available in the AI Assistant chat within your IDE. ### Other MCP clients Most MCP clients support HTTP transport and can connect directly to the server URL: - **Server URL:** `https://api.1inch.com/mcp/protocol` For clients that only support stdio transport, use [`supergateway`](https://www.npmjs.com/package/supergateway) to bridge to the HTTP server (requires Node.js 18+): ```bash npx -y supergateway \ --streamableHttp https://api.1inch.com/mcp/protocol \ --outputTransport stdio ``` Configure your client to launch this as a subprocess and communicate over stdin/stdout. ## AI Skills installation Install the 1inch AI Skill so your agent knows the server URL, tools, and auth patterns automatically: ```bash npx skills add 1inch/1inch-ai ``` No npm package required -- distribution is git-based. For more details, see [AI Skills](ecosystem.md#ai-skills). For **stdio-only** clients (e.g. Claude Desktop), the skill documents the same URLs and auth patterns, but you still need the [supergateway setup](#claude-desktop) above for the actual MCP connection. ## Authentication setup The public tools (`search`, `list_examples`, `get_example`) work without authentication. To use the execution tools (`swap`, `orderbook`, `product_api`, `debug`), pass your API key via the `Authorization` header. Get a key from the [1inch Business Portal](https://business.1inch.com/portal). For the conceptual overview of API key vs OAuth authentication, see [Authentication](ecosystem.md#authentication). **Claude Code:** ```bash claude mcp add \ --transport http \ --header "Authorization: Bearer YOUR_API_KEY" \ --scope user \ 1inch-business \ https://api.1inch.com/mcp/protocol ``` **Cursor** (`.cursor/mcp.json`): ```json { "mcpServers": { "1inch-business": { "url": "https://api.1inch.com/mcp/protocol", "headers": { "Authorization": "Bearer YOUR_API_KEY" } } } } ``` **VS Code Copilot** (`.vscode/mcp.json`): ```json { "servers": { "1inch-business": { "type": "http", "url": "https://api.1inch.com/mcp/protocol", "headers": { "Authorization": "Bearer YOUR_API_KEY" } } } } ``` **Claude Desktop** (supergateway): ```json { "mcpServers": { "1inch-business": { "command": "/absolute/path/to/node/bin/npx", "args": [ "-y", "supergateway", "--streamableHttp", "https://api.1inch.com/mcp/protocol", "--header", "Authorization: Bearer YOUR_API_KEY", "--outputTransport", "stdio" ], "env": { "PATH": "/absolute/path/to/node/bin:/usr/bin:/bin" } } } } ``` For other clients, consult the client's MCP documentation for how to set custom HTTP headers on the transport. ## Troubleshooting | Issue | Solution | | :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Connection refused | Verify the `command` path is absolute. Check that `https://api.1inch.com/mcp/protocol` is reachable from your network | | Server not appearing | Restart your AI client after modifying the configuration file. Check that the JSON is valid (no trailing commas) | | `npx` not found | Ensure Node.js 18+ is installed. Use an absolute path to `npx` in the `command` field (e.g., `/usr/local/bin/npx`) | | Too many sessions (429) | Each AI client window opens a separate session. Close windows you're not using, or wait 15 minutes for idle sessions to expire. This limit is specific to MCP sessions and does not affect your API usage | | Tools not loading | Check the AI client's MCP logs for connection errors. In Cursor, use **Developer: Open MCP Log** from the command palette | | Auth prompt not appearing | If using OAuth, ensure your MCP client supports OAuth flows. Alternatively, use an API key via the `Authorization` header (see [Authentication setup](#authentication-setup)). Some clients may require a restart after configuration changes | | Stale results | Documentation indexes are updated periodically. If recently published content is missing, try again in a few minutes | ## Optional https://business.1inch.com/portal/assets/docs-v2/apis/swap/intent-swap/migration/migration-v10-v20.md # Migration from v1.0 to v2.0 Following changes must be done to migrate from v1.0 to v2.0 ## Quoter Request Data changed ### Request Adding of parameter:\ `isPermit2`: permit2 allowance transfer encoded call ## Relayer Request Data changed ### Request Removing of parameter:\ `allowedSender`\ `offsets`\ `interactions` Adding of parameter:\ `extension` https://business.1inch.com/portal/assets/docs-v2/apis/swap/classic-swap/migration/migration-v50-v52.md Following changes must be done to migrate from v5.0 to v5.2 ## Parameter change for /quote ### Request Renaming of parameter:\ `fromTokenAddress` -> `src`\ `toTokenAddress` -> `dst` ### Added new parameter optional query params: `includeTokensInfo: boolean` - Return fromToken and toToken info in response\ `includeProtocols: boolean` - Return used swap protocols in response\ `includeGas: boolean` - Return approximated gas in response ### Response: Renaming of parameter:\ `estimatedGas` -> `gas`\ `toTokenAmount` -> `toAmount` ### Specialities: By default only `toAmount` will be in the response. Additional parameter can be activated by additional parameters. ## Parameter change for /swap ### Request Renaming of parameter:\ `fromTokenAddress` -> `src`\ `toTokenAddress` -> `dst`\ `fromAddress` -> `from`\ `destReceiver` -> `receiver`\ `referrerAddress` -> `referrer`\ `compatibilityMode` -> `compatibility` ### Added new parameter optional query params: `includeTokensInfo: boolean` - Return fromToken and toToken info in response\ `includeProtocols: boolean` - Return used swap protocols in response\ `includeGas: boolean` - Return approximated gas in response ### Response: Renaming of parameter:\ `toTokenAmount` -> `toAmount` ### Specialities: By default only `toAmount` and `tx` will be in the response. Additional parameter can be activated by additional parameters. https://business.1inch.com/portal/assets/docs-v2/apis/swap/classic-swap/migration/migration-v52-v60.md ## Parameter change for /quote ### Response Renaming of parameter:\ `fromToken` -> `srcToken`\ `toToken` -> `dstToken`\ `toAmount` -> `dstAmount` ## Parameter change for /swap ### Added new parameter optional query params: `usePermit2: boolean` - use Permit2 for approval ### Response: Renaming of parameter:\ `fromToken` -> `srcToken`\ `toToken` -> `dstToken`\ `toAmount` -> `dstAmount` https://business.1inch.com/portal/assets/docs-v2/apis/swap/classic-swap/migration/migration-v60-v61.md The following changes must be made when migrating from v6.0 to v6.1. ## Changes in `/swap` and `/quote` responses ### Structural updates - The `protocols[][][]` structure remains, but the format of protocol data has changed. - `fromTokenAddress` and `toTokenAddress` have been removed. Instead, a single `token` field is used at a higher level. ### Changed and renamed parameters - `fromTokenAddress` -> Removed (source token is now referenced at the top level). - `toTokenAddress` -> Removed (destination is now handled via `dst`). - `name` -> Moved inside protocols array within `swaps`. - `part` -> Now nested inside `swaps` and `protocols`. Compare the old version of that part of response with a new one below. ### Old response example ```json "protocols": [ [ [ { "name": "UNISWAP_V2", "part": 2, "fromTokenAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "toTokenAddress": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" }, { "name": "UNISWAP_V4", "part": 2, "fromTokenAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "toTokenAddress": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" }, { "name": "SUSHI", "part": 4, "fromTokenAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "toTokenAddress": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" }, { "name": "UNISWAP_V3", "part": 6, "fromTokenAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "toTokenAddress": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" }, { "name": "UNISWAP_V3", "part": 86, "fromTokenAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "toTokenAddress": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } ], //... ] ] ``` ### New response example ```json "protocols": [ { "token": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "hops": [ { "part": 62.5, "dst": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "fromTokenId": 0, "toTokenId": 1, "protocols": [ { "name": "UNISWAP_V4", "part": 1 }, { "name": "CURVE_V2_TRICRYPTO_NG", "part": 1 }, { "name": "UNISWAP_V3", "part": 1 }, { "name": "UNISWAP_V2", "part": 3 }, { "name": "UNISWAP_V3", "part": 5 }, { "name": "UNISWAP_V3", "part": 20 }, { "name": "FLUID_DEX_T1", "part": 69 } ] } //... ] } ] ``` For full schemas, see [Swagger documentation for the `/swap` and `/quote` endpoints](../methods/swagger.md). :::info If you disabled `includeProtocols`, change the version to a newer one. No additional actions are required. ::: https://business.1inch.com/portal/assets/docs-v2/apis/orderbook/migration/migration-v3-v4.md Following changes must be done to migrate from v3.0 to v4.0 ## Request ### Typechange of parameter: - `statuses`: change from `array` (`[1,2,3]`) to `comma-separated list` (`1,2,3`) ## LimitOrder Request Data changed ### Removing of parameters: - `allowedSender` - `offsets` - `interactions` ### Adding of parameter: - `extension`: An interaction call data. ABI encoded set of makerAssetSuffix, takerAssetSuffix, makingAmountGetter, takingAmountGetter, predicate, permit, preInteraction, postInteraction.If extension exists then lowest 160 bits of the order salt must be equal to the lowest 160 bits of the extension hash - `makerTraits`: Includes some flags like, allow multiple fills, is partial fill allowed or not, price improvement, nonce, deadline etc. ## Response ### Removing of parameters: - `allowedSender` - `offsets` - `interactions` ### Adding of parameters: - `extension`: An interaction call data. ABI encoded set of makerAssetSuffix, takerAssetSuffix, makingAmountGetter, takingAmountGetter, predicate, permit, preInteraction, postInteraction.If extension exists then lowest 160 bits of the order salt must be equal to the lowest 160 bits of the extension hash - `makerTraits`: Includes some flags like, allow multiple fills, is partial fill allowed or not, price improvement, nonce, deadline etc. ## New get order by order hash endpoint added: - `orderbook/v4.1/{chain}/order/{orderHash}` `GET` endpoint was created to enable getting orders filtered by the specified order hash https://business.1inch.com/portal/assets/docs-v2/apis/portfolio/migration/migration-v40-v50.md ## Key Difference between V4 and V5 **V5 introduces a fundamental separation between `snapshot` and `metrics`:** - `snapshot` -- a state at a specific point in time - `metrics` -- historical metrics over a selected time range (e.g. 1day, 1week) ## Migration Guide: From `/v4` to `/v5.0` When calling through the **unified gateway** at `https://api.1inch.com` or the **MCP `product_api` tool**, use the gateway prefix `/portfolio/portfolio/v5.0/...` (prepend an extra `/portfolio`). The tables below show **service / OpenAPI** paths `/portfolio/v5.0/...` after routing. ### General | V4 Endpoint | V5.0 Endpoint | Notes | | ------------------------------------------- | --------------------------------------------- | ------------------ | | `/portfolio/v4/general/is_available` | `/portfolio/v5.0/general/status` | Renamed | | `/portfolio/v4/general/supported_chains` | `/portfolio/v5.0/general/supported_chains` | Same functionality | | `/portfolio/v4/general/supported_protocols` | `/portfolio/v5.0/general/supported_protocols` | Same functionality | | `/portfolio/v4/general/current_value` | `/portfolio/v5.0/general/current_value` | Wrapped response | | `/portfolio/v4/general/profit_and_loss` | **Removed** -> see `/metrics` | Moved to metrics | | `/portfolio/v4/general/value_chart` | `/portfolio/v5.0/general/chart` | Renamed | | _(none)_ | `/portfolio/v5.0/general/address_check` | New endpoint | ### Tokens | V4 Endpoint | V5.0 Endpoint | Notes | | ---------------------------------------------- | --------------------------------- | ------------------------------------ | | `/portfolio/v4/overview/erc20/current_value` | `/portfolio/v5.0/tokens/snapshot` | Snapshot replaces current value | | `/portfolio/v4/overview/erc20/profit_and_loss` | `/portfolio/v5.0/tokens/metrics` | Historical metrics | | `/portfolio/v4/overview/erc20/details` | Covered by snapshot + metrics | Merged into `snapshot` and `metrics` | ### Protocols | V4 Endpoint | V5.0 Endpoint | Notes | | -------------------------------------------------- | ------------------------------------ | ------------------------------------ | | `/portfolio/v4/overview/protocols/current_value` | `/portfolio/v5.0/protocols/snapshot` | Snapshot replaces current value | | `/portfolio/v4/overview/protocols/profit_and_loss` | `/portfolio/v5.0/protocols/metrics` | Historical metrics | | `/portfolio/v4/overview/protocols/details` | Covered by snapshot + metrics | Merged into `snapshot` and `metrics` |