@swapkit/helpers 1.0.0-rc.10 → 1.0.0-rc.101

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 (40) hide show
  1. package/dist/index.js +2470 -0
  2. package/dist/index.js.map +30 -0
  3. package/package.json +24 -37
  4. package/src/helpers/__tests__/asset.test.ts +149 -105
  5. package/src/helpers/__tests__/memo.test.ts +52 -40
  6. package/src/helpers/__tests__/others.test.ts +42 -37
  7. package/src/helpers/__tests__/validators.test.ts +24 -0
  8. package/src/helpers/asset.ts +130 -94
  9. package/src/helpers/derivationPath.ts +53 -0
  10. package/src/helpers/liquidity.ts +50 -43
  11. package/src/helpers/memo.ts +31 -28
  12. package/src/helpers/others.ts +30 -13
  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 +414 -117
  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 +218 -152
  20. package/src/modules/bigIntArithmetics.ts +214 -165
  21. package/src/modules/requestClient.ts +39 -0
  22. package/src/modules/swapKitError.ts +33 -5
  23. package/src/modules/swapKitNumber.ts +8 -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 +220 -0
  28. package/src/types/commonTypes.ts +119 -0
  29. package/src/types/derivationPath.ts +56 -0
  30. package/src/types/errors/apiV1.ts +0 -0
  31. package/src/types/index.ts +10 -0
  32. package/src/types/network.ts +43 -0
  33. package/src/types/sdk.ts +44 -0
  34. package/src/types/tokens.ts +30 -0
  35. package/src/types/wallet.ts +78 -0
  36. package/LICENSE +0 -201
  37. package/dist/index.cjs +0 -1
  38. package/dist/index.d.ts +0 -355
  39. package/dist/index.es.js +0 -1064
  40. package/src/helpers/request.ts +0 -16
@@ -1,20 +1,37 @@
1
+ import { type ErrorKeys, SwapKitError } from "../modules/swapKitError";
2
+ import type { DerivationPathArray } from "../types/derivationPath";
3
+
1
4
  // 10 rune for register, 1 rune per year
2
5
  // 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
- };
6
+ export function getTHORNameCost(numberOfYears: number) {
7
+ if (numberOfYears < 0) throw new Error("Invalid number of years");
8
+ return 10 + numberOfYears;
9
+ }
7
10
 
8
- export const validateTHORName = (name: string) => {
9
- if (name.length > 30) return false;
11
+ // 10 CACAO for register
12
+ // 1.0512 CACAO per year
13
+ export function getMAYANameCost(numberOfYears: number) {
14
+ if (numberOfYears < 0) throw new Error("Invalid number of year");
15
+ // round to max 10 decimals
16
+ return Math.round((10 + numberOfYears * 1.0512) * 1e10) / 1e10;
17
+ }
10
18
 
11
- const regex = /^[a-zA-Z0-9+_-]+$/g;
19
+ export function derivationPathToString([network, chainId, account, change, index]:
20
+ | [number, number, number, number, number | undefined]
21
+ | DerivationPathArray) {
22
+ const shortPath = typeof index !== "number";
12
23
 
13
- return !!name.match(regex);
14
- };
24
+ return `m/${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
25
+ }
15
26
 
16
- export const derivationPathToString = ([network, chainId, account, change, index]: number[]) => {
17
- const shortPath = typeof index !== 'number';
27
+ export function wrapWithThrow<T>(fn: () => T, errorKey?: ErrorKeys) {
28
+ try {
29
+ return fn();
30
+ } catch (error) {
31
+ if (errorKey) {
32
+ throw new SwapKitError(errorKey, error);
33
+ }
18
34
 
19
- return `${network}'/${chainId}'/${account}'/${change}${shortPath ? '' : `/${index}`}`;
20
- };
35
+ return console.error(error);
36
+ }
37
+ }
@@ -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";