@centurion_project/v2-sdk 4.21.10 → 4.21.12

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.
@@ -3,7 +3,7 @@ import JSBI from 'jsbi';
3
3
  /**
4
4
  * @deprecated use FACTORY_ADDRESS_MAP instead
5
5
  */
6
- export declare const FACTORY_ADDRESS = "0x43805c9B2f5dcB8E02c60035Ef1b3cD5178cDA3A";
6
+ export declare const FACTORY_ADDRESS = "0xa5C54eC60631e48bf4449D35361D04A448CBC773";
7
7
  export declare const FACTORY_ADDRESS_MAP: {
8
8
  [chainId: number]: string;
9
9
  };
@@ -7,7 +7,7 @@ const jsbi_1 = tslib_1.__importDefault(require("jsbi"));
7
7
  /**
8
8
  * @deprecated use FACTORY_ADDRESS_MAP instead
9
9
  */
10
- exports.FACTORY_ADDRESS = '0x43805c9B2f5dcB8E02c60035Ef1b3cD5178cDA3A';
10
+ exports.FACTORY_ADDRESS = '0xa5C54eC60631e48bf4449D35361D04A448CBC773';
11
11
  exports.FACTORY_ADDRESS_MAP = sdk_core_1.V2_FACTORY_ADDRESSES;
12
12
  exports.INIT_CODE_HASH = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f';
13
13
  const UNISWAP_V2_INIT_CODE_HASH = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f';
@@ -3,7 +3,7 @@ import JSBI from 'jsbi';
3
3
  /**
4
4
  * @deprecated use FACTORY_ADDRESS_MAP instead
5
5
  */
6
- export declare const FACTORY_ADDRESS = "0x43805c9B2f5dcB8E02c60035Ef1b3cD5178cDA3A";
6
+ export declare const FACTORY_ADDRESS = "0xa5C54eC60631e48bf4449D35361D04A448CBC773";
7
7
  export declare const FACTORY_ADDRESS_MAP: {
8
8
  [chainId: number]: string;
9
9
  };
@@ -3,7 +3,7 @@ import JSBI from 'jsbi';
3
3
  /**
4
4
  * @deprecated use FACTORY_ADDRESS_MAP instead
5
5
  */
6
- export const FACTORY_ADDRESS = '0x43805c9B2f5dcB8E02c60035Ef1b3cD5178cDA3A';
6
+ export const FACTORY_ADDRESS = '0xa5C54eC60631e48bf4449D35361D04A448CBC773';
7
7
  export const FACTORY_ADDRESS_MAP = V2_FACTORY_ADDRESSES;
8
8
  export const INIT_CODE_HASH = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f';
9
9
  const UNISWAP_V2_INIT_CODE_HASH = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f';
@@ -3,7 +3,7 @@ import JSBI from 'jsbi';
3
3
  /**
4
4
  * @deprecated use FACTORY_ADDRESS_MAP instead
5
5
  */
6
- export declare const FACTORY_ADDRESS = "0x43805c9B2f5dcB8E02c60035Ef1b3cD5178cDA3A";
6
+ export declare const FACTORY_ADDRESS = "0xa5C54eC60631e48bf4449D35361D04A448CBC773";
7
7
  export declare const FACTORY_ADDRESS_MAP: {
8
8
  [chainId: number]: string;
9
9
  };
@@ -21,3 +21,4 @@ export declare const _1000: JSBI;
21
21
  export declare const BASIS_POINTS: JSBI;
22
22
  export declare const ZERO_PERCENT: Percent;
23
23
  export declare const ONE_HUNDRED_PERCENT: Percent;
24
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,OAAO,EAAwB,MAAM,6BAA6B,CAAA;AACpF,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB;;GAEG;AACH,eAAO,MAAM,eAAe,+CAA+C,CAAA;AAE3E,eAAO,MAAM,mBAAmB,EAAE;IAAE,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAA;CAAyB,CAAA;AAEtF,eAAO,MAAM,cAAc,uEAAuE,CAAA;AAIlG,eAAO,MAAM,kBAAkB,EAAE;IAAE,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAA;CAM3D,CAAA;AAED,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAGrD;AAED,eAAO,MAAM,iBAAiB,MAAoB,CAAA;AAGlD,eAAO,MAAM,IAAI,MAAiB,CAAA;AAClC,eAAO,MAAM,GAAG,MAAiB,CAAA;AACjC,eAAO,MAAM,IAAI,MAAiB,CAAA;AAClC,eAAO,MAAM,IAAI,MAAmB,CAAA;AACpC,eAAO,MAAM,KAAK,MAAoB,CAAA;AACtC,eAAO,MAAM,YAAY,MAAqB,CAAA;AAE9C,eAAO,MAAM,YAAY,SAAoB,CAAA;AAC7C,eAAO,MAAM,mBAAmB,SAAmB,CAAA"}
@@ -1,3 +1,4 @@
1
1
  export * from './pair';
2
2
  export * from './route';
3
3
  export * from './trade';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/entities/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAA;AACtB,cAAc,SAAS,CAAA;AACvB,cAAc,SAAS,CAAA"}
@@ -145,3 +145,4 @@ export declare class Pair {
145
145
  private derivePercentAfterSellFees;
146
146
  private derivePercentAfterBuyFees;
147
147
  }
148
+ //# sourceMappingURL=pair.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pair.d.ts","sourceRoot":"","sources":["../../../../src/entities/pair.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAW,KAAK,EAAQ,KAAK,EAAE,MAAM,6BAA6B,CAAA;AAoBpG,eAAO,MAAM,kBAAkB;oBAKb,MAAM;YACd,KAAK;YACL,KAAK;MACX,MAOH,CAAA;AACD,qBAAa,IAAI;IACf,SAAgB,cAAc,EAAE,KAAK,CAAA;IACrC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAgD;WAE/D,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,GAAG,MAAM;gBAK3C,eAAe,EAAE,cAAc,CAAC,KAAK,CAAC,EAAE,YAAY,EAAE,cAAc,CAAC,KAAK,CAAC;IAc9F;;;OAGG;IACI,aAAa,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO;IAI3C;;OAEG;IACH,IAAW,WAAW,IAAI,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAG5C;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAG5C;IAED;;;OAGG;IACI,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC;IAKjD;;OAEG;IACH,IAAW,OAAO,IAAI,MAAM,CAE3B;IAED,IAAW,MAAM,IAAI,KAAK,CAEzB;IAED,IAAW,MAAM,IAAI,KAAK,CAEzB;IAED,IAAW,QAAQ,IAAI,cAAc,CAAC,KAAK,CAAC,CAE3C;IAED,IAAW,QAAQ,IAAI,cAAc,CAAC,KAAK,CAAC,CAE3C;IAEM,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,cAAc,CAAC,KAAK,CAAC;IAKrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2DG;IACI,eAAe,CACpB,WAAW,EAAE,cAAc,CAAC,KAAK,CAAC,EAClC,gBAAgB,GAAE,OAAc,GAC/B,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC;IA6ChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAyCG;IACI,cAAc,CACnB,YAAY,EAAE,cAAc,CAAC,KAAK,CAAC,EACnC,gBAAgB,GAAE,OAAc,GAC/B,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC;IAuCzB,kBAAkB,CACvB,WAAW,EAAE,cAAc,CAAC,KAAK,CAAC,EAClC,YAAY,EAAE,cAAc,CAAC,KAAK,CAAC,EACnC,YAAY,EAAE,cAAc,CAAC,KAAK,CAAC,GAClC,cAAc,CAAC,KAAK,CAAC;IAwBjB,iBAAiB,CACtB,KAAK,EAAE,KAAK,EACZ,WAAW,EAAE,cAAc,CAAC,KAAK,CAAC,EAClC,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC,EAChC,KAAK,GAAE,OAAe,EACtB,KAAK,CAAC,EAAE,SAAS,GAChB,cAAc,CAAC,KAAK,CAAC;IAkCxB,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,yBAAyB;CAUlC"}
@@ -10,3 +10,4 @@ export declare class Route<TInput extends Currency, TOutput extends Currency> {
10
10
  get midPrice(): Price<TInput, TOutput>;
11
11
  get chainId(): number;
12
12
  }
13
+ //# sourceMappingURL=route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../src/entities/route.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,6BAA6B,CAAA;AAEpE,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAA;AAE7B,qBAAa,KAAK,CAAC,MAAM,SAAS,QAAQ,EAAE,OAAO,SAAS,QAAQ;IAClE,SAAgB,KAAK,EAAE,IAAI,EAAE,CAAA;IAC7B,SAAgB,IAAI,EAAE,KAAK,EAAE,CAAA;IAC7B,SAAgB,KAAK,EAAE,MAAM,CAAA;IAC7B,SAAgB,MAAM,EAAE,OAAO,CAAA;gBAEZ,KAAK,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IA0BhE,OAAO,CAAC,SAAS,CAAsC;IAEvD,IAAW,QAAQ,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAY5C;IAED,IAAW,OAAO,IAAI,MAAM,CAE3B;CACF"}
@@ -101,3 +101,4 @@ export declare class Trade<TInput extends Currency, TOutput extends Currency, TT
101
101
  static bestTradeExactOut<TInput extends Currency, TOutput extends Currency>(pairs: Pair[], currencyIn: TInput, currencyAmountOut: CurrencyAmount<TOutput>, { maxNumResults, maxHops }?: BestTradeOptions, currentPairs?: Pair[], nextAmountOut?: CurrencyAmount<Currency>, bestTrades?: Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[]): Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[];
102
102
  }
103
103
  export {};
104
+ //# sourceMappingURL=trade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trade.d.ts","sourceRoot":"","sources":["../../../../src/entities/trade.ts"],"names":[],"mappings":"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"}
@@ -14,3 +14,4 @@ export declare class InsufficientInputAmountError extends Error {
14
14
  readonly isInsufficientInputAmountError: true;
15
15
  constructor();
16
16
  }
17
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/errors.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,SAAgB,2BAA2B,EAAE,IAAI,CAAO;;CAOzD;AAED;;;GAGG;AACH,qBAAa,4BAA6B,SAAQ,KAAK;IACrD,SAAgB,8BAA8B,EAAE,IAAI,CAAO;;CAO5D"}
@@ -2,3 +2,4 @@ export { FACTORY_ADDRESS_MAP, INIT_CODE_HASH, INIT_CODE_HASH_MAP, initCodeHash,
2
2
  export * from './errors';
3
3
  export * from './entities';
4
4
  export * from './router';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,kBAAkB,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAEtH,cAAc,UAAU,CAAA;AACxB,cAAc,YAAY,CAAA;AAC1B,cAAc,UAAU,CAAA"}
@@ -62,3 +62,4 @@ export declare abstract class Router {
62
62
  */
63
63
  static swapCallParameters(trade: Trade<Currency, Currency, TradeType>, options: TradeOptions | TradeOptionsDeadline): SwapParameters;
64
64
  }
65
+ //# sourceMappingURL=router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EAER,OAAO,EACP,SAAS,EAEV,MAAM,6BAA6B,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAGlC;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,eAAe,EAAE,OAAO,CAAA;IACxB;;;;OAIG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;OAEG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,oBAAqB,SAAQ,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC;IACrE;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,CAAA;IAC3B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAA;CACd;AAQD;;GAEG;AACH,8BAAsB,MAAM;IAC1B;;OAEG;IACH,OAAO;IACP;;;;OAIG;WACW,kBAAkB,CAC9B,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,EAC3C,OAAO,EAAE,YAAY,GAAG,oBAAoB,GAC3C,cAAc;CAoElB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@centurion_project/v2-sdk",
3
- "version": "4.21.10",
3
+ "version": "4.21.12",
4
4
  "description": "Centurion V2 SDK",
5
5
  "repository": "https://github.com/CenturionDEX/centurion-dex-sdks",
6
6
  "keywords": [
@@ -21,7 +21,10 @@
21
21
  },
22
22
  "sideEffects": false,
23
23
  "files": [
24
- "dist"
24
+ "dist",
25
+ "src",
26
+ "!src/**/*.test.ts",
27
+ "!src/**/*.spec.ts"
25
28
  ],
26
29
  "engines": {
27
30
  "node": ">=18"
@@ -37,7 +40,7 @@
37
40
  "@ethersproject/address": "^5.0.2",
38
41
  "@ethersproject/bignumber": "^5.5.0",
39
42
  "@ethersproject/solidity": "^5.0.9",
40
- "@centurion_project/sdk-core": "^7.19.4",
43
+ "@centurion_project/sdk-core": "^7.19.7",
41
44
  "jsbi": "^3.1.4",
42
45
  "tiny-invariant": "^1.1.0",
43
46
  "tiny-warning": "^1.0.3",
@@ -67,7 +70,7 @@
67
70
  },
68
71
  "centurionUpstream": {
69
72
  "name": "@uniswap/v2-sdk",
70
- "version": "4.21.0",
71
- "ref": "ab3a18a62922c0bda493130e53f2c8f6fad59558"
73
+ "version": "4.21.7",
74
+ "ref": "b3851aa4b538bb6b44c64c9f6c3f9ff06587495a"
72
75
  }
73
76
  }
@@ -0,0 +1,39 @@
1
+ import { ChainId, Percent, V2_FACTORY_ADDRESSES } from '@centurion_project/sdk-core'
2
+ import JSBI from 'jsbi'
3
+
4
+ /**
5
+ * @deprecated use FACTORY_ADDRESS_MAP instead
6
+ */
7
+ export const FACTORY_ADDRESS = '0xa5C54eC60631e48bf4449D35361D04A448CBC773'
8
+
9
+ export const FACTORY_ADDRESS_MAP: { [chainId: number]: string } = V2_FACTORY_ADDRESSES
10
+
11
+ export const INIT_CODE_HASH = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
12
+
13
+ const UNISWAP_V2_INIT_CODE_HASH = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
14
+
15
+ export const INIT_CODE_HASH_MAP: { [chainId: number]: string } = {
16
+ ...Object.keys(V2_FACTORY_ADDRESSES).reduce<{ [chainId: number]: string }>((memo, chainId) => {
17
+ memo[Number(chainId)] = UNISWAP_V2_INIT_CODE_HASH
18
+ return memo
19
+ }, {}),
20
+ [ChainId.MAINNET]: INIT_CODE_HASH,
21
+ }
22
+
23
+ export function initCodeHash(chainId?: number): string {
24
+ if (chainId === undefined) return INIT_CODE_HASH
25
+ return INIT_CODE_HASH_MAP[chainId] ?? UNISWAP_V2_INIT_CODE_HASH
26
+ }
27
+
28
+ export const MINIMUM_LIQUIDITY = JSBI.BigInt(1000)
29
+
30
+ // exports for internal consumption
31
+ export const ZERO = JSBI.BigInt(0)
32
+ export const ONE = JSBI.BigInt(1)
33
+ export const FIVE = JSBI.BigInt(5)
34
+ export const _997 = JSBI.BigInt(997)
35
+ export const _1000 = JSBI.BigInt(1000)
36
+ export const BASIS_POINTS = JSBI.BigInt(10000)
37
+
38
+ export const ZERO_PERCENT = new Percent(ZERO)
39
+ export const ONE_HUNDRED_PERCENT = new Percent(ONE)
@@ -0,0 +1,3 @@
1
+ export * from './pair'
2
+ export * from './route'
3
+ export * from './trade'
@@ -0,0 +1,405 @@
1
+ import { getCreate2Address } from '@ethersproject/address'
2
+ import { BigNumber } from '@ethersproject/bignumber'
3
+ import { keccak256, pack } from '@ethersproject/solidity'
4
+ import { BigintIsh, CurrencyAmount, Percent, Price, sqrt, Token } from '@centurion_project/sdk-core'
5
+ import JSBI from 'jsbi'
6
+ import invariant from 'tiny-invariant'
7
+
8
+ import {
9
+ _1000,
10
+ _997,
11
+ BASIS_POINTS,
12
+ FACTORY_ADDRESS,
13
+ FACTORY_ADDRESS_MAP,
14
+ FIVE,
15
+ initCodeHash,
16
+ MINIMUM_LIQUIDITY,
17
+ ONE,
18
+ ONE_HUNDRED_PERCENT,
19
+ ZERO,
20
+ ZERO_PERCENT,
21
+ } from '../constants'
22
+ import { InsufficientInputAmountError, InsufficientReservesError } from '../errors'
23
+
24
+ export const computePairAddress = ({
25
+ factoryAddress,
26
+ tokenA,
27
+ tokenB,
28
+ }: {
29
+ factoryAddress: string
30
+ tokenA: Token
31
+ tokenB: Token
32
+ }): string => {
33
+ const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA] // does safety checks
34
+ return getCreate2Address(
35
+ factoryAddress,
36
+ keccak256(['bytes'], [pack(['address', 'address'], [token0.address, token1.address])]),
37
+ initCodeHash(token0.chainId)
38
+ )
39
+ }
40
+ export class Pair {
41
+ public readonly liquidityToken: Token
42
+ private readonly tokenAmounts: [CurrencyAmount<Token>, CurrencyAmount<Token>]
43
+
44
+ public static getAddress(tokenA: Token, tokenB: Token): string {
45
+ const factoryAddress = FACTORY_ADDRESS_MAP[tokenA.chainId] ?? FACTORY_ADDRESS
46
+ return computePairAddress({ factoryAddress, tokenA, tokenB })
47
+ }
48
+
49
+ public constructor(currencyAmountA: CurrencyAmount<Token>, tokenAmountB: CurrencyAmount<Token>) {
50
+ const tokenAmounts = currencyAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
51
+ ? [currencyAmountA, tokenAmountB]
52
+ : [tokenAmountB, currencyAmountA]
53
+ this.liquidityToken = new Token(
54
+ tokenAmounts[0].currency.chainId,
55
+ Pair.getAddress(tokenAmounts[0].currency, tokenAmounts[1].currency),
56
+ 18,
57
+ 'UNI-V2',
58
+ 'Uniswap V2'
59
+ )
60
+ this.tokenAmounts = tokenAmounts as [CurrencyAmount<Token>, CurrencyAmount<Token>]
61
+ }
62
+
63
+ /**
64
+ * Returns true if the token is either token0 or token1
65
+ * @param token to check
66
+ */
67
+ public involvesToken(token: Token): boolean {
68
+ return token.equals(this.token0) || token.equals(this.token1)
69
+ }
70
+
71
+ /**
72
+ * Returns the current mid price of the pair in terms of token0, i.e. the ratio of reserve1 to reserve0
73
+ */
74
+ public get token0Price(): Price<Token, Token> {
75
+ const result = this.tokenAmounts[1].divide(this.tokenAmounts[0])
76
+ return new Price(this.token0, this.token1, result.denominator, result.numerator)
77
+ }
78
+
79
+ /**
80
+ * Returns the current mid price of the pair in terms of token1, i.e. the ratio of reserve0 to reserve1
81
+ */
82
+ public get token1Price(): Price<Token, Token> {
83
+ const result = this.tokenAmounts[0].divide(this.tokenAmounts[1])
84
+ return new Price(this.token1, this.token0, result.denominator, result.numerator)
85
+ }
86
+
87
+ /**
88
+ * Return the price of the given token in terms of the other token in the pair.
89
+ * @param token token to return price of
90
+ */
91
+ public priceOf(token: Token): Price<Token, Token> {
92
+ invariant(this.involvesToken(token), 'TOKEN')
93
+ return token.equals(this.token0) ? this.token0Price : this.token1Price
94
+ }
95
+
96
+ /**
97
+ * Returns the chain ID of the tokens in the pair.
98
+ */
99
+ public get chainId(): number {
100
+ return this.token0.chainId
101
+ }
102
+
103
+ public get token0(): Token {
104
+ return this.tokenAmounts[0].currency
105
+ }
106
+
107
+ public get token1(): Token {
108
+ return this.tokenAmounts[1].currency
109
+ }
110
+
111
+ public get reserve0(): CurrencyAmount<Token> {
112
+ return this.tokenAmounts[0]
113
+ }
114
+
115
+ public get reserve1(): CurrencyAmount<Token> {
116
+ return this.tokenAmounts[1]
117
+ }
118
+
119
+ public reserveOf(token: Token): CurrencyAmount<Token> {
120
+ invariant(this.involvesToken(token), 'TOKEN')
121
+ return token.equals(this.token0) ? this.reserve0 : this.reserve1
122
+ }
123
+
124
+ /**
125
+ * getAmountOut is the linear algebra of reserve ratio against amountIn:amountOut.
126
+ * https://ethereum.stackexchange.com/questions/101629/what-is-math-for-uniswap-calculates-the-amountout-and-amountin-why-997-and-1000
127
+ * has the math deduction for the reserve calculation without fee-on-transfer fees.
128
+ *
129
+ * With fee-on-transfer tax, intuitively it's just:
130
+ * inputAmountWithFeeAndTax = 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
131
+ * = (1 - amountIn.sellFeesBips / 10000) * amountInWithFee
132
+ * where amountInWithFee is the amountIn after taking out the LP fees
133
+ * outputAmountWithTax = amountOut * (1 - amountOut.buyFeesBips / 10000)
134
+ *
135
+ * But we are illustrating the math deduction below to ensure that's the case.
136
+ *
137
+ * before swap A * B = K where A = reserveIn B = reserveOut
138
+ *
139
+ * after swap A' * B' = K where only k is a constant value
140
+ *
141
+ * getAmountOut
142
+ *
143
+ * A' = A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn # here 0.3% is deducted
144
+ * B' = B - amountOut * (1 - amountOut.buyFeesBips / 10000)
145
+ * amountOut = (B - B') / (1 - amountOut.buyFeesBips / 10000) # where A' * B' still is k
146
+ * = (B - K/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
147
+ * /
148
+ * (1 - amountOut.buyFeesBips / 10000)
149
+ * = (B - AB/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
150
+ * /
151
+ * (1 - amountOut.buyFeesBips / 10000)
152
+ * = ((BA + B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn - AB)/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
153
+ * /
154
+ * (1 - amountOut.buyFeesBips / 10000)
155
+ * = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn / (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
156
+ * /
157
+ * (1 - amountOut.buyFeesBips / 10000)
158
+ * amountOut * (1 - amountOut.buyFeesBips / 10000) = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
159
+ * /
160
+ * (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
161
+ *
162
+ * outputAmountWithTax = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
163
+ * /
164
+ * (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
165
+ * = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn * 1000
166
+ * /
167
+ * ((A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn) * 1000)
168
+ * = (B * (1 - amountIn.sellFeesBips / 10000) 997 * * amountIn
169
+ * /
170
+ * (1000 * A + (1 - amountIn.sellFeesBips / 10000) * 997 * amountIn)
171
+ * = (B * (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee)
172
+ * /
173
+ * (1000 * A + (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee)
174
+ * = (B * inputAmountWithFeeAndTax)
175
+ * /
176
+ * (1000 * A + inputAmountWithFeeAndTax)
177
+ *
178
+ * inputAmountWithFeeAndTax = (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee
179
+ * outputAmountWithTax = amountOut * (1 - amountOut.buyFeesBips / 10000)
180
+ *
181
+ * @param inputAmount
182
+ * @param calculateFotFees
183
+ */
184
+ public getOutputAmount(
185
+ inputAmount: CurrencyAmount<Token>,
186
+ calculateFotFees: boolean = true
187
+ ): [CurrencyAmount<Token>, Pair] {
188
+ invariant(this.involvesToken(inputAmount.currency), 'TOKEN')
189
+ if (JSBI.equal(this.reserve0.quotient, ZERO) || JSBI.equal(this.reserve1.quotient, ZERO)) {
190
+ throw new InsufficientReservesError()
191
+ }
192
+ const inputReserve = this.reserveOf(inputAmount.currency)
193
+ const outputReserve = this.reserveOf(inputAmount.currency.equals(this.token0) ? this.token1 : this.token0)
194
+
195
+ const percentAfterSellFees = calculateFotFees ? this.derivePercentAfterSellFees(inputAmount) : ZERO_PERCENT
196
+ const inputAmountAfterTax = percentAfterSellFees.greaterThan(ZERO_PERCENT)
197
+ ? CurrencyAmount.fromRawAmount(
198
+ inputAmount.currency,
199
+ percentAfterSellFees.multiply(inputAmount).quotient // fraction.quotient will round down by itself, which is desired
200
+ )
201
+ : inputAmount
202
+
203
+ const inputAmountWithFeeAndAfterTax = JSBI.multiply(inputAmountAfterTax.quotient, _997)
204
+ const numerator = JSBI.multiply(inputAmountWithFeeAndAfterTax, outputReserve.quotient)
205
+ const denominator = JSBI.add(JSBI.multiply(inputReserve.quotient, _1000), inputAmountWithFeeAndAfterTax)
206
+ const outputAmount = CurrencyAmount.fromRawAmount(
207
+ inputAmount.currency.equals(this.token0) ? this.token1 : this.token0,
208
+ JSBI.divide(numerator, denominator) // JSBI.divide will round down by itself, which is desired
209
+ )
210
+
211
+ if (JSBI.equal(outputAmount.quotient, ZERO)) {
212
+ throw new InsufficientInputAmountError()
213
+ }
214
+
215
+ const percentAfterBuyFees = calculateFotFees ? this.derivePercentAfterBuyFees(outputAmount) : ZERO_PERCENT
216
+ const outputAmountAfterTax = percentAfterBuyFees.greaterThan(ZERO_PERCENT)
217
+ ? CurrencyAmount.fromRawAmount(
218
+ outputAmount.currency,
219
+ outputAmount.multiply(percentAfterBuyFees).quotient // fraction.quotient will round down by itself, which is desired
220
+ )
221
+ : outputAmount
222
+ if (JSBI.equal(outputAmountAfterTax.quotient, ZERO)) {
223
+ throw new InsufficientInputAmountError()
224
+ }
225
+
226
+ return [
227
+ outputAmountAfterTax,
228
+ new Pair(inputReserve.add(inputAmountAfterTax), outputReserve.subtract(outputAmountAfterTax)),
229
+ ]
230
+ }
231
+
232
+ /**
233
+ * getAmountIn is the linear algebra of reserve ratio against amountIn:amountOut.
234
+ * https://ethereum.stackexchange.com/questions/101629/what-is-math-for-uniswap-calculates-the-amountout-and-amountin-why-997-and-1000
235
+ * has the math deduction for the reserve calculation without fee-on-transfer fees.
236
+ *
237
+ * With fee-on-transfer fees, intuitively it's just:
238
+ * outputAmountWithTax = amountOut / (1 - amountOut.buyFeesBips / 10000)
239
+ * inputAmountWithTax = amountIn / (1 - amountIn.sellFeesBips / 10000) / 0.997
240
+ *
241
+ * But we are illustrating the math deduction below to ensure that's the case.
242
+ *
243
+ * before swap A * B = K where A = reserveIn B = reserveOut
244
+ *
245
+ * after swap A' * B' = K where only k is a constant value
246
+ *
247
+ * getAmountIn
248
+ *
249
+ * B' = B - amountOut * (1 - amountOut.buyFeesBips / 10000)
250
+ * A' = A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn # here 0.3% is deducted
251
+ * amountIn = (A' - A) / (0.997 * (1 - amountIn.sellFeesBips / 10000))
252
+ * = (K / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)) - A)
253
+ * /
254
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
255
+ * = (AB / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)) - A)
256
+ * /
257
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
258
+ * = ((AB - AB + A * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
259
+ * /
260
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
261
+ * = ((A * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
262
+ * /
263
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
264
+ * = ((A * 1000 * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
265
+ * /
266
+ * (997 * (1 - amountIn.sellFeesBips / 10000))
267
+ *
268
+ * outputAmountWithTax = amountOut / (1 - amountOut.buyFeesBips / 10000)
269
+ * inputAmountWithTax = amountIn / (997 * (1 - amountIn.sellFeesBips / 10000))
270
+ * = (A * outputAmountWithTax * 1000) / ((B - outputAmountWithTax) * 997)
271
+ *
272
+ * @param outputAmount
273
+ */
274
+ public getInputAmount(
275
+ outputAmount: CurrencyAmount<Token>,
276
+ calculateFotFees: boolean = true
277
+ ): [CurrencyAmount<Token>, Pair] {
278
+ invariant(this.involvesToken(outputAmount.currency), 'TOKEN')
279
+ const percentAfterBuyFees = calculateFotFees ? this.derivePercentAfterBuyFees(outputAmount) : ZERO_PERCENT
280
+ const outputAmountBeforeTax = percentAfterBuyFees.greaterThan(ZERO_PERCENT)
281
+ ? CurrencyAmount.fromRawAmount(
282
+ outputAmount.currency,
283
+ JSBI.add(outputAmount.divide(percentAfterBuyFees).quotient, ONE) // add 1 for rounding up
284
+ )
285
+ : outputAmount
286
+
287
+ if (
288
+ JSBI.equal(this.reserve0.quotient, ZERO) ||
289
+ JSBI.equal(this.reserve1.quotient, ZERO) ||
290
+ JSBI.greaterThanOrEqual(outputAmount.quotient, this.reserveOf(outputAmount.currency).quotient) ||
291
+ JSBI.greaterThanOrEqual(outputAmountBeforeTax.quotient, this.reserveOf(outputAmount.currency).quotient)
292
+ ) {
293
+ throw new InsufficientReservesError()
294
+ }
295
+
296
+ const outputReserve = this.reserveOf(outputAmount.currency)
297
+ const inputReserve = this.reserveOf(outputAmount.currency.equals(this.token0) ? this.token1 : this.token0)
298
+
299
+ const numerator = JSBI.multiply(JSBI.multiply(inputReserve.quotient, outputAmountBeforeTax.quotient), _1000)
300
+ const denominator = JSBI.multiply(JSBI.subtract(outputReserve.quotient, outputAmountBeforeTax.quotient), _997)
301
+ const inputAmount = CurrencyAmount.fromRawAmount(
302
+ outputAmount.currency.equals(this.token0) ? this.token1 : this.token0,
303
+ JSBI.add(JSBI.divide(numerator, denominator), ONE) // add 1 here is part of the formula, no rounding needed here, since there will not be decimal at this point
304
+ )
305
+
306
+ const percentAfterSellFees = calculateFotFees ? this.derivePercentAfterSellFees(inputAmount) : ZERO_PERCENT
307
+ const inputAmountBeforeTax = percentAfterSellFees.greaterThan(ZERO_PERCENT)
308
+ ? CurrencyAmount.fromRawAmount(
309
+ inputAmount.currency,
310
+ JSBI.add(inputAmount.divide(percentAfterSellFees).quotient, ONE) // add 1 for rounding up
311
+ )
312
+ : inputAmount
313
+ return [inputAmountBeforeTax, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))]
314
+ }
315
+
316
+ public getLiquidityMinted(
317
+ totalSupply: CurrencyAmount<Token>,
318
+ tokenAmountA: CurrencyAmount<Token>,
319
+ tokenAmountB: CurrencyAmount<Token>
320
+ ): CurrencyAmount<Token> {
321
+ invariant(totalSupply.currency.equals(this.liquidityToken), 'LIQUIDITY')
322
+ const tokenAmounts = tokenAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
323
+ ? [tokenAmountA, tokenAmountB]
324
+ : [tokenAmountB, tokenAmountA]
325
+ invariant(tokenAmounts[0].currency.equals(this.token0) && tokenAmounts[1].currency.equals(this.token1), 'TOKEN')
326
+
327
+ let liquidity: JSBI
328
+ if (JSBI.equal(totalSupply.quotient, ZERO)) {
329
+ liquidity = JSBI.subtract(
330
+ sqrt(JSBI.multiply(tokenAmounts[0].quotient, tokenAmounts[1].quotient)),
331
+ MINIMUM_LIQUIDITY
332
+ )
333
+ } else {
334
+ const amount0 = JSBI.divide(JSBI.multiply(tokenAmounts[0].quotient, totalSupply.quotient), this.reserve0.quotient)
335
+ const amount1 = JSBI.divide(JSBI.multiply(tokenAmounts[1].quotient, totalSupply.quotient), this.reserve1.quotient)
336
+ liquidity = JSBI.lessThanOrEqual(amount0, amount1) ? amount0 : amount1
337
+ }
338
+ if (!JSBI.greaterThan(liquidity, ZERO)) {
339
+ throw new InsufficientInputAmountError()
340
+ }
341
+ return CurrencyAmount.fromRawAmount(this.liquidityToken, liquidity)
342
+ }
343
+
344
+ public getLiquidityValue(
345
+ token: Token,
346
+ totalSupply: CurrencyAmount<Token>,
347
+ liquidity: CurrencyAmount<Token>,
348
+ feeOn: boolean = false,
349
+ kLast?: BigintIsh
350
+ ): CurrencyAmount<Token> {
351
+ invariant(this.involvesToken(token), 'TOKEN')
352
+ invariant(totalSupply.currency.equals(this.liquidityToken), 'TOTAL_SUPPLY')
353
+ invariant(liquidity.currency.equals(this.liquidityToken), 'LIQUIDITY')
354
+ invariant(JSBI.lessThanOrEqual(liquidity.quotient, totalSupply.quotient), 'LIQUIDITY')
355
+
356
+ let totalSupplyAdjusted: CurrencyAmount<Token>
357
+ if (!feeOn) {
358
+ totalSupplyAdjusted = totalSupply
359
+ } else {
360
+ invariant(!!kLast, 'K_LAST')
361
+ const kLastParsed = JSBI.BigInt(kLast)
362
+ if (!JSBI.equal(kLastParsed, ZERO)) {
363
+ const rootK = sqrt(JSBI.multiply(this.reserve0.quotient, this.reserve1.quotient))
364
+ const rootKLast = sqrt(kLastParsed)
365
+ if (JSBI.greaterThan(rootK, rootKLast)) {
366
+ const numerator = JSBI.multiply(totalSupply.quotient, JSBI.subtract(rootK, rootKLast))
367
+ const denominator = JSBI.add(JSBI.multiply(rootK, FIVE), rootKLast)
368
+ const feeLiquidity = JSBI.divide(numerator, denominator)
369
+ totalSupplyAdjusted = totalSupply.add(CurrencyAmount.fromRawAmount(this.liquidityToken, feeLiquidity))
370
+ } else {
371
+ totalSupplyAdjusted = totalSupply
372
+ }
373
+ } else {
374
+ totalSupplyAdjusted = totalSupply
375
+ }
376
+ }
377
+
378
+ return CurrencyAmount.fromRawAmount(
379
+ token,
380
+ JSBI.divide(JSBI.multiply(liquidity.quotient, this.reserveOf(token).quotient), totalSupplyAdjusted.quotient)
381
+ )
382
+ }
383
+
384
+ private derivePercentAfterSellFees(inputAmount: CurrencyAmount<Token>): Percent {
385
+ const sellFeeBips = this.token0.wrapped.equals(inputAmount.wrapped.currency)
386
+ ? this.token0.wrapped.sellFeeBps
387
+ : this.token1.wrapped.sellFeeBps
388
+ if (sellFeeBips?.gt(BigNumber.from(0))) {
389
+ return ONE_HUNDRED_PERCENT.subtract(new Percent(JSBI.BigInt(sellFeeBips)).divide(BASIS_POINTS))
390
+ } else {
391
+ return ZERO_PERCENT
392
+ }
393
+ }
394
+
395
+ private derivePercentAfterBuyFees(outputAmount: CurrencyAmount<Token>): Percent {
396
+ const buyFeeBps = this.token0.wrapped.equals(outputAmount.wrapped.currency)
397
+ ? this.token0.wrapped.buyFeeBps
398
+ : this.token1.wrapped.buyFeeBps
399
+ if (buyFeeBps?.gt(BigNumber.from(0))) {
400
+ return ONE_HUNDRED_PERCENT.subtract(new Percent(JSBI.BigInt(buyFeeBps)).divide(BASIS_POINTS))
401
+ } else {
402
+ return ZERO_PERCENT
403
+ }
404
+ }
405
+ }
@@ -0,0 +1,57 @@
1
+ import invariant from 'tiny-invariant'
2
+ import { Currency, Price, Token } from '@centurion_project/sdk-core'
3
+
4
+ import { Pair } from './pair'
5
+
6
+ export class Route<TInput extends Currency, TOutput extends Currency> {
7
+ public readonly pairs: Pair[]
8
+ public readonly path: Token[]
9
+ public readonly input: TInput
10
+ public readonly output: TOutput
11
+
12
+ public constructor(pairs: Pair[], input: TInput, output: TOutput) {
13
+ invariant(pairs.length > 0, 'PAIRS')
14
+ const chainId: number = pairs[0].chainId
15
+ invariant(
16
+ pairs.every((pair) => pair.chainId === chainId),
17
+ 'CHAIN_IDS'
18
+ )
19
+
20
+ const wrappedInput = input.wrapped
21
+ invariant(pairs[0].involvesToken(wrappedInput), 'INPUT')
22
+ invariant(typeof output === 'undefined' || pairs[pairs.length - 1].involvesToken(output.wrapped), 'OUTPUT')
23
+
24
+ const path: Token[] = [wrappedInput]
25
+ for (const [i, pair] of pairs.entries()) {
26
+ const currentInput = path[i]
27
+ invariant(currentInput.equals(pair.token0) || currentInput.equals(pair.token1), 'PATH')
28
+ const output = currentInput.equals(pair.token0) ? pair.token1 : pair.token0
29
+ path.push(output)
30
+ }
31
+
32
+ this.pairs = pairs
33
+ this.path = path
34
+ this.input = input
35
+ this.output = output
36
+ }
37
+
38
+ private _midPrice: Price<TInput, TOutput> | null = null
39
+
40
+ public get midPrice(): Price<TInput, TOutput> {
41
+ if (this._midPrice !== null) return this._midPrice
42
+ const prices: Price<Currency, Currency>[] = []
43
+ for (const [i, pair] of this.pairs.entries()) {
44
+ prices.push(
45
+ this.path[i].equals(pair.token0)
46
+ ? new Price(pair.reserve0.currency, pair.reserve1.currency, pair.reserve0.quotient, pair.reserve1.quotient)
47
+ : new Price(pair.reserve1.currency, pair.reserve0.currency, pair.reserve1.quotient, pair.reserve0.quotient)
48
+ )
49
+ }
50
+ const reduced = prices.slice(1).reduce((accumulator, currentValue) => accumulator.multiply(currentValue), prices[0])
51
+ return (this._midPrice = new Price(this.input, this.output, reduced.denominator, reduced.numerator))
52
+ }
53
+
54
+ public get chainId(): number {
55
+ return this.pairs[0].chainId
56
+ }
57
+ }
@@ -0,0 +1,391 @@
1
+ import {
2
+ computePriceImpact,
3
+ Token,
4
+ Currency,
5
+ CurrencyAmount,
6
+ Fraction,
7
+ Percent,
8
+ Price,
9
+ sortedInsert,
10
+ TradeType,
11
+ } from '@centurion_project/sdk-core'
12
+ import JSBI from 'jsbi'
13
+ import { ONE, ZERO } from '../constants'
14
+ import invariant from 'tiny-invariant'
15
+
16
+ import { Pair } from './pair'
17
+ import { Route } from './route'
18
+
19
+ // minimal interface so the input output comparator may be shared across types
20
+ interface InputOutput<TInput extends Currency, TOutput extends Currency> {
21
+ readonly inputAmount: CurrencyAmount<TInput>
22
+ readonly outputAmount: CurrencyAmount<TOutput>
23
+ }
24
+
25
+ // comparator function that allows sorting trades by their output amounts, in decreasing order, and then input amounts
26
+ // in increasing order. i.e. the best trades have the most outputs for the least inputs and are sorted first
27
+ export function inputOutputComparator<TInput extends Currency, TOutput extends Currency>(
28
+ a: InputOutput<TInput, TOutput>,
29
+ b: InputOutput<TInput, TOutput>
30
+ ): number {
31
+ // must have same input and output token for comparison
32
+ invariant(a.inputAmount.currency.equals(b.inputAmount.currency), 'INPUT_CURRENCY')
33
+ invariant(a.outputAmount.currency.equals(b.outputAmount.currency), 'OUTPUT_CURRENCY')
34
+ if (a.outputAmount.equalTo(b.outputAmount)) {
35
+ if (a.inputAmount.equalTo(b.inputAmount)) {
36
+ return 0
37
+ }
38
+ // trade A requires less input than trade B, so A should come first
39
+ if (a.inputAmount.lessThan(b.inputAmount)) {
40
+ return -1
41
+ } else {
42
+ return 1
43
+ }
44
+ } else {
45
+ // tradeA has less output than trade B, so should come second
46
+ if (a.outputAmount.lessThan(b.outputAmount)) {
47
+ return 1
48
+ } else {
49
+ return -1
50
+ }
51
+ }
52
+ }
53
+
54
+ // extension of the input output comparator that also considers other dimensions of the trade in ranking them
55
+ export function tradeComparator<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(
56
+ a: Trade<TInput, TOutput, TTradeType>,
57
+ b: Trade<TInput, TOutput, TTradeType>
58
+ ) {
59
+ const ioComp = inputOutputComparator(a, b)
60
+ if (ioComp !== 0) {
61
+ return ioComp
62
+ }
63
+
64
+ // consider lowest slippage next, since these are less likely to fail
65
+ if (a.priceImpact.lessThan(b.priceImpact)) {
66
+ return -1
67
+ } else if (a.priceImpact.greaterThan(b.priceImpact)) {
68
+ return 1
69
+ }
70
+
71
+ // finally consider the number of hops since each hop costs gas
72
+ return a.route.path.length - b.route.path.length
73
+ }
74
+
75
+ export interface BestTradeOptions {
76
+ // how many results to return
77
+ maxNumResults?: number
78
+ // the maximum number of hops a trade should contain
79
+ maxHops?: number
80
+ }
81
+
82
+ /**
83
+ * Represents a trade executed against a list of pairs.
84
+ * Does not account for slippage, i.e. trades that front run this trade and move the price.
85
+ */
86
+ export class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
87
+ /**
88
+ * The route of the trade, i.e. which pairs the trade goes through and the input/output currencies.
89
+ */
90
+ public readonly route: Route<TInput, TOutput>
91
+ /**
92
+ * The type of the trade, either exact in or exact out.
93
+ */
94
+ public readonly tradeType: TTradeType
95
+ /**
96
+ * The input amount for the trade assuming no slippage.
97
+ */
98
+ public readonly inputAmount: CurrencyAmount<TInput>
99
+ /**
100
+ * The output amount for the trade assuming no slippage.
101
+ */
102
+ public readonly outputAmount: CurrencyAmount<TOutput>
103
+ /**
104
+ * The price expressed in terms of output amount/input amount.
105
+ */
106
+ public readonly executionPrice: Price<TInput, TOutput>
107
+ /**
108
+ * The percent difference between the mid price before the trade and the trade execution price.
109
+ */
110
+ public readonly priceImpact: Percent
111
+
112
+ /**
113
+ * Constructs an exact in trade with the given amount in and route
114
+ * @param route route of the exact in trade
115
+ * @param amountIn the amount being passed in
116
+ */
117
+ public static exactIn<TInput extends Currency, TOutput extends Currency>(
118
+ route: Route<TInput, TOutput>,
119
+ amountIn: CurrencyAmount<TInput>
120
+ ): Trade<TInput, TOutput, TradeType.EXACT_INPUT> {
121
+ return new Trade(route, amountIn, TradeType.EXACT_INPUT)
122
+ }
123
+
124
+ /**
125
+ * Constructs an exact out trade with the given amount out and route
126
+ * @param route route of the exact out trade
127
+ * @param amountOut the amount returned by the trade
128
+ */
129
+ public static exactOut<TInput extends Currency, TOutput extends Currency>(
130
+ route: Route<TInput, TOutput>,
131
+ amountOut: CurrencyAmount<TOutput>
132
+ ): Trade<TInput, TOutput, TradeType.EXACT_OUTPUT> {
133
+ return new Trade(route, amountOut, TradeType.EXACT_OUTPUT)
134
+ }
135
+
136
+ public constructor(
137
+ route: Route<TInput, TOutput>,
138
+ amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,
139
+ tradeType: TTradeType
140
+ ) {
141
+ this.route = route
142
+ this.tradeType = tradeType
143
+
144
+ const tokenAmounts: CurrencyAmount<Token>[] = new Array(route.path.length)
145
+ if (tradeType === TradeType.EXACT_INPUT) {
146
+ invariant(amount.currency.equals(route.input), 'INPUT')
147
+ tokenAmounts[0] = amount.wrapped
148
+ for (let i = 0; i < route.path.length - 1; i++) {
149
+ const pair = route.pairs[i]
150
+ const [outputAmount] = pair.getOutputAmount(tokenAmounts[i])
151
+ tokenAmounts[i + 1] = outputAmount
152
+ }
153
+ this.inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)
154
+ this.outputAmount = CurrencyAmount.fromFractionalAmount(
155
+ route.output,
156
+ tokenAmounts[tokenAmounts.length - 1].numerator,
157
+ tokenAmounts[tokenAmounts.length - 1].denominator
158
+ )
159
+ } else {
160
+ invariant(amount.currency.equals(route.output), 'OUTPUT')
161
+ tokenAmounts[tokenAmounts.length - 1] = amount.wrapped
162
+ for (let i = route.path.length - 1; i > 0; i--) {
163
+ const pair = route.pairs[i - 1]
164
+ const [inputAmount] = pair.getInputAmount(tokenAmounts[i])
165
+ tokenAmounts[i - 1] = inputAmount
166
+ }
167
+ this.inputAmount = CurrencyAmount.fromFractionalAmount(
168
+ route.input,
169
+ tokenAmounts[0].numerator,
170
+ tokenAmounts[0].denominator
171
+ )
172
+ this.outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator)
173
+ }
174
+ this.executionPrice = new Price(
175
+ this.inputAmount.currency,
176
+ this.outputAmount.currency,
177
+ this.inputAmount.quotient,
178
+ this.outputAmount.quotient
179
+ )
180
+ this.priceImpact = computePriceImpact(route.midPrice, this.inputAmount, this.outputAmount)
181
+ }
182
+
183
+ /**
184
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
185
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
186
+ */
187
+ public minimumAmountOut(slippageTolerance: Percent): CurrencyAmount<TOutput> {
188
+ invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')
189
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
190
+ return this.outputAmount
191
+ } else {
192
+ const slippageAdjustedAmountOut = new Fraction(ONE)
193
+ .subtract(slippageTolerance)
194
+ .multiply(this.outputAmount.quotient).quotient
195
+ const clampedAmount = JSBI.greaterThan(slippageAdjustedAmountOut, JSBI.BigInt(0))
196
+ ? slippageAdjustedAmountOut
197
+ : JSBI.BigInt(0)
198
+ return CurrencyAmount.fromRawAmount(this.outputAmount.currency, clampedAmount)
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
204
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
205
+ */
206
+ public maximumAmountIn(slippageTolerance: Percent): CurrencyAmount<TInput> {
207
+ invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')
208
+ if (this.tradeType === TradeType.EXACT_INPUT) {
209
+ return this.inputAmount
210
+ } else {
211
+ const slippageAdjustedAmountIn = new Fraction(ONE)
212
+ .add(slippageTolerance)
213
+ .multiply(this.inputAmount.quotient).quotient
214
+ return CurrencyAmount.fromRawAmount(this.inputAmount.currency, slippageAdjustedAmountIn)
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
220
+ * amount to an output token, making at most `maxHops` hops.
221
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
222
+ * the amount in among multiple routes.
223
+ * @param pairs the pairs to consider in finding the best trade
224
+ * @param nextAmountIn exact amount of input currency to spend
225
+ * @param currencyOut the desired currency out
226
+ * @param maxNumResults maximum number of results to return
227
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
228
+ * @param currentPairs used in recursion; the current list of pairs
229
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
230
+ * @param bestTrades used in recursion; the current list of best trades
231
+ */
232
+ public static bestTradeExactIn<TInput extends Currency, TOutput extends Currency>(
233
+ pairs: Pair[],
234
+ currencyAmountIn: CurrencyAmount<TInput>,
235
+ currencyOut: TOutput,
236
+ { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {},
237
+ // used in recursion.
238
+ currentPairs: Pair[] = [],
239
+ nextAmountIn: CurrencyAmount<Currency> = currencyAmountIn,
240
+ bestTrades: Trade<TInput, TOutput, TradeType.EXACT_INPUT>[] = []
241
+ ): Trade<TInput, TOutput, TradeType.EXACT_INPUT>[] {
242
+ invariant(pairs.length > 0, 'PAIRS')
243
+ invariant(maxHops > 0, 'MAX_HOPS')
244
+ invariant(currencyAmountIn === nextAmountIn || currentPairs.length > 0, 'INVALID_RECURSION')
245
+
246
+ const amountIn = nextAmountIn.wrapped
247
+ const tokenOut = currencyOut.wrapped
248
+ for (let i = 0; i < pairs.length; i++) {
249
+ const pair = pairs[i]
250
+ // pair irrelevant
251
+ if (!pair.token0.equals(amountIn.currency) && !pair.token1.equals(amountIn.currency)) continue
252
+ if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue
253
+
254
+ let amountOut: CurrencyAmount<Token>
255
+ try {
256
+ ;[amountOut] = pair.getOutputAmount(amountIn)
257
+ } catch (error) {
258
+ // input too low
259
+ if ((error as any).isInsufficientInputAmountError) {
260
+ continue
261
+ }
262
+ throw error
263
+ }
264
+ // we have arrived at the output token, so this is the final trade of one of the paths
265
+ if (amountOut.currency.equals(tokenOut)) {
266
+ sortedInsert(
267
+ bestTrades,
268
+ new Trade(
269
+ new Route([...currentPairs, pair], currencyAmountIn.currency, currencyOut),
270
+ currencyAmountIn,
271
+ TradeType.EXACT_INPUT
272
+ ),
273
+ maxNumResults,
274
+ tradeComparator
275
+ )
276
+ } else if (maxHops > 1 && pairs.length > 1) {
277
+ const pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length))
278
+
279
+ // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
280
+ Trade.bestTradeExactIn(
281
+ pairsExcludingThisPair,
282
+ currencyAmountIn,
283
+ currencyOut,
284
+ {
285
+ maxNumResults,
286
+ maxHops: maxHops - 1,
287
+ },
288
+ [...currentPairs, pair],
289
+ amountOut,
290
+ bestTrades
291
+ )
292
+ }
293
+ }
294
+
295
+ return bestTrades
296
+ }
297
+
298
+ /**
299
+ * Return the execution price after accounting for slippage tolerance
300
+ * @param slippageTolerance the allowed tolerated slippage
301
+ */
302
+ public worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput> {
303
+ return new Price(
304
+ this.inputAmount.currency,
305
+ this.outputAmount.currency,
306
+ this.maximumAmountIn(slippageTolerance).quotient,
307
+ this.minimumAmountOut(slippageTolerance).quotient
308
+ )
309
+ }
310
+
311
+ /**
312
+ * similar to the above method but instead targets a fixed output amount
313
+ * given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
314
+ * to an output token amount, making at most `maxHops` hops
315
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
316
+ * the amount in among multiple routes.
317
+ * @param pairs the pairs to consider in finding the best trade
318
+ * @param currencyIn the currency to spend
319
+ * @param nextAmountOut the exact amount of currency out
320
+ * @param maxNumResults maximum number of results to return
321
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
322
+ * @param currentPairs used in recursion; the current list of pairs
323
+ * @param currencyAmountOut used in recursion; the original value of the currencyAmountOut parameter
324
+ * @param bestTrades used in recursion; the current list of best trades
325
+ */
326
+ public static bestTradeExactOut<TInput extends Currency, TOutput extends Currency>(
327
+ pairs: Pair[],
328
+ currencyIn: TInput,
329
+ currencyAmountOut: CurrencyAmount<TOutput>,
330
+ { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {},
331
+ // used in recursion.
332
+ currentPairs: Pair[] = [],
333
+ nextAmountOut: CurrencyAmount<Currency> = currencyAmountOut,
334
+ bestTrades: Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[] = []
335
+ ): Trade<TInput, TOutput, TradeType.EXACT_OUTPUT>[] {
336
+ invariant(pairs.length > 0, 'PAIRS')
337
+ invariant(maxHops > 0, 'MAX_HOPS')
338
+ invariant(currencyAmountOut === nextAmountOut || currentPairs.length > 0, 'INVALID_RECURSION')
339
+
340
+ const amountOut = nextAmountOut.wrapped
341
+ const tokenIn = currencyIn.wrapped
342
+ for (let i = 0; i < pairs.length; i++) {
343
+ const pair = pairs[i]
344
+ // pair irrelevant
345
+ if (!pair.token0.equals(amountOut.currency) && !pair.token1.equals(amountOut.currency)) continue
346
+ if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue
347
+
348
+ let amountIn: CurrencyAmount<Token>
349
+ try {
350
+ ;[amountIn] = pair.getInputAmount(amountOut)
351
+ } catch (error) {
352
+ // not enough liquidity in this pair
353
+ if ((error as any).isInsufficientReservesError) {
354
+ continue
355
+ }
356
+ throw error
357
+ }
358
+ // we have arrived at the input token, so this is the first trade of one of the paths
359
+ if (amountIn.currency.equals(tokenIn)) {
360
+ sortedInsert(
361
+ bestTrades,
362
+ new Trade(
363
+ new Route([pair, ...currentPairs], currencyIn, currencyAmountOut.currency),
364
+ currencyAmountOut,
365
+ TradeType.EXACT_OUTPUT
366
+ ),
367
+ maxNumResults,
368
+ tradeComparator
369
+ )
370
+ } else if (maxHops > 1 && pairs.length > 1) {
371
+ const pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length))
372
+
373
+ // otherwise, consider all the other paths that arrive at this token as long as we have not exceeded maxHops
374
+ Trade.bestTradeExactOut(
375
+ pairsExcludingThisPair,
376
+ currencyIn,
377
+ currencyAmountOut,
378
+ {
379
+ maxNumResults,
380
+ maxHops: maxHops - 1,
381
+ },
382
+ [pair, ...currentPairs],
383
+ amountIn,
384
+ bestTrades
385
+ )
386
+ }
387
+ }
388
+
389
+ return bestTrades
390
+ }
391
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,30 @@
1
+ // see https://stackoverflow.com/a/41102306
2
+ const CAN_SET_PROTOTYPE = 'setPrototypeOf' in Object
3
+
4
+ /**
5
+ * Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
6
+ * obtained by sending any amount of input.
7
+ */
8
+ export class InsufficientReservesError extends Error {
9
+ public readonly isInsufficientReservesError: true = true
10
+
11
+ public constructor() {
12
+ super()
13
+ this.name = this.constructor.name
14
+ if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(this, new.target.prototype)
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
20
+ * than the price of a single unit of output after fees.
21
+ */
22
+ export class InsufficientInputAmountError extends Error {
23
+ public readonly isInsufficientInputAmountError: true = true
24
+
25
+ public constructor() {
26
+ super()
27
+ this.name = this.constructor.name
28
+ if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(this, new.target.prototype)
29
+ }
30
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { FACTORY_ADDRESS_MAP, INIT_CODE_HASH, INIT_CODE_HASH_MAP, initCodeHash, MINIMUM_LIQUIDITY } from './constants'
2
+
3
+ export * from './errors'
4
+ export * from './entities'
5
+ export * from './router'
package/src/router.ts ADDED
@@ -0,0 +1,153 @@
1
+ import {
2
+ Token,
3
+ Currency,
4
+ CurrencyAmount,
5
+ Percent,
6
+ TradeType,
7
+ validateAndParseAddress,
8
+ } from '@centurion_project/sdk-core'
9
+ import { Trade } from './entities'
10
+ import invariant from 'tiny-invariant'
11
+
12
+ /**
13
+ * Options for producing the arguments to send call to the router.
14
+ */
15
+ export interface TradeOptions {
16
+ /**
17
+ * How much the execution price is allowed to move unfavorably from the trade execution price.
18
+ */
19
+ allowedSlippage: Percent
20
+ /**
21
+ * How long the swap is valid until it expires, in seconds.
22
+ * This will be used to produce a `deadline` parameter which is computed from when the swap call parameters
23
+ * are generated.
24
+ */
25
+ ttl: number
26
+ /**
27
+ * The account that should receive the output of the swap.
28
+ */
29
+ recipient: string
30
+
31
+ /**
32
+ * Whether any of the tokens in the path are fee on transfer tokens, which should be handled with special methods
33
+ */
34
+ feeOnTransfer?: boolean
35
+ }
36
+
37
+ export interface TradeOptionsDeadline extends Omit<TradeOptions, 'ttl'> {
38
+ /**
39
+ * When the transaction expires.
40
+ * This is an atlernate to specifying the ttl, for when you do not want to use local time.
41
+ */
42
+ deadline: number
43
+ }
44
+
45
+ /**
46
+ * The parameters to use in the call to the Uniswap V2 Router to execute a trade.
47
+ */
48
+ export interface SwapParameters {
49
+ /**
50
+ * The method to call on the Uniswap V2 Router.
51
+ */
52
+ methodName: string
53
+ /**
54
+ * The arguments to pass to the method, all hex encoded.
55
+ */
56
+ args: (string | string[])[]
57
+ /**
58
+ * The amount of wei to send in hex.
59
+ */
60
+ value: string
61
+ }
62
+
63
+ function toHex(currencyAmount: CurrencyAmount<Currency>) {
64
+ return `0x${currencyAmount.quotient.toString(16)}`
65
+ }
66
+
67
+ const ZERO_HEX = '0x0'
68
+
69
+ /**
70
+ * Represents the Uniswap V2 Router, and has static methods for helping execute trades.
71
+ */
72
+ export abstract class Router {
73
+ /**
74
+ * Cannot be constructed.
75
+ */
76
+ private constructor() {}
77
+ /**
78
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
79
+ * @param trade to produce call parameters for
80
+ * @param options options for the call parameters
81
+ */
82
+ public static swapCallParameters(
83
+ trade: Trade<Currency, Currency, TradeType>,
84
+ options: TradeOptions | TradeOptionsDeadline
85
+ ): SwapParameters {
86
+ const etherIn = trade.inputAmount.currency.isNative
87
+ const etherOut = trade.outputAmount.currency.isNative
88
+ // the router does not support both ether in and out
89
+ invariant(!(etherIn && etherOut), 'ETHER_IN_OUT')
90
+ invariant(!('ttl' in options) || options.ttl > 0, 'TTL')
91
+
92
+ const to: string = validateAndParseAddress(options.recipient)
93
+ const amountIn: string = toHex(trade.maximumAmountIn(options.allowedSlippage))
94
+ const amountOut: string = toHex(trade.minimumAmountOut(options.allowedSlippage))
95
+ const path: string[] = trade.route.path.map((token: Token) => token.address)
96
+ const deadline =
97
+ 'ttl' in options
98
+ ? `0x${(Math.floor(new Date().getTime() / 1000) + options.ttl).toString(16)}`
99
+ : `0x${options.deadline.toString(16)}`
100
+
101
+ const useFeeOnTransfer = Boolean(options.feeOnTransfer)
102
+
103
+ let methodName: string
104
+ let args: (string | string[])[]
105
+ let value: string
106
+ switch (trade.tradeType) {
107
+ case TradeType.EXACT_INPUT:
108
+ if (etherIn) {
109
+ methodName = useFeeOnTransfer ? 'swapExactETHForTokensSupportingFeeOnTransferTokens' : 'swapExactETHForTokens'
110
+ // (uint amountOutMin, address[] calldata path, address to, uint deadline)
111
+ args = [amountOut, path, to, deadline]
112
+ value = amountIn
113
+ } else if (etherOut) {
114
+ methodName = useFeeOnTransfer ? 'swapExactTokensForETHSupportingFeeOnTransferTokens' : 'swapExactTokensForETH'
115
+ // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
116
+ args = [amountIn, amountOut, path, to, deadline]
117
+ value = ZERO_HEX
118
+ } else {
119
+ methodName = useFeeOnTransfer
120
+ ? 'swapExactTokensForTokensSupportingFeeOnTransferTokens'
121
+ : 'swapExactTokensForTokens'
122
+ // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
123
+ args = [amountIn, amountOut, path, to, deadline]
124
+ value = ZERO_HEX
125
+ }
126
+ break
127
+ case TradeType.EXACT_OUTPUT:
128
+ invariant(!useFeeOnTransfer, 'EXACT_OUT_FOT')
129
+ if (etherIn) {
130
+ methodName = 'swapETHForExactTokens'
131
+ // (uint amountOut, address[] calldata path, address to, uint deadline)
132
+ args = [amountOut, path, to, deadline]
133
+ value = amountIn
134
+ } else if (etherOut) {
135
+ methodName = 'swapTokensForExactETH'
136
+ // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
137
+ args = [amountOut, amountIn, path, to, deadline]
138
+ value = ZERO_HEX
139
+ } else {
140
+ methodName = 'swapTokensForExactTokens'
141
+ // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
142
+ args = [amountOut, amountIn, path, to, deadline]
143
+ value = ZERO_HEX
144
+ }
145
+ break
146
+ }
147
+ return {
148
+ methodName,
149
+ args,
150
+ value,
151
+ }
152
+ }
153
+ }