# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.anyalt.finance/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

AnyAlt is a developer tool designed specifically for web3 projects, empowering them to achieve seamless cross-chain execution. In an ecosystem where users hold assets on various blockchains, AnyAlt provides a streamlined way to bridge the gap between chains, enabling complex operations with ease.

At its core, AnyAlt is built on two main components:

* **Cross-Chain Swap:** This function allows end-users to swap tokens directly between different blockchain networks. For example, a user can effortlessly convert ETH on Arbitrum to SOL on Solana. This capability opens up new possibilities for decentralized finance (DeFi) and other web3 applications by removing the friction of token silos.
* **Last-Mile Transaction:** Once a token swap is complete, the last-mile transaction function comes into play. It allows end-users to execute a final, project-specific transaction. This step ensures that the desired action—whether it’s interacting with a smart contract, staking tokens, or any other blockchain operation—is completed seamlessly on the destination chain.

By integrating these two functions, AnyAlt provides a robust solution that not only supports cross-chain token swaps but also enables projects to achieve high conversion rates by simplifying the user journey. The tool abstracts much of the complexity inherent in multi-chain operations, making it easier for developers to build advanced web3 applications.

AnyAlt offers two integration interfaces:

* **Widget Interface:** Comes with a pre-built UI, minimizing implementation effort and providing a plug-and-play experience for rapid deployment.
* **SDK (Software Development Kit):** Offers core functionalities without a UI, allowing developers to incorporate AnyAlt’s features into their own custom interfaces and designs.

In summary, AnyAlt is a powerful solution for modern web3 projects looking to harness the full potential of cross-chain interactions while maintaining a high-quality user experience.


# Overview

The Widget is a plug-and-play integration option designed for developers who prefer a ready-made user interface that simplifies the implementation process. This interface encapsulates the core functionalities of AnyAlt, providing a seamless, out-of-the-box experience for executing cross-chain swaps and last-mile transactions.

**Key Features:**

* **Pre-Built User Interface:**\
  The widget comes with a fully functional, responsive UI that handles all user interactions. It minimizes development overhead by eliminating the need to build custom interfaces from scratch.
* **Simplified Integration:**\
  With the widget, projects can quickly integrate AnyAlt’s capabilities without deep diving into underlying complexities. The provided UI components take care of token selection, chain switching, and transaction execution.
* **Cross-Chain Swap Functionality:**\
  The widget facilitates the token swap process across different blockchain networks, allowing users to effortlessly convert tokens from a source chain to a destination chain. For example, users can swap ETH on Arbitrum for SOL on Solana.
* **Last-Mile Transaction Execution:**\
  After the token swap, the widget enables the final project-specific transaction to be executed. This ensures that users can complete the desired actions defined by the project in a seamless flow.
* **Customization Options:**\
  While the widget is designed to work out-of-the-box, it also offers configuration options such as theme customization and layout adjustments, allowing projects to align the interface with their branding guidelines.

The Widget interface is ideal for web3 projects that prioritize rapid development and consistent user experience. By leveraging the pre-built UI components, developers can focus on integrating core business logic while AnyAlt handles the intricacies of cross-chain operations.


# Getting Started

{% hint style="warning" %}
AnyAlt Widget requires an API key.

Contact us via the [form](https://9vi3topj6b2.typeform.com/to/F3Lnpo5u) and get your API key first.&#x20;
{% endhint %}

Integrating the AnyAlt Widget into your web3 project is simple and straightforward. Follow these steps to quickly get up and running:

### Step 1: Install the Package

Begin by installing the AnyAlt widget and \`@tanstack/react-query\`, which is a direct dependency, using your package manager of choice

```bash
npm install @anyalt/widget @tanstack/react-query
# or
yarn add @anyalt/widget @tanstack/react-query
# or
pnpm add @anyalt/widget @tanstack/react-query
```

> **Note:** Ensure that your project is using `react` and `react-dom` version 18 or 19, as these are required dependencies for the `@anyalt/widget` package.

### Step 2: Import the font family and styles

```tsx
import '@fontsource/rethink-sans/400.css';
import '@fontsource/rethink-sans/500.css';
import '@fontsource/rethink-sans/600.css';

import '@solana/wallet-adapter-react-ui/styles.css';
import '@rainbow-me/rainbowkit/styles.css';
```

### Step 2: Wrap Your Application with the providers

The `QueryClientProvider` and `WidgetProvider` set up the required context (such as theming) for the widget. In your main application file, import the provider along with the default theme and wrap your app as shown below:

```jsx
import React from "react";
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { whiteTheme, defaultTheme, WidgetProvider } from "@anyalt/widget";

const queryClient = new QueryClient();
const theme = 'default';

export const App = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <WidgetProvider theme={theme === 'white' ? whiteTheme : defaultTheme}>
        {/* Your Application Components */}
      </WidgetProvider>
    </QueryClientProvider>
  );
};
```

> **Note:**\
> You can customize the theme by providing your own theme object instead of `defaultTheme` if you wish to match your project’s branding.

### Step 3: Import and Use the AnyAltWidget

Create a component that imports and uses the `AnyaltWidget`. The widget handles the UI for cross-chain swaps and last-mile transactions. A sample integration might look like this:

```jsx
import React from "react";
import {
  AnyaltWidget,
  ChainType,
  useModal,
} from "@anyalt/widget";

import "@solana/wallet-adapter-react-ui/styles.css";
import "@rainbow-me/rainbowkit/styles.css";

const Widget = () => {
  // useModal hook provides control over the widget’s modal state
  const { isOpen, onOpen, onClose } = useModal();

  // Define a callback to estimate transaction details before execution
  const estimateCallback = async (token) => {
    // Implement estimation logic here
    return {
      amountOut: "123.45",
      priceInUSD: "567",
    };
  };

  // Define a callback to execute the last-mile transaction
  const executeCallBack = async (token) => {
    // Implement execution logic here
    return {
      approvalTxHash: "0x123",
      executeTxHash: "0x123",
      amountOut: "123.45",
    };
  };

  return (
    <>
      <button onClick={onOpen}>Open</button>
      <AnyaltWidget
        swapResultToken={{
          symbol: "USDT",
          address: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
          chainId: 42161,
          name: "USDT",
          chainType: ChainType.EVM,
          logoUrl: "https://example.com/static/logo-only.svg",
        }}
        finalToken={{
          symbol: "MYT",
          address: "0x123",
          chainId: 1,
          name: "MyToken",
          chainType: ChainType.EVM,
          logoUrl: "https://example.com/static/logo-only.svg",
        }}
        apiKey={"<YOUR_API_KEY>"}
        widgetTemplate={'DEPOSIT_TOKEN'}
        isOpen={isOpen}
        onClose={onClose}
        estimateCallback={estimateCallback}
        executeCallBack={executeCallBack}
        minDepositAmount={0}
      />
    </>
  );
};

export default Widget;
```

### How It Works

1. **Modal Control:**\
   The `useModal` hook supplies `isOpen`, `onOpen`, and `onClose` to control the display of the widget. A button or any trigger in your app can open the widget modal.
2. **Configuration Props:**
   * **`swapResultToken` and `finalToken`:** Define the tokens involved in the swap and final transaction.
   * **`widgetTemplate`:**  If value is **`TOKEN_BUY`** , then it is token purchase usecase. If you want to provide users to purchase your token, you can set your token information including logo url into **`swapResultToken`** props. In this case **`finalToken`** props is not required. Value is optional and by default it will use `DEPOSIT_TOKEN`.
   * **`apiKey`:** A required key for authentication or connecting to AnyAlt’s backend services.
   * **`minDepositAmount`:** Sets the minimum deposit amount needed to trigger a transaction.
3. **Callbacks:**
   * **`estimateCallback`:** Allows you to run custom logic (like querying exchange rates or fee estimations) before executing the final transaction.
   * **`executeCallBack`:** Executes your project-specific last-mile transaction and returns relevant transaction hashes and details.

By following these steps, you can integrate the AnyAlt Widget quickly, ensuring that your web3 project supports seamless cross-chain interactions with minimal effort.


# API Reference

The `AnyaltWidget` component exposes a variety of props and callbacks that allow you to configure its behavior and integrate it smoothly into your project. Below is an overview of its API:

### AnyaltWidget Props

<table><thead><tr><th width="217">Prop Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>swapResultToken</strong></td><td><code>Object</code></td><td>An object defining the token that the user will use in the last mile transaction. This token will always be the output of the initial swap. Contains properties such as <code>symbol</code>, <code>address</code>, <code>chainId</code>, <code>name</code>, and <code>chainType</code>.</td></tr><tr><td><strong>finalToken?</strong></td><td><code>Object</code></td><td>An object defining the token that the user will receive or use in the last mile transaction. Includes properties like <code>symbol</code>, <code>address</code>, <code>chainId</code>, <code>name</code>, <code>chainType</code>, and optionally <code>logoUrl</code> for branding.</td></tr><tr><td><strong>apiKey</strong></td><td><code>String</code></td><td>Your project’s API key for authenticating requests to the AnyAlt backend.</td></tr><tr><td><strong>widgetTemplate?</strong></td><td><code>WidgetTemplateType</code></td><td>Defines the available modes for the widget, determining its functionality based on the selected option. <strong>Default <code>DEPOSIT_TOKEN</code></strong> - Enables the widget for depositing tokens, allowing users to transfer tokens into a designated account or wallet. <strong><code>TOKEN_BUY</code></strong> - Activates the widget for purchasing tokens, adjusting the UI and logic to facilitate token acquisition.</td></tr><tr><td><strong>isOpen</strong></td><td><code>Boolean</code></td><td>A flag indicating whether the widget modal is currently open.</td></tr><tr><td><strong>onClose</strong></td><td><code>Function</code></td><td>A callback function invoked to close the widget modal.</td></tr><tr><td><strong>estimateCallback</strong></td><td><code>Function</code></td><td>An asynchronous function that is called to provide an estimation before executing the last-mile transaction. It receives the token details and should return an object with properties like <code>amountOut</code> and <code>priceInUSD</code>.</td></tr><tr><td><strong>executeCallBack</strong></td><td><code>Function</code></td><td>An asynchronous function that executes the final transaction. It receives the token details and should return transaction details such as <code>approvalTxHash</code>, <code>executeTxHash</code>, and <code>amountOut</code>.</td></tr><tr><td><strong>minDepositAmount?</strong></td><td><code>Number</code></td><td>Specifies the minimum deposit amount required to proceed with the transaction.</td></tr></tbody></table>

### Token Object Structure

Both `inputToken` and `finalToken` follow the same structure

<pre class="language-js"><code class="lang-js"><strong>interface Token {
</strong>  symbol: String,       // e.g., "USDT"
  address: String,      // Blockchain address of the token
  chainId: Number,      // Identifier for the blockchain network
  name: String,         // Human-readable name of the token
  chainType: ChainType, // Type of blockchain, e.g., ChainType.EVM
  logoUrl?: String,     // (Optional) URL for the token’s logo
  amount?: string,      // (Optional) 
  decimals?: string,    // (Optional)
}
</code></pre>

### ChainType

The `ChainType` enum helps define the type of blockchain the token belongs to. For example:

* `ChainType.EVM` for Ethereum Virtual Machine (EVM)-compatible chains.
* `ChainType.SOLANA` for the Solana chain.

### widgetTemplate

The `widgetTemplate` parameter defines the mode of the widget:

* **`TOKEN_BUY`**: Configures the widget for token purchases. In this mode:
  * `swapResultToken` represents the token the user wants to buy.
  * It is highly recommended to provide the `logoUrl` of the token for better user experience.
  * The `finalToken` parameter is **optional**.
* **`DEPOSIT_TOKEN`**: Enables the widget for token swapping followed by a deposit. In this mode:
  * Both `swapResultToken` and `finalToken` are **required**.

### Callbacks

#### estimateCallback(inputToken)

* **Purpose:**\
  A function which will estimate the output amount and dollar value price of the last mile transaction.
* **Parameters:**
  * `swapResultToken`(`Token`): the token which the user will receive as a result of the swap, same as `swapResultToken`which was passed as a prop to `<AnyaltWidget />`
* **Returns:**\
  A promise that resolves to an object with:
  * `amountOut` (`String`): Estimated output amount.
  * `priceInUSD` (`String`): Estimated price in USD.

#### executeCallBack(token)

* **Purpose:**\
  A function which will create and present the last mile transaction for the user to sign, as well as the approval transaction if necessary
* **Parameters:**
  * `swapResultToken`(`Token`): the token which the user will receive as a result of the swap, same as `swapResultToken` which was passed as a prop to `<AnyaltWidget/>`
* **Returns:**\
  A promise that resolves to an object with:
  * `approvalTxHash` (`String`): Transaction hash for the approval step (if applicable).
  * `executeTxHash` (`String`): Transaction hash for the execution step.
  * `amountOut` (`String`): Final output amount from the transaction.

### Modal Control: useModal Hook

The widget package also provides a `useModal` hook to help manage the modal state:

```js
const { isOpen, onOpen, onClose } = useModal();
```

* **isOpen:** A boolean flag indicating whether the modal is currently open.
* **onOpen:** Function to open the modal.
* **onClose:** Function to close the modal.

***

This API reference should serve as a comprehensive guide to integrating and customizing the AnyAlt Widget within your project, enabling you to leverage its full capabilities for cross-chain token swaps and last-mile transactions.


# Customize Theme

Customize theme by changing colors, backgrounds and borders

You can customize the widget's appearance by extending the default theme. The widget uses Chakra UI's theming system under the hood.&#x20;

```tsx
import { defaultTheme } from '@anyalt/widget';
import { WidgetProvider } from '@anyalt/widget';

const customTheme = {
  ...defaultTheme,
  colors: {
    brand: {
      primary: '#121212', // Main background color
      border: {
        tag: '#008080', // Tag border color
        active: '#008080', // Active state border
        bestRoute: '#008080', // Best route indicator
        secondary: '#919eab1f', // Secondary borders
        error: '#E53030', // Error state border
        primary: 'rgba(145, 158, 171, 0.12)', // Primary border color
      },
      bg: {
        primary: '#919eab1f', // Primary background
        active: '#008080', // Active state background
        hover: '#919eab1f', // Hover state background
        error: '#E530301a', // Error state background
        tag: 'transparent', // Tag background
        modal: '#0C0600', // Modal background
        cardBg: '#919eab0a', // Card background
        selectToken: 'rgba(0, 0, 0, 0.5)', // Token selector background
        skeleton: '#919eab', // Loading skeleton color
      },
      text: {
        primary: '#fff', // Primary text color
        warning: '#f9e154', // Warning text color
        error: '#E53030', // Error text color
        active: '#008080', // Active state text
        secondary: {
          0: '#ffffff', // Pure white text
          1: 'rgba(255, 255, 255, 0.80)', // High emphasis text
          2: 'rgba(255, 255, 255, 0.40)', // Medium emphasis text
          3: 'rgba(255, 255, 255, 0.08)', // Low emphasis text
          4: '#919eab', // Muted text
        },
      },
      buttons: {
        close: {
          primary: '#919eab', // Close button bg color
        },
        back: {
          primary: '#fff', // Back button bg color
        },
        accordion: {
          primary: '#fff', // Accordion button bg color
        },
        action: {
          bg: '#008080', // Action button background
          bgFaded: '#00808033', // Faded action button
          hover: '#006666', // Action button hover
          disabled: '#00808033', // Disabled action button
        },
        disabled: '#0B3E3E', // General disabled bg state
      },
      footer: {
        text: '#fff', // Footer text color
      },
    },
  },
};

// Use the custom theme in your app
const App = () => {
  return (
    <WidgetProvider theme={customTheme}>
      <AnyaltWidget
      // ... other props
      />
    </WidgetProvider>
  );
};
```

**Customize Text Colors**

```tsx
const customTheme = {
  ...defaultTheme,
  colors: {
    brand: {
      ...defaultTheme.colors.brand,
      text: {
        primary: '#ffffff', // Main text
        warning: '#f39c12', // Warnings
        error: '#e74c3c', // Errors
        secondary: {
          1: 'rgba(255, 255, 255, 0.9)', // Primary text
          2: 'rgba(255, 255, 255, 0.6)', // Secondary text
          3: 'rgba(255, 255, 255, 0.1)', // Disabled text
          4: '#95a5a6', // Muted text
        },
      },
    },
  },
};
```

Remember to maintain sufficient contrast ratios for accessibility when customizing colors.


# Overview

The AnyAlt SDK is a flexible and powerful toolkit designed for developers who need granular control over the integration of cross-chain swap and last-mile transaction functionalities. Unlike the widget, the SDK does not include a pre-built UI, enabling you to seamlessly incorporate AnyAlt's core capabilities into your own custom interface and user experience.

**Key Features:**

* **Customizability:**\
  Build tailored user experiences that align with your project’s branding and specific requirements. The SDK allows you to design every aspect of the interface while leveraging AnyAlt’s robust backend functionality.
* **Comprehensive API:**\
  Access a complete set of functions for managing cross-chain swaps and executing last-mile transactions. The API is designed to be intuitive and well-documented, simplifying the integration process.
* **Modular Design:**\
  Utilize individual components or combine them to create a seamless flow from token swapping to final transaction execution. This modular approach provides the flexibility to implement only the features you need.
* **Enhanced Control:**\
  Gain detailed control over the cross-chain execution process. The SDK enables you to manage transaction parameters, monitor process status, and handle exceptions in a way that aligns with your project’s operational logic.
* **Scalability:**\
  Built to support projects of all sizes, the SDK is optimized for high performance and can handle a large volume of cross-chain transactions without compromising speed or reliability.

The AnyAlt SDK is ideal for developers who prioritize customization and control over the user interface while still benefiting from the advanced cross-chain functionalities that AnyAlt offers. With the SDK, you can seamlessly integrate cross-chain token swaps and last-mile transaction executions into your project, ensuring a high conversion rate and a superior user experience.


# Getting Started

{% hint style="warning" %}
AnyAlt SDK requires an API key.

Contact us via the [form](https://9vi3topj6b2.typeform.com/to/F3Lnpo5u) and get your API key first.&#x20;
{% endhint %}

Integrating the AnyAlt SDK into your project gives you full control over the cross-chain swap and last-mile transaction processes without the constraints of a pre-built UI. Follow these steps to integrate and start using the SDK:

### Step 1: Install the SDK Package

Install the AnyAlt SDK using your package manager of choice

```bash
npm install @anyalt/sdk
# or
yarn add @anyalt/sdk
# or
pnpm add @anyalt/sdk
```

### Step 2: Initialize the SDK

Begin by creating an instance of the AnyAlt class using your API key. This instance will be used to access all SDK functions:

```js
import { AnyAlt } from '@anyalt/sdk';

const anyalt = new AnyAlt('<YOUR_API_KEY>');
```

### Step 3: Retrieve Available Chains and Tokens

To let your end-users select a source token and chain, fetch the list of available chains and tokens:

```js
import { useEffect, useState } from 'react';

const YourComponent = () => {
  const [chains, setChains] = useState([]);
  const [selectedChain, setSelectedChain] = useState(null);
  const [tokens, setTokens] = useState([]);

  useEffect(() => {
    const fetchChains = async () => {
      const { chains } = await anyalt.getChains();
      setChains(chains);
    };

    fetchChains();
  }, []);
  
  useEffect(() => {
    const fetchTokens = async () => {
      const { tokens } = await anyalt.getTokens({
          chainId: selectedChain.id,
          page: 0,
          pageSize: 100,
        });
        
        setTokens(tokens);
    }
  
    setTokens([]);
    
    if (selectedChain) {
      fetchTokens();
    }
  }, [selectedChain]);

  // Render your chain/token selection UI using the `chains` state
  return <div>{/* Your chain selection UI */}</div>;
};

export default YourComponent;
```

### Step 4: Obtain the Best Swap Route

Once a user selects the source and destination tokens, determine the optimal cross-chain swap route:

```js
const bestRouteRes = await anyalt.getBestRoute({
  from: '<SOURCE_TOKEN_UUID>',  // UUID of the source token
  to: '<DESTINATION_TOKEN_UUID>', // UUID of the destination token
  amount: "0.1",                // Amount of the source token as a string with decimal precision
  slippage: "100",              // Maximum acceptable slippage percentage as a string with decimal precision
});

const routeId = bestRouteRes.requestId;
const swaps = res.swaps;
```

### Step 5: Confirm the Swap Route

After obtaining the best route, confirm it by providing the selected route, wallet mappings, and the destination address:

```js
const res = await anyalt.confirmRoute({
  selectedRoute: routeId,
  // Map network names to wallet addresses for the user
  selectedWallets: {
    "BSC": "0xeae6d42093eae057e770010ffd6f4445f7956613",
    "AVAX_CCHAIN": "0xeae6d42093eae057e770010ffd6f4445f7956613"
  },
  destination: "0x6f33bb1763eebead07cf8815a62fcd7b30311fa3", // Recipient address on the destination chain, can be same or different to wallets in `selectedWallets`
});

const operationId = res.operationId;
const swaps = res.swaps;
```

### Step 6: Execute the Swap

Finally, execute the cross-chain swap. You can track the progress of the transaction using a callback function:

```js
import { useCallback, useState } from 'react';

const YourSwapComponent = () => {
  const [status, setStatus] = useState('');

  // Define a callback to handle transaction progress updates
  const handleTransactionProgress = useCallback((progress) => {
    setStatus(progress.status);
  }, []);

  const executeSwapTransaction = async () => {
    await anyalt.executeSwap(
      operationId, // The operation ID obtained from confirmRoute
      "100",       // Maximum acceptable slippage percentage
      swaps,       // List of swaps
      handleTransactionProgress // Progress callback
    );
  };

  return (
    <div>
      <button onClick={executeSwapTransaction}>Execute Swap</button>
      <p>Transaction Status: {status}</p>
    </div>
  );
};

export default YourSwapComponent;
```

The progress callback uses typical IoC or dependency injection, where the progress being injected into it is of type `TransactionProgress` :

```typescript
export type TransactionStatus =
  | 'pending'
  | 'signing'
  | 'broadcasting'
  | 'confirmed'
  | 'failed';

export interface TransactionProgressDetails {
  currentStep: number;
  totalSteps: number;
  stepDescription: string;
}

export interface TransactionProgress {
  status: TransactionStatus;
  message: string;
  txHash?: string;
  error?: string;
  details?: TransactionProgressDetails;
}
```

By following these steps, you can integrate the AnyAlt SDK into your project and build a fully customized UI for managing cross-chain swaps and transactions.


# API reference

The AnyAlt SDK provides a set of powerful functions that enable you to manage the complete cross-chain swap flow. Below is an overview of each API function available within the SDK.

### AnyAlt SDK Class

#### Constructor

* **`new AnyAlt(apiKey: string)`**
  * **Description:**\
    Creates a new instance of the AnyAlt SDK.
  * **Parameters:**
    * `apiKey` (string): Your unique API key for authenticating requests.
  * **Returns:**\
    An instance of the AnyAlt SDK.

### Methods

#### getChains

* **`getChains(): Promise<SupportedChainsResponse>`**
  * **Description:**\
    Retrieves a list of available blockchain networks.&#x20;
  * **Parameters:**

    `N/A`
  * **Returns:**

    ```typescript
    export interface SupportedChainsResponse {
      /** Array of supported chains */
      chains: SupportedChain[];
    }

    export interface SupportedChain {
      /**
       * UUID of the chain db entry
       * @example "1"
       */
      id: string;
      /**
       * Chain name
       * @example "ETH"
       */
      name: string;
      /**
       * Chain default decimals
       * @example 18
       */
      defaultDecimals: number | null;
      /**
       * Chain ID
       * @example 1
       */
      chainId: number | null;
      /**
       * Chain type
       * @example "EVM, SOLANA, etc."
       */
      chainType: string;
      /**
       * Chain logo URL
       * @example "https://example.com/logo.png"
       */
      logoUrl: string | null;
      /**
       * Chain display name
       * @example "Ethereum"
       */
      displayName: string | null;
      /**
       * Chain short name
       * @example "ETH"
       */
      shortName: string | null;
      /**
       * Chain RPC URL
       * @example "https://mainnet.infura.io/v3/..."
       */
      rpcUrl: string | null;
    }
    ```
  * **Usage Example:**

    ```js
    const response = await anyalt.getChains({});
    const chains = response.chains;
    ```

#### getTokens

* **`getTokens(params: GetTokensRequestParams): Promise<SupportedTokensResponse>`**
  * **Description:**\
    Retrieves a paginated list of tokens for a specific network.
  * **Parameters:**

    ```typescript
    export interface GetTokensRequestParams {
      keyword?: string;
      page?: number;
      pageSize?: number;
      chainId?: string;
    }
    ```
  * **Returns:**

    ```typescript
    export interface SupportedTokensResponse {
      /** Array of supported chains and their tokens */
      tokens: SupportedToken[];
    }

    export interface SupportedToken {
      /**
       * UUID of the token db entry
       * @example "1"
       */
      id: string;
      /**
       * Token Name
       * @example "USDC"
       */
      name: string;
      /**
       * Token address
       * @example "0x..."
       */
      tokenAddress: string | null;
      /**
       * Token symbol
       * @example "ETH"
       */
      symbol: string;
      /**
       * Chain name
       * @example "ETH"
       */
      chainName: string;
      /**
       * Token decimals
       * @example 18
       */
      decimals: number | null;
      /**
       * Token logo URL
       * @example "https://example.com/logo.png"
       */
      logoUrl: string;
      /** Chain */
      chain: SupportedChain | null;
    }

    // See `SupportedChain` above, in the `getChains` section
    ```
  * **Usage Example:**

    ```js
    const response = await anyalt.getTokens({
            chainId: activeChain.id,
            page: 0,
            pageSize: 100,
        });
        
    const tokens = response.tokens;
    ```

#### getBestRoute

* **`getBestRoute(args: RoutesRequest): Promise<BestRouteResponse>`**
  * **Description:**\
    Calculates the optimal route for executing a cross-chain swap between a source and destination token.
  * **Parameters:**

    ```typescript
    export interface RoutesRequest {
      /**
       * UUID of the source token. This UUID corresponds to the token metadata stored in our db.
       * @format uuid
       * @example "123e4567-e89b-12d3-a456-426614174000"
       */
      from: string;
      /**
       * UUID of the source token. This UUID corresponds to the token metadata stored in our db.
       * @format uuid
       * @example "987e6543-e21b-32d3-b654-526614174999"
       */
      to: string;
      /**
       * Amount
       * Amount of the source token to route. Represented as a string to maintain precision.
       * @example "0.1"
       */
      amount: string;
      /**
       * Slippage
       * Maximum acceptable slippage percentage for the route. Represented as a string to maintain precision.
       * @example "1.0"
       */
      slippage: string;
    }
    ```
  * **Returns:**

    ```typescript
    export interface BestRouteResponse {
      /** UUID of the request */
      requestId: string;
      /** Amount of the output token */
      outputAmount: string;
      /**
       * Array of swap routes
       * @example [{"swapperId":"0","swapperLogo":"https://example.com/logo.png","swapperType":"BRIDGE","swapChainType":"INTER_CHAIN","from":{"blockchain":"ethereum","address":"0xPLACEHOLDER","symbol":"ETH","logo":"https://example.com/logo.png","blockchainLogo":"https://example.com/logo.png","decimals":18,"usdPrice":1000},"to":{"blockchain":"binance","address":"0xPLACEHOLDER","symbol":"BNB","logo":"https://example.com/logo.png","blockchainLogo":"https://example.com/logo.png","decimals":18,"usdPrice":1000},"toAmount":"100000000","fromAmount":"100000000","fromAmountMaxValue":"100000000","fromAmountMinValue":"100000000","fromAmountPrecision":"100000000","fromAmountRestrictionType":"INCLUSIVE","routes":[{"nodes":[{"from":"ETH","fromAddress":"0xPLACEHOLDER","fromBlockchain":"ethereum","fromLogo":"https://example.com/logo.png","to":"USDT","toAddress":"0xPLACEHOLDER","toBlockchain":"binance","toLogo":"https://example.com/logo.png","nodes":[{"marketId":"0","marketName":"Uniswap","percent":45}]}]}],"internalSwaps":[],"fee":[],"estimatedTimeInSeconds":100,"timeStat":null,"includesDestinationTx":false,"maxRequiredSign":1,"recommendedSlippage":null,"warnings":[]}]
       */
      swaps: SwapResult[];
      /**
       * Indicates if the provided wallets do not include one which supports the source token's blockchain
       * @example false
       */
      missingWalletForSourceBlockchain: boolean;
    }

    export interface SwapResult {
      /** Unique Id of swapper. example: PARASWAP */
      swapperId: string;
      /** Logo of the swapper */
      swapperLogo: string;
      /** Type of swapper. example: BRIDGE, DEX, AGGREGATOR */
      swapperType: 'BRIDGE' | 'DEX' | 'AGGREGATOR' | 'OFF_CHAIN';
      /** Type of swapping. It could be inter chain or intra chain */
      swapChainType: 'INTER_CHAIN' | 'INTRA_CHAIN';
      /** The source asset */
      from: SwapResultAsset;
      /** The destination asset */
      to: SwapResultAsset;
      /** Estimated input amount of this step. Can be used for previewing to user and should not be used for real computation, since it may change when the real transaction happens due to volatility of the market */
      fromAmount: string;
      /** Estimated output amount of this step. Can be used for previewing to user and should not be used for real computation, since it may change when the real transaction happens due to volatility of the market */
      toAmount: string;
      /** The internal routing of this step showing how the initial swap request will be split and executed. This can be used for previewing purpose to give the user a sense of what's going to happen. Null indicates that there is no internal mechanism and swapping is simple and straight-forward. */
      routes: SwapRoute[] | null;
      /** The internal swaps for this step. Used for aggregators' internal steps. */
      internalSwaps: SwapResult[] | null;
      /** List of fees that are taken from user in this step */
      fee: SwapFee[];
      /** Type of from amount restriction */
      fromAmountRestrictionType: 'INCLUSIVE' | 'EXCLUSIVE';
      /** The estimated time (in seconds) that this step might take, beware that this number is just an estimation and should be used only for user preview, example: 15 */
      estimatedTimeInSeconds: number;
      /** The minimum, avg and max estimation time for this step */
      timeStat: TimeStat | null;
      /** Is it required to sign a transaction on the destination chain or not */
      includesDestinationTx: boolean;
      /** Max number of transaction signing required by the user */
      maxRequiredSign: number;
      /** Recommended slippage */
      recommendedSlippage: RecommendedSlippage | null;
      /** List of warnings for this swap step, it's usually an empty list */
      warnings: string[];
    }

    export interface SwapResultAsset {
      /** Blockchain of the source/destination asset of this step */
      blockchain: string;
      /** Contract address of the source/dest asset of this step, null for native token */
      address: string | null;
      /** Symbol of the source/destination asset of this step, example: OSMO */
      symbol: string;
      /** Absolute path of the logo of the source/destination asset of this step */
      logo: string;
      /** Absolute path of the logo of the asset blockchain */
      blockchainLogo: string;
      /** Decimals of the source/destination asset of this step, example: 18 */
      decimals: number;
      /** USD price unit for the asset if available */
      usdPrice: number | null;
    }

    export interface SwapRoute {
      /** List of parallel paths that splitting happens */
      nodes: SwapSuperNode[] | null;
    }

    export interface SwapSuperNode {
      /** Symbol of the source asset */
      from: string;
      /** Contract address of source asset, null for native tokens */
      fromAddress: string | null;
      /** Blockchain of the source asset */
      fromBlockchain: string;
      /** Absolute path of logo of the source asset */
      fromLogo: string;
      /** Symbol of the destination asset */
      to: string;
      /** Contract address of destination asset, null for native tokens */
      toAddress: string | null;
      /** Blockchain of the destination asset */
      toBlockchain: string;
      /** Absolute path of logo of the destination asset */
      toLogo: string;
      /** List of intermediate nodes in a swap path */
      nodes: SwapNode[];
    }

    export interface SwapNode {
      /** Id of the market */
      marketId: string | null;
      /** Name of the market, example: Uniswap */
      marketName: string;
      /** Percent of the allocation to this path, example: 45 */
      percent: number;
    }

    export interface SwapFee {
      /** A display name for this fee, example: Network Fee */
      name: string;
      /** Type of the fee, example: FROM_SOURCE_WALLET */
      expenseType: 'FROM_SOURCE_WALLET' | 'DECREASE_FROM_OUTPUT' | 'FROM_DESTINATION_WALLET';
      /** Underlying asset for paying fee, example: BNB for BSC blockchain */
      asset: Asset;
      /** The human readable amount of fee, example: 0.004 */
      amount: string;
      /** Price of the fee asset */
      price: number | null;
      /** EVM Fee Info for the Swap Fee */
      meta: EVMFeeMeta | null;
    }

    export interface Asset {
      /** Blockchain of the asset */
      blockchain: string;
      /** Contract address of the asset, null for native token */
      address: string | null;
      /** Symbol of the asset */
      symbol: string;
    }

    export interface EVMFeeMeta {
      /**
       * Type of the fee meta
       * @example "EvmNetworkFeeMeta"
       */
      type: string;
      /** Gas limit */
      gasLimit: string;
      /** Gas price */
      gasPrice: string;
    }

    export interface TimeStat {
      /** The minimum duration (in seconds) that usually takes for related step */
      min: number;
      /** The average duration (in seconds) that usually takes for related step */
      avg: number;
      /** The maximum duration (in seconds) that usually takes for related step */
      max: number;
    }

    export interface RecommendedSlippage {
      /** If true, means that AnyAlt failed to compute slippage for this step. */
      error: boolean;
      /** The slippage amount in percent, example: 5 */
      slippage: string;
    }
    ```
  * **Usage Example:**

    ```js
    const bestRouteRes = await anyalt.getBestRoute({
      from: '<SOURCE_TOKEN_UUID>',
      to: '<DESTINATION_TOKEN_UUID>',
      amount: "0.1",
      slippage: "3",
    });
    const routeId = bestRouteRes.requestId;
    ```

#### confirmRoute

* **`confirmRoute(args: ConfirmRouteRequest): Promise<ConfirmRouteResponse>`**
  * **Description:**\
    Confirms the selected swap route and prepares the operation for execution.
  * **Parameters:**

    ```typescript
    export interface ConfirmRouteRequestDto {
      /** The selected route to confirm */
      selectedRoute: SelectedRoute;
      /**
       * Mapping of network names to wallet addresses
       * @example {"BSC":"0xeae6d42093eae057e770010ffd6f4445f7956613","AVAX_CCHAIN":"0xeae6d42093eae057e770010ffd6f4445f7956613"}
       */
      selectedWallets: Record<string, string>;
      /**
       * Destination blockchain address
       * @example "0x6f33bb1763eebead07cf8815a62fcd7b30311fa3"
       */
      destination: string;
      /** Custom identifier for the operation */
      customId?: string;
    }

    export interface SelectedRoute {
      /**
       * The unique identifier of the selected route
       * @example "123e4567-e89b-12d3-a456-426614174000"
       */
      requestId: string;
    }
    ```
  * **Returns:**

    ```ts
    export interface ConfirmRouteResponse {
      /** Indicates if the route has been confirmed */
      ok: boolean;
      result: BestRouteResponse | null;
      /** UUID of the operation */
      operationId: string;
      /** The status of each blockchain */
      walletStatuses: BlockchainStatus[];
    }
    ```
  * **Usage Example:**

    ```js
    const res = await anyalt.confirmRoute({
      selectedRoute: { requestId: routeId },
      selectedWallets: {
        "BSC": "0xeae6d42093eae057e770010ffd6f4445f7956613",
        "AVAX_CCHAIN": "0xeae6d42093eae057e770010ffd6f4445f7956613"
      },
      destination: "0x6f33bb1763eebead07cf8815a62fcd7b30311fa3",
    });

    const operationId = res.operationId;
    ```

#### executeSwap

* **`executeSwap(operationId: string, slippage: string, swaps: SwapResult[], onProgress?: (progress: TransactionProgress) => void): Promise`**
  * **Description:**\
    Executes the cross-chain swap operation using the specified parameters and monitors its progress via a callback.
  * **Parameters:**
    * `operationId (string)`: The operation ID obtained from the `confirmRoute` function.
    * `slippage (string)`: Maximum acceptable slippage percentage, as a string (e.g., `"3"`).
    * `swaps (SwapResult[])`: The swaps attribute of the best route or confirmed route response. See `getBestRoute`above for defined types.
    * `onProgress ((progress: TransactionProgress) => void))`: A function that receives progress updates.

      ```ts
      export type TransactionStatus =
        | 'pending'
        | 'signing'
        | 'broadcasting'
        | 'confirmed'
        | 'failed';

      export interface TransactionProgressDetails {
        currentStep: number;
        totalSteps: number;
        stepDescription: string;
      }

      export interface TransactionProgress {
        status: TransactionStatus;
        message: string;
        txHash?: string;
        error?: string;
        details?: TransactionProgressDetails;
      }

      ```
  * **Returns:**\
    `void`
  * **Usage Example:**

    ```js
    import { useCallback } from 'react';

    const handleTransactionProgress = useCallback((progress) => {
      // Update UI based on progress.status
      console.log("Current progress:", progress.status);
    }, []);

    await anyalt.executeSwap(
      operationId,
      "1.0",
      swaps,
      handleTransactionProgress
    );
    ```

***

This API reference provides a comprehensive overview of the functions available in the AnyAlt SDK. Using these methods, you can build a fully customized interface to manage cross-chain swaps and last-mile transactions while maintaining complete control over the user experience.


# Integration

## Anyalt Widget Integration Guide for Token Buy Template to the HTML via iframe&#x20;

{% hint style="warning" %}
You can use this iframe widget only with the TOKEN\_BUY usecase
{% endhint %}

Add the widget to your application using an iframe:

```html
<iframe
  src="https://iframe.anyalt.finance?apiKey=your-api-key&minDepositAmount=0&tokenName=USDT&tokenSymbol=USDT&tokenAddress=0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9&tokenChainId=42161&tokenDecimals=6&tokenChainType=EVM&backgroundColor=%23f5f5f5"
  title="Widget"
  width="980px"
  height="500px"
></iframe>
```

### Required Parameters

* `apiKey`: Your API key for authentication
* `theme`: (Optional) White or Dark theme ('white' | 'dark')
* `minDepositAmount`: Minimum deposit amount (number)
* `tokenName`: Token name (e.g., "USDT")
* `tokenSymbol`: Token symbol (e.g., "USDT")
* `tokenAddress`: Token contract address
* `tokenChainId`: Chain ID (number)
* `tokenDecimals`: Number of decimals (number)
* `tokenChainType`: Chain type ("EVM", "SOLANA")
* `tokenLogoUrl`: (Optional) URL to token logo
* `backgroundColor`: (Optional) Background color of the widget container (hex color code or color name)

### Example Token Configuration

```javascript
// Example URL with token parameters and background color
const widgetUrl = `https://iframe.anyalt.finance?apiKey=your-api-key&minDepositAmount=0&tokenName=USDT&tokenSymbol=USDT&tokenAddress=0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9&tokenChainId=42161&tokenDecimals=6&tokenChainType=EVM&tokenLogoUrl=https://example.com/usdt-logo.png&backgroundColor=%23f5f5f5`;
```

### Error Handling

The widget will display validation errors in a user-friendly format if any parameters fail validation. Errors will be shown for:

* Missing required fields
* Invalid parameter formats
* Out-of-range values
* Invalid addresses for the specified chain type

Example error display:

```
Validation Errors:
• tokenAddress: Invalid token address for chain type EVM
• tokenDecimals: Decimals must be between 0 and 18
```

### Styling

The widget can be styled using standard iframe CSS properties:

```html
<iframe
  src="https://iframe.anyalt.finance?apiKey=your-api-key&minDepositAmount=0&tokenName=USDT&tokenSymbol=USDT&tokenAddress=0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9&tokenChainId=42161&tokenDecimals=6&tokenChainType=EVM&tokenLogoUrl=https://example.com/usdt-logo.png&backgroundColor=%23f5f5f5"
  style="
    width: 100%;
    height: 500px;
    border: none;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  "
  title="Widget"
></iframe>
```

### Background Color Examples

You can set the background color using:

* Hex color codes: `backgroundColor=%23f5f5f5` (URL-encoded #f5f5f5)
* Color names: `backgroundColor=white`
* RGB values: `backgroundColor=rgb(245,245,245)`

Example URLs:

```html
<!-- Light gray background -->
<iframe src="...&backgroundColor=%23f5f5f5" ...></iframe>

<!-- White background -->
<iframe src="...&backgroundColor=white" ...></iframe>

<!-- Custom RGB background -->
<iframe src="...&backgroundColor=rgb(245,245,245)" ...></iframe>
```


