### Full WebSocket API Usage Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/websocket-api.md Demonstrates the complete setup and usage of the WebSocket API, including initialization, event handling, subscribing to orders, and closing the connection. ```typescript import { WebSocketApi, NetworkEnum } from '@1inch/cross-chain-sdk' async function monitorOrders() { const wsApi = WebSocketApi.new({ url: 'wss://api.1inch.com/fusion-plus/ws' }) wsApi.init() wsApi.onOpen(() => { console.log('Connected to WebSocket') }) wsApi.onError((error) => { console.error('Connection error:', error) }) wsApi.onClose(() => { console.log('Connection closed') }) // Subscribe to order updates await wsApi.order.subscribe({ srcChainId: NetworkEnum.ETHEREUM, dstChainId: NetworkEnum.POLYGON }) // Handle incoming order updates wsApi.on('message', (data) => { console.log('New order update:', data) }) // Later: unsubscribe // await wsApi.order.unsubscribe() // wsApi.close() } monitorOrders().catch(console.error) ``` -------------------------------- ### Create Order with Custom Preset Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Demonstrates how to use the `createOrder` method with a custom auction preset. This allows fine-tuning auction parameters like duration, start delay, and rate bumps. ```typescript const { order } = sdk.createOrder(quote, { walletAddress: '0x...', hashLock, secretHashes, customPreset: { auctionDuration: 120, // 2 minutes startAuctionIn: 30, // start after 30 seconds initialRateBump: 50000, // 500% bump auctionStartAmount: '1000000000000000000', startAmount: '900000000000000000' } }) ``` -------------------------------- ### Complete Native Asset Order Workflow Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/factories.md This comprehensive example demonstrates the entire process of creating and submitting a native asset order. It includes getting a quote, creating secrets and hashes, building the order, submitting it to the relayer, and finally submitting the order on-chain. ```typescript import { SDK, EvmAddress, HashLock, NativeOrdersFactory, NetworkEnum, randomBytes } from '@1inch/cross-chain-sdk' import { Wallet } from 'ethers' async function createAndSubmitNativeOrder() { const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-key', blockchainProvider: connector }) const wallet = new Wallet(privateKey, provider) // Get quote for native asset const quote = await sdk.getQuote({ amount: '1000000000000000000', // 1 native token srcChainId: NetworkEnum.ETHEREUM, dstChainId: NetworkEnum.POLYGON, srcTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // native dstTokenAddress: '0x...', walletAddress: wallet.address, enableEstimate: true }) // Create secrets const secrets = Array.from({ length: 3 }).map(() => '0x' + randomBytes(32).toString('hex') ) const leaves = HashLock.getMerkleLeaves(secrets) const hashLock = HashLock.forMultipleFills(leaves) const secretHashes = secrets.map(s => HashLock.hashSecret(s)) // Create order const { order, quoteId } = sdk.createOrder(quote, { walletAddress: wallet.address, hashLock, secretHashes }) // Submit to relayer const orderInfo = await sdk.submitNativeOrder( quote.srcChainId, order, EvmAddress.fromString(wallet.address), quoteId, secretHashes ) // Also submit on-chain const factory = NativeOrdersFactory.default(NetworkEnum.ETHEREUM) const call = factory.create( EvmAddress.fromString(wallet.address), orderInfo.order ) const txRes = await wallet.sendTransaction({ to: call.to.toString(), data: call.data, value: call.value // Native token amount }) await provider.waitForTransaction(txRes.hash, 3) console.log('Native order submitted on-chain:', txRes.hash) console.log('Order hash:', orderInfo.orderHash) return orderInfo.orderHash } ``` -------------------------------- ### Complete SDK Import Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/modules.md A comprehensive example demonstrating how to import all major classes, addresses, cryptographic utilities, WebSocket API, factories, network enums, presets, and deployment constants from the SDK. It also shows how to import types separately. ```typescript import { // Main classes SDK, Quote, EvmCrossChainOrder, SvmCrossChainOrder, // Addresses EvmAddress, SolanaAddress, createAddress, // Cryptography HashLock, // WebSocket WebSocketApi, // Factories EvmEscrowFactory, SvmSrcEscrowFactory, SvmDstEscrowFactory, NativeOrdersFactory, // Networks NetworkEnum, isSupportedChain, isEvm, isSolana, // Presets PresetEnum, // Utilities now, randBigInt, bufferFromHex, bufferToHex, isBigintString, // Blockchain providers (from fusion-sdk) PrivateKeyProviderConnector, Web3ProviderConnector, // Contract primitives (from fusion-sdk) MakerTraits, Extension, Address, // Fees (from limit-order-sdk) Bps, // Deployments ESCROW_FACTORY, ESCROW_SRC_IMPLEMENTATION, TRUE_ERC20, // IDLs SVM_ESCROW_SRC_IDL, SVM_ESCROW_DST_IDL } from '@1inch/cross-chain-sdk' // Optional: import types separately import type { CrossChainSDKConfigParams, QuoteParams, OrderParams, PreparedOrder, OrderInfo, PaginationOutput, IntegratorFeeRequest, SupportedChain } from '@1inch/cross-chain-sdk' ``` -------------------------------- ### Full Cross-Chain Order Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/README.md This example demonstrates the complete process of creating, submitting, and managing a cross-chain order using the 1inch SDK. It includes estimating the swap, generating secrets, creating and submitting the order, and monitoring its status. ```typescript import { HashLock, NetworkEnum, OrderStatus, PresetEnum, PrivateKeyProviderConnector, SDK } from '@1inch/cross-chain-sdk' import Web3 from 'web3' import {randomBytes} from 'node:crypto' const privateKey = '0x' const rpc = 'https://ethereum-rpc.publicnode.com' const authKey = 'auth-key' const source = 'sdk-tutorial' const web3 = new Web3(rpc) const walletAddress = web3.eth.accounts.privateKeyToAccount(privateKey).address const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey, blockchainProvider: new PrivateKeyProviderConnector(privateKey, web3) // only required for order creation }) async function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)) } async function main(): Promise { // 10 USDT (Polygon) -> BNB (BSC) // estimate const quote = await sdk.getQuote({ amount: '10000000', srcChainId: NetworkEnum.POLYGON, dstChainId: NetworkEnum.BINANCE, enableEstimate: true, srcTokenAddress: '0xc2132d05d31c914a87c6611c10748aeb04b58e8f', // USDT dstTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // BNB walletAddress }) const preset = PresetEnum.fast // generate secrets const secrets = Array.from({ length: quote.presets[preset].secretsCount }).map(() => '0x' + randomBytes(32).toString('hex')) const hashLock = secrets.length === 1 ? HashLock.forSingleFill(secrets[0]) : HashLock.forMultipleFills(HashLock.getMerkleLeaves(secrets)) const secretHashes = secrets.map((s) => HashLock.hashSecret(s)) // create order const {hash, quoteId, order} = await sdk.createOrder(quote, { walletAddress, hashLock, preset, source, secretHashes }) console.log({hash}, 'order created') // submit order const _orderInfo = await sdk.submitOrder( quote.srcChainId, order, quoteId, secretHashes ) console.log({hash}, 'order submitted') // submit secrets for deployed escrows while (true) { const secretsToShare = await sdk.getReadyToAcceptSecretFills(hash) if (secretsToShare.fills.length) { for (const {idx} of secretsToShare.fills) { // it is responsibility of the client to check whether is safe to share secret (check escrow addresses and so on) await sdk.submitSecret(hash, secrets[idx]) console.log({idx}, 'shared secret') } } // check if order finished const {status} = await sdk.getOrderStatus(hash) if ( status === OrderStatus.Executed || status === OrderStatus.Expired || status === OrderStatus.Refunded ) { break } await sleep(1000) } const statusResponse = await sdk.getOrderStatus(hash) console.log(statusResponse) } main() ``` -------------------------------- ### Example: Get Order Status Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/sdk.md Demonstrates how to fetch and log the status and fills of an order using its hash. ```typescript const status = await sdk.getOrderStatus(orderHash) console.log('Order status:', status.status) console.log('Fills:', status.fills) ``` -------------------------------- ### Install Cross-Chain SDK Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/README.md Installs the @1inch/cross-chain-sdk package using npm. Requires Node.js version 18.16.0 or higher. ```bash npm install @1inch/cross-chain-sdk ``` -------------------------------- ### EVM to EVM Swaps Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/modules.md Demonstrates how to initialize the SDK, get a quote, create, and submit an order for EVM to EVM swaps. ```APIDOC ## EVM to EVM Swaps ### Description This section shows how to use the SDK for standard EVM to EVM token swaps. It covers initialization, obtaining a price quote, constructing an order, and submitting it for execution. ### Method ```typescript // Initialize SDK const sdk = new SDK({ url, authKey, blockchainProvider }) // Get quote const quote = await sdk.getQuote({...}) // Create and sign order const { order, hash } = sdk.createOrder(quote, {...}) // Submit const orderInfo = await sdk.submitOrder(...) ``` ``` -------------------------------- ### Example: Creating and Sending a Native Order Transaction Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/factories.md This example demonstrates how to instantiate the NativeOrdersFactory, create order execution data, and send a transaction including the native token value. Ensure you have the wallet and order information ready. ```typescript import { NativeOrdersFactory, EvmAddress } from '@1inch/cross-chain-sdk' const factory = NativeOrdersFactory.default(NetworkEnum.ETHEREUM) const call = factory.create( EvmAddress.fromString(walletAddress), orderInfo.order ) // Send transaction with native ETH value const txRes = await wallet.sendTransaction({ to: call.to.toString(), data: call.data, value: call.value // Include native token value }) ``` -------------------------------- ### HashLock forMultipleFills Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Example of creating a HashLock instance for multiple secrets using a Merkle tree root. Requires at least 3 leaves. ```typescript const leaves = HashLock.getMerkleLeaves(secrets) const hashLock = HashLock.forMultipleFills(leaves) ``` -------------------------------- ### HashLock getProof Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Example of generating a Merkle proof for a specific leaf. This proof can be used to verify the leaf's inclusion in a contract. ```typescript const proof = HashLock.getProof(leaves, 1) // Use proof to verify leaf[1] in contract ``` -------------------------------- ### Initialize SDK and Get Active Orders Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/sdk/README.md Demonstrates how to initialize the SDK with API credentials and retrieve a list of active orders. Ensure you replace 'your-auth-key' with your actual authentication key. ```typescript import {SDK, NetworkEnum} from '@1inch/cross-chain-sdk' async function main() { const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key' }) const orders = await sdk.getActiveOrders({page: 1, limit: 2}) } main() ``` -------------------------------- ### HashLock forSingleFill Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Example of creating a HashLock instance for a single secret. This generates a HashLock containing the keccak256 hash of the secret. ```typescript const hashLock = HashLock.forSingleFill(secret) ``` -------------------------------- ### Retrieve Active Orders with SDK Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/sdk/README.md Example of how to initialize the SDK and fetch active orders using pagination parameters. Remember to replace 'your-auth-key'. ```typescript import {SDK, NetworkEnum} from '@1inch/cross-chain-sdk' const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key' }) const orders = await sdk.getActiveOrders({page: 1, limit: 2}) ``` -------------------------------- ### Real-world Example of WebSocket API Usage Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/ws-api/README.md Demonstrates how to establish a WebSocket connection and subscribe to order events using the WebSocketApi. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/cross-chain-sdk' const wsSdk = new WebSocketApi({ url: 'wss://api.1inch.com/fusion-plus/ws', authKey: 'your-auth-key' }) wsSdk.order.onOrder((data) => { console.log('received order event', data) }) ``` -------------------------------- ### WebSocket API Initialization Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Demonstrates how to initialize and connect to the WebSocket API for real-time updates. Requires specifying the WebSocket URL and optionally the network and reconnection behavior. ```typescript import { WebSocketApi } from '@1inch/cross-chain-sdk' const wsApi = WebSocketApi.new({ url: 'wss://api.1inch.com/fusion-plus/ws', network: NetworkEnum.ETHEREUM, reconnect: true }) wsApi.init() ``` -------------------------------- ### Example: Submit a Secret Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/sdk.md Demonstrates how to generate a random 32-byte secret and submit it for a given order hash. ```typescript await sdk.submitSecret(orderHash, '0x' + randomBytes(32).toString('hex')) ``` -------------------------------- ### HashLock getMerkleLeaves Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Example of creating Merkle leaves from an array of secrets. Each leaf is generated by hashing the index and the secret. ```typescript const secrets = Array.from({ length: 3 }).map(() => '0x' + randomBytes(32).toString('hex') ) const leaves = HashLock.getMerkleLeaves(secrets) ``` -------------------------------- ### EVM to Solana Cross-Chain Swap Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/README.md Demonstrates a full cross-chain swap from Ethereum (EVM) to Solana. Requires setting up environment variables for API keys and private keys. Ensure the necessary tokens and network configurations are correct. ```typescript import { NetworkEnum, SDK, SolanaAddress, HashLock, EvmAddress, PrivateKeyProviderConnector, OrderStatus } from '@1inch/cross-chain-sdk-solana' import { JsonRpcProvider, TransactionRequest, computeAddress } from 'ethers' import assert from 'node:assert' import { randomBytes } from 'node:crypto' import { setTimeout } from 'node:timers/promises' import 'dotenv/config' const authKey = process.env.DEV_PORTAL_API_TOKEN assert(authKey, 'please provide auth key in DEV_PORTAL_API_TOKEN env. You can grab it at https://portal.1inch.dev') const signerPrivateKey = process.env.EVM_PRIVATE_KEY assert(signerPrivateKey, 'please provide evm private key of the maker wallet in EVM_PRIVATE_KEY env') const NODE_URL = 'https://web3.1inch.io/1' const ethersRpcProvider = new JsonRpcProvider(NODE_URL) const ethersProviderConnector = { eth: { call(transactionConfig: TransactionRequest): Promise { return ethersRpcProvider.call(transactionConfig) } }, extend(): void {} } const connector = new PrivateKeyProviderConnector(signerPrivateKey, ethersProviderConnector) const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: process.env.DEV_PORTAL_API_TOKEN, blockchainProvider: connector }) const maker = computeAddress(signerPrivateKey) const receiver = '93FP8NG2JrScb9xzNsJrzAze8gJJtr1TgQWUCHDgP3BW' const USDT_SOL = 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB' const USDT_ETHEREUM = '0xdac17f958d2ee523a2206206994597c13d831ec7' const amount = 10_000_000n // 10 USDT const srcToken = EvmAddress.fromString(USDT_ETHEREUM) const dstToken = SolanaAddress.fromString(USDT_SOL) // use SolanaAddress.NATIVE for native token const srcChainId = NetworkEnum.ETHEREUM const dstChainId = NetworkEnum.SOLANA async function main(): Promise { const quote = await sdk.getQuote({ amount: amount.toString(), srcChainId, dstChainId, srcTokenAddress: srcToken.toString(), dstTokenAddress: dstToken.toString(), enableEstimate: true, walletAddress: maker }) const preset = quote.getPreset(quote.recommendedPreset) assert(quote.quoteId) console.log('got preset', preset) const secrets = Array.from({ length: preset.secretsCount }).map(getSecret) const secretHashes = secrets.map(HashLock.hashSecret) const leaves = HashLock.getMerkleLeaves(secrets) const hashLock = secrets.length > 1 ? HashLock.forMultipleFills(leaves) : HashLock.forSingleFill(secrets[0]) const order = quote.createEvmOrder({ hashLock, receiver: SolanaAddress.fromString(receiver), preset: quote.recommendedPreset }) const { orderHash } = await sdk.submitOrder(srcChainId, order, quote.quoteId, secretHashes) console.log('submit order to relayer', orderHash) const alreadyShared = new Set() while (true) { const readyToAcceptSecretes = await sdk.getReadyToAcceptSecretFills(orderHash) const idxes = readyToAcceptSecretes.fills.map((f) => f.idx) for (const idx of idxes) { if (!alreadyShared.has(idx)) { // it is responsibility of the client to check whether is safe to share secret (check escrow addresses and so on) await sdk.submitSecret(orderHash, secrets[idx]).catch((err) => console.error('failed to submit secret', err)) alreadyShared.add(idx) console.log('submitted secret', secrets[idx]) } } // check if order finished const { status } = await sdk.getOrderStatus(orderHash) if (status === OrderStatus.Executed || status === OrderStatus.Expired || status === OrderStatus.Refunded) { break } await setTimeout(5000) } const statusResponse = await sdk.getOrderStatus(orderHash) console.log(statusResponse) } function getSecret(): string { return '0x' + randomBytes(32).toString('hex') } main() ``` -------------------------------- ### HashLock hashSecret Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Example of hashing a secret using keccak256. Ensure the secret is a 32-byte hex string with a 0x prefix. ```typescript import { randomBytes } from 'crypto' const secret = '0x' + randomBytes(32).toString('hex') const hash = HashLock.hashSecret(secret) ``` -------------------------------- ### Full Example: Native Asset Cross-Chain Swap Source: https://github.com/1inch/cross-chain-sdk/blob/master/README.md This snippet demonstrates a complete cross-chain swap of native assets using the 1inch SDK. It includes steps for estimating quotes, generating secrets, creating and submitting orders, broadcasting transactions, and sharing secrets to complete the swap. Ensure you have the necessary private key, RPC URL, and authentication key configured. ```typescript import { EvmCrossChainOrder, HashLock, NetworkEnum, OrderStatus, PrivateKeyProviderConnector, SDK, EvmAddress, NativeOrdersFactory, Address } from '@1inch/cross-chain-sdk' import {JsonRpcProvider, Wallet} from 'ethers' import {randomBytes} from 'node:crypto' import assert from "node:assert"; const PRIVATE_KEY = '0x' const WEB3_NODE_URL = 'https://' const AUTH_KEY = 'auth-key' const ethersRpcProvider = new JsonRpcProvider(WEB3_NODE_URL) const ethersProviderConnector = { eth: { call(transactionConfig): Promise { return ethersRpcProvider.call(transactionConfig) } }, extend(): void {} } const connector = new PrivateKeyProviderConnector( PRIVATE_KEY, ethersProviderConnector ) const wallet = new Wallet(PRIVATE_KEY, ethersRpcProvider) const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: AUTH_KEY, blockchainProvider: connector, }) async function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)) } async function main(): Promise { // estimate const quote = await sdk.getQuote({ amount: '400000000000000000', srcChainId: NetworkEnum.AVALANCHE, dstChainId: NetworkEnum.BINANCE, enableEstimate: true, srcTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // AVAX dstTokenAddress: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', // USDC walletAddress: wallet.address }) const preset = quote.recommendedPreset // generate secrets const secrets = Array.from({ length: quote.presets[preset].secretsCount }).map(() => '0x' + randomBytes(32).toString('hex')) const hashLock = secrets.length === 1 ? HashLock.forSingleFill(secrets[0]) : HashLock.forMultipleFills(HashLock.getMerkleLeaves(secrets)) const secretHashes = secrets.map((s) => HashLock.hashSecret(s)) // create order const {hash, quoteId, order} = sdk.createOrder(quote, { walletAddress: wallet.address, hashLock, preset, source: 'sdk-tutorial', secretHashes }) assert(order instanceof EvmCrossChainOrder) console.log({hash}, 'order created') // submit order const orderInfo = await sdk.submitNativeOrder( quote.srcChainId, order, EvmAddress.fromString(wallet.address), quoteId, secretHashes ) console.log({hash}, 'order submitted') const factory = NativeOrdersFactory.default(NetworkEnum.AVALANCHE) const call = factory.create(new Address(wallet.address), orderInfo.order) const txRes = await wallet.sendTransaction({ to: call.to.toString(), data: call.data, value: call.value }) console.log({txHash: txRes.hash}, 'transaction broadcasted') await wallet.provider.waitForTransaction(txRes.hash, 3) // submit secrets for deployed escrows while (true) { const secretsToShare = await sdk.getReadyToAcceptSecretFills(hash) if (secretsToShare.fills.length) { for (const {idx} of secretsToShare.fills) { // it is responsibility of the client to check whether is safe to share secret (check escrow addresses and so on) await sdk.submitSecret(hash, secrets[idx]) console.log({idx}, 'shared secret') } } // check if order finished const {status} = await sdk.getOrderStatus(hash) if ( status === OrderStatus.Executed || status === OrderStatus.Expired || status === OrderStatus.Refunded ) { break } await sleep(1000) } const statusResponse = await sdk.getOrderStatus(hash) console.log(statusResponse) } main() ``` -------------------------------- ### Handle Basis Points for Fees Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/utils.md Provides an example of creating, comparing, and calculating fee amounts using the Bps class. ```typescript import { Bps } from '@1inch/cross-chain-sdk' // Create fee const fee = new Bps(500n) // 5% // Check if equal if (fee.eq(new Bps(500n))) { console.log('Fee is 5%') } // Calculate fee amount const amount = BigInt('1000000000000000000') const feeAmount = amount * BigInt(fee.toNumber()) / BigInt(10000) ``` -------------------------------- ### Create Solana Order Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/factories.md This snippet demonstrates the complete process of creating an order on Solana. It includes fetching a quote, generating secrets, creating the order object, announcing it to the relayer, and finally submitting the on-chain instruction to the Solana network. Ensure you have the necessary SDK imports and wallet setup. ```typescript import { SDK, SvmSrcEscrowFactory, SolanaAddress, EvmAddress, HashLock, NetworkEnum, randomBytes } from '@1inch/cross-chain-sdk' import { web3 } from '@coral-xyz/anchor' async function createSolanaOrder() { const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-key' }) const maker = 'wallet_address_base58' const receiver = '0xevmaddress' // Get quote const quote = await sdk.getQuote({ amount: '1000000', // 1 USDT srcChainId: NetworkEnum.SOLANA, dstChainId: NetworkEnum.ETHEREUM, srcTokenAddress: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT dstTokenAddress: '0xdac17f958d2ee523a2206206994597c13d831ec7', walletAddress: maker, enableEstimate: true }) // Create secrets const secrets = Array.from({ length: 2 }).map(() => '0x' + randomBytes(32).toString('hex') ) const leaves = HashLock.getMerkleLeaves(secrets) const hashLock = HashLock.forMultipleFills(leaves) const secretHashes = secrets.map(s => HashLock.hashSecret(s)) // Create order const order = quote.createSolanaOrder({ hashLock, receiver: EvmAddress.fromString(receiver) }) // Announce to relayer const orderHash = await sdk.announceOrder( order, quote.quoteId, secretHashes ) // Create on-chain instruction const factory = SvmSrcEscrowFactory.DEFAULT const instruction = factory.createOrder(order, { srcTokenProgramId: SolanaAddress.TOKEN_PROGRAM_ID }) // Submit on-chain const connection = new web3.Connection(solanaRpc) const tx = new web3.Transaction().add({ data: instruction.data, programId: new web3.PublicKey(instruction.programId.toBuffer()), keys: instruction.accounts.map(a => ({ isSigner: a.isSigner, isWritable: a.isWritable, pubkey: new web3.PublicKey(a.pubkey.toBuffer()) })) }) const signature = await connection.sendTransaction(tx, [signer]) console.log('Solana order created:', orderHash) console.log('On-chain tx:', signature) return { orderHash, txSignature: signature } } ``` -------------------------------- ### Implement Custom HTTP Provider Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/sdk/README.md Provides an example of a custom HTTP provider implementation 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) } } ``` -------------------------------- ### Example: Submit Secrets for Fills Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/sdk.md Iterates through fills ready to accept secrets for a given order and submits the corresponding secret for each fill. ```typescript const { fills } = await sdk.getReadyToAcceptSecretFills(orderHash) for (const { idx } of fills) { await sdk.submitSecret(orderHash, secrets[idx]) } ``` -------------------------------- ### SDK Initialization and Usage Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/sdk/README.md Demonstrates how to initialize the SDK with API credentials and use it to fetch active orders. ```APIDOC ## SDK Initialization and Real-world Example ### Description Provides high-level functionality to work with fusion plus mode. This example shows how to initialize the SDK and fetch active orders. ### Method POST ### Endpoint /fusion-plus ### Parameters #### Constructor Arguments - **url** (string) - Required - The base URL for the 1inch API. - **authKey** (string) - Required - Your authentication key for the 1inch API. - **blockchainProvider** (BlockchainProviderConnector) - Optional - A provider for blockchain interactions. - **httpProvider** (HttpProviderConnector) - Optional - A custom HTTP provider (defaults to Axios). ### Request Example ```typescript import {SDK, NetworkEnum} from '@1inch/cross-chain-sdk' async function main() { const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key' }) const orders = await sdk.getActiveOrders({page: 1, limit: 2}) console.log(orders) } main() ``` ### Response #### Success Response (200) - **orders** (Array) - A list of active orders. #### Response Example ```json { "orders": [ { "id": "123", "status": "active" } ] } ``` ``` -------------------------------- ### Get Hex String Representation Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/addresses.md Get the hexadecimal string representation of a SolanaAddress, prefixed with '0x'. ```typescript toHex(): string ``` -------------------------------- ### Initialize SDK Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/sdk.md Instantiate the SDK with API configuration and an optional blockchain provider for signing orders. ```typescript import { SDK, PrivateKeyProviderConnector } from '@1inch/cross-chain-sdk' import Web3 from 'web3' const rpc = 'https://ethereum-rpc.publicnode.com' const web3 = new Web3(rpc) const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key', blockchainProvider: new PrivateKeyProviderConnector(privateKey, web3) }) ``` -------------------------------- ### Example of Setting Integrator Fee in Quote Request Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Demonstrates how to include an integrator fee when requesting a quote. The fee is specified with a receiver address and a value in basis points. ```typescript const quote = await sdk.getQuote({ // ... other params ... integratorFee: { receiver: EvmAddress.fromString('0x1234...'), value: new Bps(100n) // 1% fee } }) ``` -------------------------------- ### Get Active Orders - TypeScript Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/ws-api/README.md Retrieve a list of all currently active orders. This can be used to get an overview of open orders in the system. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/cross-chain-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion-plus/ws' }) ws.rpc.getActiveOrders() ``` -------------------------------- ### Web3ProviderConnector Initialization Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Sets up the SDK to use a Web3 provider (like MetaMask) for signing orders. This is useful for browser-based applications. ```typescript import { Web3ProviderConnector } from '@1inch/fusion-sdk' const connector = new Web3ProviderConnector(window.ethereum) const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key', blockchainProvider: connector }) ``` -------------------------------- ### Initialize Cross Chain SDK Source: https://github.com/1inch/cross-chain-sdk/blob/master/README.md Set up the SDK with API endpoint, authentication key, and blockchain provider. The blockchain provider is only required for order creation. ```typescript const privateKey = '0x' const rpc = 'https://ethereum-rpc.publicnode.com' const authKey = 'auth-key' const source = 'sdk-tutorial' const web3 = new Web3(rpc) const walletAddress = web3.eth.accounts.privateKeyToAccount(privateKey).address const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey, blockchainProvider: new PrivateKeyProviderConnector(privateKey, web3) // only required for order creation }) ``` -------------------------------- ### Verify Token Balance Before Order Creation Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/errors.md Prevent 'Insufficient Balance' errors by checking the maker's token balance against the order amount before creating the order. This example shows a basic balance check for native tokens. ```typescript // Verify balance before creating order const balance = await web3.eth.getBalance(makerAddress) if (BigInt(balance) < BigInt(amount)) { throw new Error('Insufficient balance') } ``` -------------------------------- ### SDK Constructor Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/sdk.md Initializes the 1inch Cross-Chain SDK with the necessary configuration. This is the main entry point for using the SDK. ```APIDOC ## Constructor Initializes the 1inch Cross-Chain SDK. ### Signature ```typescript new SDK(config: CrossChainSDKConfigParams) ``` ### Parameters #### config (`CrossChainSDKConfigParams`) - **url** (`string`) - Required - API base URL (e.g., `https://api.1inch.com/fusion-plus`) - **authKey** (`string`) - Optional - Authentication key for API requests - **blockchainProvider** (`BlockchainProviderConnector`) - Optional - Blockchain provider for signing orders; required for order creation/signing - **httpProvider** (`HttpProviderConnector`) - Optional - Custom HTTP provider for API requests ### Example ```typescript import { SDK, PrivateKeyProviderConnector } from '@1inch/cross-chain-sdk' import Web3 from 'web3' const rpc = 'https://ethereum-rpc.publicnode.com' const web3 = new Web3(rpc) const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key', blockchainProvider: new PrivateKeyProviderConnector(privateKey, web3) }) ``` ``` -------------------------------- ### HashLock getPartsCount Example Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Example of extracting the number of secrets (parts count) from a Merkle tree-based HashLock. Note that this is only valid for hash locks created with forMultipleFills(). ```typescript const hashLock = HashLock.forMultipleFills(leaves) console.log('Secrets:', Number(hashLock.getPartsCount()) + 1) ``` -------------------------------- ### now() Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/utils.md Get current Unix timestamp in seconds. ```APIDOC ## now() ### Description Get current Unix timestamp in seconds. ### Signature ```typescript function now(): bigint ``` ### Return Returns current time as bigint (seconds). ### Example ```typescript import { now } from '@1inch/cross-chain-sdk' const timestamp = now() const deadline = BigInt(Number(timestamp) + 3600) // 1 hour from now ``` ``` -------------------------------- ### PrivateKeyProviderConnector Initialization Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Configures the SDK to sign orders using a private key. Requires importing `PrivateKeyProviderConnector` and initializing it with the private key and a Web3 instance. ```typescript import { PrivateKeyProviderConnector } from '@1inch/cross-chain-sdk' import Web3 from 'web3' const web3 = new Web3(rpc) const connector = new PrivateKeyProviderConnector(privateKey, web3) const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-auth-key', blockchainProvider: connector }) ``` -------------------------------- ### Get EvmAddress as Buffer Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/addresses.md Retrieves the buffer representation of an EvmAddress. ```typescript import { EvmAddress } from '@1inch/cross-chain-sdk'; const addr = EvmAddress.fromString('0xdac17f958d2ee523a2206206994597c13d831ec7'); const buffer = addr.toBuffer(); // ``` -------------------------------- ### QuoteParams Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/sdk/README.md Parameters required to get a quote for a token swap. ```APIDOC ## QuoteParams ### Description Parameters required to get a quote for a token swap. ### Parameters #### Request Body - **fromTokenAddress** (string) - Required - The address of the token to swap from. - **toTokenAddress** (string) - Required - The address of the token to swap to. - **amount** (string) - Required - The amount of the `fromToken` to swap. - **permit** (string) - Optional - A permit (EIP-2612) call data for user approval. - **takingFeeBps** (number) - Optional - The fee in basis points (100 == 1%). ``` -------------------------------- ### Using Solana IDLs with Anchor Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/utils.md Shows how to import and use Solana IDLs with the Anchor framework to create program instances. ```typescript import { SVM_ESCROW_SRC_IDL, SVM_ESCROW_DST_IDL } from '@1inch/cross-chain-sdk' // Use with Anchor to create program instances const program = new Program(SVM_ESCROW_SRC_IDL, programId, provider) ``` -------------------------------- ### Get BigInt Representation Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/addresses.md Retrieve the BigInt representation of a SolanaAddress instance. ```typescript toBigint(): bigint ``` -------------------------------- ### Get Fills Ready for Secrets Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Checks for fills that are ready to have their secrets revealed. ```APIDOC ## GET /orders/{hash}/secrets/ready-to-accept ### Description Get fills ready for secrets ### Method GET ### Endpoint /orders/{hash}/secrets/ready-to-accept ### Parameters #### Path Parameters - **hash** (string) - Required - The unique hash of the order. ``` -------------------------------- ### Initialize SDK for EVM Swaps Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/modules.md Initializes the SDK for cross-chain operations, specifically for EVM-based swaps. Requires configuration for URL, authentication key, and blockchain provider. ```typescript import { SDK, EvmAddress, HashLock, NetworkEnum } from '@1inch/cross-chain-sdk' // Initialize SDK const sdk = new SDK({ url, authKey, blockchainProvider }) // Get quote const quote = await sdk.getQuote({...}) // Create and sign order const { order, hash } = sdk.createOrder(quote, {...}) // Submit const orderInfo = await sdk.submitOrder(...) ``` -------------------------------- ### Get Order Status Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Retrieves the status of a specific order using its hash. ```APIDOC ## GET /orders/{hash} ### Description Get order status ### Method GET ### Endpoint /orders/{hash} ### Parameters #### Path Parameters - **hash** (string) - Required - The unique hash of the order. ``` -------------------------------- ### Main Entry Point Import Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/modules.md All public APIs are available from the main entry point of the SDK. ```typescript import { ... } from '@1inch/cross-chain-sdk' ``` -------------------------------- ### toBuffer() Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/hashlock.md Gets the buffer representation of the HashLock. Returns the hash lock as a 32-byte buffer. ```APIDOC ## toBuffer() ### Description Gets the buffer representation of the HashLock. ### Return Returns the hash lock as a 32-byte buffer. ### Method Signature ```typescript toBuffer(): Buffer ``` ``` -------------------------------- ### Get Orders by Maker Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/configuration.md Retrieves all orders associated with a specific maker's address. ```APIDOC ## GET /orders/by-maker/{maker} ### Description Get orders by maker ### Method GET ### Endpoint /orders/by-maker/{maker} ### Parameters #### Path Parameters - **maker** (string) - Required - The address of the order maker. ``` -------------------------------- ### Websocket API Initialization Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/ws-api/README.md Demonstrates various ways to initialize the WebSocketApi, including custom providers and lazy initialization. ```APIDOC ## WebSocketApi Initialization ### With constructor: ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/cross-chain-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', authKey: 'your-auth-key' }) ``` ### Custom provider: User can provide custom provider for websocket (be default we are using [ws library](https://www.npmjs.com/package/ws)) ```typescript import {WsProviderConnector, WebSocketApi} from '@1inch/cross-chain-sdk' class MyFancyProvider implements WsProviderConnector { // ... user implementation } const url = 'wss://api.1inch.com/fusion-plus/ws/v1.2' const provider = new MyFancyProvider({url}) const wsSdk = new WebSocketApi(provider) ``` ### With new static method: ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/cross-chain-sdk' const ws = WebSocketApi.new({ url: 'wss://api.1inch.com/fusion-plus/ws', }) ``` ### Lazy initialization: By default, when user creates an instance of WebSocketApi, it automatically opens websocket connection which might be a problem for some use cases ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/cross-chain-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion-plus/ws', network: NetworkEnum.ETHEREUM, lazyInit: true }) ws.init() ``` ``` -------------------------------- ### Get EvmAddress as Hex String Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/addresses.md Retrieves the checksummed hexadecimal string representation of an EvmAddress. ```typescript import { EvmAddress } from '@1inch/cross-chain-sdk'; const addr = EvmAddress.fromString('0xdac17f958d2ee523a2206206994597c13d831ec7'); const hexString = addr.toString(); // '0xdAc17f958d2ee523a2206206994597c13d831Ec7' ``` -------------------------------- ### Initialize SDK with Authentication Key Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/errors.md Provide a valid API key from the Dev Portal when initializing the SDK to avoid authentication errors. ```typescript const sdk = new SDK({ url: 'https://api.1inch.com/fusion-plus', authKey: 'your-valid-key' // Get from https://portal.1inch.dev }) ``` -------------------------------- ### Get EvmAddress JSON Representation Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/addresses.md Provides the JSON serialization of an EvmAddress, which is its hexadecimal string representation. ```typescript import { EvmAddress } from '@1inch/cross-chain-sdk'; const addr = EvmAddress.fromString('0xdac17f958d2ee523a2206206994597c13d831ec7'); const jsonString = addr.toJSON(); // '0xdAc17f958d2ee523a2206206994597c13d831Ec7' ``` -------------------------------- ### Handle Native Asset Orders Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/modules.md Demonstrates how to create and submit orders for native assets (like ETH or SOL). This involves quoting for the native token, creating the order, submitting it to the relayer, and also submitting it on-chain with the correct native value. ```typescript import { SDK, EvmAddress, NativeOrdersFactory } from '@1inch/cross-chain-sdk' // Get quote for native token const quote = await sdk.getQuote({ srcTokenAddress: '0xeeee...' // native }) // Create order const order = quote.createEvmOrder({...}) // Submit to relayer const orderInfo = await sdk.submitNativeOrder( quote.srcChainId, order, EvmAddress.fromString(maker), quote.quoteId, secretHashes ) // Also submit on-chain const factory = NativeOrdersFactory.default(quote.srcChainId) const call = factory.create(EvmAddress.fromString(maker), orderInfo.order) // Send transaction with native value await wallet.sendTransaction({ to: call.to.toString(), data: call.data, value: call.value }) ``` -------------------------------- ### SvmCrossChainOrder Properties Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/orders.md Access properties of an SvmCrossChainOrder object to get details about the Solana cross-chain order. ```typescript get srcToken(): SolanaAddress get dstToken(): EvmAddress get srcAmount(): bigint get minDstAmount(): bigint get maker(): SolanaAddress get receiver(): EvmAddress get hashLock(): HashLock get auction(): AuctionDetails get multipleFillsAllowed(): boolean get dstChainId(): SupportedChain ``` -------------------------------- ### Get Cancellable Orders by API Version Source: https://github.com/1inch/cross-chain-sdk/blob/master/docs/v2-migration-guide.md Filter cancellable orders by specifying an array of `ApiVersion`. ```typescript import { ApiVersion } from '@1inch/cross-chain-sdk' // Get cancellable orders for specific version const cancellable = await sdk.getCancellableOrders( ChainType.EVM, 1, 100, [ApiVersion.V1_2] ) ``` -------------------------------- ### Creating WebSocketApi Instance with Constructor Source: https://github.com/1inch/cross-chain-sdk/blob/master/src/ws-api/README.md Shows how to instantiate the WebSocketApi using its constructor with a specified URL and authentication key. ```typescript import {WebSocketApi, NetworkEnum} from '@1inch/cross-chain-sdk' const ws = new WebSocketApi({ url: 'wss://api.1inch.com/fusion/ws', authKey: 'your-auth-key' }) ``` -------------------------------- ### Get Published Secrets Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/sdk.md Retrieves the published secrets associated with a specific order, identified by its order hash. ```typescript async getPublishedSecrets(orderHash: string): Promise ``` -------------------------------- ### Get Base58 String Representation Source: https://github.com/1inch/cross-chain-sdk/blob/master/_autodocs/api-reference/addresses.md Convert a SolanaAddress instance back to its Base58 encoded string format. ```typescript toString(): string ```