Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/availproject/nexus-sdk/llms.txt

Use this file to discover all available pages before exploring further.

swapWithExactIn

Swap tokens specifying the exact input amount. Useful when you want to swap fixed amounts from specific chains.
await sdk.swapWithExactIn(
  input: ExactInSwapInput,
  options?: OnEventParam
): Promise<SwapResult>

Parameters

input
ExactInSwapInput
required
Swap input parameters
options
OnEventParam
Event callbacks for progress tracking

Returns

SwapResult
object

Example

import { NexusSDK } from '@avail-project/nexus-core';

// Swap USDC from Optimism to ETH on Base
const result = await sdk.swapWithExactIn({
  from: [
    {
      chainId: 10, // Optimism
      tokenAddress: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85', // USDC
      amount: 1_000_000n, // 1 USDC
    },
  ],
  toChainId: 8453, // Base
  toTokenAddress: '0x0000000000000000000000000000000000000000', // ETH
});

console.log('Swap complete!');
console.log('Explorer:', result.result.explorerURL);

swapWithExactOut

Swap tokens specifying the exact output amount. The SDK automatically determines the required input from available balances.
await sdk.swapWithExactOut(
  input: ExactOutSwapInput,
  options?: OnEventParam
): Promise<SwapResult>

Parameters

input
ExactOutSwapInput
required
Swap input parameters
options
OnEventParam
Event callbacks

Returns

SwapResult
object
Same structure as swapWithExactIn() return value

Example

// Get exactly 1 ETH on Base
const result = await sdk.swapWithExactOut({
  toChainId: 8453, // Base
  toTokenAddress: '0x0000000000000000000000000000000000000000', // ETH
  toAmount: 1_000_000_000_000_000_000n, // 1 ETH
});

console.log('Received exactly 1 ETH on Base');
console.log('Source swaps:', result.result.sourceSwaps);

getSwapSupportedChains

Get list of chains and tokens that support swap operations.
sdk.getSwapSupportedChains(): SupportedChainsResult

Returns

SupportedChainsResult
array
Array of supported chains

Example

const supportedChains = sdk.getSwapSupportedChains();

console.log('Swap supported chains:');
supportedChains.forEach(chain => {
  console.log(`- ${chain.name} (${chain.id})`);
});

// Check if specific chain supports swaps
const baseSupported = supportedChains.some(c => c.id === 8453);
console.log('Base supports swaps:', baseSupported);

Swap Hooks

Set up swap intent hook for user approval:
sdk.setOnSwapIntentHook(async ({ intent, allow, deny, refresh }) => {
  // Display swap details to user
  console.log('Swap Intent:');
  console.log('From:', intent.sources);
  console.log('To:', intent.destination);
  console.log('Gas:', intent.destination.gas);
  
  // User interaction
  if (userApprovesSwap) {
    allow();
  } else {
    deny(); // Throws USER_DENIED_INTENT error
  }
  
  // Optionally refresh to get updated quote
  const refreshedIntent = await refresh();
  console.log('Updated quote:', refreshedIntent);
});

Swap Intent Structure

type SwapIntent = {
  destination: {
    amount: string; // Output amount
    chain: { id: number; name: string; logo: string };
    token: { contractAddress: Hex; decimals: number; symbol: string };
    gas: {
      amount: string; // Gas amount
      token: { contractAddress: Hex; decimals: number; symbol: string };
    };
  };
  sources: Array<{
    amount: string; // Input amount
    chain: { id: number; name: string; logo: string };
    token: { contractAddress: Hex; decimals: number; symbol: string };
  }>;
};

Swap Steps

Track swap progress with event callbacks:
import { NEXUS_EVENTS } from '@avail-project/nexus-core';

const result = await sdk.swapWithExactIn(input, {
  onEvent: (event) => {
    if (event.name === NEXUS_EVENTS.SWAP_STEP_COMPLETE) {
      const step = event.args;
      
      switch (step.type) {
        case 'SWAP_START':
          console.log('Swap started');
          break;
          
        case 'DETERMINING_SWAP':
          console.log('Calculating optimal swap route...');
          break;
          
        case 'SOURCE_SWAP_HASH':
          console.log('Source swap TX:', step.explorerURL);
          break;
          
        case 'RFF_ID':
          console.log('Request for funds ID:', step.data);
          break;
          
        case 'DESTINATION_SWAP_HASH':
          console.log('Destination swap TX:', step.explorerURL);
          break;
          
        case 'SWAP_COMPLETE':
          console.log('Swap complete!');
          break;
      }
    }
  },
});

Swap Step Types

Step TypeDescription
SWAP_STARTSwap operation started
DETERMINING_SWAPCalculating optimal swap route
CREATE_PERMIT_EOA_TO_EPHEMERALCreating permit for ephemeral wallet
CREATE_PERMIT_FOR_SOURCE_SWAPCreating permit for source swap
SOURCE_SWAP_BATCH_TXExecuting source chain swaps
SOURCE_SWAP_HASHSource swap transaction hash
BRIDGE_DEPOSITBridge deposit for cross-chain swap
RFF_IDRequest for funds ID
DESTINATION_SWAP_BATCH_TXExecuting destination swaps
DESTINATION_SWAP_HASHDestination swap transaction hash
SWAP_COMPLETESwap completed successfully
SWAP_SKIPPEDSwap skipped (sufficient balance exists)

Error Handling

import { NexusError, ERROR_CODES } from '@avail-project/nexus-core';

try {
  const result = await sdk.swapWithExactIn({
    from: [{ chainId: 10, tokenAddress: '0x...', amount: 1_000_000n }],
    toChainId: 8453,
    toTokenAddress: '0x...',
  });
} catch (error) {
  if (error instanceof NexusError) {
    switch (error.code) {
      case ERROR_CODES.INSUFFICIENT_BALANCE:
        console.error('Insufficient balance for swap');
        break;
        
      case ERROR_CODES.USER_DENIED_INTENT:
        console.log('User cancelled swap');
        break;
        
      case ERROR_CODES.SWAP_FAILED:
        console.error('Swap failed:', error.message);
        break;
        
      case ERROR_CODES.QUOTE_FAILED:
        console.error('Failed to get swap quote');
        break;
        
      case ERROR_CODES.RATES_CHANGED_BEYOND_TOLERANCE:
        console.error('Price moved too much - please try again');
        break;
        
      default:
        console.error('Swap error:', error.message);
    }
  }
}

swapAndExecute

Combine a swap operation with a smart contract execution. This is useful for scenarios where you want to swap tokens and immediately use them in a DeFi protocol.
await sdk.swapAndExecute(
  input: SwapAndExecuteParams,
  options?: OnEventParam
): Promise<SwapAndExecuteResult>

Parameters

input
SwapAndExecuteParams
required
Swap and execute parameters combining swap input with execution details
options
OnEventParam
Event callbacks for progress tracking

Example

import { NexusSDK } from '@avail-project/nexus-core';

const sdk = new NexusSDK({ network: 'mainnet' });
await sdk.initialize(window.ethereum);

// Swap to USDC and deposit into a DeFi protocol
const result = await sdk.swapAndExecute({
  toChainId: 8453, // Base
  toTokenAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
  toAmount: 100_000_000n, // 100 USDC
  execute: {
    to: '0xDeFiProtocolAddress',
    data: encodedDepositCall,
    tokenApproval: {
      token: 'USDC',
      amount: 100_000_000n,
      spender: '0xDeFiProtocolAddress',
    },
  },
});

console.log('Execution complete:', result.executeTransactionHash);
The SDK will automatically determine the optimal source chains and amounts needed to achieve the desired output amount for the swap and execution.

Balance Operations

Get balances for swap

Events & Steps

Track swap progress