Skip to Content
Avail Nexus is now live! Check out our docs to get started.

swapWithExactOut()

SET UP THE SDK BEFORE YOU START:

  1. You can find the SDK setup instructions in the Quickstart page.
  2. We also created a tutorial to make it easier to understand how devs need to initialize the Nexus SDK in their project.

Use the swapWithExactOut() function to swap tokens with an exactly defined output amount. For example, if you want to get exactly 1 ETH on the destination but don’t care which funds are used to source the swap.

Method signature

Typescript
async swapWithExactOut( input: ExactOutSwapInput, options?: OnEventParam, ): Promise<SwapResult>

Parameters

Typescript
export interface ExactOutSwapInput { toChainId: number; toTokenAddress: Hex; toAmount: bigint; }
  • ExactOutSwapInput: Parameters for using the swapWithExactOut() function.

    • toChainId (number, required): The chain ID of the destination chain.
    • toTokenAddress (Hex, required): The address of the token to be swapped to.
    • toAmount (bigint, required): The amount of tokens to be swapped to.
  • options: OnEventParam (optional): Optional callback function to listen to the events emitted by the swap operation.

    • onEvent: SDK emits these events as the transaction progresses. This is helpful to add when trying to display transaction progress to the user. With this you receive:
      • SWAP_STEP_COMPLETE: A single SwapStepType that is emitted for each completed step of the intent’s fulfillment.
  1. Either of the Swap methods don’t emit STEPS_LIST events.
  2. You can check out the type definitions for each step type in the Swap Events page.

Example

Typescript
import { SwapResult, NEXUS_EVENTS } from '@avail-project/nexus-core'; const swapWithExactOutResult = await sdk.swapWithExactOut({ toChainId: 1, toTokenAddress: '0x...', toAmount: 1_000_000n, }, { onEvent: (event) => { if (event.name === NEXUS_EVENTS.SWAP_STEP_COMPLETE) { console.log('Swap step complete:', event.args); } }, }); console.log('Swap with exact out result:', swapWithExactOutResult);

Return Value

The return value is a SwapResult object.

Typescript
export type SwapResult = | { success: true; result: SuccessfulSwapResult; } | { success: false; error: string }; export type SuccessfulSwapResult = { sourceSwaps: ChainSwap[]; explorerURL: string; destinationSwap: ChainSwap | null; }; export type ChainSwap = { chainId: number; swaps: Swap[]; txHash: Hex; }; export type Swap = { inputAmount: bigint; inputContract: Hex; inputDecimals: number; outputAmount: bigint; outputContract: Hex; outputDecimals: number; };
Last updated on