Notus API

Swap Guide

Step-by-step guide to swapping tokens with the Notus API.

Steps

Create a directory

mkdir my-create-swap
cd my-create-swap
touch index.js

Init project

npm init -y

Install viem

We’ll use viem, a library for blockchain interactions, to simplify our integration. Install it by running:

npm i viem

Initialize Wallet Account

Use your private key to initialize a wallet account. This will allow you to sign messages and interact with the blockchain.

import { privateKeyToAccount } from 'viem/accounts'
 
const BASE_URL = "https://api.notus.team/api/v1"
const API_KEY = "<api-key>"
 
const UNI_POLYGON = '0xb33eaad8d922b1083446dc23f610c2567fb5180f'
const USDC_POLYGON = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' 
 
const privateKey = '0x<private-key>'
const account = privateKeyToAccount(privateKey)

Register a Smart Wallet Address

Before initiating a swap, register and retrieve the smart wallet address used for Account Abstraction.

async function main() {
  const FACTORY_ADDRESS = "0x0000000000400CdFef5E2714E63d8040b700BC24"
  const externallyOwnedAccount = account.address
 
  let res = await fetch(`${BASE_URL}/wallets/register`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY,
    },
    body: JSON.stringify({
      externallyOwnedAccount: externallyOwnedAccount,
      factory: FACTORY_ADDRESS,
      salt: "0",
    }),
  });
 
  if (!res?.ok) {
    return
  }
 
  const response = await res.json();
 
  const smartWalletAddress = response.wallet.accountAbstraction
}

Create a Swap Quote

Query a swap quote for token swaps on the same chain (e.g., USDC to UNI on Polygon).

const { data } = await fetch(`${BASE_URL}/crypto/swap`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': API_KEY,
  },
  body: JSON.stringify(
    {
      payGasFeeToken: USDC_POLYGON,
      tokenIn: USDC_POLYGON,
      tokenOut: UNI_POLYGON,
      amountIn: "5",
      walletAddress: smartWalletAddress,
      toAddress: smartWalletAddress,
      signerAddress: externallyOwnedAccount,
      chainIdIn: 137,
      chainIdOut: 137,
      gasFeePaymentMethod: "DEDUCT_FROM_AMOUNT",
    }
  ),
}).then((res) => res.json())

If you are swapping from a native token (e.g., ETH, BNB, AVAX), use the following address as tokenIn: 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee. This ensures that the Notus API recognizes the asset as a native token.

Execute Swap

Once you have a quote, sign and execute the swap operation.

  const signature = await account.signMessage({
    message: {
      raw: data.quoteId,
    },
  })
  
  const { userOpHash } = await fetch(`${BASE_URL}/crypto/execute-user-op`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': API_KEY,
    },
    body: JSON.stringify({ signature, quoteId: data.quoteId }),
  }).then((res) => res.json())
 
  console.log(userOpHash)

On this page