### Perform a Token Swap with Fusion Mode Source: https://github.com/1inch/fusion-sdk/blob/main/README.md This example demonstrates how to set up the Fusion SDK, get a quote for a swap, create an order, submit the order, and monitor its status until it's filled, expired, or cancelled. It requires your private key, a Web3 node URL, and a Dev Portal API token. ```typescript import {FusionSDK, NetworkEnum, OrderStatus, PrivateKeyProviderConnector, Web3Like,} from "@1inch/fusion-sdk"; import {computeAddress, formatUnits, JsonRpcProvider} from "ethers"; const PRIVATE_KEY = 'YOUR_PRIVATE_KEY' const NODE_URL = 'YOUR_WEB3_NODE_URL' const DEV_PORTAL_API_TOKEN = 'YOUR_DEV_PORTAL_API_TOKEN' const ethersRpcProvider = new JsonRpcProvider(NODE_URL) const ethersProviderConnector: Web3Like = { eth: { call(transactionConfig): Promise { return ethersRpcProvider.call(transactionConfig) } }, extend(): void {} } const connector = new PrivateKeyProviderConnector( PRIVATE_KEY, ethersProviderConnector ) const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.BINANCE, blockchainProvider: connector, authKey: DEV_PORTAL_API_TOKEN }) async function main() { const params = { fromTokenAddress: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', // USDC toTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // BNB amount: '10000000000000000000', // 10 USDC walletAddress: computeAddress(PRIVATE_KEY), source: 'sdk-test' } const quote = await sdk.getQuote(params) const dstTokenDecimals = 18 console.log('Auction start amount', formatUnits(quote.presets[quote.recommendedPreset].auctionStartAmount, dstTokenDecimals)) console.log('Auction end amount', formatUnits(quote.presets[quote.recommendedPreset].auctionEndAmount), dstTokenDecimals) const preparedOrder = await sdk.createOrder(params) const info = await sdk.submitOrder(preparedOrder.order, preparedOrder.quoteId) console.log('OrderHash', info.orderHash) const start = Date.now() while (true) { try { const data = await sdk.getOrderStatus(info.orderHash) if (data.status === OrderStatus.Filled) { console.log('fills', data.fills) break } if (data.status === OrderStatus.Expired) { console.log('Order Expired') break } if (data.status === OrderStatus.Cancelled) { console.log('Order Cancelled') break } } catch (e) { console.log(e) } } console.log('Order executed for', (Date.now() - start) / 1000, 'sec') } main() ``` -------------------------------- ### Install 1inch Fusion SDK Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/INDEX.md Install the SDK using npm or yarn. Ensure you are using version 2. ```bash npm install @1inch/fusion-sdk@2 # or yarn add @1inch/fusion-sdk@2 ``` -------------------------------- ### Web3ProviderConnector Example Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/connectors.md Example of initializing Web3ProviderConnector with an existing Web3 instance. ```typescript import {Web3ProviderConnector} from '@1inch/fusion-sdk' const connector = new Web3ProviderConnector(web3Instance) ``` -------------------------------- ### Install 1inch Fusion SDK with Npm Source: https://github.com/1inch/fusion-sdk/blob/main/README.md Install the SDK using npm. Ensure you are using version 2. ```bash npm install @1inch/fusion-sdk@2 ``` -------------------------------- ### Install 1inch Fusion SDK with Yarn Source: https://github.com/1inch/fusion-sdk/blob/main/README.md Install the SDK using Yarn. Ensure you are using version 2. ```bash yarn add @1inch/fusion-sdk@2 ``` -------------------------------- ### PrivateKeyProviderConnector Example Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/connectors.md Example of initializing and using PrivateKeyProviderConnector with ethers.js and a custom Web3Like provider. ```typescript import {PrivateKeyProviderConnector, Web3Like} from '@1inch/fusion-sdk' import {JsonRpcProvider} from 'ethers' const rpcProvider = new JsonRpcProvider('https://...') const web3Provider: Web3Like = { eth: { call: (config) => rpcProvider.call(config) }, extend: () => {} } const connector = new PrivateKeyProviderConnector( '0xYOUR_PRIVATE_KEY', web3Provider ) ``` -------------------------------- ### Subscribe to RPC Updates Example Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/websocket-api.md Example of subscribing to new block headers using the RpcWebsocketApi. Ensure the RpcSubscriptionParams are correctly formatted. ```typescript ws.rpc.subscribe({ method: 'eth_subscribe', params: ['newHeads'] }) ``` -------------------------------- ### Example API URLs for Ethereum Network Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/api-endpoints.md Specific examples of API endpoints for the Ethereum network (network ID 1) using the base URL. ```bash https://api.1inch.com/fusion/quoter/v2.0/1/quote/receive/... https://api.1inch.com/fusion/relayer/v2.0/1/order/submit https://api.1inch.com/fusion/orders/v2.0/1/order/status/... ``` -------------------------------- ### Real-world Example: Connecting and Listening to Orders Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Demonstrates how to instantiate the WebSocketApi and subscribe to order events. Ensure you have the necessary authentication key and network configuration. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' const wsSdk = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', network: NetworkEnum.ETHEREUM, authKey: 'your-auth-key' }) wsSdk.order.onOrder((data) => { console.log('received order event', data) }) ``` -------------------------------- ### PresetEnum Usage Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/utilities-and-enums.md Example of creating an order with a specified preset using PresetEnum.medium. ```typescript import {PresetEnum} from '@1inch/fusion-sdk' const order = await sdk.createOrder({ preset: PresetEnum.medium }) ``` -------------------------------- ### Initialize WebSocketApi with Configuration Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/websocket-api.md Example of initializing the WebSocketApi using a configuration object, specifying the API URL, network, and reconnection settings. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' // Using config object const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion', network: NetworkEnum.ETHEREUM, reconnectInterval: 3000, maxReconnectAttempts: 5 }) ws.init() ``` -------------------------------- ### calcAuctionStartAmount Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates the auction start amount based on market return and an initial rate bump. ```APIDOC ## Static Method: calcAuctionStartAmount ### Description Calculate the auction start amount given market return and rate bump. ### Method Signature ```typescript static calcAuctionStartAmount(marketReturn: bigint, initialRateBump: number): bigint ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **marketReturn** (bigint) - Required - Market return amount - **initialRateBump** (number) - Required - Rate bump percentage ### Returns - **bigint** — Auction start amount ### Example ```typescript const marketReturn = BigInt('1000000000000000000') const rateBump = 100_000 // 10% const startAmount = AuctionCalculator.calcAuctionStartAmount(marketReturn, rateBump) console.log('Start amount:', startAmount.toString()) ``` ``` -------------------------------- ### calcAuctionStartAmount Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates the auction start amount based on market return and initial rate bump. ```APIDOC ## Static Method: calcAuctionStartAmount Calculate the auction start amount. ```typescript static calcAuctionStartAmount( marketReturn: bigint, initialRateBump: number ): bigint ``` ### Parameters #### Path Parameters - marketReturn (bigint) - Required - Market return - initialRateBump (number) - Required - Initial rate bump ### Returns `bigint` — Auction start amount ``` -------------------------------- ### AxiosProviderConnector Usage Example Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/connectors.md Demonstrates how to instantiate and use the AxiosProviderConnector with the FusionSDK. An API token is required for initialization. ```typescript import {AxiosProviderConnector} from '@1inch/fusion-sdk' const httpProvider = new AxiosProviderConnector('YOUR_API_TOKEN') // Used automatically by FusionSDK if not provided const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.ETHEREUM, httpProvider: httpProvider }) ``` -------------------------------- ### Initialize Fusion SDK Source: https://github.com/1inch/fusion-sdk/blob/main/src/sdk/README.md Instantiate the FusionSDK with API endpoint, network, and authentication key. This is a basic setup for interacting with the SDK. ```typescript import {FusionSDK, NetworkEnum} from '@1inch/fusion-sdk' async function main() { const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.ETHEREUM, authKey: 'your-auth-key' }) const orders = await sdk.getActiveOrders({page: 1, limit: 2}) } main() ``` -------------------------------- ### WebsocketClient Usage Example Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/connectors.md Shows how to create and configure a WebsocketClient instance, including setting up handlers for connection events, messages, errors, and disconnections. The connection is initiated with the init() method. ```typescript import {WebsocketClient} from '@1inch/fusion-sdk' const wsClient = new WebsocketClient({ url: 'wss://api.1inch.com/fusion' }) wsClient.onOpen(() => { console.log('Connected') }) wsClient.onMessage((msg) => { console.log('Received:', msg) }) wsClient.onError((error) => { console.error('Error:', error) }) wsClient.onClose(() => { console.log('Disconnected') }) wsClient.init() ``` -------------------------------- ### WebSocketApi Initialization with Static Method Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Demonstrates creating a WebSocketApi instance using the static `new` method, providing a concise alternative to the constructor for common setups. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' const ws = WebSocketApi.new({ url: 'wss://api.1inch.com/fusion/ws', network: NetworkEnum.ETHEREUM }) ``` -------------------------------- ### NetworkEnum Usage Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/utilities-and-enums.md Example of initializing FusionSDK with a specific network using NetworkEnum. ```typescript import {NetworkEnum} from '@1inch/fusion-sdk' const sdk = new FusionSDK({ network: NetworkEnum.ETHEREUM }) ``` -------------------------------- ### Initialize Fusion SDK Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/INDEX.md Initialize the FusionSDK with your API details, network, blockchain provider, and authentication key. This setup is required before making any SDK calls. ```typescript import {FusionSDK, NetworkEnum, PrivateKeyProviderConnector, Web3Like} from '@1inch/fusion-sdk' import {JsonRpcProvider} from 'ethers' const rpcProvider = new JsonRpcProvider('https://eth-rpc-url') const web3Provider: Web3Like = { eth: { call: (config) => rpcProvider.call(config) }, extend: () => {} } const connector = new PrivateKeyProviderConnector( 'YOUR_PRIVATE_KEY', web3Provider ) const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.ETHEREUM, blockchainProvider: connector, authKey: 'YOUR_DEV_PORTAL_TOKEN' }) ``` -------------------------------- ### AuctionDetails Constructor Source: https://github.com/1inch/fusion-sdk/blob/main/src/fusion-order/auction-details/README.md Encapsulates auction start time, duration, initial rate bump, auction price curve, and gas cost. ```APIDOC ## new AuctionDetails(params) ### Description Creates a new AuctionDetails object with the provided parameters. ### Parameters - **params** (object) - Required - An object containing the auction details. - **duration** (bigint) - Required - The duration of the auction in seconds. - **startTime** (bigint) - Required - The Unix timestamp (in seconds) when the auction starts. - **initialRateBump** (number) - Required - The initial rate bump, defined as a ratio of startTakingAmount to endTakingAmount (e.g., 10,000,000 means 100%). - **points** (array) - Required - An array of points defining the price curve. - **delay** (number) - Required - The delay relative to the previous point (or auction start for the first point). - **coefficient** (number) - Required - The rate bump for `auctionEndAmount` (e.g., 1000000 = 100%). - **gasCost** (object) - Optional - An object to adjust estimated gas costs. - **gasBumpEstimate** (bigint) - Optional - The rate bump to cover gas price, defined as a ratio of gasCostInToToken to endTakingAmount (e.g., 10,000,000 means 100%). - **gasPriceEstimate** (bigint) - Optional - The gas price at the estimation time (e.g., 1000 means 1 Gwei). ### Example ```typescript import {AuctionDetails} from '@1inch/fusion-sdk' const details = new AuctionDetails({ duration: 180n, // in seconds, startTime: 1673548149n, // unix timestamp (in sec), initialRateBump: 50000, points: [ { delay: 10, // relative to auction start time coefficient: 40000 }, { delay: 10, // relative to previous point coefficient: 40000 } ], gasCost: { gasBumpEstimate: 10_000n, gasPriceEstimate: 1000n } }) ``` ``` -------------------------------- ### Basic Swap Flow with 1inch Fusion SDK Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/INDEX.md Execute a basic swap by getting a quote, creating an order, submitting it, and checking its status. Replace placeholder addresses and amounts with your specific details. ```typescript // 1. Get quote const quote = await sdk.getQuote({ fromTokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', toTokenAddress: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', amount: '1000000000000000000', walletAddress: '0x...' }) // 2. Create order const prepared = await sdk.createOrder({ fromTokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', toTokenAddress: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', amount: '1000000000000000000', walletAddress: '0x...', preset: quote.recommendedPreset }) // 3. Submit order const orderInfo = await sdk.submitOrder(prepared.order, prepared.quoteId) console.log('Order hash:', orderInfo.orderHash) // 4. Check status const status = await sdk.getOrderStatus(orderInfo.orderHash) console.log('Status:', status.status) ``` -------------------------------- ### Standard Swap Pattern in TypeScript Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/REFERENCE-GUIDE.md Follow these steps to perform a standard swap: get a quote, create an order, submit the order, and monitor its status. Ensure you have the SDK initialized. ```typescript // 1. Get quote const quote = await sdk.getQuote({...}) // 2. Create order const prepared = await sdk.createOrder({...}) // 3. Submit const info = await sdk.submitOrder(prepared.order, prepared.quoteId) // 4. Monitor const status = await sdk.getOrderStatus(info.orderHash) ``` -------------------------------- ### Custom HTTP Provider Implementation Source: https://github.com/1inch/fusion-sdk/blob/main/src/sdk/README.md Example of implementing a custom HTTP provider using an external API library. This allows for custom request handling. ```typescript import {api} from 'my-api-lib' class CustomHttpProvider implements HttpProviderConnector { get(url: string): Promise { return api.get(url) } post(url: string, data: unknown): Promise { return api.post(url, data) } } ``` -------------------------------- ### Calculate Auction Start Amount Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Use this method to determine the initial amount for an auction based on market return and a rate bump percentage. Ensure inputs are of the correct BigInt and number types. ```typescript static calcAuctionStartAmount( marketReturn: bigint, initialRateBump: number ): bigint ``` ```typescript const marketReturn = BigInt('1000000000000000000') const rateBump = 100_000 // 10% const startAmount = AuctionCalculator.calcAuctionStartAmount(marketReturn, rateBump) console.log('Start amount:', startAmount.toString()) ``` -------------------------------- ### Get Swap Quote with Preset Auction Configurations Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/fusion-sdk.md Use this method to get a quote for a token swap. It requires source and destination token addresses, the amount to swap, and optionally includes wallet address, gas estimation, permit data, integrator fees, source tracking, Permit2 enablement, and slippage tolerance. The returned quote object contains recommended presets and auction details. ```typescript async getQuote(params: QuoteParams): Promise ``` ```typescript const quote = await sdk.getQuote({ fromTokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI toTokenAddress: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH amount: '1000000000000000000', // 1 token walletAddress: '0x...', source: 'my-app' }) console.log('Recommended preset:', quote.recommendedPreset) console.log('Auction start amount:', quote.presets[quote.recommendedPreset].auctionStartAmount) ``` -------------------------------- ### Swap Native Asset with 1inch Fusion SDK Source: https://github.com/1inch/fusion-sdk/blob/main/README.md This snippet demonstrates how to swap a native asset (like ETH) for a token (like USDC) using the 1inch Fusion SDK. It includes setup, quoting, order creation, submission, and status monitoring. Ensure you replace placeholder values for private key, node URL, and API token. ```typescript import {FusionSDK, NetworkEnum, OrderStatus, PrivateKeyProviderConnector, Web3Like, Address, NativeOrdersFactory} from "@1inch/fusion-sdk"; import {computeAddress, formatUnits, JsonRpcProvider, Wallet} from "ethers"; const PRIVATE_KEY = 'YOUR_PRIVATE_KEY' const NODE_URL = 'YOUR_WEB3_NODE_URL' const DEV_PORTAL_API_TOKEN = 'YOUR_DEV_PORTAL_API_TOKEN' const ethersRpcProvider = new JsonRpcProvider(NODE_URL) const ethersProviderConnector: Web3Like = { eth: { call(transactionConfig): Promise { return ethersRpcProvider.call(transactionConfig) } }, extend(): void {} } const connector = new PrivateKeyProviderConnector( PRIVATE_KEY, ethersProviderConnector ) const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.BINANCE, blockchainProvider: connector, authKey: DEV_PORTAL_API_TOKEN }) const wallet = new Wallet(PRIVATE_KEY, ethersRpcProvider) async function main() { const params = { fromTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // ETH toTokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC amount: '2000000000000000', // 0.002 ETH walletAddress: computeAddress(PRIVATE_KEY), source: 'sdk-test' } const quote = await sdk.getQuote(params) const dstTokenDecimals = 6 console.log('Auction start amount', formatUnits(quote.presets[quote.recommendedPreset].auctionStartAmount, dstTokenDecimals)) console.log('Auction end amount', formatUnits(quote.presets[quote.recommendedPreset].auctionEndAmount), dstTokenDecimals) const preparedOrder = await sdk.createOrder(params) const info = await sdk.submitNativeOrder(preparedOrder.order, new Address(params.walletAddress), preparedOrder.quoteId) console.log('OrderHash', info.orderHash) const factory = NativeOrdersFactory.default(NetworkEnum.BINANCE) const call = factory.create(new Address(wallet.address), preparedOrder.order.build()) const txRes = await wallet.sendTransaction({ to: call.to.toString(), data: call.data, value: call.value }) console.log('TxHash', txRes.hash) await wallet.provider.waitForTransaction(txRes.hash) const start = Date.now() while (true) { try { const data = await sdk.getOrderStatus(info.orderHash) if (data.status === OrderStatus.Filled) { console.log('fills', data.fills) break } if (data.status === OrderStatus.Expired) { console.log('Order Expired') break } if (data.status === OrderStatus.Cancelled) { console.log('Order Cancelled') break } } catch (e) { console.log(e) } } console.log('Order executed for', (Date.now() - start) / 1000, 'sec') } main() ``` -------------------------------- ### Create AuctionDetails Instance Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/fusion-order.md Instantiates an `AuctionDetails` object with configuration for an auction, including start time, duration, rate bump, and control points. Gas cost estimates are optional. ```typescript import {AuctionDetails} from '@1inch/fusion-sdk' const auction = new AuctionDetails({ startTime: BigInt(Math.floor(Date.now() / 1000) + 60), initialRateBump: 100_000, duration: 180n, points: [ {delay: 60, coefficient: 90_000}, {delay: 120, coefficient: 80_000} ] }) ``` -------------------------------- ### Calculate and Apply Fees Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Use FeeCalculator.calcFee to determine the fee amount and FeeCalculator.applyFee to get the net amount after fees are applied. This is essential for orders involving integrator or protocol fees. ```typescript import {FeeCalculator, Bps} from '@1inch/fusion-sdk' const amount = BigInt('1000000000000000000') const fee = new Bps(100n) // 1% (100 basis points) const feeAmount = FeeCalculator.calcFee(amount, fee) const netAmount = FeeCalculator.applyFee(amount, fee) console.log('Gross:', amount.toString()) console.log('Fee:', feeAmount.toString()) console.log('Net:', netAmount.toString()) ``` -------------------------------- ### Subscribe to Order Updates and Handle Messages Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/websocket-api.md Example of subscribing to specific order updates and logging all incoming messages from the WebSocket. Use the orderHash parameter for targeted updates. ```typescript ws.order.subscribe({ orderHash: '0x...' }) ws.onMessage((data) => { console.log('Order update:', data) }) ``` -------------------------------- ### WebSocket API Cleanup Example Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/websocket-api.md Demonstrates proper resource cleanup by closing the WebSocket connection on SIGINT and SIGTERM signals. Ensure all necessary event handlers are set up before initializing the connection. ```typescript const ws = WebSocketApi.new({...}) function cleanup() { ws.close() } process.on('SIGINT', cleanup) process.on('SIGTERM', cleanup) ws.init() ``` -------------------------------- ### Get Orders by Maker Address Source: https://github.com/1inch/fusion-sdk/blob/main/src/sdk/README.md Fetches orders associated with a specific maker's wallet address. Requires SDK initialization and pagination parameters. ```typescript import {FusionSDK, NetworkEnum} from '@1inch/fusion-sdk' const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.ETHEREUM }) const orders = await sdk.getOrdersByMaker({ page: 1, limit: 2, address: '0xfa80cd9b3becc0b4403b0f421384724f2810775f' }) ``` -------------------------------- ### Build Custom Auction Presets Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Create custom auction parameters using AuctionCalculator. This allows for fine-grained control over auction dynamics, including start and end amounts, and specific points in time. ```typescript const marketReturn = BigInt('1000000000000000000') // Calculate appropriate start amount (10% premium) const startAmount = AuctionCalculator.calcAuctionStartAmount( marketReturn, 100_000 ) const endAmount = AuctionCalculator.calcAuctionEndAmount( startAmount, 100_000 ) const customPreset = { auctionDuration: 300, auctionStartAmount: startAmount.toString(), auctionEndAmount: endAmount.toString(), points: [ {delay: 60, toTokenAmount: startAmount.toString()}, {delay: 150, toTokenAmount: marketReturn.toString()}, {delay: 240, toTokenAmount: endAmount.toString()} ] } const quote = await sdk.getQuoteWithCustomPreset( {fromTokenAddress: '0x...', ...}, {customPreset} ) ``` -------------------------------- ### Calculate Initial Rate Bump Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates the initial rate bump based on the auction's starting and ending amounts. The rate bump is returned as a percentage, where 1,000,000 represents 100%. ```typescript import {AuctionCalculator} from '@1inch/fusion-sdk' const startAmount = BigInt('1500000000000000000') const endAmount = BigInt('1000000000000000000') const rateBump = AuctionCalculator.calcInitialRateBump(startAmount, endAmount) console.log('Rate bump:', rateBump) // e.g., 100_000 (10%) ``` -------------------------------- ### Get Active Orders HTTP Request Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/api-endpoints.md The GET endpoint for retrieving a list of active orders. Supports pagination and filtering by API version. ```http GET /v2.0/{network}/order/active/?{queryParams} ``` -------------------------------- ### WebSocketApi Initialization with Constructor Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Shows the basic way to create an instance of WebSocketApi using its constructor with essential parameters like URL, network, and authentication key. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', network: NetworkEnum.ETHEREUM, authKey: 'your-auth-key' }) ``` -------------------------------- ### Get Orders By Maker HTTP Request Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/api-endpoints.md The GET endpoint for retrieving all orders placed by a specific maker address. Supports pagination and filtering by API version. ```http GET /v2.0/{network}/order/maker/{address}/?{queryParams} ``` -------------------------------- ### Instantiate and Encode AuctionDetails Source: https://github.com/1inch/fusion-sdk/blob/main/src/fusion-order/auction-details/README.md Instantiate AuctionDetails with auction parameters like duration, start time, initial rate bump, price curve points, and gas cost estimates. Use the encode() method to convert these details into a hexadecimal string representation. ```typescript import {AuctionDetails} from '@1inch/fusion-sdk' const details = new AuctionDetails({ duration: 180n, // in seconds, startTime: 1673548149n, // unix timestamp (in sec), /** * It defined as a ratio of startTakingAmount to endTakingAmount. 10_000_000 means 100% * * @see `AuctionCalculator.calcInitialRateBump` */ initialRateBump: 50000, /** * Points which define price curve. * Each point contains `delay` - relative to previous point (auction start for first) * and `coefficient` - rate bump for `auctionEndAmount` (10000000 = 100%) * * y(rate) ▲ * │ * 5000 │\ * │ \ * │ \ * 4000 │ \ * │ \ * │ \ * 3000 │ \ * │ \ * └─────────────────────────► * 0 10 20 end x(time) */ points: [ { delay: 10, // relative to auction start time coefficient: 40000 }, { delay: 10, // relative to previous point coefficient: 40000 } ], /** * Allows to ajust estimated gas costs to real onchain gas costs */ gasCost: { /** * Rate bump to cover gas price. * It defined as a ratio of gasCostInToToken to endTakingAmount. 10_000_000 means 100% * * @see `AuctionCalculator.calcGasBumpEstimate` */ gasBumpEstimate: 10_000n, /** * Gas price at estimation time. 1000 means 1 Gwei */ gasPriceEstimate: 1000n } }) details.encode() // #=> '0x63c051750000b400c350009c40000a009c40000a' ``` -------------------------------- ### Quoter API GET /quote/receive Request Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/api-endpoints.md HTTP GET request for fetching swap quotes. Requires query parameters like token addresses, amount, and wallet address. ```http GET /v2.0/{network}/quote/receive/?{queryParams} ``` -------------------------------- ### Get Order Status HTTP Request Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/api-endpoints.md The GET endpoint for retrieving the status of a specific order using its hash. Returns detailed information about the order's status, fills, and auction details. ```http GET /v2.0/{network}/order/status/{orderHash} ``` -------------------------------- ### Initialize WebSocket Connection Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/websocket-api.md Call `init()` to establish the WebSocket connection. Use `onOpen` to set a callback for when the connection is successfully opened. ```typescript ws.init() ws.onOpen(() => { console.log('Connected to WebSocket') }) ``` -------------------------------- ### OrderStatus Usage Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/utilities-and-enums.md Example of checking an order's status against OrderStatus.Filled and OrderStatus.Expired. ```typescript import {OrderStatus} from '@1inch/fusion-sdk' const status = await sdk.getOrderStatus(orderHash) if (status.status === OrderStatus.Filled) { console.log('Order filled!') } if (status.status === OrderStatus.Expired) { console.log('Order expired') } ``` -------------------------------- ### getAllowedMethods Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Get the list of allowed methods. This method retrieves a list of all available RPC methods. ```APIDOC ## getAllowedMethods ### Description Get the list of allowed methods. ### Example ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', network: NetworkEnum.ETHEREUM }) ws.rpc.getAllowedMethods() ``` ``` -------------------------------- ### Create and Build FusionOrder Source: https://github.com/1inch/fusion-sdk/blob/main/src/fusion-order/README.md Demonstrates how to instantiate a FusionOrder with auction and whitelist details, then encode its extension and build the final order object. Ensure all necessary imports are present. ```typescript import {AuctionDetails, FusionOrder, Whitelist, now} from '@1inch/fusion-sdk' const extensionContract = new Address('0x8273f37417da37c4a6c3995e82cf442f87a25d9c') const resolvingStartAt = now() const order = FusionOrder.new( extensionContract, { makerAsset: new Address('0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'), takerAsset: new Address('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'), makingAmount: 1000000000000000000n, takingAmount: 1420000000n, maker: new Address('0x00000000219ab540356cbb839cbe05303d7705fa'), salt: 10n }, { auction: new AuctionDetails({ duration: 180n, startTime: 1673548149n, initialRateBump: 50000, points: [ { coefficient: 20000, delay: 12 } ] }), whitelist: Whitelist.new(resolvingStartAt, [ { address: new Address( '0x00000000219ab540356cbb839cbe05303d7705fa' ), delay: 0n } ]) } ) const extension = order.extension.encode() // => 0x... const builtOrder = order.build() /* => { maker: '0x00000000219ab540356cbb839cbe05303d7705fa', makerAsset: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', makingAmount: '1000000000000000000', receiver: '0x0000000000000000000000000000000000000000', takerAsset: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', takingAmount: '1420000000', makerTraits: '29852648006495581632639394572552351243421169944806257724550573036760110989312', salt: '14832508939800728556409473652845244531014097925085' } */ ``` -------------------------------- ### WebSocketApi Initialization with Custom Provider Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Illustrates how to integrate a custom WebSocket provider with the WebSocketApi. This allows for using alternative websocket client libraries. ```typescript import {WsProviderConnector, WebSocketApi} from '@1inch/fusion-sdk' class MyFancyProvider implements WsProviderConnector { // ... user implementation } const url = 'wss://api.1inch.com/fusion/ws/v2.0/1' const provider = new MyFancyProvider({url}) const wsSdk = new WebSocketApi(provider) ``` -------------------------------- ### HttpProviderConnector Interface Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/connectors.md Defines the base interface for HTTP communication, outlining methods for GET and POST requests. ```typescript interface HttpProviderConnector { get(url: string): Promise post(url: string, body: unknown): Promise } ``` -------------------------------- ### Get Active Orders Source: https://github.com/1inch/fusion-sdk/blob/main/src/sdk/README.md Retrieves a paginated list of active orders. Requires basic SDK initialization. ```typescript import {FusionSDK, NetworkEnum} from '@1inch/fusion-sdk' const sdk = new FusionSDK({ url: 'https://api.1inch.com/fusion', network: NetworkEnum.ETHEREUM }) const orders = await sdk.getActiveOrders({page: 1, limit: 2}) ``` -------------------------------- ### Place an Order with Fusion SDK Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/fusion-sdk.md Use `placeOrder` to combine order creation and submission into a single asynchronous call. It requires token addresses, amount, and wallet address. ```typescript const orderInfo = await sdk.placeOrder({ fromTokenAddress: '0x...', toTokenAddress: '0x...', amount: '1000000000000000000', walletAddress: '0x...' }) ``` -------------------------------- ### CustomPreset Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/types.md Defines the configuration for a custom auction, including duration, start and end amounts, and intermediate points. ```APIDOC ## CustomPreset ### Description Custom auction configuration. ### Type Definition ```typescript type CustomPreset = { auctionDuration: number auctionStartAmount: string auctionEndAmount: string points?: CustomPresetPoint[] } ``` ### Fields #### auctionDuration (number) - Required Duration in seconds #### auctionStartAmount (string) - Required Initial taking amount #### auctionEndAmount (string) - Required Final taking amount #### points (CustomPresetPoint[]) - Optional Intermediate auction points ``` -------------------------------- ### calcAuctionEndAmount Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates the auction end amount using the auction start amount and an initial rate bump. ```APIDOC ## Static Method: calcAuctionEndAmount ### Description Calculate the auction end amount from start amount and rate bump. ### Method Signature ```typescript static calcAuctionEndAmount(auctionStartAmount: bigint, initialRateBump: number): bigint ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **auctionStartAmount** (bigint) - Required - Starting taking amount - **initialRateBump** (number) - Required - Rate bump percentage ### Returns - **bigint** — Auction end amount ``` -------------------------------- ### calcPoints Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates auction points based on start amount, end amount, and a list of auction points. ```APIDOC ## Static Method: calcPoints Calculate auction points. ```typescript static calcPoints( startAmount: bigint, endAmount: bigint, points: AuctionPoint[] ): bigint[] ``` ### Parameters #### Path Parameters - startAmount (bigint) - Required - Start amount - endAmount (bigint) - Required - End amount - points (AuctionPoint[]) - Required - List of auction points ### Returns `bigint[]` — Calculated auction points ``` -------------------------------- ### Calculate Taker Amount and Auction Rate with AuctionCalculator Source: https://github.com/1inch/fusion-sdk/blob/main/src/amount-calculator/auction-calculator/README.md Demonstrates how to initialize and use the AuctionCalculator to determine the auction rate bump and the final auction taking amount based on provided settlement and auction details. Ensure all necessary imports are included. ```typescript import { AuctionCalculator, SettlementPostInteractionData, AuctionDetails, Address, bpsToRatioFormat } from '@1inch/fusion-sdk' const startTime = 1673548149n const settlementData = SettlementPostInteractionData.new({ bankFee: 0n, auctionStartTime: startTime, whitelist: [ { address: new Address('0x111111111117dc0aa78b770fa6a738034120c302'), delay: 0n } ], integratorFee: { receiver: new Address('0x111111111117dc0aa78b770fa6a738034120c302'), ratio: bpsToRatioFormat(10) } }) const details = new AuctionDetails({ duration: 180n, // in seconds, startTime, // unix timestamp (in sec), initialRateBump: 50000, points: [ { delay: 10, // relative to auction start time coefficient: 40000 }, { delay: 10, // relative to previous point coefficient: 40000 } ] }) const calculator = AuctionCalculator.fromAuctionData(settlementData, details) // #=> AuctionCalculator instance const rate = calculator.calcRateBump(startTime + 11n) // #=> 40000 const auctionTakingAmount = calculator.calcAuctionTakingAmount( 1420000000n, rate ) // #=> 1427105680 ``` -------------------------------- ### calcAuctionEndAmount Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates the auction end amount based on auction start amount and initial rate bump. ```APIDOC ## Static Method: calcAuctionEndAmount Calculate the auction end amount. ```typescript static calcAuctionEndAmount( auctionStartAmount: bigint, initialRateBump: number ): bigint ``` ### Parameters #### Path Parameters - auctionStartAmount (bigint) - Required - Auction start amount - initialRateBump (number) - Required - Initial rate bump ### Returns `bigint` — Auction end amount ``` -------------------------------- ### calcInitialRateBump Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/amount-calculator.md Calculates the initial rate bump as a percentage based on the auction's start and end amounts. ```APIDOC ## Static Method: calcInitialRateBump Calculate the initial rate bump based on start and end amounts. ```typescript static calcInitialRateBump( auctionStartAmount: bigint, auctionEndAmount: bigint ): number ``` ### Parameters #### Path Parameters - auctionStartAmount (bigint) - Required - Starting taking amount - auctionEndAmount (bigint) - Required - Ending taking amount ### Returns `number` — Rate bump as percentage (where 1_000_000 = 100%) ### Request Example ```typescript import {AuctionCalculator} from '@1inch/fusion-sdk' const startAmount = BigInt('1500000000000000000') const endAmount = BigInt('1000000000000000000') const rateBump = AuctionCalculator.calcInitialRateBump(startAmount, endAmount) console.log('Rate bump:', rateBump) // e.g., 100_000 (10%) ``` ``` -------------------------------- ### Get Active Orders Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/fusion-sdk.md Retrieves a paginated list of all active orders in the network. Specify page and limit for pagination. ```typescript async getActiveOrders( options?: ActiveOrdersRequestParams ): Promise ``` ```typescript const response = await sdk.getActiveOrders({page: 1, limit: 10}) console.log(`Total: ${response.meta.totalItems}, Current page: ${response.meta.currentPage}`) response.items.forEach(order => { console.log('Order:', order.orderHash) }) ``` -------------------------------- ### FusionSDK Constructor Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/INDEX.md Initializes a new instance of the FusionSDK. This is the entry point for using the SDK's functionalities. ```APIDOC ## Constructor FusionSDK ### Description Initializes a new instance of the FusionSDK. ### Method Constructor ### Parameters (No specific parameters are detailed in the source for the constructor itself, but it's implied to be the way to start using the SDK.) ### Request Example (No example provided in source) ### Response (No response details provided in source) ``` -------------------------------- ### MakerTraits Configuration Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/utilities-and-enums.md Shows how to configure maker traits for a limit order, including setting expiration, enabling partial or multiple fills, and enabling post-interaction. ```typescript const traits = MakerTraits.default() .withExpiration(deadline) .setPartialFills(true) .setMultipleFills(true) .enablePostInteraction() ``` -------------------------------- ### onGetActiveOrders Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Subscribe to get active orders events. This method allows you to receive updates on the list of active orders. ```APIDOC ## onGetActiveOrders ### Description Subscribe to get active orders events. ### Arguments - cb: (data: PaginationOutput) => void ### Example ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', network: NetworkEnum.ETHEREUM }) ws.rpc.onGetActiveOrders((data) => { // do something }) ``` ``` -------------------------------- ### onGetAllowedMethods Source: https://github.com/1inch/fusion-sdk/blob/main/src/ws-api/README.md Subscribe to get allowed methods response. This method allows you to receive the list of allowed RPC methods. ```APIDOC ## onGetAllowedMethods ### Description Subscribe to get allowed methods response. ### Arguments - cb: (data: RpcMethod[]) => void ### Example ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/fusion-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', network: NetworkEnum.ETHEREUM }) ws.rpc.onGetAllowedMethods((data) => { // do something }) ``` ``` -------------------------------- ### CustomPresetPoint Source: https://github.com/1inch/fusion-sdk/blob/main/_autodocs/types.md Represents an intermediate point in a custom auction curve, specifying the token amount and delay from the auction start. ```APIDOC ## CustomPresetPoint ### Description Intermediate point in custom auction curve. ### Type Definition ```typescript type CustomPresetPoint = { toTokenAmount: string delay: number } ``` ### Fields #### toTokenAmount (string) - Required Token amount at this point #### delay (number) - Required Delay from auction start (seconds) ```