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

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 +2897 -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 +453 -120
  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 +217 -163
  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,7 +1,7 @@
1
- import type { Chain } from '@swapkit/types';
2
- import { MemoType } from '@swapkit/types';
1
+ import { Chain } from "../types/chains";
2
+ import { MemoType } from "../types/sdk";
3
3
 
4
- export type ThornameRegisterParam = {
4
+ export type NameRegisterParam = {
5
5
  name: string;
6
6
  chain: string;
7
7
  address: string;
@@ -10,25 +10,14 @@ export type ThornameRegisterParam = {
10
10
  expiryBlock?: string;
11
11
  };
12
12
 
13
- const getShortenedSymbol = ({
14
- symbol,
15
- ticker,
16
- chain,
17
- }: {
18
- ticker: string;
19
- symbol: string;
20
- chain: string | Chain;
21
- }) => (chain === 'ETH' && ticker !== 'ETH' ? `${ticker}-${symbol.slice(-3)}` : symbol);
22
-
23
- type WithAddress<T = {}> = T & { address: string };
24
- type WithChain<T = {}> = T & { chain: Chain };
13
+ type WithChain<T extends {}> = T & { chain: Chain };
25
14
 
26
15
  export type MemoOptions<T extends MemoType> = {
27
- [MemoType.BOND]: WithAddress;
28
- [MemoType.LEAVE]: WithAddress;
29
- [MemoType.CLOSE_LOAN]: WithAddress<{ asset: string; minAmount?: string }>;
30
- [MemoType.OPEN_LOAN]: WithAddress<{ asset: string; minAmount?: string }>;
31
- [MemoType.UNBOND]: WithAddress<{ unbondAmount: number }>;
16
+ [MemoType.BOND]: { address: string };
17
+ [MemoType.LEAVE]: { address: string };
18
+ [MemoType.CLOSE_LOAN]: { address: string; asset: string; minAmount?: string };
19
+ [MemoType.OPEN_LOAN]: { address: string; asset: string; minAmount?: string };
20
+ [MemoType.UNBOND]: { address: string; unbondAmount: number };
32
21
  [MemoType.DEPOSIT]: WithChain<{ symbol: string; address?: string; singleSide?: boolean }>;
33
22
  [MemoType.WITHDRAW]: WithChain<{
34
23
  ticker: string;
@@ -37,7 +26,7 @@ export type MemoOptions<T extends MemoType> = {
37
26
  targetAssetString?: string;
38
27
  singleSide?: boolean;
39
28
  }>;
40
- [MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>;
29
+ [MemoType.NAME_REGISTER]: Omit<NameRegisterParam, "preferredAsset" | "expiryBlock">;
41
30
  }[T];
42
31
 
43
32
  export const getMemoFor = <T extends MemoType>(memoType: T, options: MemoOptions<T>) => {
@@ -50,29 +39,43 @@ export const getMemoFor = <T extends MemoType>(memoType: T, options: MemoOptions
50
39
 
51
40
  case MemoType.UNBOND: {
52
41
  const { address, unbondAmount } = options as MemoOptions<MemoType.UNBOND>;
53
- return `${memoType}:${address}:${unbondAmount * 10 ** 8}`;
42
+ return `${memoType}:${address}:${unbondAmount}`;
54
43
  }
55
44
 
56
- case MemoType.THORNAME_REGISTER: {
57
- const { name, chain, address, owner } = options as MemoOptions<MemoType.THORNAME_REGISTER>;
58
- return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ''}`;
45
+ case MemoType.NAME_REGISTER: {
46
+ const { name, chain, address, owner } = options as MemoOptions<MemoType.NAME_REGISTER>;
47
+ return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ""}`;
59
48
  }
60
49
 
61
50
  case MemoType.DEPOSIT: {
62
51
  const { chain, symbol, address, singleSide } = options as MemoOptions<MemoType.DEPOSIT>;
63
52
 
53
+ const getPoolIdentifier = (chain: Chain, symbol: string): string => {
54
+ switch (chain) {
55
+ case Chain.Litecoin:
56
+ return "l";
57
+ case Chain.Dogecoin:
58
+ return "d";
59
+ case Chain.BitcoinCash:
60
+ return "c";
61
+ default:
62
+ return `${chain}.${symbol}`;
63
+ }
64
+ };
65
+
64
66
  return singleSide
65
- ? `${memoType}:${chain}/${symbol}::t:0`
66
- : `${memoType}:${chain}.${symbol}:${address || ''}:t:0`;
67
+ ? `${memoType}:${chain}/${symbol}`
68
+ : `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ""}`;
67
69
  }
68
70
 
69
71
  case MemoType.WITHDRAW: {
70
72
  const { chain, ticker, symbol, basisPoints, targetAssetString, singleSide } =
71
73
  options as MemoOptions<MemoType.WITHDRAW>;
72
74
 
73
- const target = !singleSide && targetAssetString ? `:${targetAssetString}` : '';
74
- const shortenedSymbol = getShortenedSymbol({ chain, symbol, ticker });
75
- const assetDivider = singleSide ? '/' : '.';
75
+ const shortenedSymbol =
76
+ chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol;
77
+ const target = !singleSide && targetAssetString ? `:${targetAssetString}` : "";
78
+ const assetDivider = singleSide ? "/" : ".";
76
79
 
77
80
  return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`;
78
81
  }
@@ -85,6 +88,6 @@ export const getMemoFor = <T extends MemoType>(memoType: T, options: MemoOptions
85
88
  }
86
89
 
87
90
  default:
88
- return '';
91
+ return "";
89
92
  }
90
93
  };
@@ -1,20 +1,54 @@
1
+ import { type ErrorKeys, SwapKitError } from "../modules/swapKitError";
2
+ import { Chain } from "../types";
3
+ import type { DerivationPathArray } from "../types/derivationPath";
4
+
1
5
  // 10 rune for register, 1 rune per year
2
6
  // MINIMUM_REGISTRATION_FEE = 11
3
- export const getTHORNameCost = (year: number) => {
4
- if (year < 0) throw new Error('Invalid number of year');
5
- return 10 + year;
6
- };
7
+ export function getTHORNameCost(numberOfYears: number) {
8
+ if (numberOfYears < 0) throw new Error("Invalid number of years");
9
+ return 10 + numberOfYears;
10
+ }
7
11
 
8
- export const validateTHORName = (name: string) => {
9
- if (name.length > 30) return false;
12
+ // 10 CACAO for register
13
+ // 1.0512 CACAO per year
14
+ export function getMAYANameCost(numberOfYears: number) {
15
+ if (numberOfYears < 0) throw new Error("Invalid number of year");
16
+ // round to max 10 decimals
17
+ return Math.round((10 + numberOfYears * 1.0512) * 1e10) / 1e10;
18
+ }
10
19
 
11
- const regex = /^[a-zA-Z0-9+_-]+$/g;
20
+ export function derivationPathToString([network, chainId, account, change, index]:
21
+ | [number, number, number, number, number | undefined]
22
+ | DerivationPathArray) {
23
+ const shortPath = typeof index !== "number";
12
24
 
13
- return !!name.match(regex);
14
- };
25
+ return `m/${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
26
+ }
27
+
28
+ export function wrapWithThrow<T>(fn: () => T, errorKey?: ErrorKeys) {
29
+ try {
30
+ return fn();
31
+ } catch (error) {
32
+ if (errorKey) {
33
+ throw new SwapKitError(errorKey, error);
34
+ }
35
+
36
+ return console.error(error);
37
+ }
38
+ }
39
+
40
+ export const getChainIdentifier = (chain: Chain) => {
41
+ switch (chain) {
42
+ case Chain.THORChain:
43
+ return `${chain}.RUNE`;
44
+
45
+ case Chain.Cosmos:
46
+ return `${chain}.ATOM`;
15
47
 
16
- export const derivationPathToString = ([network, chainId, account, change, index]: number[]) => {
17
- const shortPath = typeof index !== 'number';
48
+ case Chain.BinanceSmartChain:
49
+ return `${chain}`;
18
50
 
19
- return `${network}'/${chainId}'/${account}'/${change}${shortPath ? '' : `/${index}`}`;
51
+ default:
52
+ return `${chain}.${chain}`;
53
+ }
20
54
  };
@@ -1,17 +1,26 @@
1
- import { Chain } from '@swapkit/types';
1
+ import { Chain } from "../types/chains";
2
2
 
3
- const supportedChains = Object.values(Chain);
3
+ // Backward compatibility
4
+ const supportedChains = [...Object.values(Chain), "TERRA"];
4
5
 
5
- export const validateIdentifier = (identifier: string = '') => {
6
+ export function validateIdentifier(identifier = "") {
6
7
  const uppercasedIdentifier = identifier.toUpperCase();
7
8
 
8
- const [chain] = uppercasedIdentifier.split('.') as [Chain, string];
9
+ const [chain] = uppercasedIdentifier.split(".") as [Chain, string];
9
10
  if (supportedChains.includes(chain)) return true;
10
11
 
11
- const [synthChain] = uppercasedIdentifier.split('/') as [Chain, string];
12
+ const [synthChain] = uppercasedIdentifier.split("/") as [Chain, string];
12
13
  if (supportedChains.includes(synthChain)) return true;
13
14
 
14
15
  throw new Error(
15
16
  `Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`,
16
17
  );
17
- };
18
+ }
19
+
20
+ export function validateTNS(name: string) {
21
+ if (name.length > 30) return false;
22
+
23
+ const regex = /^[a-zA-Z0-9+_-]+$/g;
24
+
25
+ return !!name.match(regex);
26
+ }
@@ -0,0 +1,200 @@
1
+ import type { BrowserProvider } from "ethers";
2
+ import {
3
+ ChainId,
4
+ type EIP6963AnnounceProviderEvent,
5
+ type EIP6963Provider,
6
+ WalletOption,
7
+ } from "../types";
8
+
9
+ export type EthereumWindowProvider = BrowserProvider & {
10
+ __XDEFI?: boolean;
11
+ isBraveWallet?: boolean;
12
+ isCoinbaseWallet?: boolean;
13
+ isMetaMask?: boolean;
14
+ isOkxWallet?: boolean;
15
+ isTrust?: boolean;
16
+ on: (event: string, callback?: () => void) => void;
17
+ overrideIsMetaMask?: boolean;
18
+ request: <T = unknown>(args: { method: string; params?: unknown[] }) => Promise<T>;
19
+ selectedProvider?: EthereumWindowProvider;
20
+ };
21
+
22
+ declare const window: {
23
+ ethereum: EthereumWindowProvider;
24
+ trustwallet: EthereumWindowProvider;
25
+ coinbaseWalletExtension: EthereumWindowProvider;
26
+ braveSolana: Todo;
27
+ } & Window;
28
+
29
+ // declare global {
30
+ // interface Window {
31
+ // ethereum: EthereumWindowProvider;
32
+ // trustwallet: EthereumWindowProvider;
33
+ // coinbaseWalletExtension: EthereumWindowProvider;
34
+ // braveSolana: Todo;
35
+ // }
36
+ // }
37
+
38
+ type NetworkParams = {
39
+ chainId: ChainId;
40
+ chainName: string;
41
+ nativeCurrency: {
42
+ name: string;
43
+ symbol: string;
44
+ decimals: number;
45
+ };
46
+ rpcUrls: string[];
47
+ blockExplorerUrls: string[];
48
+ };
49
+
50
+ type ProviderRequestParams = {
51
+ provider?: BrowserProvider;
52
+ params?: Todo;
53
+ method:
54
+ | "wallet_addEthereumChain"
55
+ | "wallet_switchEthereumChain"
56
+ | "eth_requestAccounts"
57
+ | "eth_sendTransaction"
58
+ | "eth_signTransaction";
59
+ };
60
+
61
+ const methodsToWrap = [
62
+ "approve",
63
+ "approvedAmount",
64
+ "call",
65
+ "sendTransaction",
66
+ "transfer",
67
+ "isApproved",
68
+ "approvedAmount",
69
+ "EIP1193SendTransaction",
70
+ "getFeeData",
71
+ "broadcastTransaction",
72
+ "estimateCall",
73
+ "estimateGasLimit",
74
+ "estimateGasPrices",
75
+ "createContractTxObject",
76
+ ];
77
+
78
+ export const wrapMethodWithNetworkSwitch = <T extends (...args: Todo[]) => Todo>(
79
+ func: T,
80
+ provider: BrowserProvider,
81
+ chainId: ChainId,
82
+ ) =>
83
+ (async (...args: Todo[]) => {
84
+ try {
85
+ await switchEVMWalletNetwork(provider, chainId);
86
+ } catch (error) {
87
+ throw new Error(`Failed to switch network: ${error}`);
88
+ }
89
+ return func(...args);
90
+ }) as unknown as T;
91
+
92
+ const providerRequest = ({ provider, params, method }: ProviderRequestParams) => {
93
+ if (!provider?.send) throw new Error("Provider not found");
94
+
95
+ const providerParams = params ? (Array.isArray(params) ? params : [params]) : [];
96
+ return provider.send(method, providerParams);
97
+ };
98
+
99
+ export const prepareNetworkSwitch = <T extends { [key: string]: (...args: Todo[]) => Todo }>({
100
+ toolbox,
101
+ chainId,
102
+ provider = window.ethereum,
103
+ }: {
104
+ toolbox: T;
105
+ chainId: ChainId;
106
+ provider?: BrowserProvider;
107
+ }) => {
108
+ const wrappedMethods = methodsToWrap.reduce((object, methodName) => {
109
+ if (!toolbox[methodName]) return object;
110
+ const method = toolbox[methodName];
111
+
112
+ if (typeof method !== "function") return object;
113
+
114
+ return {
115
+ // biome-ignore lint/performance/noAccumulatingSpread: This is a valid use case
116
+ ...object,
117
+ [methodName]: wrapMethodWithNetworkSwitch<typeof method>(method, provider, chainId),
118
+ };
119
+ }, {});
120
+
121
+ return { ...toolbox, ...wrappedMethods };
122
+ };
123
+
124
+ export const addEVMWalletNetwork = (provider: BrowserProvider, networkParams: NetworkParams) =>
125
+ providerRequest({ provider, method: "wallet_addEthereumChain", params: [networkParams] });
126
+
127
+ export const switchEVMWalletNetwork = (provider: BrowserProvider, chainId = ChainId.EthereumHex) =>
128
+ providerRequest({ provider, method: "wallet_switchEthereumChain", params: [{ chainId }] });
129
+
130
+ export const addAccountsChangedCallback = (callback: () => void) => {
131
+ window.ethereum?.on("accountsChanged", () => callback());
132
+ // @ts-expect-error that should be implemented in xdefi and hooked up via swapkit core
133
+ window.xfi?.ethereum.on("accountsChanged", () => callback());
134
+ };
135
+
136
+ export const getETHDefaultWallet = () => {
137
+ const { isTrust, isBraveWallet, __XDEFI, overrideIsMetaMask, selectedProvider } =
138
+ window?.ethereum || {};
139
+ if (isTrust) return WalletOption.TRUSTWALLET_WEB;
140
+ if (isBraveWallet) return WalletOption.BRAVE;
141
+ if (overrideIsMetaMask && selectedProvider?.isCoinbaseWallet) return WalletOption.COINBASE_WEB;
142
+ if (__XDEFI) WalletOption.XDEFI;
143
+ return WalletOption.METAMASK;
144
+ };
145
+
146
+ export const isDetected = (walletOption: WalletOption) => {
147
+ return listWeb3EVMWallets().includes(walletOption);
148
+ };
149
+
150
+ export const listWeb3EVMWallets = () => {
151
+ const metamaskEnabled = window?.ethereum && !window.ethereum?.isBraveWallet;
152
+ // @ts-ignore that should be implemented in xdefi and hooked up via swapkit core
153
+ const xdefiEnabled = window?.xfi || window?.ethereum?.__XDEFI;
154
+ const braveEnabled = window?.ethereum?.isBraveWallet;
155
+ const trustEnabled = window?.ethereum?.isTrust || window?.trustwallet;
156
+ const coinbaseEnabled =
157
+ (window?.ethereum?.overrideIsMetaMask &&
158
+ window?.ethereum?.selectedProvider?.isCoinbaseWallet) ||
159
+ window?.coinbaseWalletExtension;
160
+
161
+ const wallets = [];
162
+ if (metamaskEnabled) wallets.push(WalletOption.METAMASK);
163
+ if (xdefiEnabled) wallets.push(WalletOption.XDEFI);
164
+ if (braveEnabled) wallets.push(WalletOption.BRAVE);
165
+ if (trustEnabled) wallets.push(WalletOption.TRUSTWALLET_WEB);
166
+ if (coinbaseEnabled) wallets.push(WalletOption.COINBASE_WEB);
167
+ if (okxMobileEnabled()) wallets.push(WalletOption.OKX_MOBILE);
168
+
169
+ return wallets;
170
+ };
171
+
172
+ export function getEIP6963Wallets() {
173
+ const providers: EIP6963Provider[] = [];
174
+
175
+ function onAnnouncement(event: EIP6963AnnounceProviderEvent) {
176
+ if (providers.map((p) => p.info.uuid).includes(event.detail.info.uuid)) return;
177
+ providers.push(event.detail);
178
+ }
179
+
180
+ window.addEventListener("eip6963:announceProvider", onAnnouncement);
181
+ window.dispatchEvent(new Event("eip6963:requestProvider"));
182
+
183
+ function removeEIP6963EventListener() {
184
+ window.removeEventListener("eip6963:announceProvider", onAnnouncement);
185
+ }
186
+
187
+ return { providers, removeEIP6963EventListener };
188
+ }
189
+
190
+ export const okxMobileEnabled = () => {
191
+ const ua = navigator.userAgent;
192
+ const isIOS = /iphone|ipad|ipod|ios/i.test(ua);
193
+ const isAndroid = /android|XiaoMi|MiuiBrowser/i.test(ua);
194
+ const isMobile = isIOS || isAndroid;
195
+ const isOKApp = /OKApp/i.test(ua);
196
+
197
+ return isMobile && isOKApp;
198
+ };
199
+
200
+ export const isWeb3Detected = () => typeof window.ethereum !== "undefined";
package/src/index.ts CHANGED
@@ -1,16 +1,21 @@
1
+ export * from "./types/index.ts";
2
+
1
3
  /**
2
4
  * Helpers
3
5
  */
4
- export * from './helpers/asset.ts';
5
- export * from './helpers/liquidity.ts';
6
- export * from './helpers/memo.ts';
7
- export * from './helpers/others.ts';
8
- export * from './helpers/request.ts';
6
+ export * from "./helpers/asset.ts";
7
+ export * from "./helpers/derivationPath.ts";
8
+ export * from "./helpers/liquidity.ts";
9
+ export * from "./helpers/memo.ts";
10
+ export * from "./helpers/others.ts";
11
+ export * from "./helpers/validators.ts";
12
+ export * from "./helpers/web3wallets.ts";
9
13
 
10
14
  /**
11
15
  * Modules
12
16
  */
13
- export * from './modules/assetValue.ts';
14
- export * from './modules/bigIntArithmetics.ts';
15
- export * from './modules/swapKitError.ts';
16
- export * from './modules/swapKitNumber.ts';
17
+ export * from "./modules/assetValue.ts";
18
+ export * from "./modules/bigIntArithmetics.ts";
19
+ export * from "./modules/requestClient.ts";
20
+ export * from "./modules/swapKitError.ts";
21
+ export * from "./modules/swapKitNumber.ts";