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.
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.
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);
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,
},
};
bitcoind: Configuration for the Bitcoin blockchain.
geth: Configuration for the Ethereum blockchain.
lnd: Configuration for the Lightning Network Daemon.
trades:
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.
The DEX class is the heart of the Swap SDK, providing essential functionalities for managing assets and executing trades on the decentralized exchange.
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
Number = dex.xfer( source, dest_addr, asset, qty )
Example:
const transferredQty = dex.xfer(source, dest_addr, asset, qty);
trade = dex.trade( order_type, goals,
sell_asset, sell_qty,
buy_asset, buy_qty );
Boolean = dex.close()
Example
const isClosed = dex.close();
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 )
Example
const foundTrade = dex.find(order_id);
Array = dex.history()
Example
const tradeHistory = dex.history();
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.
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);
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.
Example
// Getting the current state of the trade
const currentState = trade.state;
console.log(`Trade is currently in state: ${currentState}`);
String = trade.state
Returns the current state of the trade, allowing developers to dynamically respond to the evolving nature of trades.
Example
// Getting the current state of the trade
const currentState = trade.state;
console.log(`Trade is currently in state: ${currentState}`);
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.
Format:
{
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
}
Example
// Retrieving trade parameters, including order ID, asset quantities, and state
const tradeParameters = trade.parameters;
console.log("Trade Parameters:", tradeParameters);
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 = 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 = 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 = 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.
Example
// 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
trade.clear('event_name');
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.
Dive into our most frequently asked curiosities and discover more!
Subscribe now and be the first to catch every thrilling update!