Unveiling the Power of Swap SDK and Its DEX & Trade Class: A Comprehensive Guide

Janesh Balchandani

Jan 13, 2024


The cryptocurrency ecosystem continues to evolve, and with it comes a demand for efficient and user-friendly tools to navigate the decentralized exchange (DEX) landscape. In this article, we'll delve into the Swap SDK and explore its DEX Class—a powerful set of tools designed to simplify crypto-asset management and trading.

Understanding the Swap SDK:

Swap SDK is a robust Javascript module designed to provide seamless integration with decentralized exchanges, specifically the Portal DEX network. Whether you're operating in a browser environment or on a server using node.js, Swap SDK offers a simple yet powerful interface for crypto-asset management.

Initialization with Swap SDK:

The entry point to the Swap SDK is the SDK.init() function. This function takes a configuration object as its parameter, defining crucial aspects such as the network details and blockchain configurations. It returns an instance of the DEX class, representing a connection to a particular instance of the Portal DEX network for a specific user.

const dex = SDK.init(config);

Configuration Object Format:

The config object is structured to provide essential details for initializing the SDK. Here is a breakdown of its format:

const config = {
  network: {
    hostname: String,
    port: Number,
  blockchains: {
    bitcoind: {
      chain_id: String,
      rest_url: String,
      port: Number,
      zmq: String,
    geth: {
      chain_id: String,
      rest_url: String,
      port: Number,
    lnd: {
      rest_url: String,
      port: Number,
  trades: {
    recovery: String,
    storage: String,

Config Object Properties:


  • hostname: String - The hostname of the network.
  • port: Number - The port number for the network.


bitcoind: Configuration for the Bitcoin blockchain.

  • chain_id: String - The chain ID for Bitcoin.
  • rest_url: String - The REST URL for Bitcoin.
  • port: Number - The port number for Bitcoin.
  • zmq: String - The ZeroMQ connection string for Bitcoin.

geth: Configuration for the Ethereum blockchain.

  • chain_id: String - The chain ID for Ethereum.
  • rest_url: String - The REST URL for Ethereum.
  • port: Number - The port number for Ethereum.

lnd: Configuration for the Lightning Network Daemon.

  • rest_url: String - The REST URL for the Lightning Network Daemon.
  • port: Number - The port number for the Lightning Network Daemon.


  • recovery: String - Recovery information for trades.
  • storage: String - Storage information for trades.

Handling Errors with SDK.init():

After initializing the SDK with SDK.init(), it returns an instance of the DEX class representing a connection to a particular instance of the Portal DEX network for a specific user.

try {
  const dex = SDK.init(config);
  // Proceed with DEX operations
} catch (error) {
  console.error("Error initializing Swap SDK:", error.message);
  // Handle the error appropriately

It's important to note that SDK.init() will throw an exception if there are any errors in the provided configuration or if there are issues connecting to the network. Therefore, it is advisable to wrap the initialization call in a try/catch block to gracefully handle any potential errors.

This error-handling approach ensures a more robust implementation, allowing developers to catch and handle errors effectively, providing a smoother user experience when interacting with the Swap SDK.

DEX Class: Orchestrating Asset Flow

The DEX class is the heart of the Swap SDK, providing essential functionalities for managing assets and executing trades on the decentralized exchange.

1. Constructor:

  • Instances of the DEX class cannot be manually constructed; they are only accessible as a return value of SDK.init().
  • Each instance represents a connection to a particular instance of the Portal DEX network for a specific user.
  • The DEX instance initially contains no assets, and assets must be transferred into it using the DEX.xfer() method before any trades can be executed.

2. Instance Properties - Assets:

The DEX class maintains an array of assets and their quantities currently available through the dex.assets property.

Assets = dex.assets;
// Returns an array of { asset: String, qty: Number } objects

3. Instance Methods:

 Transfer Assets DEX.xfer():

Number = dex.xfer( source, dest_addr, asset, qty )


  • Transfers one or more assets into the receiver from the specified source.
  • Must be called before any trades are executed.
  • Returns the quantity of the crypto-asset transferred.


const transferredQty = dex.xfer(source, dest_addr, asset, qty);


Execute Trade DEX.trade():
  • Performs a swap of specified assets under the given conditions.
  • Returns an instance of the Trade class.
  • Throws an exception if there are any errors in the arguments.


trade = dex.trade( order_type, goals,
                  sell_asset, sell_qty,
                  buy_asset, buy_qty );

Close Connection DEX.close():
  • Closes the connection to the receiver.
  • Returns true if successful, else false.

Boolean = dex.close()


const isClosed = dex.close();

Find Trade by Order ID DEX.find():

Returns the instance of Trade with the specified order_id or undefined if no trade with that order_id was executed on the receiver.

trade = dex.find( order_id )


const foundTrade = dex.find(order_id);


Retrieve Trade History DEX.history():
  • Returns an array of Trade instances in the order in which trade() was called on the receiver.
  • Allows users to employ the methods of the Array class to filter for specific trades.

Array = dex.history()   


const tradeHistory = dex.history();

Trade Class: Navigating the Lifecycle of Trades

At the core of the Swap SDK lies the Trade class, a powerful entity that encapsulates the lifecycle and events associated with trades on the Portal DEX network.

1. Constructor:

The Trade class, a fundamental component of Swap SDK, cannot be manually constructed. Instead, it is only accessible as a return value of the DEX.trade() function. This encapsulation ensures that trades are managed consistently and adhere to the predefined behaviour of the Trade class.

// Accessing Trade class through DEX.trade()
const trade = dex.trade(order_type, goals, sell_asset, sell_qty,      buy_asset, buy_qty);

2. States and Events:

Trade instances follow a predefined sequence of states during their lifecycle, and transitions between these states are triggered by specific events. The Trade.state property provides developers with real-time access to the current state of a trade. Events, denoted by rectangles, drive these state transitions. Handlers can be attached or detached to events using the Trade.on(), Trade.once(), and Trade.off() methods, offering a fine-tuned approach to managing trade-related events.

States and Events for Trade instances
                                                                                                                                                                 States and Events for Trade instances


// Getting the current state of the trade
const currentState = trade.state;
console.log(`Trade is currently in state: ${currentState}`);

3. Instance Properties

Trade State:
String = trade.state

Returns the current state of the trade, allowing developers to dynamically respond to the evolving nature of trades.


// Getting the current state of the trade
const currentState = trade.state;
console.log(`Trade is currently in state: ${currentState}`);

Trade Parameters:
Object = trade.parameters

Provides a comprehensive snapshot of the trade's current state, including details such as order ID, order type, asset quantities, and any contextual information passed during the trade initiation or returns an object containing all arguments to DEX.trade(). The error property captures the message from the most recent error or remains an empty string if no error occurred.


  order_id: String,        // internally generated
  order_type: String,
  sell_asset: String,
  sell_qty: Number,
  sell_ctx: Object,
  buy_asset: String,
  buy_qty: Number,
  buy_ctx: Object,   // arguments given to Dex.trade()
  state: String,    // current state as would be returned by trade.state
  error: String    // message from most recent error or empty string


// Retrieving trade parameters, including order ID, asset quantities, and state
const tradeParameters = trade.parameters;
console.log("Trade Parameters:", tradeParameters);

4. Instance Methods:

Trade On:
trade = trade.on(event_name, handler)

Adds a handler to be called when a specific event occurs on the trade. The method returns the trade instance, allowing for method chaining.

Trade Once:
trade = trade.once(event_name, handler)

Similar to trade.on(), this method adds a handler to respond to a specific event, but the handler is automatically removed from the queue after being executed once.

Trade Off:
trade = trade.off(event_name, handler, position)

Removes one or more instances of a specified handler from the event queue based on the provided position parameter. The trade instance is returned, enabling seamless chaining.

Trade Clear:
trade = trade.clear(event_name)

Empties the event handler queue for a named event, including anonymous handlers. This method is chainable, allowing developers to streamline their code.


// Adding a handler for a specific event
trade.on('event_name', (eventData) => {
  console.log(`Event occurred: ${eventData}`);

// Adding a one-time handler for an event
trade.once('one_time_event', () => {
  console.log('This handler will be executed once.');

// Removing a handler for a specific event
trade.off('event_name', handlerFunction);

// Clearing all handlers for a named event

Notes on Instance Methods:

  • Invalid arguments provided to these methods will result in the throwing of the error event. Developers can diagnose the cause of the error by examining the error property of the Trade instance originating the error event.
  • It's important to note that anonymous handlers (lambdas) cannot be removed using trade.off().


The Swap SDK with its DEX and Trade Class provides developers with a powerful toolkit to interact with decentralized exchanges seamlessly. Whether you are managing assets, executing trades, or retrieving trade history, the Swap SDK simplifies the complexities of decentralized finance, making it accessible to a broader audience of developers. Explore the possibilities of the Swap SDK and take your decentralized trading experience to new heights.

Got Questions? We've Got Answers!

Dive into our most frequently asked curiosities and discover more!

1/ What is Portal?
2/ How is Portal's Omnichain Liquidity Layer?
3/ What is the Portal P2P DEX?
4/What is the Portal Atomic Swap Protocol?
5/ What is PortalOS?
6/ What distinguishes Portal from other cross-chain solutions?
7/ What is HyperBitcoinization, and how is Portal contributing to it?
8/ Where can I learn more about Portal's technology and infrastructure?

Dive into the Latest!

Subscribe now and be the first to catch every thrilling update!

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.