@pancakeswap/swap-sdk-core 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Noah Zinsmeister
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,257 @@
1
+ import JSBI from 'jsbi';
2
+ export { default as JSBI } from 'jsbi';
3
+
4
+ declare type BigintIsh = JSBI | number | string;
5
+ declare enum TradeType {
6
+ EXACT_INPUT = 0,
7
+ EXACT_OUTPUT = 1
8
+ }
9
+ declare enum Rounding {
10
+ ROUND_DOWN = 0,
11
+ ROUND_HALF_UP = 1,
12
+ ROUND_UP = 2
13
+ }
14
+ declare const MINIMUM_LIQUIDITY: JSBI;
15
+ declare const ZERO: JSBI;
16
+ declare const ONE: JSBI;
17
+ declare const TWO: JSBI;
18
+ declare const THREE: JSBI;
19
+ declare const FIVE: JSBI;
20
+ declare const TEN: JSBI;
21
+ declare const _100: JSBI;
22
+ declare const _9975: JSBI;
23
+ declare const _10000: JSBI;
24
+ declare const MaxUint256: JSBI;
25
+ declare enum VMType {
26
+ uint8 = "uint8",
27
+ uint256 = "uint256"
28
+ }
29
+ declare const VM_TYPE_MAXIMA: {
30
+ uint8: JSBI;
31
+ uint256: JSBI;
32
+ };
33
+
34
+ /**
35
+ * Represents the native currency of the chain on which it resides, e.g.
36
+ */
37
+ declare abstract class NativeCurrency extends BaseCurrency {
38
+ readonly isNative: true;
39
+ readonly isToken: false;
40
+ }
41
+
42
+ interface SerializedToken {
43
+ chainId: number;
44
+ address: string;
45
+ decimals: number;
46
+ symbol: string;
47
+ name?: string;
48
+ projectLink?: string;
49
+ }
50
+ /**
51
+ * Represents an ERC20 token with a unique address and some metadata.
52
+ */
53
+ declare class Token extends BaseCurrency {
54
+ readonly isNative: false;
55
+ readonly isToken: true;
56
+ /**
57
+ * The contract address on the chain on which this token lives
58
+ */
59
+ readonly address: string;
60
+ readonly projectLink?: string;
61
+ constructor(chainId: number, address: string, decimals: number, symbol: string, name?: string, projectLink?: string);
62
+ /**
63
+ * Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
64
+ * @param other other token to compare
65
+ */
66
+ equals(other: Currency): boolean;
67
+ /**
68
+ * Returns true if the address of this token sorts before the address of the other token
69
+ * @param other other token to compare
70
+ * @throws if the tokens have the same address
71
+ * @throws if the tokens are on different chains
72
+ */
73
+ sortsBefore(other: Token): boolean;
74
+ /**
75
+ * Return this token, which does not need to be wrapped
76
+ */
77
+ get wrapped(): Token;
78
+ get serialize(): SerializedToken;
79
+ }
80
+
81
+ declare type Currency = NativeCurrency | Token;
82
+
83
+ /**
84
+ * A currency is any fungible financial instrument, including Ether, all ERC20 tokens, and other chain-native currencies
85
+ */
86
+ declare abstract class BaseCurrency {
87
+ /**
88
+ * Returns whether the currency is native to the chain and must be wrapped (e.g. Ether)
89
+ */
90
+ abstract readonly isNative: boolean;
91
+ /**
92
+ * Returns whether the currency is a token that is usable in PancakeSwap without wrapping
93
+ */
94
+ abstract readonly isToken: boolean;
95
+ /**
96
+ * The chain ID on which this currency resides
97
+ */
98
+ readonly chainId: number;
99
+ /**
100
+ * The decimals used in representing currency amounts
101
+ */
102
+ readonly decimals: number;
103
+ /**
104
+ * The symbol of the currency, i.e. a short textual non-unique identifier
105
+ */
106
+ readonly symbol: string;
107
+ /**
108
+ * The name of the currency, i.e. a descriptive textual non-unique identifier
109
+ */
110
+ readonly name?: string;
111
+ /**
112
+ * Constructs an instance of the base class `BaseCurrency`.
113
+ * @param chainId the chain ID on which this currency resides
114
+ * @param decimals decimals of the currency
115
+ * @param symbol symbol of the currency
116
+ * @param name of the currency
117
+ */
118
+ protected constructor(chainId: number, decimals: number, symbol: string, name?: string);
119
+ /**
120
+ * Returns whether this currency is functionally equivalent to the other currency
121
+ * @param other the other currency
122
+ */
123
+ abstract equals(other: Currency): boolean;
124
+ /**
125
+ * Return the wrapped version of this currency that can be used with the PancakeSwap contracts. Currencies must
126
+ * implement this to be used in PancakeSwap
127
+ */
128
+ abstract get wrapped(): Token;
129
+ }
130
+
131
+ declare class Fraction {
132
+ readonly numerator: JSBI;
133
+ readonly denominator: JSBI;
134
+ constructor(numerator: BigintIsh, denominator?: BigintIsh);
135
+ private static tryParseFraction;
136
+ get quotient(): JSBI;
137
+ get remainder(): Fraction;
138
+ invert(): Fraction;
139
+ add(other: Fraction | BigintIsh): Fraction;
140
+ subtract(other: Fraction | BigintIsh): Fraction;
141
+ lessThan(other: Fraction | BigintIsh): boolean;
142
+ equalTo(other: Fraction | BigintIsh): boolean;
143
+ greaterThan(other: Fraction | BigintIsh): boolean;
144
+ multiply(other: Fraction | BigintIsh): Fraction;
145
+ divide(other: Fraction | BigintIsh): Fraction;
146
+ toSignificant(significantDigits: number, format?: object, rounding?: Rounding): string;
147
+ toFixed(decimalPlaces: number, format?: object, rounding?: Rounding): string;
148
+ /**
149
+ * Helper method for converting any super class back to a fraction
150
+ */
151
+ get asFraction(): Fraction;
152
+ }
153
+
154
+ declare class Percent extends Fraction {
155
+ /**
156
+ * This boolean prevents a fraction from being interpreted as a Percent
157
+ */
158
+ readonly isPercent: true;
159
+ add(other: Fraction | BigintIsh): Percent;
160
+ subtract(other: Fraction | BigintIsh): Percent;
161
+ multiply(other: Fraction | BigintIsh): Percent;
162
+ divide(other: Fraction | BigintIsh): Percent;
163
+ toSignificant(significantDigits?: number, format?: object, rounding?: Rounding): string;
164
+ toFixed(decimalPlaces?: number, format?: object, rounding?: Rounding): string;
165
+ }
166
+
167
+ declare class CurrencyAmount<T extends Currency> extends Fraction {
168
+ readonly currency: T;
169
+ readonly decimalScale: JSBI;
170
+ /**
171
+ * Returns a new currency amount instance from the unitless amount of token, i.e. the raw amount
172
+ * @param currency the currency in the amount
173
+ * @param rawAmount the raw token or ether amount
174
+ */
175
+ static fromRawAmount<T extends Currency>(currency: T, rawAmount: BigintIsh): CurrencyAmount<T>;
176
+ /**
177
+ * Construct a currency amount with a denominator that is not equal to 1
178
+ * @param currency the currency
179
+ * @param numerator the numerator of the fractional token amount
180
+ * @param denominator the denominator of the fractional token amount
181
+ */
182
+ static fromFractionalAmount<T extends Currency>(currency: T, numerator: BigintIsh, denominator: BigintIsh): CurrencyAmount<T>;
183
+ protected constructor(currency: T, numerator: BigintIsh, denominator?: BigintIsh);
184
+ add(other: CurrencyAmount<T>): CurrencyAmount<T>;
185
+ subtract(other: CurrencyAmount<T>): CurrencyAmount<T>;
186
+ multiply(other: Fraction | BigintIsh): CurrencyAmount<T>;
187
+ divide(other: Fraction | BigintIsh): CurrencyAmount<T>;
188
+ toSignificant(significantDigits?: number, format?: object, rounding?: Rounding): string;
189
+ toFixed(decimalPlaces?: number, format?: object, rounding?: Rounding): string;
190
+ toExact(format?: object): string;
191
+ get wrapped(): CurrencyAmount<Token>;
192
+ }
193
+
194
+ declare class Price<TBase extends Currency, TQuote extends Currency> extends Fraction {
195
+ readonly baseCurrency: TBase;
196
+ readonly quoteCurrency: TQuote;
197
+ readonly scalar: Fraction;
198
+ /**
199
+ * Construct a price, either with the base and quote currency amount, or the
200
+ * @param args
201
+ */
202
+ constructor(...args: [TBase, TQuote, BigintIsh, BigintIsh] | [{
203
+ baseAmount: CurrencyAmount<TBase>;
204
+ quoteAmount: CurrencyAmount<TQuote>;
205
+ }]);
206
+ /**
207
+ * Flip the price, switching the base and quote currency
208
+ */
209
+ invert(): Price<TQuote, TBase>;
210
+ /**
211
+ * Multiply the price by another price, returning a new price. The other price must have the same base currency as this price's quote currency
212
+ * @param other the other price
213
+ */
214
+ multiply<TOtherQuote extends Currency>(other: Price<TQuote, TOtherQuote>): Price<TBase, TOtherQuote>;
215
+ /**
216
+ * Return the amount of quote currency corresponding to a given amount of the base currency
217
+ * @param currencyAmount the amount of base currency to quote against the price
218
+ */
219
+ quote(currencyAmount: CurrencyAmount<TBase>): CurrencyAmount<TQuote>;
220
+ /**
221
+ * Get the value scaled by decimals for formatting
222
+ * @private
223
+ */
224
+ private get adjustedForDecimals();
225
+ toSignificant(significantDigits?: number, format?: object, rounding?: Rounding): string;
226
+ toFixed(decimalPlaces?: number, format?: object, rounding?: Rounding): string;
227
+ }
228
+
229
+ /**
230
+ * Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
231
+ * obtained by sending any amount of input.
232
+ */
233
+ declare class InsufficientReservesError extends Error {
234
+ readonly isInsufficientReservesError: true;
235
+ constructor();
236
+ }
237
+ /**
238
+ * Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
239
+ * than the price of a single unit of output after fees.
240
+ */
241
+ declare class InsufficientInputAmountError extends Error {
242
+ readonly isInsufficientInputAmountError: true;
243
+ constructor();
244
+ }
245
+
246
+ declare function validateVMTypeInstance(value: JSBI, vmType: VMType): void;
247
+ declare function sqrt(y: JSBI): JSBI;
248
+ declare function sortedInsert<T>(items: T[], add: T, maxSize: number, comparator: (a: T, b: T) => number): T | null;
249
+ /**
250
+ * Returns the percent difference between the mid price and the execution price, i.e. price impact.
251
+ * @param midPrice mid price before the trade
252
+ * @param inputAmount the input amount of the trade
253
+ * @param outputAmount the output amount of the trade
254
+ */
255
+ declare function computePriceImpact<TBase extends Currency, TQuote extends Currency>(midPrice: Price<TBase, TQuote>, inputAmount: CurrencyAmount<TBase>, outputAmount: CurrencyAmount<TQuote>): Percent;
256
+
257
+ export { BaseCurrency, BigintIsh, Currency, CurrencyAmount, FIVE, Fraction, InsufficientInputAmountError, InsufficientReservesError, MINIMUM_LIQUIDITY, MaxUint256, NativeCurrency, ONE, Percent, Price, Rounding, SerializedToken, TEN, THREE, TWO, Token, TradeType, VMType, VM_TYPE_MAXIMA, ZERO, _100, _10000, _9975, computePriceImpact, sortedInsert, sqrt, validateVMTypeInstance };
package/dist/index.js ADDED
@@ -0,0 +1,480 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // src/index.ts
24
+ var src_exports = {};
25
+ __export(src_exports, {
26
+ BaseCurrency: () => BaseCurrency,
27
+ CurrencyAmount: () => CurrencyAmount,
28
+ FIVE: () => FIVE,
29
+ Fraction: () => Fraction,
30
+ InsufficientInputAmountError: () => InsufficientInputAmountError,
31
+ InsufficientReservesError: () => InsufficientReservesError,
32
+ JSBI: () => import_jsbi7.default,
33
+ MINIMUM_LIQUIDITY: () => MINIMUM_LIQUIDITY,
34
+ MaxUint256: () => MaxUint256,
35
+ NativeCurrency: () => NativeCurrency,
36
+ ONE: () => ONE,
37
+ Percent: () => Percent,
38
+ Price: () => Price,
39
+ Rounding: () => Rounding,
40
+ TEN: () => TEN,
41
+ THREE: () => THREE,
42
+ TWO: () => TWO,
43
+ Token: () => Token,
44
+ TradeType: () => TradeType,
45
+ VMType: () => VMType,
46
+ VM_TYPE_MAXIMA: () => VM_TYPE_MAXIMA,
47
+ ZERO: () => ZERO,
48
+ _100: () => _100,
49
+ _10000: () => _10000,
50
+ _9975: () => _9975,
51
+ computePriceImpact: () => computePriceImpact,
52
+ sortedInsert: () => sortedInsert,
53
+ sqrt: () => sqrt,
54
+ validateVMTypeInstance: () => validateVMTypeInstance
55
+ });
56
+ module.exports = __toCommonJS(src_exports);
57
+ var import_jsbi7 = __toESM(require("jsbi"));
58
+
59
+ // src/constants.ts
60
+ var import_jsbi = __toESM(require("jsbi"));
61
+ var TradeType = /* @__PURE__ */ ((TradeType2) => {
62
+ TradeType2[TradeType2["EXACT_INPUT"] = 0] = "EXACT_INPUT";
63
+ TradeType2[TradeType2["EXACT_OUTPUT"] = 1] = "EXACT_OUTPUT";
64
+ return TradeType2;
65
+ })(TradeType || {});
66
+ var Rounding = /* @__PURE__ */ ((Rounding2) => {
67
+ Rounding2[Rounding2["ROUND_DOWN"] = 0] = "ROUND_DOWN";
68
+ Rounding2[Rounding2["ROUND_HALF_UP"] = 1] = "ROUND_HALF_UP";
69
+ Rounding2[Rounding2["ROUND_UP"] = 2] = "ROUND_UP";
70
+ return Rounding2;
71
+ })(Rounding || {});
72
+ var MINIMUM_LIQUIDITY = import_jsbi.default.BigInt(1e3);
73
+ var ZERO = import_jsbi.default.BigInt(0);
74
+ var ONE = import_jsbi.default.BigInt(1);
75
+ var TWO = import_jsbi.default.BigInt(2);
76
+ var THREE = import_jsbi.default.BigInt(3);
77
+ var FIVE = import_jsbi.default.BigInt(5);
78
+ var TEN = import_jsbi.default.BigInt(10);
79
+ var _100 = import_jsbi.default.BigInt(100);
80
+ var _9975 = import_jsbi.default.BigInt(9975);
81
+ var _10000 = import_jsbi.default.BigInt(1e4);
82
+ var MaxUint256 = import_jsbi.default.BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
83
+ var VMType = /* @__PURE__ */ ((VMType2) => {
84
+ VMType2["uint8"] = "uint8";
85
+ VMType2["uint256"] = "uint256";
86
+ return VMType2;
87
+ })(VMType || {});
88
+ var VM_TYPE_MAXIMA = {
89
+ ["uint8" /* uint8 */]: import_jsbi.default.BigInt("0xff"),
90
+ ["uint256" /* uint256 */]: import_jsbi.default.BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
91
+ };
92
+
93
+ // src/baseCurrency.ts
94
+ var import_tiny_invariant = __toESM(require("tiny-invariant"));
95
+ var BaseCurrency = class {
96
+ constructor(chainId, decimals, symbol, name) {
97
+ (0, import_tiny_invariant.default)(Number.isSafeInteger(chainId), "CHAIN_ID");
98
+ (0, import_tiny_invariant.default)(decimals >= 0 && decimals < 255 && Number.isInteger(decimals), "DECIMALS");
99
+ this.chainId = chainId;
100
+ this.decimals = decimals;
101
+ this.symbol = symbol;
102
+ this.name = name;
103
+ }
104
+ };
105
+
106
+ // src/fractions/fraction.ts
107
+ var import_jsbi2 = __toESM(require("jsbi"));
108
+ var import_tiny_invariant2 = __toESM(require("tiny-invariant"));
109
+ var import_decimal = __toESM(require("decimal.js-light"));
110
+ var import_big = __toESM(require("big.js"));
111
+ var import_toformat = __toESM(require("toformat"));
112
+ var Decimal = (0, import_toformat.default)(import_decimal.default);
113
+ var Big = (0, import_toformat.default)(import_big.default);
114
+ var toSignificantRounding = {
115
+ [0 /* ROUND_DOWN */]: Decimal.ROUND_DOWN,
116
+ [1 /* ROUND_HALF_UP */]: Decimal.ROUND_HALF_UP,
117
+ [2 /* ROUND_UP */]: Decimal.ROUND_UP
118
+ };
119
+ var toFixedRounding = {
120
+ [0 /* ROUND_DOWN */]: 0 /* RoundDown */,
121
+ [1 /* ROUND_HALF_UP */]: 1 /* RoundHalfUp */,
122
+ [2 /* ROUND_UP */]: 3 /* RoundUp */
123
+ };
124
+ var Fraction = class {
125
+ constructor(numerator, denominator = import_jsbi2.default.BigInt(1)) {
126
+ this.numerator = import_jsbi2.default.BigInt(numerator);
127
+ this.denominator = import_jsbi2.default.BigInt(denominator);
128
+ }
129
+ static tryParseFraction(fractionish) {
130
+ if (fractionish instanceof import_jsbi2.default || typeof fractionish === "number" || typeof fractionish === "string")
131
+ return new Fraction(fractionish);
132
+ if ("numerator" in fractionish && "denominator" in fractionish)
133
+ return fractionish;
134
+ throw new Error("Could not parse fraction");
135
+ }
136
+ get quotient() {
137
+ return import_jsbi2.default.divide(this.numerator, this.denominator);
138
+ }
139
+ get remainder() {
140
+ return new Fraction(import_jsbi2.default.remainder(this.numerator, this.denominator), this.denominator);
141
+ }
142
+ invert() {
143
+ return new Fraction(this.denominator, this.numerator);
144
+ }
145
+ add(other) {
146
+ const otherParsed = Fraction.tryParseFraction(other);
147
+ if (import_jsbi2.default.equal(this.denominator, otherParsed.denominator)) {
148
+ return new Fraction(import_jsbi2.default.add(this.numerator, otherParsed.numerator), this.denominator);
149
+ }
150
+ return new Fraction(import_jsbi2.default.add(import_jsbi2.default.multiply(this.numerator, otherParsed.denominator), import_jsbi2.default.multiply(otherParsed.numerator, this.denominator)), import_jsbi2.default.multiply(this.denominator, otherParsed.denominator));
151
+ }
152
+ subtract(other) {
153
+ const otherParsed = Fraction.tryParseFraction(other);
154
+ if (import_jsbi2.default.equal(this.denominator, otherParsed.denominator)) {
155
+ return new Fraction(import_jsbi2.default.subtract(this.numerator, otherParsed.numerator), this.denominator);
156
+ }
157
+ return new Fraction(import_jsbi2.default.subtract(import_jsbi2.default.multiply(this.numerator, otherParsed.denominator), import_jsbi2.default.multiply(otherParsed.numerator, this.denominator)), import_jsbi2.default.multiply(this.denominator, otherParsed.denominator));
158
+ }
159
+ lessThan(other) {
160
+ const otherParsed = Fraction.tryParseFraction(other);
161
+ return import_jsbi2.default.lessThan(import_jsbi2.default.multiply(this.numerator, otherParsed.denominator), import_jsbi2.default.multiply(otherParsed.numerator, this.denominator));
162
+ }
163
+ equalTo(other) {
164
+ const otherParsed = Fraction.tryParseFraction(other);
165
+ return import_jsbi2.default.equal(import_jsbi2.default.multiply(this.numerator, otherParsed.denominator), import_jsbi2.default.multiply(otherParsed.numerator, this.denominator));
166
+ }
167
+ greaterThan(other) {
168
+ const otherParsed = Fraction.tryParseFraction(other);
169
+ return import_jsbi2.default.greaterThan(import_jsbi2.default.multiply(this.numerator, otherParsed.denominator), import_jsbi2.default.multiply(otherParsed.numerator, this.denominator));
170
+ }
171
+ multiply(other) {
172
+ const otherParsed = Fraction.tryParseFraction(other);
173
+ return new Fraction(import_jsbi2.default.multiply(this.numerator, otherParsed.numerator), import_jsbi2.default.multiply(this.denominator, otherParsed.denominator));
174
+ }
175
+ divide(other) {
176
+ const otherParsed = Fraction.tryParseFraction(other);
177
+ return new Fraction(import_jsbi2.default.multiply(this.numerator, otherParsed.denominator), import_jsbi2.default.multiply(this.denominator, otherParsed.numerator));
178
+ }
179
+ toSignificant(significantDigits, format = { groupSeparator: "" }, rounding = 1 /* ROUND_HALF_UP */) {
180
+ (0, import_tiny_invariant2.default)(Number.isInteger(significantDigits), `${significantDigits} is not an integer.`);
181
+ (0, import_tiny_invariant2.default)(significantDigits > 0, `${significantDigits} is not positive.`);
182
+ Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] });
183
+ const quotient = new Decimal(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(significantDigits);
184
+ return quotient.toFormat(quotient.decimalPlaces(), format);
185
+ }
186
+ toFixed(decimalPlaces, format = { groupSeparator: "" }, rounding = 1 /* ROUND_HALF_UP */) {
187
+ (0, import_tiny_invariant2.default)(Number.isInteger(decimalPlaces), `${decimalPlaces} is not an integer.`);
188
+ (0, import_tiny_invariant2.default)(decimalPlaces >= 0, `${decimalPlaces} is negative.`);
189
+ Big.DP = decimalPlaces;
190
+ Big.RM = toFixedRounding[rounding];
191
+ return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format);
192
+ }
193
+ get asFraction() {
194
+ return new Fraction(this.numerator, this.denominator);
195
+ }
196
+ };
197
+
198
+ // src/fractions/percent.ts
199
+ var import_jsbi3 = __toESM(require("jsbi"));
200
+ var ONE_HUNDRED = new Fraction(import_jsbi3.default.BigInt(100));
201
+ function toPercent(fraction) {
202
+ return new Percent(fraction.numerator, fraction.denominator);
203
+ }
204
+ var Percent = class extends Fraction {
205
+ constructor() {
206
+ super(...arguments);
207
+ this.isPercent = true;
208
+ }
209
+ add(other) {
210
+ return toPercent(super.add(other));
211
+ }
212
+ subtract(other) {
213
+ return toPercent(super.subtract(other));
214
+ }
215
+ multiply(other) {
216
+ return toPercent(super.multiply(other));
217
+ }
218
+ divide(other) {
219
+ return toPercent(super.divide(other));
220
+ }
221
+ toSignificant(significantDigits = 5, format, rounding) {
222
+ return super.multiply(ONE_HUNDRED).toSignificant(significantDigits, format, rounding);
223
+ }
224
+ toFixed(decimalPlaces = 2, format, rounding) {
225
+ return super.multiply(ONE_HUNDRED).toFixed(decimalPlaces, format, rounding);
226
+ }
227
+ };
228
+
229
+ // src/fractions/currencyAmount.ts
230
+ var import_tiny_invariant3 = __toESM(require("tiny-invariant"));
231
+ var import_jsbi4 = __toESM(require("jsbi"));
232
+ var import_big2 = __toESM(require("big.js"));
233
+ var import_toformat2 = __toESM(require("toformat"));
234
+ var Big2 = (0, import_toformat2.default)(import_big2.default);
235
+ var CurrencyAmount = class extends Fraction {
236
+ constructor(currency, numerator, denominator) {
237
+ super(numerator, denominator);
238
+ (0, import_tiny_invariant3.default)(import_jsbi4.default.lessThanOrEqual(this.quotient, MaxUint256), "AMOUNT");
239
+ this.currency = currency;
240
+ this.decimalScale = import_jsbi4.default.exponentiate(import_jsbi4.default.BigInt(10), import_jsbi4.default.BigInt(currency.decimals));
241
+ }
242
+ static fromRawAmount(currency, rawAmount) {
243
+ return new CurrencyAmount(currency, rawAmount);
244
+ }
245
+ static fromFractionalAmount(currency, numerator, denominator) {
246
+ return new CurrencyAmount(currency, numerator, denominator);
247
+ }
248
+ add(other) {
249
+ (0, import_tiny_invariant3.default)(this.currency.equals(other.currency), "CURRENCY");
250
+ const added = super.add(other);
251
+ return CurrencyAmount.fromFractionalAmount(this.currency, added.numerator, added.denominator);
252
+ }
253
+ subtract(other) {
254
+ (0, import_tiny_invariant3.default)(this.currency.equals(other.currency), "CURRENCY");
255
+ const subtracted = super.subtract(other);
256
+ return CurrencyAmount.fromFractionalAmount(this.currency, subtracted.numerator, subtracted.denominator);
257
+ }
258
+ multiply(other) {
259
+ const multiplied = super.multiply(other);
260
+ return CurrencyAmount.fromFractionalAmount(this.currency, multiplied.numerator, multiplied.denominator);
261
+ }
262
+ divide(other) {
263
+ const divided = super.divide(other);
264
+ return CurrencyAmount.fromFractionalAmount(this.currency, divided.numerator, divided.denominator);
265
+ }
266
+ toSignificant(significantDigits = 6, format, rounding = 0 /* ROUND_DOWN */) {
267
+ return super.divide(this.decimalScale).toSignificant(significantDigits, format, rounding);
268
+ }
269
+ toFixed(decimalPlaces = this.currency.decimals, format, rounding = 0 /* ROUND_DOWN */) {
270
+ (0, import_tiny_invariant3.default)(decimalPlaces <= this.currency.decimals, "DECIMALS");
271
+ return super.divide(this.decimalScale).toFixed(decimalPlaces, format, rounding);
272
+ }
273
+ toExact(format = { groupSeparator: "" }) {
274
+ Big2.DP = this.currency.decimals;
275
+ return new Big2(this.quotient.toString()).div(this.decimalScale.toString()).toFormat(format);
276
+ }
277
+ get wrapped() {
278
+ if (this.currency.isToken)
279
+ return this;
280
+ return CurrencyAmount.fromFractionalAmount(this.currency.wrapped, this.numerator, this.denominator);
281
+ }
282
+ };
283
+
284
+ // src/fractions/price.ts
285
+ var import_jsbi5 = __toESM(require("jsbi"));
286
+ var import_tiny_invariant4 = __toESM(require("tiny-invariant"));
287
+ var Price = class extends Fraction {
288
+ constructor(...args) {
289
+ let baseCurrency;
290
+ let quoteCurrency;
291
+ let denominator;
292
+ let numerator;
293
+ if (args.length === 4) {
294
+ ;
295
+ [baseCurrency, quoteCurrency, denominator, numerator] = args;
296
+ } else {
297
+ const result = args[0].quoteAmount.divide(args[0].baseAmount);
298
+ [baseCurrency, quoteCurrency, denominator, numerator] = [
299
+ args[0].baseAmount.currency,
300
+ args[0].quoteAmount.currency,
301
+ result.denominator,
302
+ result.numerator
303
+ ];
304
+ }
305
+ super(numerator, denominator);
306
+ this.baseCurrency = baseCurrency;
307
+ this.quoteCurrency = quoteCurrency;
308
+ this.scalar = new Fraction(import_jsbi5.default.exponentiate(import_jsbi5.default.BigInt(10), import_jsbi5.default.BigInt(baseCurrency.decimals)), import_jsbi5.default.exponentiate(import_jsbi5.default.BigInt(10), import_jsbi5.default.BigInt(quoteCurrency.decimals)));
309
+ }
310
+ invert() {
311
+ return new Price(this.quoteCurrency, this.baseCurrency, this.numerator, this.denominator);
312
+ }
313
+ multiply(other) {
314
+ (0, import_tiny_invariant4.default)(this.quoteCurrency.equals(other.baseCurrency), "TOKEN");
315
+ const fraction = super.multiply(other);
316
+ return new Price(this.baseCurrency, other.quoteCurrency, fraction.denominator, fraction.numerator);
317
+ }
318
+ quote(currencyAmount) {
319
+ (0, import_tiny_invariant4.default)(currencyAmount.currency.equals(this.baseCurrency), "TOKEN");
320
+ const result = super.multiply(currencyAmount);
321
+ return CurrencyAmount.fromFractionalAmount(this.quoteCurrency, result.numerator, result.denominator);
322
+ }
323
+ get adjustedForDecimals() {
324
+ return super.multiply(this.scalar);
325
+ }
326
+ toSignificant(significantDigits = 6, format, rounding) {
327
+ return this.adjustedForDecimals.toSignificant(significantDigits, format, rounding);
328
+ }
329
+ toFixed(decimalPlaces = 4, format, rounding) {
330
+ return this.adjustedForDecimals.toFixed(decimalPlaces, format, rounding);
331
+ }
332
+ };
333
+
334
+ // src/nativeCurrency.ts
335
+ var NativeCurrency = class extends BaseCurrency {
336
+ constructor() {
337
+ super(...arguments);
338
+ this.isNative = true;
339
+ this.isToken = false;
340
+ }
341
+ };
342
+
343
+ // src/token.ts
344
+ var import_tiny_invariant5 = __toESM(require("tiny-invariant"));
345
+ var Token = class extends BaseCurrency {
346
+ constructor(chainId, address, decimals, symbol, name, projectLink) {
347
+ super(chainId, decimals, symbol, name);
348
+ this.isNative = false;
349
+ this.isToken = true;
350
+ this.address = address;
351
+ this.projectLink = projectLink;
352
+ }
353
+ equals(other) {
354
+ return other.isToken && this.chainId === other.chainId && this.address === other.address;
355
+ }
356
+ sortsBefore(other) {
357
+ (0, import_tiny_invariant5.default)(this.chainId === other.chainId, "CHAIN_IDS");
358
+ (0, import_tiny_invariant5.default)(this.address !== other.address, "ADDRESSES");
359
+ return this.address.toLowerCase() < other.address.toLowerCase();
360
+ }
361
+ get wrapped() {
362
+ return this;
363
+ }
364
+ get serialize() {
365
+ return {
366
+ address: this.address,
367
+ chainId: this.chainId,
368
+ decimals: this.decimals,
369
+ symbol: this.symbol,
370
+ name: this.name,
371
+ projectLink: this.projectLink
372
+ };
373
+ }
374
+ };
375
+
376
+ // src/errors.ts
377
+ var CAN_SET_PROTOTYPE = "setPrototypeOf" in Object;
378
+ var InsufficientReservesError = class extends Error {
379
+ constructor() {
380
+ super();
381
+ this.isInsufficientReservesError = true;
382
+ this.name = this.constructor.name;
383
+ if (CAN_SET_PROTOTYPE)
384
+ Object.setPrototypeOf(this, new.target.prototype);
385
+ }
386
+ };
387
+ var InsufficientInputAmountError = class extends Error {
388
+ constructor() {
389
+ super();
390
+ this.isInsufficientInputAmountError = true;
391
+ this.name = this.constructor.name;
392
+ if (CAN_SET_PROTOTYPE)
393
+ Object.setPrototypeOf(this, new.target.prototype);
394
+ }
395
+ };
396
+
397
+ // src/utils.ts
398
+ var import_jsbi6 = __toESM(require("jsbi"));
399
+ var import_tiny_invariant6 = __toESM(require("tiny-invariant"));
400
+ function validateVMTypeInstance(value, vmType) {
401
+ (0, import_tiny_invariant6.default)(import_jsbi6.default.greaterThanOrEqual(value, ZERO), `${value} is not a ${vmType}.`);
402
+ (0, import_tiny_invariant6.default)(import_jsbi6.default.lessThanOrEqual(value, VM_TYPE_MAXIMA[vmType]), `${value} is not a ${vmType}.`);
403
+ }
404
+ function sqrt(y) {
405
+ validateVMTypeInstance(y, "uint256" /* uint256 */);
406
+ let z = ZERO;
407
+ let x;
408
+ if (import_jsbi6.default.greaterThan(y, THREE)) {
409
+ z = y;
410
+ x = import_jsbi6.default.add(import_jsbi6.default.divide(y, TWO), ONE);
411
+ while (import_jsbi6.default.lessThan(x, z)) {
412
+ z = x;
413
+ x = import_jsbi6.default.divide(import_jsbi6.default.add(import_jsbi6.default.divide(y, x), x), TWO);
414
+ }
415
+ } else if (import_jsbi6.default.notEqual(y, ZERO)) {
416
+ z = ONE;
417
+ }
418
+ return z;
419
+ }
420
+ function sortedInsert(items, add, maxSize, comparator) {
421
+ (0, import_tiny_invariant6.default)(maxSize > 0, "MAX_SIZE_ZERO");
422
+ (0, import_tiny_invariant6.default)(items.length <= maxSize, "ITEMS_SIZE");
423
+ if (items.length === 0) {
424
+ items.push(add);
425
+ return null;
426
+ } else {
427
+ const isFull = items.length === maxSize;
428
+ if (isFull && comparator(items[items.length - 1], add) <= 0) {
429
+ return add;
430
+ }
431
+ let lo = 0, hi = items.length;
432
+ while (lo < hi) {
433
+ const mid = lo + hi >>> 1;
434
+ if (comparator(items[mid], add) <= 0) {
435
+ lo = mid + 1;
436
+ } else {
437
+ hi = mid;
438
+ }
439
+ }
440
+ items.splice(lo, 0, add);
441
+ return isFull ? items.pop() : null;
442
+ }
443
+ }
444
+ function computePriceImpact(midPrice, inputAmount, outputAmount) {
445
+ const quotedOutputAmount = midPrice.quote(inputAmount);
446
+ const priceImpact = quotedOutputAmount.subtract(outputAmount).divide(quotedOutputAmount);
447
+ return new Percent(priceImpact.numerator, priceImpact.denominator);
448
+ }
449
+ // Annotate the CommonJS export names for ESM import in node:
450
+ 0 && (module.exports = {
451
+ BaseCurrency,
452
+ CurrencyAmount,
453
+ FIVE,
454
+ Fraction,
455
+ InsufficientInputAmountError,
456
+ InsufficientReservesError,
457
+ JSBI,
458
+ MINIMUM_LIQUIDITY,
459
+ MaxUint256,
460
+ NativeCurrency,
461
+ ONE,
462
+ Percent,
463
+ Price,
464
+ Rounding,
465
+ TEN,
466
+ THREE,
467
+ TWO,
468
+ Token,
469
+ TradeType,
470
+ VMType,
471
+ VM_TYPE_MAXIMA,
472
+ ZERO,
473
+ _100,
474
+ _10000,
475
+ _9975,
476
+ computePriceImpact,
477
+ sortedInsert,
478
+ sqrt,
479
+ validateVMTypeInstance
480
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,424 @@
1
+ // src/index.ts
2
+ import JSBI7 from "jsbi";
3
+
4
+ // src/constants.ts
5
+ import JSBI from "jsbi";
6
+ var TradeType = /* @__PURE__ */ ((TradeType2) => {
7
+ TradeType2[TradeType2["EXACT_INPUT"] = 0] = "EXACT_INPUT";
8
+ TradeType2[TradeType2["EXACT_OUTPUT"] = 1] = "EXACT_OUTPUT";
9
+ return TradeType2;
10
+ })(TradeType || {});
11
+ var Rounding = /* @__PURE__ */ ((Rounding2) => {
12
+ Rounding2[Rounding2["ROUND_DOWN"] = 0] = "ROUND_DOWN";
13
+ Rounding2[Rounding2["ROUND_HALF_UP"] = 1] = "ROUND_HALF_UP";
14
+ Rounding2[Rounding2["ROUND_UP"] = 2] = "ROUND_UP";
15
+ return Rounding2;
16
+ })(Rounding || {});
17
+ var MINIMUM_LIQUIDITY = JSBI.BigInt(1e3);
18
+ var ZERO = JSBI.BigInt(0);
19
+ var ONE = JSBI.BigInt(1);
20
+ var TWO = JSBI.BigInt(2);
21
+ var THREE = JSBI.BigInt(3);
22
+ var FIVE = JSBI.BigInt(5);
23
+ var TEN = JSBI.BigInt(10);
24
+ var _100 = JSBI.BigInt(100);
25
+ var _9975 = JSBI.BigInt(9975);
26
+ var _10000 = JSBI.BigInt(1e4);
27
+ var MaxUint256 = JSBI.BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
28
+ var VMType = /* @__PURE__ */ ((VMType2) => {
29
+ VMType2["uint8"] = "uint8";
30
+ VMType2["uint256"] = "uint256";
31
+ return VMType2;
32
+ })(VMType || {});
33
+ var VM_TYPE_MAXIMA = {
34
+ ["uint8" /* uint8 */]: JSBI.BigInt("0xff"),
35
+ ["uint256" /* uint256 */]: JSBI.BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
36
+ };
37
+
38
+ // src/baseCurrency.ts
39
+ import invariant from "tiny-invariant";
40
+ var BaseCurrency = class {
41
+ constructor(chainId, decimals, symbol, name) {
42
+ invariant(Number.isSafeInteger(chainId), "CHAIN_ID");
43
+ invariant(decimals >= 0 && decimals < 255 && Number.isInteger(decimals), "DECIMALS");
44
+ this.chainId = chainId;
45
+ this.decimals = decimals;
46
+ this.symbol = symbol;
47
+ this.name = name;
48
+ }
49
+ };
50
+
51
+ // src/fractions/fraction.ts
52
+ import JSBI2 from "jsbi";
53
+ import invariant2 from "tiny-invariant";
54
+ import _Decimal from "decimal.js-light";
55
+ import _Big from "big.js";
56
+ import toFormat from "toformat";
57
+ var Decimal = toFormat(_Decimal);
58
+ var Big = toFormat(_Big);
59
+ var toSignificantRounding = {
60
+ [0 /* ROUND_DOWN */]: Decimal.ROUND_DOWN,
61
+ [1 /* ROUND_HALF_UP */]: Decimal.ROUND_HALF_UP,
62
+ [2 /* ROUND_UP */]: Decimal.ROUND_UP
63
+ };
64
+ var toFixedRounding = {
65
+ [0 /* ROUND_DOWN */]: 0 /* RoundDown */,
66
+ [1 /* ROUND_HALF_UP */]: 1 /* RoundHalfUp */,
67
+ [2 /* ROUND_UP */]: 3 /* RoundUp */
68
+ };
69
+ var Fraction = class {
70
+ constructor(numerator, denominator = JSBI2.BigInt(1)) {
71
+ this.numerator = JSBI2.BigInt(numerator);
72
+ this.denominator = JSBI2.BigInt(denominator);
73
+ }
74
+ static tryParseFraction(fractionish) {
75
+ if (fractionish instanceof JSBI2 || typeof fractionish === "number" || typeof fractionish === "string")
76
+ return new Fraction(fractionish);
77
+ if ("numerator" in fractionish && "denominator" in fractionish)
78
+ return fractionish;
79
+ throw new Error("Could not parse fraction");
80
+ }
81
+ get quotient() {
82
+ return JSBI2.divide(this.numerator, this.denominator);
83
+ }
84
+ get remainder() {
85
+ return new Fraction(JSBI2.remainder(this.numerator, this.denominator), this.denominator);
86
+ }
87
+ invert() {
88
+ return new Fraction(this.denominator, this.numerator);
89
+ }
90
+ add(other) {
91
+ const otherParsed = Fraction.tryParseFraction(other);
92
+ if (JSBI2.equal(this.denominator, otherParsed.denominator)) {
93
+ return new Fraction(JSBI2.add(this.numerator, otherParsed.numerator), this.denominator);
94
+ }
95
+ return new Fraction(JSBI2.add(JSBI2.multiply(this.numerator, otherParsed.denominator), JSBI2.multiply(otherParsed.numerator, this.denominator)), JSBI2.multiply(this.denominator, otherParsed.denominator));
96
+ }
97
+ subtract(other) {
98
+ const otherParsed = Fraction.tryParseFraction(other);
99
+ if (JSBI2.equal(this.denominator, otherParsed.denominator)) {
100
+ return new Fraction(JSBI2.subtract(this.numerator, otherParsed.numerator), this.denominator);
101
+ }
102
+ return new Fraction(JSBI2.subtract(JSBI2.multiply(this.numerator, otherParsed.denominator), JSBI2.multiply(otherParsed.numerator, this.denominator)), JSBI2.multiply(this.denominator, otherParsed.denominator));
103
+ }
104
+ lessThan(other) {
105
+ const otherParsed = Fraction.tryParseFraction(other);
106
+ return JSBI2.lessThan(JSBI2.multiply(this.numerator, otherParsed.denominator), JSBI2.multiply(otherParsed.numerator, this.denominator));
107
+ }
108
+ equalTo(other) {
109
+ const otherParsed = Fraction.tryParseFraction(other);
110
+ return JSBI2.equal(JSBI2.multiply(this.numerator, otherParsed.denominator), JSBI2.multiply(otherParsed.numerator, this.denominator));
111
+ }
112
+ greaterThan(other) {
113
+ const otherParsed = Fraction.tryParseFraction(other);
114
+ return JSBI2.greaterThan(JSBI2.multiply(this.numerator, otherParsed.denominator), JSBI2.multiply(otherParsed.numerator, this.denominator));
115
+ }
116
+ multiply(other) {
117
+ const otherParsed = Fraction.tryParseFraction(other);
118
+ return new Fraction(JSBI2.multiply(this.numerator, otherParsed.numerator), JSBI2.multiply(this.denominator, otherParsed.denominator));
119
+ }
120
+ divide(other) {
121
+ const otherParsed = Fraction.tryParseFraction(other);
122
+ return new Fraction(JSBI2.multiply(this.numerator, otherParsed.denominator), JSBI2.multiply(this.denominator, otherParsed.numerator));
123
+ }
124
+ toSignificant(significantDigits, format = { groupSeparator: "" }, rounding = 1 /* ROUND_HALF_UP */) {
125
+ invariant2(Number.isInteger(significantDigits), `${significantDigits} is not an integer.`);
126
+ invariant2(significantDigits > 0, `${significantDigits} is not positive.`);
127
+ Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] });
128
+ const quotient = new Decimal(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(significantDigits);
129
+ return quotient.toFormat(quotient.decimalPlaces(), format);
130
+ }
131
+ toFixed(decimalPlaces, format = { groupSeparator: "" }, rounding = 1 /* ROUND_HALF_UP */) {
132
+ invariant2(Number.isInteger(decimalPlaces), `${decimalPlaces} is not an integer.`);
133
+ invariant2(decimalPlaces >= 0, `${decimalPlaces} is negative.`);
134
+ Big.DP = decimalPlaces;
135
+ Big.RM = toFixedRounding[rounding];
136
+ return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format);
137
+ }
138
+ get asFraction() {
139
+ return new Fraction(this.numerator, this.denominator);
140
+ }
141
+ };
142
+
143
+ // src/fractions/percent.ts
144
+ import JSBI3 from "jsbi";
145
+ var ONE_HUNDRED = new Fraction(JSBI3.BigInt(100));
146
+ function toPercent(fraction) {
147
+ return new Percent(fraction.numerator, fraction.denominator);
148
+ }
149
+ var Percent = class extends Fraction {
150
+ constructor() {
151
+ super(...arguments);
152
+ this.isPercent = true;
153
+ }
154
+ add(other) {
155
+ return toPercent(super.add(other));
156
+ }
157
+ subtract(other) {
158
+ return toPercent(super.subtract(other));
159
+ }
160
+ multiply(other) {
161
+ return toPercent(super.multiply(other));
162
+ }
163
+ divide(other) {
164
+ return toPercent(super.divide(other));
165
+ }
166
+ toSignificant(significantDigits = 5, format, rounding) {
167
+ return super.multiply(ONE_HUNDRED).toSignificant(significantDigits, format, rounding);
168
+ }
169
+ toFixed(decimalPlaces = 2, format, rounding) {
170
+ return super.multiply(ONE_HUNDRED).toFixed(decimalPlaces, format, rounding);
171
+ }
172
+ };
173
+
174
+ // src/fractions/currencyAmount.ts
175
+ import invariant3 from "tiny-invariant";
176
+ import JSBI4 from "jsbi";
177
+ import _Big2 from "big.js";
178
+ import toFormat2 from "toformat";
179
+ var Big2 = toFormat2(_Big2);
180
+ var CurrencyAmount = class extends Fraction {
181
+ constructor(currency, numerator, denominator) {
182
+ super(numerator, denominator);
183
+ invariant3(JSBI4.lessThanOrEqual(this.quotient, MaxUint256), "AMOUNT");
184
+ this.currency = currency;
185
+ this.decimalScale = JSBI4.exponentiate(JSBI4.BigInt(10), JSBI4.BigInt(currency.decimals));
186
+ }
187
+ static fromRawAmount(currency, rawAmount) {
188
+ return new CurrencyAmount(currency, rawAmount);
189
+ }
190
+ static fromFractionalAmount(currency, numerator, denominator) {
191
+ return new CurrencyAmount(currency, numerator, denominator);
192
+ }
193
+ add(other) {
194
+ invariant3(this.currency.equals(other.currency), "CURRENCY");
195
+ const added = super.add(other);
196
+ return CurrencyAmount.fromFractionalAmount(this.currency, added.numerator, added.denominator);
197
+ }
198
+ subtract(other) {
199
+ invariant3(this.currency.equals(other.currency), "CURRENCY");
200
+ const subtracted = super.subtract(other);
201
+ return CurrencyAmount.fromFractionalAmount(this.currency, subtracted.numerator, subtracted.denominator);
202
+ }
203
+ multiply(other) {
204
+ const multiplied = super.multiply(other);
205
+ return CurrencyAmount.fromFractionalAmount(this.currency, multiplied.numerator, multiplied.denominator);
206
+ }
207
+ divide(other) {
208
+ const divided = super.divide(other);
209
+ return CurrencyAmount.fromFractionalAmount(this.currency, divided.numerator, divided.denominator);
210
+ }
211
+ toSignificant(significantDigits = 6, format, rounding = 0 /* ROUND_DOWN */) {
212
+ return super.divide(this.decimalScale).toSignificant(significantDigits, format, rounding);
213
+ }
214
+ toFixed(decimalPlaces = this.currency.decimals, format, rounding = 0 /* ROUND_DOWN */) {
215
+ invariant3(decimalPlaces <= this.currency.decimals, "DECIMALS");
216
+ return super.divide(this.decimalScale).toFixed(decimalPlaces, format, rounding);
217
+ }
218
+ toExact(format = { groupSeparator: "" }) {
219
+ Big2.DP = this.currency.decimals;
220
+ return new Big2(this.quotient.toString()).div(this.decimalScale.toString()).toFormat(format);
221
+ }
222
+ get wrapped() {
223
+ if (this.currency.isToken)
224
+ return this;
225
+ return CurrencyAmount.fromFractionalAmount(this.currency.wrapped, this.numerator, this.denominator);
226
+ }
227
+ };
228
+
229
+ // src/fractions/price.ts
230
+ import JSBI5 from "jsbi";
231
+ import invariant4 from "tiny-invariant";
232
+ var Price = class extends Fraction {
233
+ constructor(...args) {
234
+ let baseCurrency;
235
+ let quoteCurrency;
236
+ let denominator;
237
+ let numerator;
238
+ if (args.length === 4) {
239
+ ;
240
+ [baseCurrency, quoteCurrency, denominator, numerator] = args;
241
+ } else {
242
+ const result = args[0].quoteAmount.divide(args[0].baseAmount);
243
+ [baseCurrency, quoteCurrency, denominator, numerator] = [
244
+ args[0].baseAmount.currency,
245
+ args[0].quoteAmount.currency,
246
+ result.denominator,
247
+ result.numerator
248
+ ];
249
+ }
250
+ super(numerator, denominator);
251
+ this.baseCurrency = baseCurrency;
252
+ this.quoteCurrency = quoteCurrency;
253
+ this.scalar = new Fraction(JSBI5.exponentiate(JSBI5.BigInt(10), JSBI5.BigInt(baseCurrency.decimals)), JSBI5.exponentiate(JSBI5.BigInt(10), JSBI5.BigInt(quoteCurrency.decimals)));
254
+ }
255
+ invert() {
256
+ return new Price(this.quoteCurrency, this.baseCurrency, this.numerator, this.denominator);
257
+ }
258
+ multiply(other) {
259
+ invariant4(this.quoteCurrency.equals(other.baseCurrency), "TOKEN");
260
+ const fraction = super.multiply(other);
261
+ return new Price(this.baseCurrency, other.quoteCurrency, fraction.denominator, fraction.numerator);
262
+ }
263
+ quote(currencyAmount) {
264
+ invariant4(currencyAmount.currency.equals(this.baseCurrency), "TOKEN");
265
+ const result = super.multiply(currencyAmount);
266
+ return CurrencyAmount.fromFractionalAmount(this.quoteCurrency, result.numerator, result.denominator);
267
+ }
268
+ get adjustedForDecimals() {
269
+ return super.multiply(this.scalar);
270
+ }
271
+ toSignificant(significantDigits = 6, format, rounding) {
272
+ return this.adjustedForDecimals.toSignificant(significantDigits, format, rounding);
273
+ }
274
+ toFixed(decimalPlaces = 4, format, rounding) {
275
+ return this.adjustedForDecimals.toFixed(decimalPlaces, format, rounding);
276
+ }
277
+ };
278
+
279
+ // src/nativeCurrency.ts
280
+ var NativeCurrency = class extends BaseCurrency {
281
+ constructor() {
282
+ super(...arguments);
283
+ this.isNative = true;
284
+ this.isToken = false;
285
+ }
286
+ };
287
+
288
+ // src/token.ts
289
+ import invariant5 from "tiny-invariant";
290
+ var Token = class extends BaseCurrency {
291
+ constructor(chainId, address, decimals, symbol, name, projectLink) {
292
+ super(chainId, decimals, symbol, name);
293
+ this.isNative = false;
294
+ this.isToken = true;
295
+ this.address = address;
296
+ this.projectLink = projectLink;
297
+ }
298
+ equals(other) {
299
+ return other.isToken && this.chainId === other.chainId && this.address === other.address;
300
+ }
301
+ sortsBefore(other) {
302
+ invariant5(this.chainId === other.chainId, "CHAIN_IDS");
303
+ invariant5(this.address !== other.address, "ADDRESSES");
304
+ return this.address.toLowerCase() < other.address.toLowerCase();
305
+ }
306
+ get wrapped() {
307
+ return this;
308
+ }
309
+ get serialize() {
310
+ return {
311
+ address: this.address,
312
+ chainId: this.chainId,
313
+ decimals: this.decimals,
314
+ symbol: this.symbol,
315
+ name: this.name,
316
+ projectLink: this.projectLink
317
+ };
318
+ }
319
+ };
320
+
321
+ // src/errors.ts
322
+ var CAN_SET_PROTOTYPE = "setPrototypeOf" in Object;
323
+ var InsufficientReservesError = class extends Error {
324
+ constructor() {
325
+ super();
326
+ this.isInsufficientReservesError = true;
327
+ this.name = this.constructor.name;
328
+ if (CAN_SET_PROTOTYPE)
329
+ Object.setPrototypeOf(this, new.target.prototype);
330
+ }
331
+ };
332
+ var InsufficientInputAmountError = class extends Error {
333
+ constructor() {
334
+ super();
335
+ this.isInsufficientInputAmountError = true;
336
+ this.name = this.constructor.name;
337
+ if (CAN_SET_PROTOTYPE)
338
+ Object.setPrototypeOf(this, new.target.prototype);
339
+ }
340
+ };
341
+
342
+ // src/utils.ts
343
+ import JSBI6 from "jsbi";
344
+ import invariant6 from "tiny-invariant";
345
+ function validateVMTypeInstance(value, vmType) {
346
+ invariant6(JSBI6.greaterThanOrEqual(value, ZERO), `${value} is not a ${vmType}.`);
347
+ invariant6(JSBI6.lessThanOrEqual(value, VM_TYPE_MAXIMA[vmType]), `${value} is not a ${vmType}.`);
348
+ }
349
+ function sqrt(y) {
350
+ validateVMTypeInstance(y, "uint256" /* uint256 */);
351
+ let z = ZERO;
352
+ let x;
353
+ if (JSBI6.greaterThan(y, THREE)) {
354
+ z = y;
355
+ x = JSBI6.add(JSBI6.divide(y, TWO), ONE);
356
+ while (JSBI6.lessThan(x, z)) {
357
+ z = x;
358
+ x = JSBI6.divide(JSBI6.add(JSBI6.divide(y, x), x), TWO);
359
+ }
360
+ } else if (JSBI6.notEqual(y, ZERO)) {
361
+ z = ONE;
362
+ }
363
+ return z;
364
+ }
365
+ function sortedInsert(items, add, maxSize, comparator) {
366
+ invariant6(maxSize > 0, "MAX_SIZE_ZERO");
367
+ invariant6(items.length <= maxSize, "ITEMS_SIZE");
368
+ if (items.length === 0) {
369
+ items.push(add);
370
+ return null;
371
+ } else {
372
+ const isFull = items.length === maxSize;
373
+ if (isFull && comparator(items[items.length - 1], add) <= 0) {
374
+ return add;
375
+ }
376
+ let lo = 0, hi = items.length;
377
+ while (lo < hi) {
378
+ const mid = lo + hi >>> 1;
379
+ if (comparator(items[mid], add) <= 0) {
380
+ lo = mid + 1;
381
+ } else {
382
+ hi = mid;
383
+ }
384
+ }
385
+ items.splice(lo, 0, add);
386
+ return isFull ? items.pop() : null;
387
+ }
388
+ }
389
+ function computePriceImpact(midPrice, inputAmount, outputAmount) {
390
+ const quotedOutputAmount = midPrice.quote(inputAmount);
391
+ const priceImpact = quotedOutputAmount.subtract(outputAmount).divide(quotedOutputAmount);
392
+ return new Percent(priceImpact.numerator, priceImpact.denominator);
393
+ }
394
+ export {
395
+ BaseCurrency,
396
+ CurrencyAmount,
397
+ FIVE,
398
+ Fraction,
399
+ InsufficientInputAmountError,
400
+ InsufficientReservesError,
401
+ JSBI7 as JSBI,
402
+ MINIMUM_LIQUIDITY,
403
+ MaxUint256,
404
+ NativeCurrency,
405
+ ONE,
406
+ Percent,
407
+ Price,
408
+ Rounding,
409
+ TEN,
410
+ THREE,
411
+ TWO,
412
+ Token,
413
+ TradeType,
414
+ VMType,
415
+ VM_TYPE_MAXIMA,
416
+ ZERO,
417
+ _100,
418
+ _10000,
419
+ _9975,
420
+ computePriceImpact,
421
+ sortedInsert,
422
+ sqrt,
423
+ validateVMTypeInstance
424
+ };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@pancakeswap/swap-sdk-core",
3
+ "license": "MIT",
4
+ "version": "0.0.1",
5
+ "description": "🛠 An SDK for building applications on top of Pancakeswap.",
6
+ "main": "dist/index.js",
7
+ "typings": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/pancakeswap/pancake-frontend.git",
14
+ "directory": "packages/swap-sdk"
15
+ },
16
+ "keywords": [
17
+ "pancakeswap"
18
+ ],
19
+ "module": "dist/index.mjs",
20
+ "scripts": {
21
+ "lint": "eslint src test",
22
+ "build": "tsup src/index.ts --format esm,cjs --dts",
23
+ "dev": "tsup src/index.ts --format esm,cjs --watch --dts",
24
+ "test": "jest",
25
+ "prepublishOnly": "yarn run build",
26
+ "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
27
+ },
28
+ "dependencies": {
29
+ "big.js": "^5.2.2",
30
+ "decimal.js-light": "^2.5.0",
31
+ "jsbi": "^3.1.4",
32
+ "tiny-invariant": "^1.1.0",
33
+ "tiny-warning": "^1.0.3",
34
+ "toformat": "^2.0.0"
35
+ },
36
+ "peerDependencies": {},
37
+ "devDependencies": {
38
+ "@swc/core": "^1.2.215",
39
+ "@swc/jest": "^0.2.21",
40
+ "@types/big.js": "^4.0.5",
41
+ "@types/jest": "^24.0.25",
42
+ "babel-plugin-transform-jsbi-to-bigint": "^1.3.1",
43
+ "tsup": "^5.10.1"
44
+ },
45
+ "engines": {
46
+ "node": ">=10"
47
+ },
48
+ "prettier": {
49
+ "printWidth": 120,
50
+ "semi": false,
51
+ "singleQuote": true
52
+ }
53
+ }