Skip to content

Commit

Permalink
params detailed description improved, integration details added
Browse files Browse the repository at this point in the history
  • Loading branch information
unixvb committed Oct 20, 2024
1 parent 7b7f3c8 commit b53488b
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 47 deletions.
78 changes: 45 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,85 @@
# Rainbow Swap 🌈 SDK

This SDK is designed for building applications on top of [Rainbow Swap 🌈](https://github.com/0xblackbot/rainbow-swap) - The Next Gen DEX Aggregator on the TON blockchain 💎.
This SDK is designed for building applications on top of [Rainbow.ag](https://github.com/0xblackbot/rainbow-swap) - Swap Aggregator on TON blockchain 💎.

---
---

**We have plans to integrate commissions and share them with those who have integrated this SDK into their DApps.**
**To receive your `partnerId`, set custom fees, and enjoy a 50% revenue share, contact us in our [Community Chat](https://t.me/rainbow_swap_chat).**

---

[![npm version](https://badge.fury.io/js/rainbow-swap-sdk.svg)](https://badge.fury.io/js/rainbow-swap-sdk)
![NPM License](https://img.shields.io/npm/l/rainbow-swap-sdk)

### Installation
## Installation

You can install the Rainbow Swap SDK using either npm or Yarn:

To install the rainbow-swap-sdk, use the following npm command:
**Using npm:**
```shell
npm install rainbow-swap-sdk
```

### Integrate your dApp
**Using Yarn:**
```shell
yarn add rainbow-swap-sdk
```

## Integrate Your dApp

### Example: Swapping 1.35 TON to USDT

```typescript
import {
getAssetsRecord,
getBestRoute
} from 'rainbow-swap-sdk';
import {getAssetsRecord, getBestRoute, toNano} from 'rainbow-swap-sdk';

// 1. Load the list of available tokens
const assetsRecord = await getAssetsRecord();

...
const inputAsset = assetsRecord['ton']; // TON asset
const outputAsset = assetsRecord['EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs']; // USDT asset

// 2. Load the best swap route and swap messages
const bestRouteResponse = await getBestRoute({
inputAssetAmount: toNano('1.35', inputAsset.decimals).toString(), // Convert 1.35 TON to nano format
inputAssetAddress: inputAsset.address,
outputAssetAddress: outputAsset.address,
senderAddress: 'UQDGGjjuwhikx8ZPJsrLbKXGq7mx26D8pK_l8GqBejzB52Pa', // Optional user wallet address; if set, swap messages will be returned
partnerId: 'demo-partner' // Optional unique identifier in our App Developer Partnership program
});

// 2. Load the best swap route & swap messages
const params = {
inputAssetAmount: '1000000000', // 1 TON in nano
inputAssetAddress: 'ton', // TON
outputAssetAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', // USDT jetton master address
maxDepth: 2, // optional number of maximum route length (should be in range from 1 to 3)
userAddress: 'UQDGGjjuwhikx8ZPJsrLbKXGq7mx26D8pK_l8GqBejzB52Pa', // optional user wallet address, if set - swapMessages will return
slippageTolerance: 5 // optional max slippage value (should be in range )
};
// 3. Sign and send messages to the blockchain to execute the swap.
// This example uses the React UI client. For other frameworks, refer to https://docs.ton.org/develop/dapps/ton-connect/overview
import {useTonConnectUI} from '@tonconnect/ui-react';

const bestRouteResponse = await getBestRoute(params);
const [tonConnectUI] = useTonConnectUI();

const bestRoute = bestRouteResponse.bestRoute; // Route of the best possible swap route
const swapMessages = bestRouteResponse.swapMessages; // Array of messages that should be sent to @tonconnect
const result = await tonConnectUI.sendTransaction({
validUntil: Math.floor(Date.now() / 1000) + 60, // 60 seconds from now
messages: bestRouteResponse.swapMessages
});
```

### Application status check
## Application Status Check

Additionally, you might want to check if everything is functioning correctly. For instance, you could temporarily disable swaps if block production on TON is disrupted due to the DOGS listing.
You may want to check the status of your application to ensure everything is functioning correctly. For example, temporarily disable swaps if block production on TON is disrupted due to an external event like the DOGS listing.

```typescript
import { getAppStatus } from 'rainbow-swap-sdk';
import {getAppStatus} from 'rainbow-swap-sdk';

const {
isSwapsEnabled, // true - if everything works fine
message // explanations why swaps are disabled
isSwapsEnabled, // true if everything is working fine
message // Explanation of why swaps are disabled, if applicable
} = await getAppStatus();
```

### Live example
## Live Example

For a live example of using the SDK, visit [Rainbow Swap 🌈 repository](https://github.com/0xblackbot/rainbow-swap).
For a live example of using the SDK, visit the [Rainbow Swap 🌈 Repository](https://github.com/0xblackbot/rainbow-swap).

### Contact
## Contact

For questions and suggestions, contact us at [Blackbot](https://blackbot.technology/).
For questions and suggestions, visit [Community Chat](https://t.me/rainbow_swap_chat).

### License
## License

This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "rainbow-swap-sdk",
"version": "1.4.4",
"description": "SDK for building applications on top of Rainbow Swap - Swap Aggregator on TON 💎.",
"version": "1.4.5",
"description": "SDK for building applications on top of Rainbow.ag - Swap Aggregator on TON 💎.",
"repository": "https://github.com/0xblackbot/rainbow-swap-sdk.git",
"license": "Apache-2.0",
"main": "dist/index.js",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ export type {BestRouteResponse} from './types/best-route-response.type';
export type {CalculatedSwapRoute} from './types/calculated-swap-route.type';

export {getAssetsRecord, getBestRoute, getAppStatus} from './utils/api.utils';
export {toNano, fromNano} from './utils/big-int.utils';
export {getQueryId} from './utils/transfer-params.utils';
11 changes: 11 additions & 0 deletions src/types/best-route-display-data.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type BestRouteDisplayData = {
inputAssetAmount: number;
inputAssetUsdAmount: number;
outputAssetAmount: number;
outputAssetUsdAmount: number;
minOutputAssetAmount: number;
exchangeRate: number;
maxSlippage: number;
routingFeePercent: number;
priceImprovementPercent: number;
};
59 changes: 59 additions & 0 deletions src/types/best-route-params.type.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,67 @@
export type BestRouteParams = {
/**
* The amount of the input asset that the user wants to send, specified in nano units.
* This should be a string representation of a bigint value.
*
* **Example:** `'1350000000'` (represents 1.35 TON in nano).
*/
inputAssetAmount: string;

/**
* The address or identifier of the asset that the user wants to send.
*
* **Example:**
* - `'ton'` for TON.
* - `'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs'` for USDT.
*/
inputAssetAddress: string;

/**
* The address or identifier of the asset that the user wants to receive.
*
* **Example:**
* - `'ton'` for TON.
* - `'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs'` for USDT.
*/
outputAssetAddress: string;

/**
* (Optional) The maximum length of the route.
* Should be a number between **1 and 3** (inclusive).
*
* **Default:** `2`
*/
maxDepth?: number;

/**
* (Optional) The wallet address of the user.
* If not provided, the `swapMessages` will return an empty array (`[]`).
*/
senderAddress?: string;

/**
* (Optional) The percentage setting for slippage tolerance.
* Should be a number between **0 and 100** (inclusive).
*
* **Example:** `1.5` for 1.5% slippage tolerance.
*
* **Default:** `5`
*/
maxSlippage?: number;

/**
* (Optional) The referral address of a user.
* Refer a new user and earn a share of their trading fees.
*
* For more details, visit the **Rewards Center** at [rainbow.ag](https://rainbow.ag).
*/
referralAddress?: string;

/**
* (Optional) A unique identifier in our App Developer Partnership program.
* Integrate our SDK to enable in-app swaps, set custom fees, and enjoy a 50% revenue share.
*
* For more details, contact us at **Community Chat**: [https://t.me/rainbow_swap_chat](https://t.me/rainbow_swap_chat).
*/
partnerId?: string;
};
31 changes: 19 additions & 12 deletions src/types/best-route-response.type.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import {BestRouteDisplayData} from './best-route-display-data.type';
import {CalculatedSwapRoute} from './calculated-swap-route.type';
import {Message} from '../interfaces/message.interface';

export type BestRouteResponse = {
bestRoute: CalculatedSwapRoute[];
displayData: {
inputAssetAmount: number;
inputAssetUsdAmount: number;
outputAssetAmount: number;
outputAssetUsdAmount: number;
minOutputAssetAmount: number;
exchangeRate: number;
maxSlippage: number;
routingFeePercent: number;
priceImprovementPercent: number;
};
/**
* A user-friendly representation of the best route details.
*/
displayData: BestRouteDisplayData;

/**
* An array of messages that should be signed and sent to the blockchain to execute the swap.
*
* - For TON dApps, it is recommended to use `@tonconnect/sdk`.
* - If the `senderAddress` parameter in the request was not set, an empty array (`[]`) will be returned.
* - An empty array in other cases indicates that no route was found between the input asset and the output asset.
*/
swapMessages: Message[];

/**
* Detailed information about the most efficient routes for swapping the user's input asset,
* taking into account swap distribution and gas costs.
*/
bestRoute: CalculatedSwapRoute[];
};
42 changes: 42 additions & 0 deletions src/utils/big-int.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export const toNano = (src: string, decimals: number) => {
const precision = 10n ** BigInt(decimals);

// Check sign
let neg = false;
while (src.startsWith('-')) {
neg = !neg;
src = src.slice(1);
}
// Split string
if (src === '.') {
throw Error('Invalid number');
}
const parts = src.split('.');
if (parts.length > 2) {
throw Error('Invalid number');
}
// Prepare parts
let whole = parts[0];
let frac = parts[1];
if (!whole) {
whole = '0';
}
if (!frac) {
frac = '';
}
if (frac.length > decimals) {
throw Error('Invalid number');
}
while (frac.length < decimals) {
frac += '0';
}
// Convert
let r = BigInt(whole) * precision + BigInt(frac);
if (neg) {
r = -r;
}
return r;
};

export const fromNano = (value: bigint, decimals: number) =>
String(Number(value) / 10 ** decimals);

0 comments on commit b53488b

Please sign in to comment.