Guide
This guide outlines how to use the Swap API to execute a swap. The full source code of this guide can be found in this Github repository.
Follow these steps to complete a swap:
1. Obtain an API Key
The API is currently available by request only. To obtain API keys, contact the team directly on Telegram: @whoiskevinn or @beranoulli.
2. Check Allowances
Before initiating trades with the Swap API, it is crucial to approve the ERC20 token intended for the swap (the input token) against the router. Ensure there is sufficient allowance granted to OBRouter. You can verify this programmatically or manually by calling the allowance function directly on the ERC20's contract on-chain.
The example code is written using bun and viem. But it should be equally simple to integrate using other runtimes such as node.js and other EVM libraries such as ether.js
Setting up the environment:
import {
http,
type Address,
createWalletClient,
maxUint256,
parseEther,
publicActions,
zeroAddress,
} from "viem"; // Main library used to interface with the blockchain
import { privateKeyToAccount } from "viem/accounts";
import { berachainTestnetbArtio } from "viem/chains";
if (!process.env.PRIVATE_KEY) throw new Error("PRIVATE_KEY is required");
if (!process.env.PUBLIC_API_URL) throw new Error("PUBLIC_API_URL is required");
if (!process.env.API_KEY) throw new Error("API_KEY is required");
const PRIVATE_KEY = process.env.PRIVATE_KEY as Address; // Private key of the account to make the trade
const PUBLIC_API_URL = process.env.PUBLIC_API_URL;
const API_KEY = process.env.API_KEY;Setting the account and initializing the EVM libraries:
Defining the swap parameters (this example uses a 0.01 HONEY to BERA swap):
The Swap API also allows developers to query the allowances directly instead of doing on-chain.
Everytime the Swap API is queried, the API_KEY has to be provided on the fetch call.
getAllowance fits into the main execution body likeso:
3. Approving Allowances
Approving if neccesary:
4. Execute Swap
Once the necessary allowances are in place, you can call the final API endpoint to generate a quote. If the quote meets your expectations, proceed to execute the trade.
The swap query doubles as a quote, providing essential details about the trade. Comprehensive information about the quote can be found in the API reference.
Additionally, the quote endpoint generates the complete transaction body, ready to be signed and submitted directly on-chain.
Theres object can be printed to view the complete routing path and detailed information about the swap. For a comprehensive breakdown of the response, refer to the API Reference.
Executing:
Last updated