@swapkit/helpers 1.0.0-rc.11 → 1.0.0-rc.111

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.
Files changed (42) hide show
  1. package/dist/index.js +2900 -0
  2. package/dist/index.js.map +31 -0
  3. package/package.json +26 -37
  4. package/src/helpers/__tests__/asset.test.ts +186 -103
  5. package/src/helpers/__tests__/memo.test.ts +53 -41
  6. package/src/helpers/__tests__/others.test.ts +44 -37
  7. package/src/helpers/__tests__/validators.test.ts +24 -0
  8. package/src/helpers/asset.ts +184 -95
  9. package/src/helpers/derivationPath.ts +53 -0
  10. package/src/helpers/liquidity.ts +50 -43
  11. package/src/helpers/memo.ts +34 -31
  12. package/src/helpers/others.ts +46 -12
  13. package/src/helpers/validators.ts +15 -6
  14. package/src/helpers/web3wallets.ts +200 -0
  15. package/src/index.ts +14 -9
  16. package/src/modules/__tests__/assetValue.test.ts +486 -129
  17. package/src/modules/__tests__/bigIntArithmetics.test.ts +30 -0
  18. package/src/modules/__tests__/swapKitNumber.test.ts +306 -183
  19. package/src/modules/assetValue.ts +220 -162
  20. package/src/modules/bigIntArithmetics.ts +214 -165
  21. package/src/modules/requestClient.ts +38 -0
  22. package/src/modules/swapKitError.ts +41 -5
  23. package/src/modules/swapKitNumber.ts +1 -1
  24. package/src/types/abis/erc20.ts +99 -0
  25. package/src/types/abis/mayaEvmVaults.ts +331 -0
  26. package/src/types/abis/tcEthVault.ts +496 -0
  27. package/src/types/chains.ts +226 -0
  28. package/src/types/commonTypes.ts +123 -0
  29. package/src/types/derivationPath.ts +58 -0
  30. package/src/types/errors/apiV1.ts +0 -0
  31. package/src/types/index.ts +12 -0
  32. package/src/types/network.ts +45 -0
  33. package/src/types/quotes.ts +391 -0
  34. package/src/types/radix.ts +14 -0
  35. package/src/types/sdk.ts +126 -0
  36. package/src/types/tokens.ts +30 -0
  37. package/src/types/wallet.ts +72 -0
  38. package/LICENSE +0 -201
  39. package/dist/index.cjs +0 -1
  40. package/dist/index.d.ts +0 -356
  41. package/dist/index.es.js +0 -1071
  42. package/src/helpers/request.ts +0 -16
@@ -1,55 +1,99 @@
1
- import type { EVMChain } from '@swapkit/types';
2
- import { BaseDecimal, Chain, ChainToRPC, FeeOption } from '@swapkit/types';
1
+ import { AssetValue } from "../modules/assetValue.ts";
2
+ import { RequestClient } from "../modules/requestClient.ts";
3
+ import { BaseDecimal, Chain, ChainToRPC, type EVMChain, EVMChains } from "../types/chains.ts";
4
+ import type { RadixCoreStateResourceDTO } from "../types/radix.ts";
5
+ import type { TokenNames } from "../types/tokens.ts";
3
6
 
4
- import { type AssetValue, RequestClient } from '../index.ts';
7
+ const getDecimalMethodHex = "0x313ce567";
5
8
 
6
- const getDecimalMethodHex = '0x313ce567';
7
-
8
- export type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
9
+ export type CommonAssetString =
10
+ | `${Chain.Maya}.MAYA`
11
+ | `${Chain.Ethereum}.THOR`
12
+ | `${Chain.Ethereum}.vTHOR`
13
+ | `${Chain.Kujira}.USK`
14
+ | Chain;
9
15
 
10
16
  const getContractDecimals = async ({ chain, to }: { chain: EVMChain; to: string }) => {
11
17
  try {
12
18
  const { result } = await RequestClient.post<{ result: string }>(ChainToRPC[chain], {
13
- headers: { accept: '*/*', 'cache-control': 'no-cache' },
19
+ headers: {
20
+ accept: "*/*",
21
+ "content-type": "application/json",
22
+ "cache-control": "no-cache",
23
+ },
14
24
  body: JSON.stringify({
15
25
  id: 44,
16
- jsonrpc: '2.0',
17
- method: 'eth_call',
18
- params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, 'latest'],
26
+ jsonrpc: "2.0",
27
+ method: "eth_call",
28
+ params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, "latest"],
19
29
  }),
20
30
  });
21
31
 
22
- return parseInt(BigInt(result).toString());
32
+ return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString());
23
33
  } catch (error) {
24
34
  console.error(error);
25
35
  return BaseDecimal[chain];
26
36
  }
27
37
  };
28
38
 
29
- const getETHAssetDecimal = async (symbol: string) => {
39
+ const getRadixResourceDecimals = async ({ symbol }: { symbol: string }) => {
40
+ try {
41
+ const resourceAddress = symbol.split("-")[1]?.toLowerCase();
42
+
43
+ const { manager } = await RequestClient.post<RadixCoreStateResourceDTO>(
44
+ `${ChainToRPC[Chain.Radix]}/state/resource`,
45
+ {
46
+ headers: {
47
+ Accept: "*/*",
48
+ "Content-Type": "application/json",
49
+ },
50
+ body: JSON.stringify({
51
+ network: "mainnet",
52
+ resource_address: resourceAddress,
53
+ }),
54
+ },
55
+ );
56
+
57
+ return manager.divisibility.value.divisibility;
58
+ } catch (error) {
59
+ console.error(error);
60
+ return BaseDecimal[Chain.Radix];
61
+ }
62
+ };
63
+
64
+ const getETHAssetDecimal = (symbol: string) => {
30
65
  if (symbol === Chain.Ethereum) return BaseDecimal.ETH;
31
- const [, address] = symbol.split('-');
66
+ const splitSymbol = symbol.split("-");
67
+ const address =
68
+ splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1]?.toLowerCase();
32
69
 
33
- return address?.startsWith('0x')
70
+ return address?.startsWith("0x")
34
71
  ? getContractDecimals({ chain: Chain.Ethereum, to: address })
35
72
  : BaseDecimal.ETH;
36
73
  };
37
74
 
38
- const getAVAXAssetDecimal = async (symbol: string) => {
39
- const [, address] = symbol.split('-');
75
+ const getAVAXAssetDecimal = (symbol: string) => {
76
+ const splitSymbol = symbol.split("-");
77
+ const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
40
78
 
41
- return address?.startsWith('0x')
79
+ return address?.startsWith("0x")
42
80
  ? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() })
43
81
  : BaseDecimal.AVAX;
44
82
  };
45
83
 
46
- const getBSCAssetDecimal = async (symbol: string) => {
84
+ const getBSCAssetDecimal = (symbol: string) => {
47
85
  if (symbol === Chain.BinanceSmartChain) return BaseDecimal.BSC;
48
86
 
49
87
  return BaseDecimal.BSC;
50
88
  };
51
89
 
52
- export const getDecimal = async ({ chain, symbol }: { chain: Chain; symbol: string }) => {
90
+ const getRadixAssetDecimal = (symbol: string) => {
91
+ if (symbol === Chain.Radix) return BaseDecimal.XRD;
92
+
93
+ return getRadixResourceDecimals({ symbol });
94
+ };
95
+
96
+ export const getDecimal = ({ chain, symbol }: { chain: Chain; symbol: string }) => {
53
97
  switch (chain) {
54
98
  case Chain.Ethereum:
55
99
  return getETHAssetDecimal(symbol);
@@ -57,46 +101,48 @@ export const getDecimal = async ({ chain, symbol }: { chain: Chain; symbol: stri
57
101
  return getAVAXAssetDecimal(symbol);
58
102
  case Chain.BinanceSmartChain:
59
103
  return getBSCAssetDecimal(symbol);
104
+ case Chain.Radix:
105
+ return getRadixAssetDecimal(symbol);
60
106
  default:
61
107
  return BaseDecimal[chain];
62
108
  }
63
109
  };
64
110
 
65
- export const gasFeeMultiplier: Record<FeeOption, number> = {
66
- [FeeOption.Average]: 1.2,
67
- [FeeOption.Fast]: 1.5,
68
- [FeeOption.Fastest]: 2,
111
+ export const getGasAsset = ({ chain }: { chain: Chain }) => {
112
+ switch (chain) {
113
+ case Chain.Arbitrum:
114
+ case Chain.Optimism:
115
+ return AssetValue.fromStringSync(`${chain}.ETH`);
116
+ case Chain.Maya:
117
+ return AssetValue.fromStringSync(`${chain}.CACAO`);
118
+ case Chain.Cosmos:
119
+ return AssetValue.fromStringSync(`${chain}.ATOM`);
120
+ case Chain.BinanceSmartChain:
121
+ return AssetValue.fromStringSync(`${chain}.BNB`);
122
+ case Chain.THORChain:
123
+ return AssetValue.fromStringSync(`${chain}.RUNE`);
124
+
125
+ default:
126
+ return AssetValue.fromStringSync(`${chain}.${chain}`);
127
+ }
69
128
  };
70
129
 
71
130
  export const isGasAsset = ({ chain, symbol }: { chain: Chain; symbol: string }) => {
72
131
  switch (chain) {
73
- case Chain.Bitcoin:
74
- case Chain.BitcoinCash:
75
- case Chain.Litecoin:
76
- case Chain.Dogecoin:
77
- case Chain.Binance:
78
- case Chain.Ethereum:
79
- case Chain.Avalanche:
80
- return symbol === chain;
81
-
82
132
  case Chain.Arbitrum:
83
133
  case Chain.Optimism:
84
- return 'ETH' === symbol;
85
-
134
+ return symbol === "ETH";
86
135
  case Chain.Maya:
87
- return symbol === 'CACAO';
88
-
89
- case Chain.Kujira:
90
- return symbol === 'KUJI';
91
-
136
+ return symbol === "CACAO";
92
137
  case Chain.Cosmos:
93
- return symbol === 'ATOM';
94
- case Chain.Polygon:
95
- return symbol === 'MATIC';
138
+ return symbol === "ATOM";
96
139
  case Chain.BinanceSmartChain:
97
- return symbol === 'BNB';
140
+ return symbol === "BNB";
98
141
  case Chain.THORChain:
99
- return symbol === 'RUNE';
142
+ return symbol === "RUNE";
143
+
144
+ default:
145
+ return symbol === chain;
100
146
  }
101
147
  };
102
148
 
@@ -104,86 +150,129 @@ export const getCommonAssetInfo = (
104
150
  assetString: CommonAssetString,
105
151
  ): { identifier: string; decimal: number } => {
106
152
  switch (assetString) {
107
- case 'ETH.THOR':
108
- return { identifier: 'ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044', decimal: 18 };
109
- case 'ETH.vTHOR':
110
- return { identifier: 'ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d', decimal: 18 };
111
-
153
+ case `${Chain.Ethereum}.THOR`:
154
+ return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
155
+ case `${Chain.Ethereum}.vTHOR`:
156
+ return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
157
+ case Chain.Arbitrum:
158
+ return { identifier: `${Chain.Arbitrum}.ETH`, decimal: BaseDecimal[assetString] };
159
+ case Chain.Optimism:
160
+ return { identifier: `${Chain.Optimism}.ETH`, decimal: BaseDecimal[assetString] };
112
161
  case Chain.Cosmos:
113
- return { identifier: 'GAIA.ATOM', decimal: BaseDecimal[assetString] };
162
+ return { identifier: "GAIA.ATOM", decimal: BaseDecimal[assetString] };
114
163
  case Chain.THORChain:
115
- return { identifier: 'THOR.RUNE', decimal: BaseDecimal[assetString] };
164
+ return { identifier: "THOR.RUNE", decimal: BaseDecimal[assetString] };
116
165
  case Chain.BinanceSmartChain:
117
- return { identifier: 'BSC.BNB', decimal: BaseDecimal[assetString] };
166
+ return { identifier: "BSC.BNB", decimal: BaseDecimal[assetString] };
118
167
  case Chain.Maya:
119
- return { identifier: 'MAYA.CACAO', decimal: BaseDecimal.MAYA };
120
- case 'MAYA.MAYA':
121
- return { identifier: 'MAYA.MAYA', decimal: 4 };
168
+ return { identifier: "MAYA.CACAO", decimal: BaseDecimal.MAYA };
169
+ case `${Chain.Maya}.MAYA`:
170
+ return { identifier: "MAYA.MAYA", decimal: 4 };
171
+ case `${Chain.Kujira}.USK`:
172
+ return { identifier: `${Chain.Kujira}.USK`, decimal: 6 };
173
+ case Chain.Radix:
174
+ return { identifier: `${Chain.Radix}.XRD`, decimal: BaseDecimal.XRD };
122
175
 
123
- case Chain.Kujira:
124
- case Chain.Arbitrum:
125
- case Chain.Optimism:
126
- case Chain.BitcoinCash:
127
- case Chain.Litecoin:
128
- case Chain.Dogecoin:
129
- case Chain.Binance:
130
- case Chain.Avalanche:
131
- case Chain.Polygon:
132
- case Chain.Bitcoin:
133
- case Chain.Ethereum:
176
+ default:
134
177
  return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] };
135
178
  }
136
179
  };
137
180
 
181
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor
138
182
  export const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }) => {
139
- if (symbol.includes('/')) return 'Synth';
183
+ if (symbol.includes("/")) return "Synth";
140
184
 
141
185
  switch (chain) {
142
- case Chain.Bitcoin:
143
- case Chain.BitcoinCash:
144
- case Chain.Dogecoin:
145
- case Chain.Litecoin:
146
- case Chain.Maya:
147
- case Chain.THORChain:
148
- return 'Native';
149
-
150
186
  case Chain.Cosmos:
151
- return symbol === 'ATOM' ? 'Native' : Chain.Cosmos;
187
+ return symbol === "ATOM" ? "Native" : Chain.Cosmos;
152
188
  case Chain.Kujira:
153
- return symbol === Chain.Kujira ? 'Native' : Chain.Kujira;
189
+ return symbol === Chain.Kujira ? "Native" : Chain.Kujira;
154
190
  case Chain.Binance:
155
- return symbol === Chain.Binance ? 'Native' : 'BEP2';
191
+ return symbol === Chain.Binance ? "Native" : "BEP2";
156
192
  case Chain.BinanceSmartChain:
157
- return symbol === Chain.Binance ? 'Native' : 'BEP20';
193
+ return symbol === Chain.Binance ? "Native" : "BEP20";
158
194
  case Chain.Ethereum:
159
- return symbol === Chain.Ethereum ? 'Native' : 'ERC20';
195
+ return symbol === Chain.Ethereum ? "Native" : "ERC20";
160
196
  case Chain.Avalanche:
161
- return symbol === Chain.Avalanche ? 'Native' : Chain.Avalanche;
197
+ return symbol === Chain.Avalanche ? "Native" : Chain.Avalanche;
162
198
  case Chain.Polygon:
163
- return symbol === Chain.Polygon ? 'Native' : 'POLYGON';
164
-
199
+ return symbol === Chain.Polygon ? "Native" : "POLYGON";
165
200
  case Chain.Arbitrum:
166
- return [Chain.Ethereum, Chain.Arbitrum].includes(symbol as Chain) ? 'Native' : 'ARBITRUM';
201
+ return [Chain.Ethereum, Chain.Arbitrum].includes(symbol as Chain) ? "Native" : "ARBITRUM";
167
202
  case Chain.Optimism:
168
- return [Chain.Ethereum, Chain.Optimism].includes(symbol as Chain) ? 'Native' : 'OPTIMISM';
203
+ return [Chain.Ethereum, Chain.Optimism].includes(symbol as Chain) ? "Native" : "OPTIMISM";
204
+ case Chain.Radix:
205
+ return symbol === Chain.Radix ? "Native" : "RADIX";
206
+
207
+ default:
208
+ return "Native";
169
209
  }
170
210
  };
171
211
 
172
212
  export const assetFromString = (assetString: string) => {
173
- const [chain, ...symbolArray] = assetString.split('.') as [Chain, ...(string | undefined)[]];
174
- const synth = assetString.includes('/');
175
- const symbol = symbolArray.join('.');
176
- const ticker = symbol?.split('-')?.[0];
213
+ const [chain, ...symbolArray] = assetString.split(".") as [Chain, ...(string | undefined)[]];
214
+ const synth = assetString.includes("/");
215
+ const symbol = symbolArray.join(".");
216
+ const splitSymbol = symbol?.split("-");
217
+ const ticker = splitSymbol?.length
218
+ ? splitSymbol.length === 1
219
+ ? splitSymbol[0]
220
+ : splitSymbol.slice(0, -1).join("-")
221
+ : undefined;
177
222
 
178
223
  return { chain, symbol, ticker, synth };
179
224
  };
180
225
 
181
226
  const potentialScamRegex = new RegExp(
182
227
  /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
183
- 'gmi',
228
+ "gmi",
184
229
  );
185
- export const filterAssets = (assets: AssetValue[]) =>
186
- assets.filter(
187
- (asset) =>
188
- !potentialScamRegex.test(asset.toString()) && !asset.toString().includes('undefined'),
189
- );
230
+
231
+ const evmAssetHasAddress = (assetString: string) => {
232
+ const [chain, symbol] = assetString.split(".") as [EVMChain, string];
233
+ if (!EVMChains.includes(chain as EVMChain)) return true;
234
+ const splitSymbol = symbol.split("-");
235
+ const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
236
+
237
+ return isGasAsset({ chain: chain as Chain, symbol }) || !!address;
238
+ };
239
+
240
+ export const filterAssets = (
241
+ tokens: {
242
+ value: string;
243
+ decimal: number;
244
+ chain: Chain;
245
+ symbol: string;
246
+ }[],
247
+ ) =>
248
+ tokens.filter(({ chain, value, symbol }) => {
249
+ const assetString = `${chain}.${symbol}`;
250
+
251
+ return (
252
+ !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== "0"
253
+ );
254
+ });
255
+
256
+ export async function findAssetBy(
257
+ params: { chain: EVMChain; contract: string } | { identifier: `${Chain}.${string}` },
258
+ ) {
259
+ const tokenPackages = await import("@swapkit/tokens");
260
+
261
+ for (const tokenList of Object.values(tokenPackages)) {
262
+ for (const { identifier, chain: tokenChain, ...rest } of tokenList.tokens) {
263
+ if ("identifier" in params && identifier === params.identifier) {
264
+ return identifier as TokenNames;
265
+ }
266
+
267
+ if (
268
+ "address" in rest &&
269
+ "chain" in params &&
270
+ tokenChain === params.chain &&
271
+ rest.address.toLowerCase() === params.contract.toLowerCase()
272
+ )
273
+ return identifier as TokenNames;
274
+ }
275
+ }
276
+
277
+ return;
278
+ }
@@ -0,0 +1,53 @@
1
+ import {
2
+ Chain,
3
+ type DerivationPathArray,
4
+ type EVMChain,
5
+ EVMChains,
6
+ NetworkDerivationPath,
7
+ } from "../types";
8
+
9
+ type Params = {
10
+ chain: Chain;
11
+ index: number;
12
+ addressIndex?: number;
13
+ type?: "legacy" | "ledgerLive" | "nativeSegwitMiddleAccount" | "segwit";
14
+ };
15
+
16
+ const updatedLastIndex = (path: DerivationPathArray, index: number) => [
17
+ ...path.slice(0, path.length - 1),
18
+ index,
19
+ ];
20
+
21
+ export function getDerivationPathFor({ chain, index, addressIndex = 0, type }: Params) {
22
+ if (EVMChains.includes(chain as EVMChain)) {
23
+ if (type === "legacy") return [44, 60, 0, index];
24
+ if (type === "ledgerLive") return [44, 60, index, 0, addressIndex];
25
+ return updatedLastIndex(NetworkDerivationPath[chain], index);
26
+ }
27
+
28
+ if ([Chain.Bitcoin, Chain.Litecoin].includes(chain)) {
29
+ const chainId = chain === Chain.Bitcoin ? 0 : 2;
30
+
31
+ if (type === "nativeSegwitMiddleAccount") return [84, chainId, index, 0, addressIndex];
32
+ if (type === "segwit") return [49, chainId, 0, 0, index];
33
+ if (type === "legacy") return [44, chainId, 0, 0, index];
34
+ return updatedLastIndex(NetworkDerivationPath[chain], index);
35
+ }
36
+
37
+ return updatedLastIndex(NetworkDerivationPath[chain], index);
38
+ }
39
+
40
+ export function getWalletFormatFor(path: string) {
41
+ const [_, purpose, chainId] = path.split("/").map((p) => Number.parseInt(p, 10));
42
+
43
+ if (chainId === 145) "cashaddr";
44
+
45
+ switch (purpose) {
46
+ case 44:
47
+ return "legacy";
48
+ case 49:
49
+ return "p2sh";
50
+ default:
51
+ return "bech32";
52
+ }
53
+ }
@@ -1,13 +1,12 @@
1
- import { BaseDecimal } from '@swapkit/types';
1
+ import { SwapKitNumber } from "../index.ts";
2
+ import { BaseDecimal } from "../types/chains.ts";
2
3
 
3
- import { SwapKitNumber } from '../index.ts';
4
-
5
- type ShareParams<T = {}> = T & {
4
+ type ShareParams<T extends {}> = T & {
6
5
  liquidityUnits: string;
7
6
  poolUnits: string;
8
7
  };
9
8
 
10
- type PoolParams<T = {}> = T & {
9
+ type PoolParams = {
11
10
  runeAmount: string;
12
11
  assetAmount: string;
13
12
  runeDepth: string;
@@ -25,11 +24,11 @@ type PoolParams<T = {}> = T & {
25
24
  * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3
26
25
  * (part1 * (part2 - part3 + part4)) / part5
27
26
  */
28
- export const getAsymmetricRuneShare = ({
27
+ export function getAsymmetricRuneShare({
29
28
  liquidityUnits,
30
29
  poolUnits,
31
30
  runeDepth,
32
- }: ShareParams<{ runeDepth: string }>) => {
31
+ }: ShareParams<{ runeDepth: string }>) {
33
32
  const s = toTCSwapKitNumber(liquidityUnits);
34
33
  const T = toTCSwapKitNumber(poolUnits);
35
34
  const A = toTCSwapKitNumber(runeDepth);
@@ -43,13 +42,13 @@ export const getAsymmetricRuneShare = ({
43
42
  const numerator = part1.mul(part2.sub(part3).add(part4));
44
43
 
45
44
  return numerator.div(part5);
46
- };
45
+ }
47
46
 
48
- export const getAsymmetricAssetShare = ({
47
+ export function getAsymmetricAssetShare({
49
48
  liquidityUnits,
50
49
  poolUnits,
51
50
  assetDepth,
52
- }: ShareParams<{ assetDepth: string }>) => {
51
+ }: ShareParams<{ assetDepth: string }>) {
53
52
  const s = toTCSwapKitNumber(liquidityUnits);
54
53
  const T = toTCSwapKitNumber(poolUnits);
55
54
  const A = toTCSwapKitNumber(assetDepth);
@@ -62,28 +61,31 @@ export const getAsymmetricAssetShare = ({
62
61
  const part5 = T.mul(T).mul(T);
63
62
 
64
63
  return numerator.div(part5);
65
- };
64
+ }
66
65
 
67
- export const getAsymmetricRuneWithdrawAmount = ({
66
+ export function getAsymmetricRuneWithdrawAmount({
68
67
  percent,
69
68
  runeDepth,
70
69
  liquidityUnits,
71
70
  poolUnits,
72
- }: ShareParams<{ percent: number; runeDepth: string }>) =>
73
- getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);
71
+ }: ShareParams<{ percent: number; runeDepth: string }>) {
72
+ return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);
73
+ }
74
74
 
75
- export const getAsymmetricAssetWithdrawAmount = ({
75
+ export function getAsymmetricAssetWithdrawAmount({
76
76
  percent,
77
77
  assetDepth,
78
78
  liquidityUnits,
79
79
  poolUnits,
80
- }: ShareParams<{ percent: number; assetDepth: string }>) =>
81
- getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
80
+ }: ShareParams<{ percent: number; assetDepth: string }>) {
81
+ return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
82
+ }
82
83
 
83
- const toTCSwapKitNumber = (value: string) =>
84
- new SwapKitNumber({ value, decimal: BaseDecimal.THOR });
84
+ function toTCSwapKitNumber(value: string) {
85
+ return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);
86
+ }
85
87
 
86
- export const getSymmetricPoolShare = ({
88
+ export function getSymmetricPoolShare({
87
89
  liquidityUnits,
88
90
  poolUnits,
89
91
  runeDepth,
@@ -91,12 +93,14 @@ export const getSymmetricPoolShare = ({
91
93
  }: ShareParams<{
92
94
  runeDepth: string;
93
95
  assetDepth: string;
94
- }>) => ({
95
- assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
96
- runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits),
97
- });
98
-
99
- export const getSymmetricWithdraw = ({
96
+ }>) {
97
+ return {
98
+ assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
99
+ runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits),
100
+ };
101
+ }
102
+
103
+ export function getSymmetricWithdraw({
100
104
  liquidityUnits,
101
105
  poolUnits,
102
106
  runeDepth,
@@ -106,14 +110,15 @@ export const getSymmetricWithdraw = ({
106
110
  runeDepth: string;
107
111
  assetDepth: string;
108
112
  percent: number;
109
- }>) =>
110
- Object.fromEntries(
113
+ }>) {
114
+ return Object.fromEntries(
111
115
  Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(
112
116
  ([name, value]) => [name, value.mul(percent)],
113
117
  ),
114
118
  );
119
+ }
115
120
 
116
- export const getEstimatedPoolShare = ({
121
+ export function getEstimatedPoolShare({
117
122
  runeDepth,
118
123
  poolUnits,
119
124
  assetDepth,
@@ -125,12 +130,12 @@ export const getEstimatedPoolShare = ({
125
130
  assetAmount: string;
126
131
  runeDepth: string;
127
132
  assetDepth: string;
128
- }>) => {
129
- const R = toTCSwapKitNumber(runeDepth);
130
- const A = toTCSwapKitNumber(assetDepth);
131
- const P = toTCSwapKitNumber(poolUnits);
132
- const runeAddAmount = toTCSwapKitNumber(runeAmount);
133
- const assetAddAmount = toTCSwapKitNumber(assetAmount);
133
+ }>) {
134
+ const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });
135
+ const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });
136
+ const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });
137
+ const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });
138
+ const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });
134
139
 
135
140
  // liquidityUnits = P * (r*A + a*R + 2*r*a) / (r*A + a*R + 2*R*A)
136
141
  const rA = runeAddAmount.mul(A);
@@ -142,22 +147,24 @@ export const getEstimatedPoolShare = ({
142
147
  const liquidityUnitsAfterAdd = numerator.div(denominator);
143
148
  const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
144
149
 
145
- if (liquidityUnitsAfterAdd.baseValueNumber === 0) {
146
- return estimatedLiquidityUnits.div(P).baseValueNumber;
150
+ if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) {
151
+ return estimatedLiquidityUnits.div(P).getBaseValue("number");
147
152
  }
148
153
 
149
154
  // get pool units after add
150
155
  const newPoolUnits = P.add(estimatedLiquidityUnits);
151
156
 
152
- return estimatedLiquidityUnits.div(newPoolUnits).baseValueNumber;
153
- };
157
+ return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number");
158
+ }
154
159
 
155
- export const getLiquiditySlippage = ({
160
+ export function getLiquiditySlippage({
156
161
  runeAmount,
157
162
  assetAmount,
158
163
  runeDepth,
159
164
  assetDepth,
160
- }: PoolParams) => {
165
+ }: PoolParams) {
166
+ if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0")
167
+ return 0;
161
168
  // formula: (t * R - T * r)/ (T*r + R*T)
162
169
  const R = toTCSwapKitNumber(runeDepth);
163
170
  const T = toTCSwapKitNumber(assetDepth);
@@ -168,5 +175,5 @@ export const getLiquiditySlippage = ({
168
175
  const denominator = T.mul(runeAddAmount).add(R.mul(T));
169
176
 
170
177
  // set absolute value of percent, no negative allowed
171
- return Math.abs(numerator.div(denominator).baseValueNumber);
172
- };
178
+ return Math.abs(numerator.div(denominator).getBaseValue("number"));
179
+ }