# Portal Swap SDK Overview

[*This document is for informational purposes only. It is a specification of a product that is under active development and should be expected to change. It does not provide any guarantees or warranties as to how the final product will operate.*](#user-content-fn-1)[^1]

The Portal SDK packages classes presenting simple yet powerful interfaces to the Portal DEX, to wallets, and for crypto-asset management in general. This document describes the initial version of the Portal SDK used for interfacing with the Portal DEX to execute swaps of crypto-assets.

The SDK is avilable as a Javascript module that can be imported into browser or server (e.g. node.js) environments:

```javascript
npm install '@portaldefi/sdk'
import SDK from '@portaldefi/sdk'
```

The `SDK` module exports a single function which must be executed in order to access any capabilities of the SDK:

```javascript
const dex = SDK.init( config )
```

<mark style="color:blue;">`config`</mark> is an Object with format:

```json
{
   network: {
      hostname: String,
      port: Number
   },
   blockchains: {
      bitcoind: Object,
      geth: Object,
      lnd: Object
   },
   swaps: Object
}
```

<mark style="color:yellow;">`SDK.init()`</mark> returns an instance of the DEX class representing a connection to a particular instance of the Portal DEX network for a particular user. The interface of the DEX class is specified in the next section.

<mark style="color:yellow;">`SDK.init()`</mark> will throw an exception if there are any errors in <mark style="color:blue;">`config`</mark> or any errors connecting to the network - thus it is advisable to call this function in a try/catch block.

[^1]:


# DEX Class

### Constructor

Instances of <mark style="color:orange;">`DEX`</mark> cannot be constructed manually. They are only accessible as a return value of <mark style="color:yellow;">`SDK.init()`</mark>. Each instance of the DEX class represents a connection to a particular instance of the Portal DEX network for a particular user.

The DEX instance returned by <mark style="color:yellow;">`SDK.init()`</mark> contains no assets. Before any trades are executed on that instance, assets must be transferred into it using <mark style="color:orange;">`DEX.xfer()`</mark>.

### Instance Properties

```javascript
Array = dex.assets
```

Returns the assets and their quantities currently available. The elements of the Array are Objects with format: `{ asset: String, qty: Number }`.

### Instance Methods

```javascript
Array = dex.xfer( source, assets )
```

Transfers one or more assets into the receiver from the specified source. Instances of DEX initially contain no assets and this method must be called before any trades are executed.

<table><thead><tr><th width="131">Argument</th><th>Type and Semantics</th></tr></thead><tbody><tr><td><mark style="color:blue;"><code>source</code></mark></td><td>Object. Specifies the source of the assets and the parameters necessary for transferring them. Format depends on the source.</td></tr><tr><td><mark style="color:blue;"><code>assets</code></mark></td><td>Array. Specifies quantities of assets to transfer. The elements of the Array are Objects with format: <code>{ asset: String, qty: Number }</code></td></tr></tbody></table>

<mark style="color:orange;">`DEX.xfer`</mark>`()` returns an Array whose elements are Objects with format:

```json
{
   status: String,
   asset: String,
   qty: Number      // quantity actually in wallet
}
```

```javascript
trade = dex.trade( order_id, order_type, goals,
                   sell_asset, sell_qty,
                   buy_asset,  buy_qty )
```

Performs a swap of the specified assets under the specified conditions. Returns an instance of the Trade class. Will throw an exception if there are any errors in the arguments - thus it is advisable to call this function in a try/catch block.

<table><thead><tr><th width="220">Argument</th><th>Type and semantics</th></tr></thead><tbody><tr><td><code>order_id</code></td><td>String (case sensitive). A user-defined identifier of this trade. Stored in the instance and returned on every method call to that instance.</td></tr><tr><td><code>order_type</code></td><td>String (case insensitive). One of: "limit" or "market".</td></tr><tr><td>goals</td><td>Object.</td></tr><tr><td><code>sell_asset, buy_asset</code></td><td>String (case insensitive). One of: "BTC" or "ETH".</td></tr><tr><td><code>sell_qty, buy_qty</code></td><td>Number</td></tr><tr><td><code>sell_ctx, buy_ctx</code></td><td>Object. Format is dependent on the values of <code>order_type</code>, <code>sell_asset</code>, and <code>buy_asset</code>.</td></tr></tbody></table>

```javascript
Boolean = dex.close()
```

Close the connection to receiver. Returns `true` if successful else `false`.

```javascript
trade = dex.find( order_id )
```

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

```javascript
Array = dex.history()
```


# Trade Class

### Constructor

Instances of Trade cannot be constructed manually. They are only accessible as a return value of <mark style="color:orange;">`DEX.trade()`</mark>.

### States and Events

During their lifetime, Trade instances traverse a fixed sequence of states where transitions between states are caused by events as depicted in Figure 1 (where states are represented as rectangles and event names are in red). The current state of a Trade instance is accessible via the <mark style="color:yellow;">`Trade.state`</mark> property and handlers may be attached/detached to events using the <mark style="color:yellow;">`Trade.on()`</mark>, <mark style="color:yellow;">`Trade.once()`</mark>, and <mark style="color:yellow;">`Trade.off()`</mark> methods. See below for details.

<figure><img src="https://1515503655-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyKeENtRbfrAq9xUdpeX3%2Fuploads%2F7OMsRWMGolOnOxUAfJGf%2Fstates%20%26%20events.svg?alt=media&amp;token=94217051-e7f4-4318-a2dc-6f681c31dc65" alt=""><figcaption><p>Figure 1: States and Events for Trade Instances</p></figcaption></figure>

### Instance Properties

```javascript
String = trade.state
```

Returns the current state of the receiver. The return value is one of the state names in Figure 1.

```javascript
Object = trade.parameters
```

Returns an Object containing all arguments to `DEX.trade()` (which were used to construct the receiver) plus current state and an error property. The return value has the following format:

```javascript
{
order_id: String,
order_type: String,
sell_asset: String,
sell_qty: Number,
sell_ctx: Object
buy_asset: String,
buy_qty: Number, 
buy_ctx: Object,     // this and above are 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
}
```

### Instance Methods

```javascript
trade = trade.on( event_name, handler )
trade = trade.once( event_name, handler )
trade = trade.off( event_name, handler, position )
```

Add or remove `handler` to be called when `event_name` occurs on receiver. Returns the receiver to allow chaining.

<table><thead><tr><th width="158">Argument</th><th>Type and Semantics</th></tr></thead><tbody><tr><td>event_name</td><td>String (case sensitive). One of the event names in Figure 1.</td></tr><tr><td>handler</td><td>Function. Handler interface is <code>handler( event_name, trade )</code> where <code>trade</code> is a reference to the Trade instance on which the event occurred.</td></tr><tr><td>position</td><td>String (case insensitive). One of: "first", "last", or "all". Specifies which instances of a handler are to be removed from the named event handler queue. If this argument is absent, "all" is the default value.</td></tr></tbody></table>

Upon construction of each Trade instance, an initially empty queue of handlers is associated with each event to which Trade responds. Upon the occurrence of an event, handlers are executed in queue order. `trade.on()` and `trade.once()` append the specified handler to the end of the specified queue. Handlers appended with `trade.on()` persist in the queue after each occurrence of an event; handlers appended with `trade.once()` are removed from the queue after being executed once. If the same handler is appended to the queue multiple times, it will be called multiple times in the order in which it appears in the queue. `trade.off()` removes the first, last, or all instances of a handler depending on the value of `position` - these are removed whether they were added with `trade.on()` or `trade.once()`. Anonymous handlers (lambdas) cannot be removed by `trade.off()`.

If called with invalid arguments, these methods will throw the "error" event. The cause of the error can be determined by accessing the `error` property of the Trade instance which originated the error event.

```javascript
trade = trade.clear( event_name )
```

Empty the event handler queue for the named event - including anonymous handlers. Returns the receiver to allow chaining.


# Business Source License 1.1

```
Business Source License 1.1

License text copyright (c) 2023 MariaDB plc, All Rights Reserved.
"Business Source License" is a trademark of MariaDB plc.

-----------------------------------------------------------------------------

Parameters

Licensor:             Tides.Network, Inc.

Licensed Work:        Portal Swap SDK
                      The Licensed Work is (c) 2023 Tides.Network, Inc.

Additional Use Grant: NONE
                      

Change Date:          November 13, 2025

Change License:       GNU General Public License v2.0 or later

-----------------------------------------------------------------------------

Terms

The Licensor hereby grants you the right to copy, modify, create derivative
works, redistribute, and make non-production use of the Licensed Work. The
Licensor may make an Additional Use Grant, above, permitting limited
production use.

Effective on the Change Date, or the fourth anniversary of the first publicly
available distribution of a specific version of the Licensed Work under this
License, whichever comes first, the Licensor hereby grants you rights under
the terms of the Change License, and the rights granted in the paragraph
above terminate.

If your use of the Licensed Work does not comply with the requirements
currently in effect as described in this License, you must purchase a
commercial license from the Licensor, its affiliated entities, or authorized
resellers, or you must refrain from using the Licensed Work.

All copies of the original and modified Licensed Work, and derivative works
of the Licensed Work, are subject to this License. This License applies
separately for each version of the Licensed Work and the Change Date may vary
for each version of the Licensed Work released by Licensor.

You must conspicuously display this License on each original or modified copy
of the Licensed Work. If you receive the Licensed Work in original or
modified form from a third party, the terms and conditions set forth in this
License apply to your use of that work.

Any use of the Licensed Work in violation of this License will automatically
terminate your rights under this License for the current and all other
versions of the Licensed Work.

This License does not grant you any right in any trademark or logo of
Licensor or its affiliates (provided that you may use a trademark or logo of
Licensor as expressly required by this License).

TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
TITLE.

MariaDB hereby grants you permission to use this License’s text to license
your works, and to refer to it using the trademark "Business Source License",
as long as you comply with the Covenants of Licensor below.

-----------------------------------------------------------------------------

Covenants of Licensor

In consideration of the right to use this License’s text and the "Business
Source License" name and trademark, Licensor covenants to MariaDB, and to all
other recipients of the licensed work to be provided by Licensor:

1. To specify as the Change License the GPL Version 2.0 or any later version,
   or a license that is compatible with GPL Version 2.0 or a later version,
   where "compatible" means that software provided under the Change License can
   be included in a program with software provided under GPL Version 2.0 or a
   later version. Licensor may specify additional Change Licenses without
   limitation.

2. To either: (a) specify an additional grant of rights to use that does not
   impose any additional restriction on the right granted in this License, as
   the Additional Use Grant; or (b) insert the text "None".

3. To specify a Change Date.

4. Not to modify this License in any other way.

-----------------------------------------------------------------------------

Notice

The Business Source License (this document, or the "License") is not an Open
Source license. However, the Licensed Work will eventually be made available
under an Open Source License, as stated in this License.
```


