Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@pontem/liquidswap-sdk

Package Overview
Dependencies
Maintainers
4
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pontem/liquidswap-sdk - npm Package Compare versions

Comparing version 0.2.0 to 0.3.0

4

dist/tsc/main.d.ts
import { SDK, SdkOptions } from "./sdk";
import { SwapModule, CalculateRatesParams, CreateTXPayloadParams } from "./modules/SwapModule";
import { ResourcesModule } from "./modules/ResourcesModule";
import { getCoinsInWithFeesStable, getCoinsOutWithFeesStable, getCoinOutWithFees, getCoinInWithFees } from './utils';
export { SDK, SwapModule, ResourcesModule, SdkOptions, CalculateRatesParams, CreateTXPayloadParams, getCoinInWithFees, getCoinOutWithFees, getCoinsOutWithFeesStable, getCoinsInWithFeesStable };
import { getCoinsInWithFeesStable, getCoinsOutWithFeesStable, getCoinOutWithFees, getCoinInWithFees, convertValueToDecimal, convertDecimalToFixedString } from './utils';
export { SDK, SwapModule, ResourcesModule, SdkOptions, CalculateRatesParams, CreateTXPayloadParams, getCoinInWithFees, getCoinOutWithFees, getCoinsOutWithFeesStable, getCoinsInWithFeesStable, convertValueToDecimal, convertDecimalToFixedString };
export default SDK;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCoinsInWithFeesStable = exports.getCoinsOutWithFeesStable = exports.getCoinOutWithFees = exports.getCoinInWithFees = exports.ResourcesModule = exports.SwapModule = exports.SDK = void 0;
exports.convertDecimalToFixedString = exports.convertValueToDecimal = exports.getCoinsInWithFeesStable = exports.getCoinsOutWithFeesStable = exports.getCoinOutWithFees = exports.getCoinInWithFees = exports.ResourcesModule = exports.SwapModule = exports.SDK = void 0;
const sdk_1 = require("./sdk");

@@ -15,3 +15,5 @@ Object.defineProperty(exports, "SDK", { enumerable: true, get: function () { return sdk_1.SDK; } });

Object.defineProperty(exports, "getCoinInWithFees", { enumerable: true, get: function () { return utils_1.getCoinInWithFees; } });
Object.defineProperty(exports, "convertValueToDecimal", { enumerable: true, get: function () { return utils_1.convertValueToDecimal; } });
Object.defineProperty(exports, "convertDecimalToFixedString", { enumerable: true, get: function () { return utils_1.convertDecimalToFixedString; } });
exports.default = sdk_1.SDK;
//# sourceMappingURL=main.js.map

@@ -8,3 +8,3 @@ import Decimal from 'decimal.js';

toToken: AptosResourceType;
amount: Decimal;
amount: number;
interactiveToken: 'from' | 'to';

@@ -19,3 +19,3 @@ curveType: CurveType;

interactiveToken: 'from' | 'to';
slippage: Decimal;
slippage: number;
stableSwapType: 'high' | 'normal';

@@ -22,0 +22,0 @@ curveType: CurveType;

@@ -17,4 +17,16 @@ "use strict";

const { modules } = this.sdk.networkOptions;
const fromCoinInfo = yield this.sdk.Resources.fetchAccountResource((0, utils_1.extractAddressFromType)(params.fromToken), (0, utils_1.composeType)(modules.CoinInfo, [params.fromToken]));
const toCoinInfo = yield this.sdk.Resources.fetchAccountResource((0, utils_1.extractAddressFromType)(params.toToken), (0, utils_1.composeType)(modules.CoinInfo, [params.toToken]));
let fromCoinInfo;
try {
fromCoinInfo = yield this.sdk.Resources.fetchAccountResource((0, utils_1.extractAddressFromType)(params.fromToken), (0, utils_1.composeType)(modules.CoinInfo, [params.fromToken]));
}
catch (e) {
console.log(e);
}
let toCoinInfo;
try {
toCoinInfo = yield this.sdk.Resources.fetchAccountResource((0, utils_1.extractAddressFromType)(params.toToken), (0, utils_1.composeType)(modules.CoinInfo, [params.toToken]));
}
catch (e) {
console.log(e);
}
if (!fromCoinInfo) {

@@ -40,28 +52,35 @@ throw new Error('From Coin not exists');

(0, utils_1.d)(liquidityPoolResource.data.coin_x_reserve.value);
if (params.interactiveToken === 'to' && toReserve.lessThan(params.amount)) {
throw new Error(`Insufficient funds in Liquidity Pool`);
}
const fee = (0, utils_1.d)(liquidityPoolResource.data.fee);
const coinFromDecimals = +sortedFromCoinInfo.data.decimals;
const coinToDecimals = +sortedToCoinInfo.data.decimals;
let rate;
if (!params.amount) {
const amount = params.interactiveToken === 'from'
? (0, utils_1.convertValueToDecimal)(params.amount, coinToDecimals)
: (0, utils_1.convertValueToDecimal)(params.amount, coinFromDecimals);
if (amount.comparedTo(0) === 0) {
throw new Error(`Amount equals zero or undefined`);
}
if (params.interactiveToken === 'to' && toReserve.lessThan(amount)) {
throw new Error(`Insufficient funds in Liquidity Pool`);
}
let rate;
if (params.curveType === 'uncorrelated') {
rate = params.interactiveToken === 'from'
? (0, utils_1.getCoinOutWithFees)(params.amount, fromReserve, toReserve, fee)
: (0, utils_1.getCoinInWithFees)(params.amount, toReserve, fromReserve, fee);
? (0, utils_1.getCoinOutWithFees)(amount, fromReserve, toReserve, fee)
: (0, utils_1.getCoinInWithFees)(amount, toReserve, fromReserve, fee);
}
else {
rate = params.interactiveToken === 'from'
? (0, utils_1.getCoinsOutWithFeesStable)(params.amount, fromReserve, toReserve, (0, utils_1.d)(Math.pow(10, coinFromDecimals)), (0, utils_1.d)(Math.pow(10, coinToDecimals)), fee)
: (0, utils_1.getCoinsInWithFeesStable)(params.amount, toReserve, fromReserve, (0, utils_1.d)(Math.pow(10, coinToDecimals)), (0, utils_1.d)(Math.pow(10, coinFromDecimals)), fee);
? (0, utils_1.getCoinsOutWithFeesStable)(amount, fromReserve, toReserve, (0, utils_1.d)(Math.pow(10, coinFromDecimals)), (0, utils_1.d)(Math.pow(10, coinToDecimals)), fee)
: (0, utils_1.getCoinsInWithFeesStable)(amount, toReserve, fromReserve, (0, utils_1.d)(Math.pow(10, coinToDecimals)), (0, utils_1.d)(Math.pow(10, coinFromDecimals)), fee);
}
return rate.toString();
const outputRate = params.interactiveToken === 'from'
? (0, utils_1.convertDecimalToFixedString)(rate, coinFromDecimals)
: (0, utils_1.convertDecimalToFixedString)(rate, coinToDecimals);
return outputRate;
});
}
createSwapTransactionPayload(params) {
if (params.slippage.gte(1) || params.slippage.lte(0)) {
throw new Error(`Invalid slippage (${params.slippage}) value`);
const slippage = (0, utils_1.d)(params.slippage);
if (slippage.gte(1) || slippage.lte(0)) {
throw new Error(`Invalid slippage (${params.slippage}) value, it should be from 0 to 1`);
}

@@ -81,6 +100,6 @@ const { modules } = this.sdk.networkOptions;

? params.fromAmount
: (0, utils_1.withSlippage)(params.slippage, params.fromAmount, true).toFixed(0);
: (0, utils_1.withSlippage)(slippage, params.fromAmount, true).toFixed(0);
const toAmount = params.interactiveToken === 'to'
? params.toAmount
: (0, utils_1.withSlippage)(params.slippage, params.toAmount, false).toFixed(0);
: (0, utils_1.withSlippage)(slippage, params.toAmount, false).toFixed(0);
const args = [fromAmount.toString(), toAmount.toString()];

@@ -87,0 +106,0 @@ return {

export { getCoinInWithFees, getCoinOutWithFees, getCoinsOutWithFeesStable, getCoinsInWithFeesStable } from './swap-math';
export { is_sorted, withSlippage, composeType, extractAddressFromType } from './contracts';
export { calcReceivedLP, calcOutputBurnLiquidity, getOptimalLiquidityAmount } from './liquidity';
export { d, decimalsMultiplier } from './numbers';
export { d, decimalsMultiplier, convertValueToDecimal, convertDecimalToFixedString } from './numbers';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decimalsMultiplier = exports.d = exports.getOptimalLiquidityAmount = exports.calcOutputBurnLiquidity = exports.calcReceivedLP = exports.extractAddressFromType = exports.composeType = exports.withSlippage = exports.is_sorted = exports.getCoinsInWithFeesStable = exports.getCoinsOutWithFeesStable = exports.getCoinOutWithFees = exports.getCoinInWithFees = void 0;
exports.convertDecimalToFixedString = exports.convertValueToDecimal = exports.decimalsMultiplier = exports.d = exports.getOptimalLiquidityAmount = exports.calcOutputBurnLiquidity = exports.calcReceivedLP = exports.extractAddressFromType = exports.composeType = exports.withSlippage = exports.is_sorted = exports.getCoinsInWithFeesStable = exports.getCoinsOutWithFeesStable = exports.getCoinOutWithFees = exports.getCoinInWithFees = void 0;
var swap_math_1 = require("./swap-math");

@@ -21,2 +21,4 @@ Object.defineProperty(exports, "getCoinInWithFees", { enumerable: true, get: function () { return swap_math_1.getCoinInWithFees; } });

Object.defineProperty(exports, "decimalsMultiplier", { enumerable: true, get: function () { return numbers_1.decimalsMultiplier; } });
Object.defineProperty(exports, "convertValueToDecimal", { enumerable: true, get: function () { return numbers_1.convertValueToDecimal; } });
Object.defineProperty(exports, "convertDecimalToFixedString", { enumerable: true, get: function () { return numbers_1.convertDecimalToFixedString; } });
//# sourceMappingURL=index.js.map
import Decimal from "decimal.js";
export declare function d(value?: Decimal.Value): Decimal.Instance;
export declare function decimalsMultiplier(decimals?: Decimal.Value): Decimal.Instance;
export declare function convertValueToDecimal(value: number | string, decimals?: number | undefined): Decimal;
export declare function convertDecimalToFixedString(value: Decimal, decimals: number): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decimalsMultiplier = exports.d = void 0;
exports.convertDecimalToFixedString = exports.convertValueToDecimal = exports.decimalsMultiplier = exports.d = void 0;
const tslib_1 = require("tslib");

@@ -17,2 +17,12 @@ const decimal_js_1 = tslib_1.__importDefault(require("decimal.js"));

exports.decimalsMultiplier = decimalsMultiplier;
function convertValueToDecimal(value, decimals = 0) {
const mul = decimalsMultiplier(decimals);
return d(value).mul(mul);
}
exports.convertValueToDecimal = convertValueToDecimal;
function convertDecimalToFixedString(value, decimals) {
const mul = decimalsMultiplier(decimals);
return value.div(mul).toFixed(decimals);
}
exports.convertDecimalToFixedString = convertDecimalToFixedString;
//# sourceMappingURL=numbers.js.map

@@ -10,3 +10,3 @@ module.exports = {

},
testTimeout: 20000,
testTimeout: 30000,
}
{
"name": "@pontem/liquidswap-sdk",
"version": "0.2.0",
"version": "0.3.0",
"description": "SDK for use any functions of LiquidSwap",

@@ -5,0 +5,0 @@ "author": "Igor Demko <igor@pontem.network>",

@@ -14,4 +14,3 @@ # LiquidSwap SDK

```typescript
import { SDK } from '@pontem/liquidswap-sdk';
import Decimal from 'decimal.js';
import { SDK, convertValueToDecimal } from '@pontem/liquidswap-sdk';

@@ -35,3 +34,13 @@ const sdk = new SDK({

```
### You want to convert 15 coins to Decimal type with 8 decimals (coins like APTOS, BTC, etc);
```typescript
const decimalValue = convertValueToDecimal(15, 8);
or // convertValueToDecimal return Decimal type;
const decimalValue2 = convertValueToDecimal('15', 8);
```
### You want swap EXACTLY 1 APTOS to SLIPPAGED layerzero USDT amount

@@ -42,24 +51,29 @@

// Get USDT amount
const output = await sdk.Swap.calculateRates({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT', // layerzero USDT
amount: new Decimal(100000000), // 1 APTOS as Decimal amount
curveType: 'uncorrelated',
interactiveToken: 'from',
})
console.log(amount) // '4995851.2364508969978' (4.995851 USDT)
try {
const output = await sdk.Swap.calculateRates({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT', // layerzero USDT
amount: 1, // 1 APTOS as Decimal amount
curveType: 'uncorrelated',
interactiveToken: 'from',
})
console.log(amount) // '4.304638' USDT
// Generate TX payload for swap 1 APTOS to maximum 4.995851 USDT
// and minimum 4.746058 USDT - 5% (with slippage 5%)
const txPayload = sdk.Swap.createSwapTransactionPayload({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT', // layerzero USDT
fromAmount: new Decimal(100000000), // 1 APTOS,
toAmount: new Decimal(4995851), // 4.995851 USDT,
interactiveToken: 'from',
slippage: new Decimal(0.05), // 5% (1 - 100%, 0 - 0%)
stableSwapType: 'normal',
curveType: 'uncorrelated',
})
console.log(txPayload);
// Generate TX payload for swap 1 APTOS to maximum 4.304638 USDT
// and minimum 4.283115 USDT (with slippage -0.5%)
const txPayload = sdk.Swap.createSwapTransactionPayload({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT', // layerzero USDT
fromAmount: convertValueToDecimal(1, 8), // 1 APTOS,
toAmount: convertValueToDecimal(4.304638, 6), // 4.304638 USDT,
interactiveToken: 'from',
slippage: 0.005, // 0.5% (1 - 100%, 0 - 0%)
stableSwapType: 'high',
curveType: 'uncorrelated',
})
console.log(txPayload);
} catch(e) {
console.log(e)
}
/**

@@ -75,3 +89,3 @@ Output:

],
arguments: [ '100000000', '4746058' ]
arguments: [ '100000000', '4283115' ]
}

@@ -83,28 +97,33 @@

### You want get EXACTLY 1 BTC and send SLIPPAGED APTOS amount
### You want get EXACTLY 1 USDT and send SLIPPAGED APTOS amount
```typescript
(async () => {
// Get APTOS amount
const amount = await sdk.Swap.calculateRates({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT',
amount: new Decimal(1000000), // 1 USDT
interactiveToken: 'to', // 'from' - calculate TO amount, 'to' - calculate FROM amount
curveType: 'uncorrelated',
})
console.log(amount) // '20032733.69689480612' (0.20032734 APTOS)
try {
const amount = await sdk.Swap.calculateRates({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT',
amount: 1, // 1 layerzero USDT
interactiveToken: 'to',
curveType: 'uncorrelated',
})
console.log(amount) // '0.23211815' APTOS
// Generate TX payload for get EXACTLY 1 USDT
// and minimum send 0.20032734 + 5% (with slippage 5%)
const txPayload = sdk.Swap.createSwapTransactionPayload({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT',
fromAmount: new Decimal(20032734), // 0.20032734 APTOS,
toAmount: new Decimal(1000000), // 1 USDT,
interactiveToken: 'to',
slippage: new Decimal(0.05), // 5% (1 - 100%, 0 - 0%)
stableSwapType: 'normal',
curveType: 'uncorrelated',
})
console.log(txPayload);
// Generate TX payload for get EXACTLY 1 USDT
// and minimum send 0.23327874 (with slippage +0.5%)
const txPayload = sdk.Swap.createSwapTransactionPayload({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT',
fromAmount: convertValueToDecimal(0.23211815, 8), // 0.23211815 APTOS,
toAmount: convertValueToDecimal(1, 6), // 1 layerzero USDT,
interactiveToken: 'to',
slippage: 0.005, // 0.5% (1 - 100%, 0 - 0%)
stableSwapType: 'hign',
curveType: 'uncorrelated',
})
console.log(txPayload);
} catch (e) {
console.log(e);
}
/**

@@ -120,3 +139,3 @@ Output:

],
arguments: [ '21034371', '1000000' ]
arguments: [ '23327874', '1000000' ]
}

@@ -126,1 +145,97 @@ */

```
### You want swap EXACTLY 1 APTOS to wormhole WETH with curve - 'stable', stableSwapType - 'normal' and 0.5% slippage
```typescript
(async () => {
// Get WETH amount
try {
const amount = await sdk.Swap.calculateRates({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xcc8a89c8dce9693d354449f1f73e60e14e347417854f029db5bc8e7454008abb::coin::T', // wormhole WETH (whWETH)
amount: 1, // 1 APTOS
interactiveToken: 'from',
curveType: 'stable',
})
console.log(amount) // '0.00175257' whWETH
// Generate TX payload to swap 1 APTOS to
// and minimum send 0.00174381 (with slippage -0.5%)
const txPayload = sdk.Swap.createSwapTransactionPayload({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0xf22bede237a07e121b56d91a491eb7bcdfd1f5907926a9e58338f964a01b17fa::asset::USDT',
fromAmount: convertValueToDecimal(1, 8), // 1 Aptos
toAmount: convertValueToDecimal(0.00175257, 8), // 0.00175257 whWETH,
interactiveToken: 'from',
slippage: 0.005, // 0.5% (1 - 100%, 0 - 0%)
stableSwapType: 'normal',
curveType: 'stable',
})
console.log(txPayload);
} catch (e) {
console.log(e);
}
/**
Output:
{
type: 'entry_function_payload',
function: '0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::scripts_v2::swap_unchecked',
typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xcc8a89c8dce9693d354449f1f73e60e14e347417854f029db5bc8e7454008abb::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Stable'
],
arguments: [ '100000000', '174381' ]
}
*/
})()
```
### You want to get EXACTLY 1 USDA and send SLIPPAGED APTOS amount with curve - 'stable', stableSwapType - 'high' and 0.5% slippage
```typescript
(async () => {
// Get APTOS amount
try {
const amount = await sdk.Swap.calculateRates({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0x1000000fa32d122c18a6a31c009ce5e71674f22d06a581bb0a15575e6addadcc::usda::USDA', // USDA
amount: 1, // 1 USDA
interactiveToken: 'to',
curveType: 'stable',
})
console.log(amount) // '0.12356861' APTOS
// Generate TX payload to swap 1 APTOS to
// and minimum send 0.12418645 (with slippage +0.5%)
const txPayload = sdk.Swap.createSwapTransactionPayload({
fromToken: '0x1::aptos_coin::AptosCoin',
toToken: '0x1000000fa32d122c18a6a31c009ce5e71674f22d06a581bb0a15575e6addadcc::usda::USDA',
fromAmount: convertValueToDecimal(0.12356861, 8), // 0.12356861 APTOS
toAmount: convertValueToDecimal(1, 6), // 1 USDA,
interactiveToken: 'to',
slippage: 0.005, // 0.5% (1 - 100%, 0 - 0%)
stableSwapType: 'high',
curveType: 'stable',
})
console.log(txPayload);
} catch (e) {
console.log(e);
}
/**
Output:
{
type: 'entry_function_payload',
function: '0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::scripts_v2::swap_into',
typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0x1000000fa32d122c18a6a31c009ce5e71674f22d06a581bb0a15575e6addadcc::usda::USDA',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Stable'
],
arguments: [ '12418645', '1000000' ]
}
*/
})()
```
### For additional examples feel free to explore '[src/main.test.ts](src/main.test.ts)' file;

@@ -1,3 +0,4 @@

import SDK from './main'
import { d, decimalsMultiplier } from "./utils";
import { CURVE_STABLE, CURVE_UNCORRELATED } from './constants/index';
import SDK from './main';
import { d, decimalsMultiplier, convertValueToDecimal } from "./utils";

@@ -11,3 +12,3 @@ const TokensMapping: Record<string, string> = {

const CoinInfo: Record<string, { decimals: number }> = {
const CoinInfo: Record<string, { decimals: number; }> = {
APTOS: { decimals: 8 },

@@ -17,3 +18,3 @@ USDT: { decimals: 6 },

WETH: { decimals: 8 }
}
};

@@ -23,101 +24,127 @@ function convertToDecimals(amount: number | string, token: string) {

return d(amount).mul(mul)
return d(amount).mul(mul);
}
function prettyAmount(amount: number | string, token: string) {
const mul = decimalsMultiplier(CoinInfo[token]?.decimals || 0);
return d(amount).div(mul)
}
describe('Swap Module', () => {
const sdk = new SDK({
nodeUrl: 'https://fullnode.mainnet.aptoslabs.com/v1',
})
});
test('calculateRates (from mode)', async () => {
console.log({amountIn: convertToDecimals(1, 'APTOS')});
const output = await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.USDT,
amount: convertToDecimals(1, 'APTOS'),
amount: 1,
curveType: 'uncorrelated',
interactiveToken: 'from',
})
console.log({
amount: output,
pretty: prettyAmount(output, 'USDT'),
});
expect(1).toBe(1)
console.log(`1 APT → ${output} USDT`);
expect(typeof output).toBe('string');
expect(output.length).toBeGreaterThan(0);
});
test('calculateRates (to mode)', async () => {
console.log({amountInToMode: convertToDecimals(1, 'USDT')});
const output = await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.USDT,
amount: convertToDecimals('1', 'USDT'),
amount: 1,
curveType: 'uncorrelated',
interactiveToken: 'to',
})
console.log({
amount: output,
pretty: prettyAmount(output, 'APTOS'),
});
expect(1).toBe(1)
console.log(`${output} APT → 1 USDT`);
expect(typeof output).toBe('string');
expect(output.length).toBeGreaterThan(0);
});
test('calculateRates (from mode stable)', async () => {
console.log({amountIn: convertToDecimals(1, 'APTOS')});
const output = await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
amount: convertToDecimals('1', 'APTOS'),
amount: 1,
curveType: 'stable',
interactiveToken: 'from',
})
console.log({
amount: output,
pretty: prettyAmount(output, 'WETH'),
});
expect(1).toBe(1);
console.log(`1 APT → ${output} WETH`);
expect(typeof output).toBe('string');
expect(output.length).toBeGreaterThan(0);
});
test('calculateRates (to mode stable) and get error', async () => {
console.log({amountIn: convertToDecimals(1, 'WETH')});
test('calculateRates (to mode stable) and get error', async () => {
try {
await sdk.Swap.calculateRates({
fromToken: TokensMapping.BTC,
toToken: TokensMapping.WETH,
amount: 1,
curveType: 'stable',
interactiveToken: 'to',
});
} catch (e) {
expect(e).toMatchObject(new Error(`LiquidityPool (0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::liquidity_pool::LiquidityPool<${TokensMapping.BTC},${TokensMapping.WETH},${CURVE_STABLE}>) not found`));
}
try {
const output = await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS + '0',
toToken: TokensMapping.WETH,
amount: convertToDecimals('1', 'WETH'),
amount: 1,
curveType: 'stable',
interactiveToken: 'to',
})
});
} catch (e) {
expect(e).toMatchObject(new Error('From Coin not exists'));
}
console.log({
amount: output,
pretty: prettyAmount(output, 'WETH'),
try {
await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH + '0',
amount: 1,
curveType: 'stable',
interactiveToken: 'to',
});
} catch(e) {
} catch (e) {
expect(e).toMatchObject(new Error('To Coin not exists'));
}
try {
await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
amount: 1,
curveType: 'stable',
interactiveToken: 'to',
});
} catch (e) {
expect(e).toMatchObject(new Error('Insufficient funds in Liquidity Pool'));
}
try {
await sdk.Swap.calculateRates({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
amount: 0,
curveType: 'stable',
interactiveToken: 'to',
});
} catch (e) {
expect(e).toMatchObject(new Error('Amount equals zero or undefined'));
}
});
test('createSwapTransactionPayload (uncorrelated from mode high)', async () => {
test('createSwapTransactionPayload (uncorrelated from mode high)', () => {
const output = sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.BTC,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('4.995851', 'USDT'),
toToken: TokensMapping.USDT,
fromAmount: convertValueToDecimal(1, 8),
toAmount: convertValueToDecimal('4.304638', 6),
interactiveToken: 'from',
slippage: d(0.05),
slippage: 0.005,
stableSwapType: 'high',
curveType: 'uncorrelated',
})
});

@@ -128,21 +155,21 @@ expect(output).toStrictEqual({

typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xae478ff7d83ed072dbc5e264250e67ef58f57c99d89b447efd8a0a2e8b2be76e::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Uncorrelated'
TokensMapping.APTOS,
TokensMapping.USDT,
CURVE_UNCORRELATED
],
arguments: ['100000000', '4746058']
})
})
arguments: ['100000000', '4283115']
});
});
test('createSwapTransactionPayload (uncorrelated to mode high)', async () => {
test('createSwapTransactionPayload (uncorrelated to mode high)', () => {
const output = sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.BTC,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('4.995851', 'USDT'),
toToken: TokensMapping.USDT,
fromAmount: convertValueToDecimal(0.23211815, 8),
toAmount: convertValueToDecimal(1, 6),
interactiveToken: 'to',
slippage: d(0.05),
slippage: 0.005,
stableSwapType: 'high',
curveType: 'uncorrelated',
})
});

@@ -153,21 +180,21 @@ expect(output).toStrictEqual({

typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xae478ff7d83ed072dbc5e264250e67ef58f57c99d89b447efd8a0a2e8b2be76e::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Uncorrelated'
TokensMapping.APTOS,
TokensMapping.USDT,
CURVE_UNCORRELATED
],
arguments: ['105000000', '4995851']
})
arguments: ['23327874', '1000000']
});
});
test('createSwapTransactionPayload (stable from mode high)', async () => {
test('createSwapTransactionPayload (stable from mode high)', () => {
const output = sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('0.000846', 'WETH'),
fromAmount: convertValueToDecimal(0.04, 8),
toAmount: convertValueToDecimal('0.00037818', 8),
interactiveToken: 'from',
slippage: d(0.05),
slippage: 0.005,
stableSwapType: 'high',
curveType: 'stable',
})
});

@@ -178,21 +205,21 @@ expect(output).toStrictEqual({

typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xcc8a89c8dce9693d354449f1f73e60e14e347417854f029db5bc8e7454008abb::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Stable'
TokensMapping.APTOS,
TokensMapping.WETH,
CURVE_STABLE
],
arguments: ['100000000', '80370']
})
arguments: ['4000000', '37629']
});
});
test('createSwapTransactionPayload (stable to mode high)', async () => {
test('createSwapTransactionPayload (stable to mode high)', () => {
const output = sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('0.000846', 'WETH'),
fromAmount: convertToDecimals('0.03998981', 'APTOS'),
toAmount: convertToDecimals('0.0003781', 'WETH'),
interactiveToken: 'to',
slippage: d(0.05),
slippage: 0.005,
stableSwapType: 'high',
curveType: 'stable',
})
});

@@ -203,11 +230,11 @@ expect(output).toStrictEqual({

typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xcc8a89c8dce9693d354449f1f73e60e14e347417854f029db5bc8e7454008abb::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Stable'
TokensMapping.APTOS,
TokensMapping.WETH,
CURVE_STABLE
],
arguments: ['105000000', '84600']
arguments: ['4018976', '37810']
});
});
test('createSwapTransactionPayload (stable from mode normal)', async () => {
test('createSwapTransactionPayload (stable from mode normal)', () => {
const output = sdk.Swap.createSwapTransactionPayload({

@@ -217,8 +244,8 @@ fromToken: TokensMapping.APTOS,

fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('0.000846', 'WETH'),
toAmount: convertToDecimals('0.00175257', 'WETH'),
interactiveToken: 'from',
slippage: d(0.05),
slippage: 0.005,
stableSwapType: 'normal',
curveType: 'stable',
})
});

@@ -229,21 +256,21 @@ expect(output).toStrictEqual({

typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xcc8a89c8dce9693d354449f1f73e60e14e347417854f029db5bc8e7454008abb::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Stable'
TokensMapping.APTOS,
TokensMapping.WETH,
CURVE_STABLE
],
arguments: ['100000000', '80370']
})
arguments: ['100000000', '174381']
});
});
test('createSwapTransactionPayload (stable to mode normal)', async () => {
test('createSwapTransactionPayload (stable to mode normal)', () => {
const output = sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('0.000846', 'WETH'),
fromAmount: convertToDecimals('0.00400045', 'APTOS'),
toAmount: convertToDecimals('0.00004339', 'WETH'),
interactiveToken: 'to',
slippage: d(0.05),
slippage: 0.005,
stableSwapType: 'normal',
curveType: 'stable',
})
});

@@ -254,9 +281,43 @@ expect(output).toStrictEqual({

typeArguments: [
'0x1::aptos_coin::AptosCoin',
'0xcc8a89c8dce9693d354449f1f73e60e14e347417854f029db5bc8e7454008abb::coin::T',
'0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12::curves::Stable'
TokensMapping.APTOS,
TokensMapping.WETH,
CURVE_STABLE
],
arguments: ['105000000', '84600']
})
arguments: ['402045', '4339']
});
});
})
test('createSwapTransactionPayload Errors', () => {
expect.assertions(2);
try {
sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('0.000846', 'WETH'),
interactiveToken: 'to',
slippage: -0.01,
stableSwapType: 'high',
curveType: 'stable',
});
} catch (e) {
expect(e).toMatchObject(new Error(`Invalid slippage (-0.01) value, it should be from 0 to 1`));
}
try {
sdk.Swap.createSwapTransactionPayload({
fromToken: TokensMapping.APTOS,
toToken: TokensMapping.WETH,
fromAmount: convertToDecimals('1', 'APTOS'),
toAmount: convertToDecimals('0.000846', 'WETH'),
interactiveToken: 'to',
slippage: 1.01,
stableSwapType: 'high',
curveType: 'stable',
});
} catch (e) {
expect(e).toMatchObject(new Error(`Invalid slippage (1.01) value, it should be from 0 to 1`));
}
});
});
import { SDK, SdkOptions } from "./sdk";
import { SwapModule, CalculateRatesParams, CreateTXPayloadParams } from "./modules/SwapModule";
import { ResourcesModule } from "./modules/ResourcesModule";
import { getCoinsInWithFeesStable, getCoinsOutWithFeesStable, getCoinOutWithFees, getCoinInWithFees } from './utils'
import {
getCoinsInWithFeesStable,
getCoinsOutWithFeesStable,
getCoinOutWithFees,
getCoinInWithFees,
convertValueToDecimal,
convertDecimalToFixedString,
} from './utils';

@@ -16,5 +23,7 @@ export {

getCoinsOutWithFeesStable,
getCoinsInWithFeesStable
getCoinsInWithFeesStable,
convertValueToDecimal,
convertDecimalToFixedString
};
export default SDK;

@@ -1,5 +0,5 @@

import {SDK} from "../sdk";
import {IModule} from "../interfaces/IModule";
import {AptosResource, AptosResourceType} from "../types/aptos";
import {isAxiosError} from "../utils/is";
import { SDK } from "../sdk";
import { IModule } from "../interfaces/IModule";
import { AptosResource, AptosResourceType } from "../types/aptos";
import { isAxiosError } from "../utils/is";

@@ -23,4 +23,4 @@

} catch (e: unknown) {
if(isAxiosError(e)) {
if(e.response?.status === 404) {
if (isAxiosError(e)) {
if (e.response?.status === 404) {
return undefined;

@@ -27,0 +27,0 @@ }

@@ -22,2 +22,4 @@ import Decimal from 'decimal.js';

is_sorted,
convertValueToDecimal,
convertDecimalToFixedString
} from "../utils";

@@ -34,3 +36,3 @@ import {

toToken: AptosResourceType;
amount: Decimal;
amount: number;
interactiveToken: 'from' | 'to';

@@ -46,3 +48,3 @@ curveType: CurveType;

interactiveToken: 'from' | 'to';
slippage: Decimal;
slippage: number;
stableSwapType: 'high' | 'normal';

@@ -66,11 +68,21 @@ curveType: CurveType;

const fromCoinInfo = await this.sdk.Resources.fetchAccountResource<AptosCoinInfoResource>(
extractAddressFromType(params.fromToken),
composeType(modules.CoinInfo, [params.fromToken])
);
let fromCoinInfo;
try {
fromCoinInfo = await this.sdk.Resources.fetchAccountResource<AptosCoinInfoResource>(
extractAddressFromType(params.fromToken),
composeType(modules.CoinInfo, [params.fromToken])
);
} catch (e) {
console.log(e);
}
const toCoinInfo = await this.sdk.Resources.fetchAccountResource<AptosCoinInfoResource>(
extractAddressFromType(params.toToken),
composeType(modules.CoinInfo, [params.toToken])
);
let toCoinInfo;
try {
toCoinInfo = await this.sdk.Resources.fetchAccountResource<AptosCoinInfoResource>(
extractAddressFromType(params.toToken),
composeType(modules.CoinInfo, [params.toToken])
);
} catch (e) {
console.log(e);
}

@@ -104,6 +116,2 @@ if (!fromCoinInfo) {

if (params.interactiveToken === 'to' && toReserve.lessThan(params.amount)) {
throw new Error(`Insufficient funds in Liquidity Pool`);
}
const fee = d(liquidityPoolResource.data.fee);

@@ -114,15 +122,24 @@

let rate;
if (!params.amount) {
const amount = params.interactiveToken === 'from'
? convertValueToDecimal(params.amount, coinToDecimals)
: convertValueToDecimal(params.amount, coinFromDecimals);
if (amount.comparedTo(0) === 0) {
throw new Error(`Amount equals zero or undefined`);
}
if (params.interactiveToken === 'to' && toReserve.lessThan(amount)) {
throw new Error(`Insufficient funds in Liquidity Pool`);
}
let rate;
if (params.curveType === 'uncorrelated') {
rate = params.interactiveToken === 'from'
? getCoinOutWithFees(params.amount, fromReserve, toReserve, fee)
: getCoinInWithFees(params.amount, toReserve, fromReserve, fee);
? getCoinOutWithFees(amount, fromReserve, toReserve, fee)
: getCoinInWithFees(amount, toReserve, fromReserve, fee);
} else {
rate = params.interactiveToken === 'from'
? getCoinsOutWithFeesStable(
params.amount,
amount,
fromReserve,

@@ -135,3 +152,3 @@ toReserve,

: getCoinsInWithFeesStable(
params.amount,
amount,
toReserve,

@@ -144,8 +161,13 @@ fromReserve,

}
return rate.toString();
const outputRate = params.interactiveToken === 'from'
? convertDecimalToFixedString(rate, coinFromDecimals)
: convertDecimalToFixedString(rate, coinToDecimals);
return outputRate;
}
createSwapTransactionPayload(params: CreateTXPayloadParams): TAptosTxPayload {
if (params.slippage.gte(1) || params.slippage.lte(0)) {
throw new Error(`Invalid slippage (${params.slippage}) value`);
const slippage = d(params.slippage);
if (slippage.gte(1) || slippage.lte(0)) {
throw new Error(`Invalid slippage (${params.slippage}) value, it should be from 0 to 1`);
}

@@ -175,7 +197,7 @@

? params.fromAmount
: withSlippage(params.slippage, params.fromAmount, true).toFixed(0);
: withSlippage(slippage, params.fromAmount, true).toFixed(0);
const toAmount =
params.interactiveToken === 'to'
? params.toAmount
: withSlippage(params.slippage, params.toAmount, false).toFixed(0);
: withSlippage(slippage, params.toAmount, false).toFixed(0);

@@ -182,0 +204,0 @@ const args = [fromAmount.toString(), toAmount.toString()];

@@ -1,5 +0,5 @@

import {AptosClient} from "aptos";
import {SwapModule} from "./modules/SwapModule";
import {ResourcesModule} from "./modules/ResourcesModule";
import {AptosResourceType} from "./types/aptos";
import { AptosClient } from "aptos";
import { SwapModule } from "./modules/SwapModule";
import { ResourcesModule } from "./modules/ResourcesModule";
import { AptosResourceType } from "./types/aptos";

@@ -13,3 +13,3 @@ const initialNetworkOptions = {

},
}
};

@@ -22,3 +22,3 @@ interface INetworkOptions {

Scripts: AptosResourceType;
} & Record<string, AptosResourceType>
} & Record<string, AptosResourceType>;
}

@@ -25,0 +25,0 @@

@@ -6,3 +6,3 @@ export type AptosResourceType = string;

type: string,
}
};

@@ -19,4 +19,4 @@ export type AptosCoinInfoResource = {

export type AptosPoolResource = {
coin_x_reserve: { value: string };
coin_y_reserve: { value: string };
coin_x_reserve: { value: string; };
coin_y_reserve: { value: string; };
last_block_timestamp: string;

@@ -43,3 +43,3 @@ last_price_x_cumulative: string;

type: 'module_bundle_payload';
modules: { bytecode: string }[];
modules: { bytecode: string; }[];
};

@@ -46,0 +46,0 @@

@@ -145,3 +145,3 @@ import { Buffer } from "buffer";

type: any,
options: { leadingZero: boolean } = { leadingZero: true }
options: { leadingZero: boolean; } = { leadingZero: true }
): boolean {

@@ -148,0 +148,0 @@ if (typeof type !== 'string') {

@@ -20,3 +20,3 @@ const HEX_REGEXP = /^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;

address: any,
options: { leadingZero: boolean } = { leadingZero: true }
options: { leadingZero: boolean; } = { leadingZero: true }
): boolean {

@@ -47,21 +47,21 @@ if (typeof address !== 'string') {

if (Array.isArray(v)) {
v = Buffer.from(v)
v = Buffer.from(v);
} else if (typeof v === 'string') {
if (exports.isHexString(v)) {
v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex')
v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex');
} else {
v = Buffer.from(v)
v = Buffer.from(v);
}
} else if (typeof v === 'number') {
v = exports.intToBuffer(v)
v = exports.intToBuffer(v);
} else if (v === null || v === undefined) {
v = Buffer.allocUnsafe(0)
v = Buffer.allocUnsafe(0);
} else if (v.toArray) {
// converts a BN to a Buffer
v = Buffer.from(v.toArray())
v = Buffer.from(v.toArray());
} else {
throw new Error('invalid type')
throw new Error('invalid type');
}
}
return v
return v;
}

@@ -71,3 +71,3 @@

type: any,
options: { leadingZero: boolean } = { leadingZero: true }
options: { leadingZero: boolean; } = { leadingZero: true }
): boolean {

@@ -74,0 +74,0 @@ if (typeof type !== 'string') {

export { getCoinInWithFees, getCoinOutWithFees, getCoinsOutWithFeesStable, getCoinsInWithFeesStable } from './swap-math';
export { is_sorted, withSlippage, composeType, extractAddressFromType } from './contracts';
export { calcReceivedLP, calcOutputBurnLiquidity, getOptimalLiquidityAmount } from './liquidity';
export { d, decimalsMultiplier } from './numbers';
export { d, decimalsMultiplier, convertValueToDecimal, convertDecimalToFixedString } from './numbers';
import { AxiosError } from 'axios';
export function isAxiosError(e: any): e is AxiosError {
if(e.isAxiosError) {
if (e.isAxiosError) {
return e;
}
return e;
return e;
}

@@ -13,1 +13,13 @@ import Decimal from "decimal.js";

}
export function convertValueToDecimal(value: number | string, decimals: number | undefined = 0) {
const mul = decimalsMultiplier(decimals);
return d(value).mul(mul);
}
export function convertDecimalToFixedString(value: Decimal, decimals: number) {
const mul = decimalsMultiplier(decimals);
return value.div(mul).toFixed(decimals);
}
import Decimal from 'decimal.js';
import { d } from '../utils'
import { d } from '../utils';

@@ -4,0 +4,0 @@ const e8 = new Decimal('100000000');

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc