@alcorexchange/alcor-swap-sdk 1.0.11 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintignore CHANGED
@@ -1,2 +1,3 @@
1
1
  node_modules
2
- dist
2
+ dist
3
+ test.ts
package/README.md CHANGED
@@ -39,8 +39,7 @@ export function parseToken(token) {
39
39
  return new Token(
40
40
  token.contract,
41
41
  asset(token.quantity).symbol.precision(),
42
- asset(token.quantity).symbol.code().to_string(),
43
- (asset(token.quantity).symbol.code().to_string() + '-' + token.contract).toLowerCase()
42
+ asset(token.quantity).symbol.code().to_string()
44
43
  )
45
44
  }
46
45
 
@@ -15,10 +15,6 @@ export declare abstract class BaseCurrency {
15
15
  * The symbol of the currency, i.e. a short textual non-unique identifier
16
16
  */
17
17
  readonly symbol: string;
18
- /**
19
- * The id of the currency(<symbol-contract>), i.e. eos-eosio.token
20
- */
21
- readonly id?: string;
22
18
  /**
23
19
  * Constructs an instance of the base class `BaseCurrency`.
24
20
  * @param chainId the chain ID on which this currency resides
@@ -26,7 +22,7 @@ export declare abstract class BaseCurrency {
26
22
  * @param symbol symbol of the currency
27
23
  * @param name of the currency
28
24
  */
29
- protected constructor(contract: string, decimals: number, symbol: string, id?: string);
25
+ protected constructor(contract: string, decimals: number, symbol: string);
30
26
  /**
31
27
  * Returns whether this currency is functionally equivalent to the other currency
32
28
  * @param other the other currency
@@ -16,12 +16,11 @@ class BaseCurrency {
16
16
  * @param symbol symbol of the currency
17
17
  * @param name of the currency
18
18
  */
19
- constructor(contract, decimals, symbol, id) {
19
+ constructor(contract, decimals, symbol) {
20
20
  (0, tiny_invariant_1.default)(decimals >= 0 && decimals < 19 && Number.isInteger(decimals), "DECIMALS");
21
21
  this.contract = contract;
22
22
  this.decimals = decimals;
23
23
  this.symbol = symbol;
24
- this.id = id;
25
24
  }
26
25
  }
27
26
  exports.BaseCurrency = BaseCurrency;
@@ -9,8 +9,9 @@ export declare class Token extends BaseCurrency {
9
9
  * @param symbol {@link BaseCurrency#symbol}
10
10
  * @param id {@link BaseCurrency#id}
11
11
  */
12
- constructor(contract: string, decimals: number, symbol: string, id?: string);
12
+ constructor(contract: string, decimals: number, symbol: string);
13
13
  get name(): string;
14
+ get id(): string;
14
15
  /**
15
16
  * Returns true if the two tokens are equivalent, i.e. have the same contract and symbol.
16
17
  * @param other other token to compare
@@ -17,13 +17,16 @@ class Token extends baseCurrency_1.BaseCurrency {
17
17
  * @param symbol {@link BaseCurrency#symbol}
18
18
  * @param id {@link BaseCurrency#id}
19
19
  */
20
- constructor(contract, decimals, symbol, id) {
21
- super(contract, decimals, symbol, id);
20
+ constructor(contract, decimals, symbol) {
21
+ super(contract, decimals, symbol);
22
22
  }
23
23
  get name() {
24
24
  console.warn('Token.name is deprecated, use token.id');
25
25
  return this.symbol.toLowerCase() + '-' + this.contract;
26
26
  }
27
+ get id() {
28
+ return this.symbol.toLowerCase() + '-' + this.contract;
29
+ }
27
30
  /**
28
31
  * Returns true if the two tokens are equivalent, i.e. have the same contract and symbol.
29
32
  * @param other other token to compare
@@ -219,4 +219,5 @@ export declare class Trade<TInput extends Currency, TOutput extends Currency, TT
219
219
  * @returns The exact out trade
220
220
  */
221
221
  static bestTradeExactOut<TInput extends Currency, TOutput extends Currency>(pools: Pool[], currencyIn: TInput, currencyAmountOut: CurrencyAmount<TOutput>, { maxNumResults, maxHops }?: BestTradeOptions, currentPools?: Pool[], nextAmountOut?: CurrencyAmount<Currency>, bestTrades?: Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[]): Promise<Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[]>;
222
+ static bestTradeExactIn2<TInput extends Currency, TOutput extends Currency>(routes: Route<TInput, TOutput>[], pools: Pool[], currencyAmountIn: CurrencyAmount<TInput>, maxNumResults?: number): Promise<Trade<TInput, TOutput, TradeType.EXACT_INPUT>[]>;
222
223
  }
@@ -383,7 +383,11 @@ class Trade {
383
383
  }
384
384
  // we have arrived at the output token, so this is the final trade of one of the paths
385
385
  if (amountOut.currency && amountOut.currency.equals(tokenOut)) {
386
- (0, utils_1.sortedInsert)(bestTrades, yield Trade.fromRoute(new route_1.Route([...currentPools, pool], currencyAmountIn.currency, currencyOut), currencyAmountIn, internalConstants_1.TradeType.EXACT_INPUT), maxNumResults, tradeComparator);
386
+ const trade = yield Trade.fromRoute(new route_1.Route([...currentPools, pool], currencyAmountIn.currency, currencyOut), currencyAmountIn, internalConstants_1.TradeType.EXACT_INPUT);
387
+ //FIX hotfix, i do not really sure about it
388
+ if (!trade.inputAmount.greaterThan(0) || !trade.priceImpact.greaterThan(0))
389
+ continue;
390
+ (0, utils_1.sortedInsert)(bestTrades, trade, maxNumResults, tradeComparator);
387
391
  }
388
392
  else if (maxHops > 1 && pools.length > 1) {
389
393
  const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
@@ -443,7 +447,7 @@ class Trade {
443
447
  if (amountIn.currency.equals(tokenIn)) {
444
448
  const trade = yield Trade.fromRoute(new route_1.Route([pool, ...currentPools], currencyIn, currencyAmountOut.currency), currencyAmountOut, internalConstants_1.TradeType.EXACT_OUTPUT);
445
449
  // FIX hotfix, i do not really sure about it
446
- if (!trade.inputAmount.greaterThan(0) || trade.priceImpact.lessThan(0))
450
+ if (!trade.inputAmount.greaterThan(0) || !trade.priceImpact.greaterThan(0))
447
451
  continue;
448
452
  //
449
453
  (0, utils_1.sortedInsert)(bestTrades, trade, maxNumResults, tradeComparator);
@@ -460,5 +464,18 @@ class Trade {
460
464
  return bestTrades;
461
465
  });
462
466
  }
467
+ static bestTradeExactIn2(routes, pools, currencyAmountIn, maxNumResults = 3) {
468
+ return __awaiter(this, void 0, void 0, function* () {
469
+ (0, tiny_invariant_1.default)(pools.length > 0, 'POOLS');
470
+ const bestTrades = [];
471
+ for (const route of routes) {
472
+ const trade = yield Trade.fromRoute(route, currencyAmountIn, internalConstants_1.TradeType.EXACT_INPUT);
473
+ if (!trade.inputAmount.greaterThan(0) || !trade.priceImpact.greaterThan(0))
474
+ continue;
475
+ (0, utils_1.sortedInsert)(bestTrades, trade, maxNumResults, tradeComparator);
476
+ }
477
+ return bestTrades;
478
+ });
479
+ }
463
480
  }
464
481
  exports.Trade = Trade;
@@ -10,8 +10,7 @@ export function parseToken(token) {
10
10
  return new Token(
11
11
  token.contract,
12
12
  asset(token.quantity).symbol.precision(),
13
- asset(token.quantity).symbol.code().to_string(),
14
- (asset(token.quantity).symbol.code().to_string() + '-' + token.contract).toLowerCase()
13
+ asset(token.quantity).symbol.code().to_string()
15
14
  )
16
15
  }
17
16
 
@@ -13,8 +13,7 @@ export function parseToken(token) {
13
13
  return new Token(
14
14
  token.contract,
15
15
  asset(token.quantity).symbol.precision(),
16
- asset(token.quantity).symbol.code().to_string(),
17
- (asset(token.quantity).symbol.code().to_string() + '-' + token.contract).toLowerCase()
16
+ asset(token.quantity).symbol.code().to_string()
18
17
  )
19
18
  }
20
19
 
@@ -54,9 +53,6 @@ async function main() {
54
53
  code: 'swap.alcor',
55
54
  })
56
55
 
57
- console.log(JSON.stringify(ticks))
58
- return
59
-
60
56
  const pool = new Pool({
61
57
  ...poolRow,
62
58
  tokenA: parseToken(tokenA),
@@ -11,8 +11,7 @@ export function parseToken(token) {
11
11
  return new Token(
12
12
  token.contract,
13
13
  asset(token.quantity).symbol.precision(),
14
- asset(token.quantity).symbol.code().to_string(),
15
- (asset(token.quantity).symbol.code().to_string() + '-' + token.contract).toLowerCase()
14
+ asset(token.quantity).symbol.code().to_string()
16
15
  )
17
16
  }
18
17
 
@@ -37,6 +36,8 @@ async function main() {
37
36
  code: 'swap.alcor',
38
37
  })
39
38
 
39
+ if (ticks.length == 0) continue
40
+
40
41
  pools.push(new Pool({
41
42
  ...p,
42
43
  tokenA: parseToken(tokenA),
@@ -1,39 +1,72 @@
1
+ import fetch from 'node-fetch'
2
+
1
3
  const MAX_PAGINATION_FETCHES = 99
2
4
 
3
- export const fetchAllRows =
4
- async (rpc, options, indexName = 'id'): Promise<any> => {
5
- const mergedOptions = {
6
- json: true,
7
- lower_bound: 0,
8
- upper_bound: undefined,
9
- limit: 9999,
10
- ...options
11
- }
5
+ export const fetchAllRows = async (
6
+ rpc,
7
+ options,
8
+ indexName = 'id'
9
+ ) => {
10
+ const mergedOptions = {
11
+ json: true,
12
+ lower_bound: 0,
13
+ upper_bound: undefined,
14
+ limit: 9999,
15
+ ...options,
16
+ }
17
+
18
+ const bigNumberFix = options.bigNumberFix ?? false
12
19
 
13
- let rows = []
14
- let lowerBound = mergedOptions.lower_bound
20
+ if (bigNumberFix) {
21
+ delete mergedOptions.bigNumberFix
22
+ }
23
+
24
+ let rows = []
25
+ let lowerBound = mergedOptions.lower_bound
15
26
 
16
- for (let i = 0; i < MAX_PAGINATION_FETCHES; i += 1) {
17
- const result = await rpc.get_table_rows({
27
+ for (let i = 0; i < MAX_PAGINATION_FETCHES; i += 1) {
28
+ let result
29
+
30
+ if (bigNumberFix) {
31
+ const response = await fetch((rpc.endpoint ?? rpc.currentEndpoint) + '/v1/chain/get_table_rows', {
32
+ method: 'POST',
33
+ body: JSON.stringify({
34
+ ...mergedOptions,
35
+ lower_bound: lowerBound,
36
+ }),
37
+ headers: {
38
+ 'Content-type': 'application/json; charset=UTF-8',
39
+ },
40
+ })
41
+
42
+ result = JSON.parse(
43
+ (await response.text()).replace(/:(-?\d+),/g, ': "$1",')
44
+ )
45
+
46
+ } else {
47
+ result = await rpc.get_table_rows({
18
48
  ...mergedOptions,
19
- lower_bound: lowerBound
49
+ lower_bound: lowerBound,
20
50
  })
21
- rows = rows.concat(result.rows)
22
-
23
- if (!result.more || result.rows.length === 0) break
24
-
25
- // EOS 2.0 api
26
- // TODO Add 'more' key
27
- if (typeof result.next_key !== 'undefined') {
28
- lowerBound = result.next_key
29
- } else {
30
- lowerBound =
31
- Number.parseInt(
32
- `${result.rows[result.rows.length - 1][indexName]}`,
33
- 10
34
- ) + 1
35
- }
36
51
  }
37
52
 
38
- return rows
53
+ rows = rows.concat(result.rows)
54
+
55
+
56
+ if (!result.more || result.rows.length === 0 || rows.length >= mergedOptions.limit) break
57
+
58
+ // EOS 2.0 api
59
+ // TODO Add 'more' key
60
+ if (typeof result.next_key !== 'undefined') {
61
+ lowerBound = result.next_key
62
+ } else {
63
+ lowerBound =
64
+ Number.parseInt(
65
+ `${result.rows[result.rows.length - 1][indexName]}`,
66
+ 10
67
+ ) + 1
68
+ }
39
69
  }
70
+
71
+ return rows
72
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alcorexchange/alcor-swap-sdk",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
4
4
  "description": "",
5
5
  "main": "build/index.js",
6
6
  "scripts": {
@@ -42,7 +42,13 @@
42
42
  "rimraf": "^4.1.1",
43
43
  "ts-jest": "^28.0.4",
44
44
  "ts-node": "^10.9.1",
45
- "typescript": "^4.9.4"
45
+ "typescript": "^4.9.4",
46
+ "@wharfkit/antelope": "^0.10.0",
47
+ "@wharfkit/contract": "^0.4.3",
48
+ "dotenv": "^16.3.1",
49
+ "enf-eosjs": "^23.0.0",
50
+ "mongoose": "5.13.14",
51
+ "redis": "^4.6.10"
46
52
  },
47
53
  "dependencies": {
48
54
  "big.js": "^5.2.2",
@@ -17,10 +17,6 @@ export abstract class BaseCurrency {
17
17
  * The symbol of the currency, i.e. a short textual non-unique identifier
18
18
  */
19
19
  public readonly symbol: string;
20
- /**
21
- * The id of the currency(<symbol-contract>), i.e. eos-eosio.token
22
- */
23
- public readonly id?: string;
24
20
 
25
21
  /**
26
22
  * Constructs an instance of the base class `BaseCurrency`.
@@ -33,7 +29,6 @@ export abstract class BaseCurrency {
33
29
  contract: string,
34
30
  decimals: number,
35
31
  symbol: string,
36
- id?: string
37
32
  ) {
38
33
  invariant(
39
34
  decimals >= 0 && decimals < 19 && Number.isInteger(decimals),
@@ -42,7 +37,6 @@ export abstract class BaseCurrency {
42
37
  this.contract = contract;
43
38
  this.decimals = decimals;
44
39
  this.symbol = symbol;
45
- this.id = id;
46
40
  }
47
41
 
48
42
  /**
@@ -16,9 +16,8 @@ export class Token extends BaseCurrency {
16
16
  contract: string,
17
17
  decimals: number,
18
18
  symbol: string,
19
- id?: string
20
19
  ) {
21
- super(contract, decimals, symbol, id);
20
+ super(contract, decimals, symbol);
22
21
  }
23
22
 
24
23
  public get name(): string {
@@ -26,6 +25,10 @@ export class Token extends BaseCurrency {
26
25
  return this.symbol.toLowerCase() + '-' + this.contract
27
26
  }
28
27
 
28
+ public get id(): string {
29
+ return this.symbol.toLowerCase() + '-' + this.contract
30
+ }
31
+
29
32
  /**
30
33
  * Returns true if the two tokens are equivalent, i.e. have the same contract and symbol.
31
34
  * @param other other token to compare
@@ -529,13 +529,18 @@ export class Trade<TInput extends Currency, TOutput extends Currency, TTradeType
529
529
  }
530
530
  // we have arrived at the output token, so this is the final trade of one of the paths
531
531
  if (amountOut.currency && amountOut.currency.equals(tokenOut)) {
532
+ const trade = await Trade.fromRoute(
533
+ new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
534
+ currencyAmountIn,
535
+ TradeType.EXACT_INPUT
536
+ )
537
+
538
+ //FIX hotfix, i do not really sure about it
539
+ if (!trade.inputAmount.greaterThan(0) || !trade.priceImpact.greaterThan(0)) continue
540
+
532
541
  sortedInsert(
533
542
  bestTrades,
534
- await Trade.fromRoute(
535
- new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
536
- currencyAmountIn,
537
- TradeType.EXACT_INPUT
538
- ),
543
+ trade,
539
544
  maxNumResults,
540
545
  tradeComparator
541
546
  )
@@ -617,7 +622,7 @@ export class Trade<TInput extends Currency, TOutput extends Currency, TTradeType
617
622
  )
618
623
 
619
624
  // FIX hotfix, i do not really sure about it
620
- if (!trade.inputAmount.greaterThan(0) || trade.priceImpact.lessThan(0)) continue
625
+ if (!trade.inputAmount.greaterThan(0) || !trade.priceImpact.greaterThan(0)) continue
621
626
  //
622
627
 
623
628
  sortedInsert(
@@ -647,4 +652,34 @@ export class Trade<TInput extends Currency, TOutput extends Currency, TTradeType
647
652
 
648
653
  return bestTrades
649
654
  }
655
+
656
+ public static async bestTradeExactIn2<TInput extends Currency, TOutput extends Currency>(
657
+ routes: Route<TInput, TOutput>[],
658
+ pools: Pool[],
659
+ currencyAmountIn: CurrencyAmount<TInput>,
660
+ maxNumResults = 3,
661
+ ): Promise<Trade<TInput, TOutput, TradeType.EXACT_INPUT>[]> {
662
+ invariant(pools.length > 0, 'POOLS')
663
+
664
+ const bestTrades: Trade<TInput, TOutput, TradeType.EXACT_INPUT>[] = []
665
+
666
+ for (const route of routes) {
667
+ const trade = await Trade.fromRoute(
668
+ route,
669
+ currencyAmountIn,
670
+ TradeType.EXACT_INPUT
671
+ )
672
+
673
+ if (!trade.inputAmount.greaterThan(0) || !trade.priceImpact.greaterThan(0)) continue
674
+
675
+ sortedInsert(
676
+ bestTrades,
677
+ trade,
678
+ maxNumResults,
679
+ tradeComparator
680
+ )
681
+ }
682
+
683
+ return bestTrades
684
+ }
650
685
  }
@@ -12,3 +12,4 @@ export * from "./tickList";
12
12
  export * from "./priceTickConversions";
13
13
  export * from "./sqrtPriceMath";
14
14
  export * from "./sortedInsert";
15
+ export * from "./computeAllRoutes";
@@ -15,12 +15,7 @@ function parseToken(token) {
15
15
  return new Token(
16
16
  token.contract,
17
17
  asset(token.quantity).symbol.precision(),
18
- asset(token.quantity).symbol.code().to_string(),
19
- (
20
- asset(token.quantity).symbol.code().to_string() +
21
- "-" +
22
- token.contract
23
- ).toLowerCase()
18
+ asset(token.quantity).symbol.code().to_string()
24
19
  );
25
20
  }
26
21
 
@@ -1,107 +0,0 @@
1
- import fetch from 'node-fetch'
2
-
3
- // Alcor v2 sdk: https://github.com/alcorexchange/alcor-v2-sdk
4
- import { Token, Position, Pool } from '../src'
5
- import { fetchAllRows } from './utils/rpc'
6
-
7
- import { asset } from 'eos-common'
8
- import { JsonRpc } from 'eosjs'
9
- import { Serialize } from 'eosjs'
10
-
11
-
12
- export function parseToken(token) {
13
- return new Token(
14
- token.contract,
15
- asset(token.quantity).symbol.precision(),
16
- asset(token.quantity).symbol.code().to_string(),
17
- (asset(token.quantity).symbol.code().to_string() + '-' + token.contract).toLowerCase()
18
- )
19
- }
20
-
21
- const rpc = new JsonRpc('https://wax-api.alcor.exchange', { fetch });
22
-
23
- const types: any = Serialize.createInitialTypes()
24
-
25
- export const nameToUint64 = (name) => {
26
- const ser = new Serialize.SerialBuffer()
27
- ser.pushName(name)
28
- return types.get('uint64').deserialize(ser)
29
- }
30
-
31
- async function main() {
32
- const account = 'alcordexfund'
33
-
34
- const pools = await fetchAllRows(rpc, {
35
- scope: 'swap.alcor',
36
- table: 'pools',
37
- code: 'swap.alcor',
38
- })
39
-
40
- // First pool for example (TLM / WAX)
41
- const poolRow= pools[0]
42
-
43
- // Or Specific pool
44
- //const poolRow= pools.find(p => p.id == 205)
45
-
46
- const { id, tokenA, tokenB, currSlot: { sqrtPriceX64, tick } } = poolRow
47
-
48
- // Or Specific pool
49
- //const { id, tokenA, tokenB, currSlot: { sqrtPriceX64, tick } } = poolRow
50
-
51
- const ticks = await fetchAllRows(rpc, {
52
- scope: id,
53
- table: 'ticks',
54
- code: 'swap.alcor',
55
- })
56
-
57
- const pool = new Pool({
58
- ...poolRow,
59
- tokenA: parseToken(tokenA),
60
- tokenB: parseToken(tokenB),
61
- sqrtPriceX64,
62
- tickCurrent: tick,
63
- ticks: ticks.sort((a, b) => a.id - b.id)
64
- })
65
-
66
- const { rows: positions } = await rpc.get_table_rows({
67
- scope: pool.id,
68
- table: 'positions',
69
- code: 'swap.alcor',
70
-
71
- // TO get positions by account name
72
- // key_type: 'i64',
73
- // index_position: 3,
74
- // lower_bound: nameToUint64(account),
75
- // upper_bound: nameToUint64(account)
76
- })
77
-
78
- // or Specific position by id
79
- // const { rows: positions } = await rpc.get_table_rows({
80
- // scope: pool.id,
81
- // table: 'positions',
82
- // code: 'swap.alcor',
83
- // lower_bound: 14235,
84
- // upper_bound: 14235
85
- // })
86
-
87
- //console.log({ pool: pool.id, positions })
88
-
89
- const position = new Position({
90
- ...positions[0], // Only first of account position
91
- pool
92
- })
93
-
94
- console.log('amountA:', position.amountA.toAsset())
95
- console.log('amountB:', position.amountB.toAsset())
96
-
97
- // fees:
98
- const { feesA, feesB } = await position.getFees()
99
-
100
- console.log('feesA', feesA.toAsset())
101
- console.log('feesB', feesB.toAsset())
102
- }
103
-
104
- main()
105
-
106
- // amountA: 103.4332 TLM
107
- // amountB: 29.16056021 WAX