@swapkit/helpers 1.0.0-rc.115 → 1.0.0-rc.117

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/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "author": "swapkit-oss",
3
3
  "description": "SwapKit - Helpers",
4
4
  "dependencies": {
5
- "@swapkit/tokens": "1.0.0-rc.57",
5
+ "@swapkit/tokens": "undefined",
6
6
  "ky": "1.3.0",
7
7
  "zod": "3.23.8"
8
8
  },
@@ -29,5 +29,5 @@
29
29
  },
30
30
  "type": "module",
31
31
  "types": "./src/index.ts",
32
- "version": "1.0.0-rc.115"
32
+ "version": "1.0.0-rc.117"
33
33
  }
@@ -34,7 +34,7 @@ describe("getTHORNameCost", () => {
34
34
  });
35
35
 
36
36
  test("throws an error for negative years", () => {
37
- expect(() => getTHORNameCost(-1)).toThrow("Invalid number of year");
37
+ expect(() => getTHORNameCost(-1)).toThrow("helpers_invalid_number_of_years");
38
38
  });
39
39
  });
40
40
 
@@ -1,3 +1,4 @@
1
+ import { SwapKitError } from "../modules/swapKitError";
1
2
  import { Chain } from "../types/chains";
2
3
  import { MemoType } from "../types/sdk";
3
4
 
@@ -195,6 +196,9 @@ export const getMemoFor = <T extends MemoType>(memoType: T, options: MemoOptions
195
196
  }
196
197
 
197
198
  default:
198
- throw new Error(`Unsupported memo type: ${memoType}`);
199
+ throw new SwapKitError({
200
+ errorKey: "helpers_invalid_memo_type",
201
+ info: { memoType },
202
+ });
199
203
  }
200
204
  };
@@ -5,14 +5,22 @@ import type { DerivationPathArray } from "../types/derivationPath";
5
5
  // 10 rune for register, 1 rune per year
6
6
  // MINIMUM_REGISTRATION_FEE = 11
7
7
  export function getTHORNameCost(numberOfYears: number) {
8
- if (numberOfYears < 0) throw new Error("Invalid number of years");
8
+ if (numberOfYears < 0)
9
+ throw new SwapKitError({
10
+ errorKey: "helpers_invalid_number_of_years",
11
+ info: { numberOfYears },
12
+ });
9
13
  return 10 + numberOfYears;
10
14
  }
11
15
 
12
16
  // 10 CACAO for register
13
17
  // 1.0512 CACAO per year
14
18
  export function getMAYANameCost(numberOfYears: number) {
15
- if (numberOfYears < 0) throw new Error("Invalid number of year");
19
+ if (numberOfYears < 0)
20
+ throw new SwapKitError({
21
+ errorKey: "helpers_invalid_number_of_years",
22
+ info: { numberOfYears },
23
+ });
16
24
  // round to max 10 decimals
17
25
  return Math.round((10 + numberOfYears * 1.0512) * 1e10) / 1e10;
18
26
  }
@@ -1,3 +1,4 @@
1
+ import { SwapKitError } from "../modules/swapKitError";
1
2
  import { Chain } from "../types/chains";
2
3
 
3
4
  // Backward compatibility
@@ -12,9 +13,13 @@ export function validateIdentifier(identifier = "") {
12
13
  const [synthChain] = uppercasedIdentifier.split("/") as [Chain, string];
13
14
  if (supportedChains.includes(synthChain)) return true;
14
15
 
15
- throw new Error(
16
- `Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`,
17
- );
16
+ throw new SwapKitError({
17
+ errorKey: "helpers_invalid_identifier",
18
+ info: {
19
+ message: `Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`,
20
+ identifier,
21
+ },
22
+ });
18
23
  }
19
24
 
20
25
  export function validateTNS(name: string) {
@@ -1,4 +1,5 @@
1
1
  import type { BrowserProvider } from "ethers";
2
+ import { SwapKitError } from "../modules/swapKitError";
2
3
  import {
3
4
  ChainId,
4
5
  type EIP6963AnnounceProviderEvent,
@@ -85,13 +86,18 @@ export const wrapMethodWithNetworkSwitch = <T extends (...args: Todo[]) => Todo>
85
86
  try {
86
87
  await switchEVMWalletNetwork(provider, chainId);
87
88
  } catch (error) {
88
- throw new Error(`Failed to switch network: ${error}`);
89
+ throw new SwapKitError({
90
+ errorKey: "helpers_failed_to_switch_network",
91
+ info: { error },
92
+ });
89
93
  }
90
94
  return func(...args);
91
95
  }) as unknown as T;
92
96
 
93
97
  const providerRequest = ({ provider, params, method }: ProviderRequestParams) => {
94
- if (!provider?.send) throw new Error("Provider not found");
98
+ if (!provider?.send) {
99
+ throw new SwapKitError("helpers_not_found_provider");
100
+ }
95
101
 
96
102
  const providerParams = params ? (Array.isArray(params) ? params : [params]) : [];
97
103
  return provider.send(method, providerParams);
@@ -411,8 +411,8 @@ describe("AssetValue", () => {
411
411
  decimal: 8,
412
412
  isGasAsset: false,
413
413
  isSynthetic: false,
414
- symbol: "BTC.b-0x152b9d0fdc40c096757f570a51e494bd4b943e50",
415
- ticker: "BTC.b",
414
+ symbol: "BTC.B-0x152b9d0fdc40c096757f570a51e494bd4b943e50",
415
+ ticker: "BTC.B",
416
416
  }),
417
417
  );
418
418
  });
@@ -6,6 +6,7 @@ import type { TokenNames, TokenTax } from "../types/tokens.ts";
6
6
 
7
7
  import type { NumberPrimitives } from "./bigIntArithmetics.ts";
8
8
  import { BigIntArithmetics, formatBigIntToSafeValue } from "./bigIntArithmetics.ts";
9
+ import { SwapKitError } from "./swapKitError.ts";
9
10
  import { SwapKitNumber, type SwapKitValueType } from "./swapKitNumber.ts";
10
11
 
11
12
  const staticTokensMap = new Map<
@@ -71,7 +72,12 @@ export class AssetValue extends BigIntArithmetics {
71
72
  // ETH.THOR-0x1234567890
72
73
  static fromUrl(urlAsset: string, value: NumberPrimitives = 0) {
73
74
  const [chain, ticker, symbol] = urlAsset.split(".");
74
- if (!(chain && ticker)) throw new Error("Invalid asset url");
75
+ if (!(chain && ticker)) {
76
+ throw new SwapKitError({
77
+ errorKey: "helpers_invalid_asset_url",
78
+ info: { urlAsset },
79
+ });
80
+ }
75
81
 
76
82
  const assetString =
77
83
  chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;
@@ -83,11 +89,7 @@ export class AssetValue extends BigIntArithmetics {
83
89
  return createAssetValue(assetString, value);
84
90
  }
85
91
  static fromIdentifier(
86
- assetString:
87
- | `${Chain}.${string}`
88
- | `${Chain}/${string}`
89
- | `${Chain}.${string}-${string}`
90
- | TokenNames,
92
+ assetString: `${Chain}.${string}` | `${Chain}/${string}` | TokenNames,
91
93
  value: NumberPrimitives = 0,
92
94
  ) {
93
95
  return createAssetValue(assetString, value);
@@ -128,7 +130,7 @@ export class AssetValue extends BigIntArithmetics {
128
130
  from: 0,
129
131
  to: baseDecimal,
130
132
  }).getBaseValue("string");
131
- const assetValue = await AssetValue.fromString(assetString, value);
133
+ const assetValue = await AssetValue.fromString(assetString);
132
134
 
133
135
  return assetValue.set(shiftedAmount);
134
136
  }
@@ -257,7 +259,12 @@ function createSyntheticAssetValue(identifier: string, value: NumberPrimitives =
257
259
  ? identifier.split(".").slice(1).join().split("/")
258
260
  : identifier.split("/");
259
261
 
260
- if (!(synthChain && symbol)) throw new Error("Invalid asset identifier");
262
+ if (!(synthChain && symbol)) {
263
+ throw new SwapKitError({
264
+ errorKey: "helpers_invalid_asset_identifier",
265
+ info: { identifier },
266
+ });
267
+ }
261
268
 
262
269
  return new AssetValue({
263
270
  decimal: 8,
@@ -284,7 +291,12 @@ function getAssetInfo(identifier: string) {
284
291
  ? identifier.split(".").slice(1).join().split("/")
285
292
  : identifier.split("/");
286
293
 
287
- if (isSynthetic && !(synthChain && synthSymbol)) throw new Error("Invalid asset identifier");
294
+ if (isSynthetic && !(synthChain && synthSymbol)) {
295
+ throw new SwapKitError({
296
+ errorKey: "helpers_invalid_asset_identifier",
297
+ info: { identifier },
298
+ });
299
+ }
288
300
 
289
301
  const adjustedIdentifier =
290
302
  identifier.includes(".") && !isSynthetic
@@ -1,8 +1,7 @@
1
- const errorMessages = {
1
+ const errorCodes = {
2
2
  /**
3
3
  * Core
4
4
  */
5
- core_wallet_connection_not_found: 10001,
6
5
  core_estimated_max_spendable_chain_not_supported: 10002,
7
6
  core_extend_error: 10003,
8
7
  core_inbound_data_not_found: 10004,
@@ -10,10 +9,10 @@ const errorMessages = {
10
9
  core_plugin_not_found: 10006,
11
10
  core_plugin_swap_not_found: 10007,
12
11
  core_approve_asset_target_invalid: 10008,
12
+ core_explorer_unsupported_chain: 10009,
13
13
  core_chain_halted: 10099,
14
- /**
15
- * Core - Wallet Connection
16
- */
14
+
15
+ core_wallet_connection_not_found: 10100,
17
16
  core_wallet_xdefi_not_installed: 10101,
18
17
  core_wallet_evmwallet_not_installed: 10102,
19
18
  core_wallet_walletconnect_not_installed: 10103,
@@ -56,40 +55,86 @@ const errorMessages = {
56
55
  * Wallets
57
56
  */
58
57
  wallet_connection_rejected_by_user: 20000,
59
- wallet_ledger_connection_error: 20001,
60
- wallet_ledger_connection_claimed: 20002,
61
- wallet_ledger_get_address_error: 20003,
62
- wallet_ledger_device_not_found: 20004,
63
- wallet_ledger_device_locked: 20005,
64
- wallet_phantom_not_found: 20101,
65
- wallet_xdefi_not_found: 20201,
66
- wallet_xdefi_failed_to_add_or_switch_network: 20202,
58
+ wallet_missing_api_key: 20001,
59
+ wallet_chain_not_supported: 20002,
60
+ wallet_missing_params: 20003,
61
+ wallet_provider_not_found: 20004,
62
+ wallet_failed_to_add_or_switch_network: 20005,
63
+ wallet_ledger_connection_error: 20101,
64
+ wallet_ledger_connection_claimed: 20102,
65
+ wallet_ledger_get_address_error: 20103,
66
+ wallet_ledger_device_not_found: 20104,
67
+ wallet_ledger_device_locked: 20105,
68
+ wallet_phantom_not_found: 20201,
69
+ wallet_xdefi_not_found: 20301,
70
+ wallet_xdefi_send_transaction_no_address: 20302,
71
+ wallet_xdefi_contract_address_not_provided: 20303,
72
+ wallet_xdefi_asset_not_defined: 20304,
73
+ wallet_walletconnect_project_id_not_specified: 20401,
74
+ wallet_walletconnect_connection_not_established: 20402,
75
+ wallet_walletconnect_namespace_not_supported: 20403,
76
+ wallet_trezor_failed_to_sign_transaction: 20501,
77
+ wallet_trezor_derivation_path_not_supported: 20502,
78
+ wallet_trezor_failed_to_get_address: 20503,
79
+ wallet_talisman_not_enabled: 20601,
80
+ wallet_talisman_not_found: 20602,
67
81
  /**
68
82
  * Chainflip
69
83
  */
70
84
  chainflip_channel_error: 30001,
71
- chainflip_broker_recipient_error: 30002,
72
- chainflip_unknown_asset: 30003,
85
+ chainflip_unknown_asset: 30002,
86
+ chainflip_broker_invalid_params: 30100,
87
+ chainflip_broker_recipient_error: 30101,
88
+ chainflip_broker_register: 30102,
89
+ chainflip_broker_tx_error: 30103,
90
+ chainflip_broker_withdraw: 30104,
91
+ chainflip_broker_fund_only_flip_supported: 30105,
92
+ chainflip_broker_fund_invalid_address: 30106,
73
93
  /**
74
94
  * THORChain
75
95
  */
76
96
  thorchain_chain_halted: 40001,
77
97
  thorchain_trading_halted: 40002,
98
+ thorchain_swapin_router_required: 40100,
99
+ thorchain_swapin_vault_required: 40101,
100
+ thorchain_swapin_memo_required: 40102,
101
+ thorchain_swapin_token_required: 40103,
78
102
  /**
79
103
  * SwapKit API
80
104
  */
81
105
  api_v2_invalid_response: 50001,
82
106
 
107
+ /**
108
+ * Toolboxes
109
+ */
110
+ toolbox_cosmos_signer_not_defined: 90101,
111
+ toolbox_cosmos_no_accounts_found: 90102,
83
112
  /**
84
113
  * Helpers
85
114
  */
86
- helpers_number_different_decimals: 99001,
115
+ helpers_invalid_number_different_decimals: 99000,
116
+ helpers_invalid_number_of_years: 99001,
117
+ helpers_invalid_identifier: 99002,
118
+ helpers_invalid_asset_url: 99003,
119
+ helpers_invalid_asset_identifier: 99004,
120
+ helpers_invalid_memo_type: 99005,
121
+ helpers_failed_to_switch_network: 99103,
122
+ helpers_not_found_provider: 99200,
87
123
  } as const;
88
124
 
89
- export type ErrorKeys = keyof typeof errorMessages;
125
+ export type ErrorKeys = keyof typeof errorCodes;
90
126
 
91
127
  export class SwapKitError extends Error {
92
- constructor(errorKey: ErrorKeys, sourceError?: NotWorth) {
128
+ static ErrorCode = errorCodes;
129
+
130
+ constructor(
131
+ errorOrErrorKey: ErrorKeys | { errorKey: ErrorKeys; info?: Record<string, NotWorth> },
132
+ sourceError?: NotWorth,
133
+ ) {
134
+ const isErrorString = typeof errorOrErrorKey === "string";
135
+
136
+ const errorKey = isErrorString ? errorOrErrorKey : errorOrErrorKey.errorKey;
137
+
93
138
  if (sourceError) {
94
139
  console.error(sourceError, {
95
140
  stack: sourceError?.stack,
@@ -98,8 +143,12 @@ export class SwapKitError extends Error {
98
143
  }
99
144
 
100
145
  super(errorKey, {
101
- cause: { code: errorMessages[errorKey], message: errorKey },
146
+ cause: {
147
+ code: SwapKitError.ErrorCode[errorKey],
148
+ message: `${errorKey}${isErrorString ? "" : `: ${JSON.stringify(errorOrErrorKey.info)}`}`,
149
+ },
102
150
  });
151
+
103
152
  Object.setPrototypeOf(this, SwapKitError.prototype);
104
153
  }
105
154
  }