@swapkit/helpers 4.5.9 → 4.12.4

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 (109) hide show
  1. package/dist/LICENSE +246 -0
  2. package/dist/api/index.cjs +0 -4
  3. package/dist/api/index.js +1 -4
  4. package/dist/chunk-1m30h0t9.js +1 -0
  5. package/dist/chunk-57tjgeg1.js +5 -0
  6. package/dist/chunk-7xv3mp86.js +4 -0
  7. package/dist/contracts.cjs +0 -3
  8. package/dist/contracts.js +0 -3
  9. package/dist/index.cjs +1 -7
  10. package/dist/index.js +1 -7
  11. package/dist/tokens.cjs +0 -3
  12. package/dist/tokens.js +0 -3
  13. package/dist/types/api/index.d.ts +129 -153
  14. package/dist/types/api/index.d.ts.map +1 -1
  15. package/dist/types/api/midgard/endpoints.d.ts +2 -1
  16. package/dist/types/api/midgard/endpoints.d.ts.map +1 -1
  17. package/dist/types/api/swapkitApi/endpoints.d.ts +137 -159
  18. package/dist/types/api/swapkitApi/endpoints.d.ts.map +1 -1
  19. package/dist/types/api/swapkitApi/types.d.ts +1050 -23
  20. package/dist/types/api/swapkitApi/types.d.ts.map +1 -1
  21. package/dist/types/api/thornode/endpoints.d.ts +1 -1
  22. package/dist/types/api/thornode/endpoints.d.ts.map +1 -1
  23. package/dist/types/index.d.ts +5 -0
  24. package/dist/types/index.d.ts.map +1 -1
  25. package/dist/types/modules/assetValue.d.ts +6 -7
  26. package/dist/types/modules/assetValue.d.ts.map +1 -1
  27. package/dist/types/modules/requestClient.d.ts +1 -1
  28. package/dist/types/modules/requestClient.d.ts.map +1 -1
  29. package/dist/types/modules/swapKitConfig.d.ts +24 -78
  30. package/dist/types/modules/swapKitConfig.d.ts.map +1 -1
  31. package/dist/types/modules/swapKitError.d.ts +150 -14
  32. package/dist/types/modules/swapKitError.d.ts.map +1 -1
  33. package/dist/types/modules/widgetAuth.d.ts +6 -0
  34. package/dist/types/modules/widgetAuth.d.ts.map +1 -0
  35. package/dist/types/types/derivationPath.d.ts +1 -1
  36. package/dist/types/types/derivationPath.d.ts.map +1 -1
  37. package/dist/types/types/quotes.d.ts +2 -6
  38. package/dist/types/types/quotes.d.ts.map +1 -1
  39. package/dist/types/types/sdk.d.ts +6 -0
  40. package/dist/types/types/sdk.d.ts.map +1 -1
  41. package/dist/types/types/wallet.d.ts +12 -3
  42. package/dist/types/types/wallet.d.ts.map +1 -1
  43. package/dist/types/utils/asset.d.ts +17 -1
  44. package/dist/types/utils/asset.d.ts.map +1 -1
  45. package/dist/types/utils/chains.d.ts +5 -0
  46. package/dist/types/utils/chains.d.ts.map +1 -1
  47. package/dist/types/utils/derivationPath.d.ts +4 -2
  48. package/dist/types/utils/derivationPath.d.ts.map +1 -1
  49. package/dist/types/utils/wallets.d.ts +18 -2
  50. package/dist/types/utils/wallets.d.ts.map +1 -1
  51. package/package.json +12 -30
  52. package/dist/api/index.cjs.map +0 -14
  53. package/dist/api/index.js.map +0 -14
  54. package/dist/chunk-pfmeq01a.js +0 -5
  55. package/dist/chunk-pfmeq01a.js.map +0 -9
  56. package/dist/chunk-vb4wtm2w.js +0 -4
  57. package/dist/chunk-vb4wtm2w.js.map +0 -9
  58. package/dist/contracts.cjs.map +0 -10
  59. package/dist/contracts.js.map +0 -10
  60. package/dist/index.cjs.map +0 -30
  61. package/dist/index.js.map +0 -30
  62. package/dist/tokens.cjs.map +0 -10
  63. package/dist/tokens.js.map +0 -10
  64. package/src/api/index.ts +0 -9
  65. package/src/api/midgard/endpoints.ts +0 -348
  66. package/src/api/midgard/types.ts +0 -515
  67. package/src/api/swapkitApi/endpoints.ts +0 -247
  68. package/src/api/swapkitApi/types.ts +0 -624
  69. package/src/api/thornode/endpoints.ts +0 -105
  70. package/src/api/thornode/types.ts +0 -247
  71. package/src/contracts.ts +0 -1
  72. package/src/index.ts +0 -28
  73. package/src/modules/__tests__/assetValue.test.ts +0 -2452
  74. package/src/modules/__tests__/bigIntArithmetics.test.ts +0 -410
  75. package/src/modules/__tests__/feeMultiplier.test.ts +0 -125
  76. package/src/modules/__tests__/swapKitConfig.test.ts +0 -425
  77. package/src/modules/__tests__/swapKitNumber.test.ts +0 -435
  78. package/src/modules/assetValue.ts +0 -532
  79. package/src/modules/bigIntArithmetics.ts +0 -362
  80. package/src/modules/feeMultiplier.ts +0 -80
  81. package/src/modules/requestClient.ts +0 -110
  82. package/src/modules/swapKitConfig.ts +0 -174
  83. package/src/modules/swapKitError.ts +0 -470
  84. package/src/modules/swapKitNumber.ts +0 -13
  85. package/src/tokens.ts +0 -1
  86. package/src/types/commonTypes.ts +0 -10
  87. package/src/types/derivationPath.ts +0 -11
  88. package/src/types/errors/apiV1.ts +0 -0
  89. package/src/types/index.ts +0 -5
  90. package/src/types/quotes.ts +0 -174
  91. package/src/types/sdk.ts +0 -38
  92. package/src/types/wallet.ts +0 -124
  93. package/src/utils/__tests__/asset.test.ts +0 -186
  94. package/src/utils/__tests__/derivationPath.test.ts +0 -142
  95. package/src/utils/__tests__/explorerUrls.test.ts +0 -59
  96. package/src/utils/__tests__/liquidity.test.ts +0 -302
  97. package/src/utils/__tests__/memo.test.ts +0 -99
  98. package/src/utils/__tests__/others.test.ts +0 -165
  99. package/src/utils/__tests__/validators.test.ts +0 -84
  100. package/src/utils/__tests__/wallets.test.ts +0 -621
  101. package/src/utils/asset.ts +0 -399
  102. package/src/utils/chains.ts +0 -100
  103. package/src/utils/derivationPath.ts +0 -101
  104. package/src/utils/explorerUrls.ts +0 -32
  105. package/src/utils/liquidity.ts +0 -150
  106. package/src/utils/memo.ts +0 -102
  107. package/src/utils/others.ts +0 -62
  108. package/src/utils/validators.ts +0 -32
  109. package/src/utils/wallets.ts +0 -237
@@ -1,150 +0,0 @@
1
- import { Chain, getChainConfig } from "@swapkit/types";
2
- import { SwapKitNumber } from "../modules/swapKitNumber";
3
-
4
- type ShareParams<T extends {}> = T & { liquidityUnits: string; poolUnits: string };
5
-
6
- type PoolParams = { runeAmount: string; assetAmount: string; runeDepth: string; assetDepth: string };
7
-
8
- /**
9
- * Ref: https://gitlab.com/thorchain/thornode/-/issues/657
10
- * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3
11
- * s = stakeUnits for member (after factoring in withdrawBasisPoints)
12
- * T = totalPoolUnits for pool
13
- * A = assetDepth to be withdrawn
14
- *
15
- * Formula:
16
- * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3
17
- * (part1 * (part2 - part3 + part4)) / part5
18
- */
19
- export function getAsymmetricRuneShare({ liquidityUnits, poolUnits, runeDepth }: ShareParams<{ runeDepth: string }>) {
20
- const s = toTCSwapKitNumber(liquidityUnits);
21
- const T = toTCSwapKitNumber(poolUnits);
22
- const A = toTCSwapKitNumber(runeDepth);
23
-
24
- const part1 = s.mul(A);
25
- const part2 = T.mul(T).mul(2);
26
- const part3 = T.mul(s).mul(2);
27
- const part4 = s.mul(s);
28
- const part5 = T.mul(T).mul(T);
29
-
30
- const numerator = part1.mul(part2.sub(part3).add(part4));
31
-
32
- return numerator.div(part5);
33
- }
34
-
35
- export function getAsymmetricAssetShare({
36
- liquidityUnits,
37
- poolUnits,
38
- assetDepth,
39
- }: ShareParams<{ assetDepth: string }>) {
40
- const s = toTCSwapKitNumber(liquidityUnits);
41
- const T = toTCSwapKitNumber(poolUnits);
42
- const A = toTCSwapKitNumber(assetDepth);
43
-
44
- const part1 = s.mul(A);
45
- const part2 = T.mul(T).mul(2);
46
- const part3 = T.mul(s).mul(2);
47
- const part4 = s.mul(s);
48
- const numerator = part1.mul(part2.sub(part3).add(part4));
49
- const part5 = T.mul(T).mul(T);
50
-
51
- return numerator.div(part5);
52
- }
53
-
54
- export function getAsymmetricRuneWithdrawAmount({
55
- percent,
56
- runeDepth,
57
- liquidityUnits,
58
- poolUnits,
59
- }: ShareParams<{ percent: number; runeDepth: string }>) {
60
- return getAsymmetricRuneShare({ liquidityUnits, poolUnits, runeDepth }).mul(percent);
61
- }
62
-
63
- export function getAsymmetricAssetWithdrawAmount({
64
- percent,
65
- assetDepth,
66
- liquidityUnits,
67
- poolUnits,
68
- }: ShareParams<{ percent: number; assetDepth: string }>) {
69
- return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
70
- }
71
-
72
- function toTCSwapKitNumber(value: string) {
73
- return SwapKitNumber.fromBigInt(BigInt(value), getChainConfig(Chain.THORChain).baseDecimal);
74
- }
75
-
76
- export function getSymmetricPoolShare({
77
- liquidityUnits,
78
- poolUnits,
79
- runeDepth,
80
- assetDepth,
81
- }: ShareParams<{ runeDepth: string; assetDepth: string }>) {
82
- return {
83
- assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
84
- runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits),
85
- };
86
- }
87
-
88
- export function getSymmetricWithdraw({
89
- liquidityUnits,
90
- poolUnits,
91
- runeDepth,
92
- assetDepth,
93
- percent,
94
- }: ShareParams<{ runeDepth: string; assetDepth: string; percent: number }>) {
95
- return Object.fromEntries(
96
- Object.entries(getSymmetricPoolShare({ assetDepth, liquidityUnits, poolUnits, runeDepth })).map(([name, value]) => [
97
- name,
98
- value.mul(percent),
99
- ]),
100
- );
101
- }
102
-
103
- export function getEstimatedPoolShare({
104
- runeDepth,
105
- poolUnits,
106
- assetDepth,
107
- liquidityUnits,
108
- runeAmount,
109
- assetAmount,
110
- }: ShareParams<{ runeAmount: string; assetAmount: string; runeDepth: string; assetDepth: string }>) {
111
- const R = new SwapKitNumber({ decimal: 8, value: runeDepth });
112
- const A = new SwapKitNumber({ decimal: 8, value: assetDepth });
113
- const P = new SwapKitNumber({ decimal: 8, value: poolUnits });
114
- const runeAddAmount = new SwapKitNumber({ decimal: 8, value: runeAmount });
115
- const assetAddAmount = new SwapKitNumber({ decimal: 8, value: assetAmount });
116
-
117
- // liquidityUnits = P * (r*A + a*R + 2*r*a) / (r*A + a*R + 2*R*A)
118
- const rA = runeAddAmount.mul(A);
119
- const aR = assetAddAmount.mul(R);
120
- const ra = runeAddAmount.mul(assetAddAmount);
121
- const RA = R.mul(A);
122
- const numerator = P.mul(rA.add(aR.add(ra.mul(2))));
123
- const denominator = rA.add(aR.add(RA.mul(2)));
124
- const liquidityUnitsAfterAdd = numerator.div(denominator);
125
- const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
126
-
127
- if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) {
128
- return estimatedLiquidityUnits.div(P).getBaseValue("number");
129
- }
130
-
131
- // get pool units after add
132
- const newPoolUnits = P.add(estimatedLiquidityUnits);
133
-
134
- return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number");
135
- }
136
-
137
- export function getLiquiditySlippage({ runeAmount, assetAmount, runeDepth, assetDepth }: PoolParams) {
138
- if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0") return 0;
139
- // formula: (t * R - T * r)/ (T*r + R*T)
140
- const R = toTCSwapKitNumber(runeDepth);
141
- const T = toTCSwapKitNumber(assetDepth);
142
- const assetAddAmount = toTCSwapKitNumber(assetAmount);
143
- const runeAddAmount = toTCSwapKitNumber(runeAmount);
144
-
145
- const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount));
146
- const denominator = T.mul(runeAddAmount).add(R.mul(T));
147
-
148
- // set absolute value of percent, no negative allowed
149
- return Math.abs(numerator.div(denominator).getBaseValue("number"));
150
- }
package/src/utils/memo.ts DELETED
@@ -1,102 +0,0 @@
1
- import { Chain } from "@swapkit/types";
2
- import { match } from "ts-pattern";
3
- import { MemoType } from "../types/sdk";
4
-
5
- export function getMemoForLeaveAndBond({ type, address }: BondOrLeaveParams) {
6
- return `${type}:${address}`;
7
- }
8
-
9
- export function getMemoForUnbond({ address, unbondAmount }: UnbondParams) {
10
- return `${MemoType.UNBOND}:${address}:${unbondAmount}`;
11
- }
12
-
13
- /**
14
- * Deposit
15
- */
16
- export function getMemoForRunePoolDeposit(affiliate?: WithAffiliate<{}>) {
17
- return addAffiliate(MemoType.RUNEPOOL_DEPOSIT, affiliate);
18
- }
19
-
20
- export function getMemoForDeposit({
21
- chain,
22
- symbol,
23
- address,
24
- ...affiliate
25
- }: WithAffiliate<{ chain: Chain; symbol: string; address?: string }>) {
26
- const poolIdentifier = getPoolIdentifier({ chain, symbol });
27
- const addressPart = address ? `:${address}:` : ":";
28
-
29
- return addAffiliate(`${MemoType.DEPOSIT}:${poolIdentifier}${addressPart}`, affiliate);
30
- }
31
-
32
- /**
33
- * Withdraw
34
- */
35
- export function getMemoForWithdraw({ chain, symbol, ticker, basisPoints, targetAsset }: WithdrawParams) {
36
- const shortenedSymbol = chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol;
37
- const targetPart = targetAsset ? `:${targetAsset}` : "";
38
-
39
- return `${MemoType.WITHDRAW}:${chain}.${shortenedSymbol}:${basisPoints}${targetPart}`;
40
- }
41
-
42
- export function getMemoForRunePoolWithdraw({ basisPoints, ...affiliate }: WithAffiliate<{ basisPoints: number }>) {
43
- return addAffiliate(`${MemoType.RUNEPOOL_WITHDRAW}:${basisPoints}`, affiliate);
44
- }
45
-
46
- /**
47
- * TNS
48
- */
49
- export function getMemoForNameRegister({ name, chain, address, owner }: NameRegisterParams) {
50
- const baseMemo = `${MemoType.NAME_REGISTER}:${name}:${chain}:${address}`;
51
- const ownerAssignmentOrChangePart = owner ? `:${owner}` : "";
52
-
53
- return `${baseMemo}${ownerAssignmentOrChangePart}`;
54
- }
55
-
56
- export function getMemoForNamePreferredAssetRegister({
57
- name,
58
- chain,
59
- asset,
60
- payout,
61
- owner,
62
- }: PreferredAssetRegisterParams) {
63
- return `${MemoType.NAME_REGISTER}:${name}:${chain}:${payout}:${owner}:${asset}`;
64
- }
65
-
66
- export function getMemoForTcyClaim(memoType: MemoType.CLAIM_TCY, { address }: WithAffiliate<{ address: string }>) {
67
- return `${memoType}:${address}`;
68
- }
69
-
70
- export function getMemoForTcyStake(
71
- memoType: MemoType.STAKE_TCY | MemoType.UNSTAKE_TCY,
72
- { unstakeBps, ...affiliate }: WithAffiliate<{ unstakeBps?: number }>,
73
- ) {
74
- const bps = unstakeBps ? `:${unstakeBps}` : "";
75
- const baseMemo = `${memoType}${bps}`;
76
-
77
- return addAffiliate(`${baseMemo}`, affiliate);
78
- }
79
-
80
- /**
81
- * Internal helpers
82
- */
83
- function addAffiliate(memo: string, { affiliateAddress, affiliateBasisPoints }: WithAffiliate<{}> = {}) {
84
- const affiliatedMemo = `${memo}${affiliateAddress ? `:${affiliateAddress}:${affiliateBasisPoints || 0}` : ""}`;
85
-
86
- return affiliatedMemo.endsWith(":") ? affiliatedMemo.slice(0, -1) : affiliatedMemo;
87
- }
88
-
89
- function getPoolIdentifier({ chain, symbol }: { chain: Chain; symbol: string }) {
90
- return match(chain)
91
- .with(Chain.Bitcoin, Chain.Dogecoin, Chain.Litecoin, () => chain.slice(0, 1).toLowerCase())
92
- .with(Chain.BitcoinCash, () => "c")
93
- .otherwise(() => `${chain}.${symbol}`);
94
- }
95
-
96
- type WithAffiliate<T extends {}> = T & { affiliateAddress?: string; affiliateBasisPoints?: number };
97
-
98
- type BondOrLeaveParams = { type: MemoType.BOND | MemoType.LEAVE; address: string };
99
- type UnbondParams = { address: string; unbondAmount: number };
100
- type NameRegisterParams = { name: string; chain: string; address: string; owner?: string };
101
- type PreferredAssetRegisterParams = { name: string; chain: Chain; asset: string; payout: string; owner: string };
102
- type WithdrawParams = { chain: Chain; symbol: string; ticker: string; basisPoints: number; targetAsset?: string };
@@ -1,62 +0,0 @@
1
- import { Chain } from "@swapkit/types";
2
- import { type ErrorKeys, SwapKitError } from "../modules/swapKitError";
3
-
4
- // 10 rune for register, 1 rune per year
5
- // MINIMUM_REGISTRATION_FEE = 11
6
- export function getTHORNameCost(numberOfYears: number) {
7
- if (numberOfYears < 0)
8
- throw new SwapKitError({ errorKey: "helpers_invalid_number_of_years", info: { numberOfYears } });
9
- return 10 + numberOfYears;
10
- }
11
-
12
- // 10 CACAO for register
13
- // 1.0512 CACAO per year
14
- export function getMAYANameCost(numberOfYears: number) {
15
- if (numberOfYears < 0)
16
- throw new SwapKitError({ errorKey: "helpers_invalid_number_of_years", info: { numberOfYears } });
17
- // round to max 10 decimals
18
- return Math.round((10 + numberOfYears * 1.0512) * 1e10) / 1e10;
19
- }
20
-
21
- export function wrapWithThrow<T>(fn: () => T, errorKey?: ErrorKeys) {
22
- try {
23
- return fn();
24
- } catch (error) {
25
- if (errorKey) {
26
- throw new SwapKitError(errorKey, error);
27
- }
28
-
29
- return;
30
- }
31
- }
32
-
33
- export function getChainIdentifier<T extends Chain>(chain: T) {
34
- switch (chain) {
35
- case Chain.THORChain:
36
- return `${chain}.RUNE`;
37
-
38
- case Chain.Cosmos:
39
- return `${chain}.ATOM`;
40
-
41
- case Chain.BinanceSmartChain:
42
- return `${chain}`;
43
-
44
- default:
45
- return `${chain}.${chain}`;
46
- }
47
- }
48
-
49
- const warnings = new Set();
50
- export function warnOnce({ condition, id, warning }: { condition: boolean; id: string; warning: string }) {
51
- if (condition) {
52
- if (warnings.has(id)) {
53
- return;
54
- }
55
-
56
- if (process.env.NODE_ENV !== "test") {
57
- console.warn(warning);
58
- }
59
-
60
- warnings.add(id);
61
- }
62
- }
@@ -1,32 +0,0 @@
1
- import type { Chain } from "@swapkit/types";
2
- import { SKConfig } from "../modules/swapKitConfig";
3
- import { SwapKitError } from "../modules/swapKitError";
4
-
5
- // Backward compatibility
6
- const supportedChains = ["TERRA", ...SKConfig.get("chains")];
7
-
8
- export function validateIdentifier(identifier = "") {
9
- const uppercasedIdentifier = identifier.toUpperCase();
10
-
11
- const [chain] = uppercasedIdentifier.split(".") as [Chain, string];
12
- if (supportedChains.includes(chain)) return true;
13
-
14
- const [synthChain] = uppercasedIdentifier.split("/") as [Chain, string];
15
- if (supportedChains.includes(synthChain)) return true;
16
-
17
- throw new SwapKitError({
18
- errorKey: "helpers_invalid_identifier",
19
- info: {
20
- identifier,
21
- message: `Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`,
22
- },
23
- });
24
- }
25
-
26
- export function validateTNS(name: string) {
27
- if (name.length > 30) return false;
28
-
29
- const regex = /^[a-zA-Z0-9+_-]+$/g;
30
-
31
- return !!name.match(regex);
32
- }
@@ -1,237 +0,0 @@
1
- import { type Chain, getChainConfig } from "@swapkit/types";
2
- import type { BrowserProvider, JsonRpcProvider } from "ethers";
3
- import { SwapKitError } from "../modules/swapKitError";
4
- import {
5
- type EIP6963AnnounceProviderEvent,
6
- type EIP6963Provider,
7
- type EthereumWindowProvider,
8
- type NetworkParams,
9
- WalletOption,
10
- } from "../types";
11
- import { warnOnce } from "./others";
12
-
13
- declare const window: {
14
- ethereum: EthereumWindowProvider;
15
- trustwallet: EthereumWindowProvider;
16
- coinbaseWalletExtension: EthereumWindowProvider;
17
- braveSolana: any;
18
- bitkeep?: { ethereum: EthereumWindowProvider };
19
- ctrl?: { ethereum: EthereumWindowProvider };
20
- $onekey?: { ethereum: EthereumWindowProvider };
21
- vultisig?: { ethereum: EthereumWindowProvider };
22
- } & Window;
23
-
24
- export function isWeb3Detected() {
25
- return typeof window.ethereum !== "undefined";
26
- }
27
-
28
- export function isDetected(walletOption: WalletOption) {
29
- return listWeb3EVMWallets().includes(walletOption);
30
- }
31
-
32
- export function listWeb3EVMWallets() {
33
- const metamaskEnabled = window?.ethereum && !window.ethereum?.isBraveWallet;
34
- const ctrlEnabled = window?.ctrl || window?.ethereum?.__XDEFI;
35
- const vultisigEnabled = window?.vultisig;
36
- const braveEnabled = window?.ethereum?.isBraveWallet;
37
- const trustEnabled = window?.ethereum?.isTrust || window?.trustwallet;
38
- const coinbaseEnabled =
39
- (window?.ethereum?.overrideIsMetaMask && window?.ethereum?.selectedProvider?.isCoinbaseWallet) ||
40
- window?.coinbaseWalletExtension;
41
- const bitgetEnabled = window?.bitkeep?.ethereum;
42
- const onekeyEnabled = window?.$onekey?.ethereum;
43
-
44
- const wallets = [];
45
- if (metamaskEnabled) wallets.push(WalletOption.METAMASK);
46
- if (ctrlEnabled) wallets.push(WalletOption.CTRL);
47
- if (vultisigEnabled) wallets.push(WalletOption.VULTISIG);
48
- if (braveEnabled) wallets.push(WalletOption.BRAVE);
49
- if (trustEnabled) wallets.push(WalletOption.TRUSTWALLET_WEB);
50
- if (coinbaseEnabled) wallets.push(WalletOption.COINBASE_WEB);
51
- if (okxMobileEnabled()) wallets.push(WalletOption.OKX_MOBILE);
52
- if (bitgetEnabled) wallets.push(WalletOption.BITGET);
53
- if (onekeyEnabled) wallets.push(WalletOption.ONEKEY);
54
-
55
- return wallets;
56
- }
57
-
58
- export async function switchEVMWalletNetwork(provider: BrowserProvider, chain: Chain, networkParams?: NetworkParams) {
59
- const chainConfig = getChainConfig(chain);
60
-
61
- try {
62
- await providerRequest({
63
- method: "wallet_switchEthereumChain",
64
- params: [{ chainId: chainConfig.chainIdHex }],
65
- provider,
66
- });
67
- } catch (error) {
68
- if (!networkParams) {
69
- throw new SwapKitError("helpers_failed_to_switch_network", {
70
- error: error,
71
- reason: "networkParams not provided",
72
- });
73
- }
74
- await addEVMWalletNetwork(provider, networkParams);
75
- }
76
- }
77
-
78
- export function filterSupportedChains<T extends string[]>({
79
- chains,
80
- supportedChains,
81
- walletType,
82
- }: {
83
- chains: Chain[];
84
- supportedChains: T;
85
- walletType?: WalletOption;
86
- }) {
87
- const supported = chains.filter((chain) => !chain || supportedChains.includes(chain));
88
-
89
- if (supported.length === 0) {
90
- throw new SwapKitError("wallet_chain_not_supported", { chain: chains.join(", "), wallet: walletType });
91
- }
92
-
93
- const unsupported = chains.filter((chain) => !supportedChains.includes(chain));
94
-
95
- warnOnce({
96
- condition: unsupported.length > 0,
97
- id: `wallet_chain_not_supported_${walletType}`,
98
- warning: `${walletType} wallet does not support the following chains: ${unsupported.join(
99
- ", ",
100
- )}. These chains will be ignored.`,
101
- });
102
-
103
- return supported as T;
104
- }
105
-
106
- export function wrapMethodWithNetworkSwitch<T extends (...args: any[]) => any>(
107
- func: T,
108
- provider: BrowserProvider,
109
- chain: Chain,
110
- ) {
111
- return (async (...args: any[]) => {
112
- const { chainIdHex } = getChainConfig(chain);
113
- if ((await provider.getNetwork()).chainId.toString() === chainIdHex) {
114
- return func(...args);
115
- }
116
- try {
117
- await switchEVMWalletNetwork(provider, chain);
118
- } catch (error) {
119
- throw new SwapKitError({ errorKey: "helpers_failed_to_switch_network", info: { error } });
120
- }
121
- return func(...args);
122
- }) as unknown as T;
123
- }
124
-
125
- export function prepareNetworkSwitch<T extends Record<string, unknown>, M extends keyof T>({
126
- toolbox,
127
- chain,
128
- provider = window.ethereum,
129
- methodNames = [],
130
- }: {
131
- toolbox: T;
132
- chain: Chain;
133
- provider?: BrowserProvider | JsonRpcProvider;
134
- methodNames?: M[];
135
- }) {
136
- const methodsToWrap = [
137
- ...methodNames,
138
- "approve",
139
- "approvedAmount",
140
- "call",
141
- "sendTransaction",
142
- "transfer",
143
- "isApproved",
144
- "approvedAmount",
145
- "EIP1193SendTransaction",
146
- "getFeeData",
147
- "broadcastTransaction",
148
- "estimateCall",
149
- "estimateGasLimit",
150
- "estimateGasPrices",
151
- "createContractTxObject",
152
- ] as M[];
153
- const wrappedMethods = methodsToWrap.reduce((object, methodName) => {
154
- if (!toolbox[methodName]) return object;
155
-
156
- const method = toolbox[methodName];
157
-
158
- if (typeof method !== "function") return object;
159
-
160
- // @ts-expect-error
161
- const wrappedMethod = wrapMethodWithNetworkSwitch(method, provider, chain);
162
-
163
- // biome-ignore lint/performance/noAccumulatingSpread: valid use case
164
- return { ...object, [methodName]: wrappedMethod };
165
- }, {});
166
-
167
- return { ...toolbox, ...wrappedMethods };
168
- }
169
-
170
- export function addEVMWalletNetwork(provider: BrowserProvider, networkParams: NetworkParams) {
171
- return providerRequest({ method: "wallet_addEthereumChain", params: [networkParams], provider });
172
- }
173
-
174
- export function addAccountsChangedCallback(callback: () => void) {
175
- window.ethereum?.on("accountsChanged", () => callback());
176
- window.ctrl?.ethereum.on("accountsChanged", () => callback());
177
- }
178
-
179
- export function getETHDefaultWallet() {
180
- const { isTrust, isBraveWallet, __XDEFI, overrideIsMetaMask, selectedProvider } = window?.ethereum || {};
181
- if (isTrust) return WalletOption.TRUSTWALLET_WEB;
182
- if (isBraveWallet) return WalletOption.BRAVE;
183
- if (overrideIsMetaMask && selectedProvider?.isCoinbaseWallet) return WalletOption.COINBASE_WEB;
184
- if (__XDEFI) return WalletOption.CTRL;
185
- if (window?.$onekey?.ethereum) return WalletOption.ONEKEY;
186
- return WalletOption.METAMASK;
187
- }
188
-
189
- export function getEIP6963Wallets() {
190
- const providers: EIP6963Provider[] = [];
191
-
192
- function onAnnouncement(event: EIP6963AnnounceProviderEvent) {
193
- if (providers.map((p) => p.info.uuid).includes(event.detail.info.uuid)) return;
194
- providers.push(event.detail);
195
- }
196
-
197
- window.addEventListener("eip6963:announceProvider", onAnnouncement);
198
- window.dispatchEvent(new Event("eip6963:requestProvider"));
199
-
200
- function removeEIP6963EventListener() {
201
- window.removeEventListener("eip6963:announceProvider", onAnnouncement);
202
- }
203
-
204
- return { providers, removeEIP6963EventListener };
205
- }
206
-
207
- export function okxMobileEnabled() {
208
- const ua = navigator.userAgent;
209
- const isIOS = /iphone|ipad|ipod|ios/i.test(ua);
210
- const isAndroid = /android|XiaoMi|MiuiBrowser/i.test(ua);
211
- const isMobile = isIOS || isAndroid;
212
- const isOKApp = /OKApp/i.test(ua);
213
-
214
- return isMobile && isOKApp;
215
- }
216
-
217
- export function providerRequest({
218
- provider,
219
- params,
220
- method,
221
- }: {
222
- provider?: BrowserProvider;
223
- params?: any;
224
- method:
225
- | "wallet_addEthereumChain"
226
- | "wallet_switchEthereumChain"
227
- | "eth_requestAccounts"
228
- | "eth_sendTransaction"
229
- | "eth_signTransaction";
230
- }) {
231
- if (!provider?.send) {
232
- throw new SwapKitError("helpers_not_found_provider");
233
- }
234
-
235
- const providerParams = params ? (Array.isArray(params) ? params : [params]) : [];
236
- return provider.send(method, providerParams);
237
- }