# Swap SDK

We’re excited to launch the public release of StellaSwap’s Development Kit (SDK 😉), a tool that allows developers & projects to interact with StellaSwap’s DEX and access our deep-liquidity. As the most-used DEX on Polkadot, we’re proud to be the *schelling point* of native assets and users wanting to trade & stake in a familiar EVM-environment.

<figure><img src="https://2469068479-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fk79kvXbQmvjLmP78Scbp%2Fuploads%2FPd39a5k6DnQaKiwWLEIU%2Fimage.png?alt=media&#x26;token=d2ea806a-6ba1-4db5-a7f2-b93b0b9be521" alt=""><figcaption></figcaption></figure>

## Overview of our SDK <a href="#id-7914" id="id-7914"></a>

Our public SDK provides functionality for integrating swaps on Moonbeam into any app or plugin. Moonbeam is the leading EVM parachain in Polkadot, and therefore taps on the best of Polkadot’s security and Ethereum’s convenience.

Developers and projects can integrate our our DEX for various applications that leverages on our liquidity. Our SDK features a range of useful documentation and APRs that entails technical specifications and code samples.

## Description <a href="#id-7914" id="id-7914"></a>

The @stellaswap/swap-sdk provides functionality for integrating swap on Moonbeam into any app or plugin. StellaSwap SDK allows end-users to exchange tokens seamlessly on Moonbeam network.

#### Features

* Uses state-of-the-art Hybrid Router
* Utilizes Stable, V2, V3 AMMs
* Error Handling

#### Installation

To install the package, use npm or yarn:

```
npm install @stellaswap/swap-sdk
# OR
yarn add @stellaswap/swap-sdk
```

### Usage

#### Importing the SDK

First, import the SDK.

```
import stellaSwap from '@stellaswap/swap-sdk';
```

#### Allowance

This helps to check allowance of tokenAddress against spender, it will return allowed number if there is any.

```
const addresses = await stellaSwap.getAddresses();
const spender = addresses.permit2;
const allowance = await stellaSwap.checkAllowance(
  account,
  erc20Instance,
  spender
);
```

```
Response: 0
```

**Approve**

To perform approve pass desired value as `amountIn` and for unlimited approval use `0`. In response, it returns transaction hash.

```
const addresses = await stellaSwap.getAddresses();
const spender = addresses.permit2;
const tx = await stellaSwap.approve(amountIn, erc20Instance, spender);
```

#### Get Quote

To get `amountOut` of a trade use `getQuote`. For `account` it can be null if user is not connected. For native asset pass `ETH` as `token0Addr` or `token1Addr`.

```
const quote = await stellaSwap.getQuote(
  token0Addr,
  token1Addr,
  amountIn,
  account,
  slippage
);
```

**Response**

To filter out `amountOut` use `quote.result.amountOut`. For the rest of the response, it includes;

* Complete trade path.
* Execution with commands and inputs

#### Swap

This can executes actual swap, for native asset pass `ETH` as `token0Addr` or `token1Addr`.

```
const tx = await stellaSwap.executeSwap(
  token0Addr,
  token1Addr,
  amountIn,
  signer,
  slippage
);
```

#### Swap Native to ERC20

To swap native to ERC20, pass `token0Addr` as `ETH` and `token1Addr` as erc20 address.

```
const encodedTxData = await stellaSwap.executeNativeSwap(
  token0Addr,
  token1Addr,
  amountIn,
  slippage,
  aggregatorContractInstance
);
const txParams = {
  from: ACCOUNT,
  value: amountIn,
  to: aggregatorContractInstance.address,
  data: encodedTxData,
  gasLimit: 1_500_000,
  gasPrice: await signer.getGasPrice(),
};

const txResponse = await signer.sendTransaction(txParams);
await txResponse.wait();
return txResponse.hash;
```

#### Swap ERC20 to ERC20

To swap native to ERC20, pass `token0Addr` as erc20 address and `token1Addr` as erc20 address.

```
const { signature, permit } = await permit2.getPermit2Signature(
  token0Addr,
  amountIn,
  signer
);

const encodedTxData = await stellaSwap.executeERC20Swap(
  token0Addr,
  token1Addr,
  amountIn,
  slippage,
  aggregatorContractInstance,
  permit,
  signature
);
const txParams = {
  to: aggregatorContractInstance.address,
  data: encodedTxData,
  gasLimit: 1_500_000,
  gasPrice: await signer.getGasPrice(),
};

const txResponse = await signer.sendTransaction(txParams);
await txResponse.wait();

console.log("Transaction hash:", txResponse.hash);
return txResponse.hash;
```

#### Example for `getPermit2Signature`

```
import {
  PermitTransferFrom,
  Witness,
  SignatureTransfer,
  MaxUint256,
} from "@uniswap/permit2-sdk";
import { joinSignature, splitSignature } from "@ethersproject/bytes";
import stellaSwap from "@stellaswap/swap-sdkÏ";

const permit2 = {
  async getPermit2Signature(token0Addr: string, amountIn: string, signer: any) {
    const addresses = await stellaSwap.getAddresses();
    const AGGREGATOR_ADDRESS = addresses.aggregator;
    const PERMIT2_ADDRESS = addresses.permit2;

    const spender = AGGREGATOR_ADDRESS;

    const permit: PermitTransferFrom = {
      permitted: {
        token: token0Addr,
        amount: amountIn,
      },
      spender: spender,
      nonce: await utils.calcNonces(signer),
      deadline: MaxUint256,
    };

    const witness: Witness = {
      witnessTypeName: "Witness",
      witnessType: { Witness: [{ name: "user", type: "address" }] },
      witness: { user: spender },
    };

    const { domain, types, values } = SignatureTransfer.getPermitData(
      permit,
      PERMIT2_ADDRESS,
      await signer.getChainId(),
      witness
    );

    const signature = await signer._signTypedData(domain, types, values);

    let { r, s, v } = splitSignature(signature);

    if (v == 0) v = 27;
    if (v == 1) v = 28;

    const joined = joinSignature({ r, s, v });

    return { signature: joined, permit, witness };
  },
};

export default permit2;
```

### Dependencies

* axios
* @uniswap/permit2-sdk

### Configuration

The SDK is pre-configured to be used with the Moonbeam mainnet and doesn't require an API key.

### Error Handling

The SDK includes basic error handling. All methods return Promises, so you can use `.catch()` to handle errors as you see fit.

```
stellaSwap.checkAllowance(tokenAddress, signer, spender).catch((error) => {
  console.error("Check Allowance failed:", error.message);
});
```

### Contribution

Feel free to submit issues and enhancement requests.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.stellaswap.com/developers/swap-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
