@dappworks/kit 0.5.34 → 0.5.36

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 (55) hide show
  1. package/dist/{PromiseState-DVdsif1j.d.ts → PromiseState-e64b3707.d.ts} +1 -1
  2. package/dist/{StorageState-qapaHguM.d.ts → StorageState-cfd942cb.d.ts} +1 -1
  3. package/dist/aiem.d.mts +3 -3
  4. package/dist/aiem.mjs +2 -2
  5. package/dist/{chunk-BQSQ4L7R.mjs → chunk-5BTB7HRK.mjs} +2 -2
  6. package/dist/chunk-6F7H4PAA.mjs +35 -0
  7. package/dist/{chunk-I2RSE63R.mjs → chunk-72E76L6J.mjs} +2 -2
  8. package/dist/{chunk-2L5EKCYR.mjs → chunk-AVG4JG4V.mjs} +4 -4
  9. package/dist/chunk-BR7IWH2E.mjs +1284 -0
  10. package/dist/chunk-BR7IWH2E.mjs.map +1 -0
  11. package/dist/{chunk-SA53R6TL.mjs → chunk-KIS52LFU.mjs} +7 -7
  12. package/dist/{chunk-SA53R6TL.mjs.map → chunk-KIS52LFU.mjs.map} +1 -1
  13. package/dist/{chunk-FWK5VZHE.mjs → chunk-NKGQRF5D.mjs} +3 -3
  14. package/dist/{chunk-BAXWSAXB.mjs → chunk-SPFKGNUY.mjs} +364 -388
  15. package/dist/chunk-SPFKGNUY.mjs.map +1 -0
  16. package/dist/{chunk-WWCB4WOQ.mjs → chunk-WMV5O3PI.mjs} +4 -4
  17. package/dist/chunk-WMV5O3PI.mjs.map +1 -0
  18. package/dist/dev.d.mts +1 -1
  19. package/dist/dev.mjs +2 -2
  20. package/dist/experimental.d.mts +5 -5
  21. package/dist/experimental.mjs +3 -3
  22. package/dist/form.d.mts +14 -14
  23. package/dist/form.mjs +3 -3
  24. package/dist/form.mjs.map +1 -1
  25. package/dist/{index-CUKoRIdy.d.ts → index-38be834f.d.ts} +1 -1
  26. package/dist/index.d.mts +5 -5
  27. package/dist/index.mjs +6 -6
  28. package/dist/inspector.d.mts +1 -1
  29. package/dist/inspector.mjs +1 -1
  30. package/dist/jsoncomponent.d.mts +1 -1
  31. package/dist/jsoncomponent.mjs +1 -1
  32. package/dist/jsontable.d.mts +2 -2
  33. package/dist/jsontable.mjs +4 -4
  34. package/dist/metrics.d.mts +1 -1
  35. package/dist/metrics.mjs +4 -4
  36. package/dist/plugins.d.mts +8 -8
  37. package/dist/plugins.mjs +5 -5
  38. package/dist/{root-BPMUmS6H.d.ts → root-218afa4f.d.ts} +1 -1
  39. package/dist/ui.mjs +3 -3
  40. package/dist/utils.d.mts +19 -100
  41. package/dist/utils.mjs +1 -1
  42. package/dist/wallet.d.mts +4 -4
  43. package/dist/wallet.mjs +7 -7
  44. package/package.json +175 -174
  45. package/dist/chunk-4KRVA5CB.mjs +0 -23690
  46. package/dist/chunk-4KRVA5CB.mjs.map +0 -1
  47. package/dist/chunk-BAXWSAXB.mjs.map +0 -1
  48. package/dist/chunk-VIK2VI34.mjs +0 -69
  49. package/dist/chunk-WWCB4WOQ.mjs.map +0 -1
  50. /package/dist/{PaginationState-Bmrrw0ky.d.ts → PaginationState-c19e621a.d.ts} +0 -0
  51. /package/dist/{chunk-BQSQ4L7R.mjs.map → chunk-5BTB7HRK.mjs.map} +0 -0
  52. /package/dist/{chunk-VIK2VI34.mjs.map → chunk-6F7H4PAA.mjs.map} +0 -0
  53. /package/dist/{chunk-I2RSE63R.mjs.map → chunk-72E76L6J.mjs.map} +0 -0
  54. /package/dist/{chunk-2L5EKCYR.mjs.map → chunk-AVG4JG4V.mjs.map} +0 -0
  55. /package/dist/{chunk-FWK5VZHE.mjs.map → chunk-NKGQRF5D.mjs.map} +0 -0
@@ -0,0 +1,1284 @@
1
+ import { AIem } from './chunk-WMV5O3PI.mjs';
2
+ import { DialogStore } from './chunk-NKGQRF5D.mjs';
3
+ import { ToastPlugin } from './chunk-7EL2RQI7.mjs';
4
+ import { RootStore, rootStore } from './chunk-KIS52LFU.mjs';
5
+ import { helper } from './chunk-7WJMHFRA.mjs';
6
+ import { __spreadProps, __spreadValues } from './chunk-6F7H4PAA.mjs';
7
+ import { observable, makeAutoObservable } from 'mobx';
8
+ import BigNumber2 from 'bignumber.js';
9
+ import React3, { useEffect } from 'react';
10
+ import { useRouter } from 'next/router.js';
11
+ import { observer } from 'mobx-react-lite';
12
+ import { toHex, createWalletClient, custom, publicActions } from 'viem';
13
+ import EventEmitter from 'events';
14
+ import { useAccount, useSwitchChain, useConnect, useDisconnect, useWalletClient } from 'wagmi';
15
+ import { getDefaultConfig, useConnectModal } from '@rainbow-me/rainbowkit';
16
+ import { Icon } from '@iconify/react';
17
+ import { iopayWallet, metaMaskWallet, walletConnectWallet, okxWallet, binanceWallet, safeWallet, gateWallet } from '@rainbow-me/rainbowkit/wallets';
18
+ import SafeAppsSDK, { TransactionStatus } from '@safe-global/safe-apps-sdk';
19
+ import { Card, Input } from '@nextui-org/react';
20
+ import TransportWebUSB from '@ledgerhq/hw-transport-webusb';
21
+ import Eth from '@ledgerhq/hw-app-eth';
22
+ import { ethers } from 'ethers';
23
+
24
+ //@ts-ignore
25
+ observable();
26
+ var PromiseHook = class {
27
+ static Get(cls) {
28
+ try {
29
+ return async ({ args, select, id, unselect }) => {
30
+ let instance;
31
+ if (!id || !this.entities[id]) {
32
+ instance = new cls(args);
33
+ instance.refresh = async () => {
34
+ const hooks = Object.entries(instance).filter((i) => {
35
+ if (!this.isPromiseHook(instance[i[0]]))
36
+ return false;
37
+ if (i[1].lazy)
38
+ return false;
39
+ if (select && !select[i[0]])
40
+ return false;
41
+ if (unselect && unselect[i[0]])
42
+ return false;
43
+ return true;
44
+ }).map((i) => {
45
+ const hook = instance[i[0]];
46
+ return hook;
47
+ });
48
+ await Promise.all(hooks.map((i) => i.call()));
49
+ };
50
+ if (id) {
51
+ this.entities[id] = instance;
52
+ }
53
+ } else {
54
+ instance = this.entities[id];
55
+ }
56
+ await instance.refresh();
57
+ return instance;
58
+ };
59
+ } catch (e) {
60
+ throw e;
61
+ }
62
+ }
63
+ static isPromiseHook(target) {
64
+ return (target == null ? void 0 : target._type) == "promiseHook";
65
+ }
66
+ //ttl : ms
67
+ static wrap({ func, defaultValue, lazy }) {
68
+ let context;
69
+ const call = (args) => {
70
+ context.loading = true;
71
+ if (!context._call) {
72
+ context._call = func(args).then((i) => {
73
+ context.value = i;
74
+ context.loading = false;
75
+ context._call = null;
76
+ return i;
77
+ }).catch((i) => {
78
+ console.error(i, func);
79
+ context.value = defaultValue;
80
+ context._call = null;
81
+ context.loading = false;
82
+ throw i;
83
+ });
84
+ }
85
+ return context._call;
86
+ };
87
+ const get = async (args) => {
88
+ if (!context.value) {
89
+ return call(args);
90
+ }
91
+ return context.value;
92
+ };
93
+ if (!context) {
94
+ context = observable({
95
+ _type: "promiseHook",
96
+ _value: defaultValue,
97
+ get value() {
98
+ return context["_value"];
99
+ },
100
+ set value(val) {
101
+ context["_value"] = val;
102
+ },
103
+ get,
104
+ lazy,
105
+ loading: false,
106
+ call,
107
+ defaultValue,
108
+ toJSON() {
109
+ return context.value;
110
+ },
111
+ toString() {
112
+ return context.value;
113
+ }
114
+ });
115
+ }
116
+ return context;
117
+ }
118
+ };
119
+ PromiseHook.entities = observable([]);
120
+ var BigNumberState = class {
121
+ constructor(args) {
122
+ this.value = new BigNumber2(0);
123
+ this.loading = false;
124
+ this.decimals = 18;
125
+ this.fixed = 6;
126
+ Object.assign(this, args);
127
+ makeAutoObservable(this, {
128
+ getFormat: false
129
+ });
130
+ }
131
+ get format() {
132
+ if (this.loading)
133
+ return "...";
134
+ return this.getFormat();
135
+ }
136
+ getFormat({ decimals = this.decimals, fixed = this.fixed } = {}) {
137
+ if (this.loading)
138
+ return "...";
139
+ if (this.formatter)
140
+ return this.formatter(this);
141
+ return helper.number.toPrecisionFloor(new BigNumber2(this.value).dividedBy(10 ** decimals).toFixed(), {
142
+ decimals: fixed
143
+ });
144
+ }
145
+ setDecimals(decimals) {
146
+ this.decimals = decimals;
147
+ }
148
+ setValue(value) {
149
+ this.value = value;
150
+ this.setLoading(false);
151
+ }
152
+ setLoading(val) {
153
+ this.loading = val;
154
+ }
155
+ };
156
+ var BigNumberInputState = class {
157
+ constructor(args) {
158
+ this.value = new BigNumber2(0);
159
+ this.format = "";
160
+ this.loading = false;
161
+ this.decimals = 18;
162
+ Object.assign(this, args);
163
+ makeAutoObservable(this);
164
+ }
165
+ get noDecimasValue() {
166
+ return new BigNumber2(this.value).dividedBy(10 ** this.decimals);
167
+ }
168
+ setValue(value) {
169
+ this.value = new BigNumber2(value);
170
+ this.format = helper.number.warpBigNumber(this.value.toFixed(), this.decimals, { format: "0.000", fallback: "" }).format;
171
+ this.setLoading(false);
172
+ }
173
+ setFormat(val) {
174
+ this.format = val;
175
+ this.value = new BigNumber2(val).multipliedBy(10 ** this.decimals);
176
+ }
177
+ setLoading(val) {
178
+ this.loading = val;
179
+ }
180
+ setDecimals(val) {
181
+ this.decimals = val;
182
+ }
183
+ get isZero() {
184
+ return this.value.isZero() && this.format == "";
185
+ }
186
+ };
187
+ var StorageState = class _StorageState {
188
+ constructor(args) {
189
+ this.value = null;
190
+ this.default = null;
191
+ Object.assign(this, args);
192
+ makeAutoObservable(this);
193
+ this.load();
194
+ }
195
+ static safeParse(val) {
196
+ try {
197
+ return JSON.parse(val);
198
+ } catch (error) {
199
+ return val;
200
+ }
201
+ }
202
+ load() {
203
+ var _a;
204
+ try {
205
+ if (typeof window == "undefined")
206
+ return;
207
+ const value = (_a = window == null ? void 0 : window.localStorage) == null ? void 0 : _a.getItem(this.key);
208
+ this.value = _StorageState.safeParse(value);
209
+ if (this.value == null) {
210
+ this.value = this.default;
211
+ }
212
+ return this.value;
213
+ } catch (error) {
214
+ console.error(error);
215
+ return null;
216
+ }
217
+ }
218
+ save(value) {
219
+ try {
220
+ if (typeof window == "undefined")
221
+ return;
222
+ if (value !== null || value !== void 0) {
223
+ this.value = value;
224
+ }
225
+ window == null ? void 0 : window.localStorage.setItem(this.key, JSON.stringify(value));
226
+ } catch (error) {
227
+ console.error(error);
228
+ return null;
229
+ }
230
+ }
231
+ setValue(value) {
232
+ this.save(value);
233
+ }
234
+ clear() {
235
+ try {
236
+ if (typeof window == "undefined")
237
+ return;
238
+ window == null ? void 0 : window.localStorage.removeItem(this.key);
239
+ } catch (error) {
240
+ return null;
241
+ }
242
+ }
243
+ };
244
+ var StorageListState = class _StorageListState {
245
+ constructor(args) {
246
+ this.list = [];
247
+ Object.assign(this, args);
248
+ makeAutoObservable(this);
249
+ this.load();
250
+ }
251
+ static safeParse(val) {
252
+ try {
253
+ return JSON.parse(val);
254
+ } catch (error) {
255
+ return val;
256
+ }
257
+ }
258
+ load() {
259
+ try {
260
+ const value = localStorage.getItem(this.key);
261
+ if (value) {
262
+ this.list = _StorageListState.safeParse(value);
263
+ }
264
+ return _StorageListState.safeParse(value);
265
+ } catch (error) {
266
+ console.error(error);
267
+ return null;
268
+ }
269
+ }
270
+ push(value) {
271
+ this.list.push(value);
272
+ this.save();
273
+ }
274
+ remove(index) {
275
+ this.list.splice(index, 1);
276
+ this.save();
277
+ }
278
+ save() {
279
+ try {
280
+ localStorage.setItem(this.key, JSON.stringify(this.list));
281
+ } catch (error) {
282
+ }
283
+ }
284
+ clear() {
285
+ try {
286
+ localStorage.removeItem(this.key);
287
+ this.list = [];
288
+ } catch (error) {
289
+ }
290
+ }
291
+ };
292
+
293
+ // store/standard/ObjectPool.ts
294
+ var _ObjectPool = class _ObjectPool {
295
+ static get(key, func) {
296
+ if (!_ObjectPool.pool[key]) {
297
+ _ObjectPool.pool[key] = func();
298
+ }
299
+ return _ObjectPool.pool[key];
300
+ }
301
+ };
302
+ _ObjectPool.pool = {};
303
+ var ObjectPool = _ObjectPool;
304
+ var WalletConfigStore = class {
305
+ constructor(args) {
306
+ this.sid = "WalletConfigStore";
307
+ this.autoObservable = true;
308
+ this.appName = "Dappkit";
309
+ this.projectId = "b69e844f38265667350efd78e3e1a5fb";
310
+ this.defaultChainId = 4689;
311
+ this.updateTicker = 1;
312
+ this.walletUpdateTick = 0;
313
+ this.isConnect = false;
314
+ this.isInSafeApp = false;
315
+ // This mode to resolve and walletClient and nextui in some extreme cases cause page infinite redraw bugs
316
+ this.compatibleMode = true;
317
+ Object.assign(this, args);
318
+ }
319
+ set(params) {
320
+ Object.assign(this, params);
321
+ this.updateTicker += 1;
322
+ }
323
+ get reconnectOnMount() {
324
+ if (!this.compatibleMode)
325
+ return true;
326
+ if (!this.isConnect && this.walletUpdateTick == 0) {
327
+ return true;
328
+ }
329
+ if (!this.isConnect && this.walletUpdateTick != 0) {
330
+ return false;
331
+ }
332
+ if (this.isConnect) {
333
+ return true;
334
+ }
335
+ }
336
+ get rainbowKitConfig() {
337
+ var _a;
338
+ return ObjectPool.get(`rainbowKitConfig-${(_a = this.supportedChains) == null ? void 0 : _a.map((i) => i.id).join("-")}`, () => {
339
+ return getDefaultConfig({
340
+ pollingInterval: 2500,
341
+ appName: this.appName,
342
+ projectId: this.projectId,
343
+ //@ts-ignore
344
+ chains: this.supportedChains,
345
+ wallets: [
346
+ {
347
+ groupName: "Recommended",
348
+ wallets: [iopayWallet, metaMaskWallet]
349
+ },
350
+ {
351
+ groupName: "Others",
352
+ wallets: [metaMaskWallet, walletConnectWallet, iopayWallet, okxWallet, binanceWallet, safeWallet, gateWallet]
353
+ }
354
+ ]
355
+ });
356
+ });
357
+ }
358
+ };
359
+
360
+ // module/Wallet/walletPluginStore.tsx
361
+ var defaultRPCList = [
362
+ { name: "https://babel-api.fastblocks.io", latency: 0, height: 0, custom: false },
363
+ { name: "https://babel-api.mainnet.iotex.one", latency: 0, height: 0 },
364
+ { name: "https://babel-api.mainnet.iotex.io", latency: 0, height: 0 },
365
+ { name: "https://iotex-network.rpc.thirdweb.com", latency: 0, height: 0 },
366
+ // { name: 'https://iotexrpc.com', latency: 0, height: 0, },
367
+ { name: "https://iotex.api.onfinality.io/public", latency: 0, height: 0 }
368
+ // { name: 'https://rpc.ankr.com/iotex', latency: 0, height: 0, },
369
+ ];
370
+ var WalletRpcStore = class {
371
+ constructor() {
372
+ this.sid = "WalletPluginStore";
373
+ this.autoObservable = true;
374
+ this.curRpc = new StorageState({ default: "https://babel-api.mainnet.iotex.one", key: "curRPC-v2", value: "https://babel-api.mainnet.iotex.one" });
375
+ this.isAutoSelectRpc = new StorageState({ key: "isAutoSelectRpc", default: true });
376
+ this.customRpc = "";
377
+ this.rpcList = new StorageState({ key: "customRpcList-v2", default: defaultRPCList, value: [] });
378
+ this.showCustomRpc = false;
379
+ }
380
+ get currentRpc() {
381
+ var _a, _b;
382
+ console.log((_a = this.rpcList.value) == null ? void 0 : _a.find((i) => i.name == this.curRpc));
383
+ return ((_b = this.rpcList.value) == null ? void 0 : _b.find((i) => i.name == this.curRpc.value)) || null;
384
+ }
385
+ addCustomRpc() {
386
+ const item = { name: this.customRpc, latency: 0, height: 0, custom: true };
387
+ if (defaultRPCList.find((i) => i.name === item.name)) {
388
+ return RootStore.Get(ToastPlugin).error("Rpc already exists");
389
+ }
390
+ if (this.rpcList.value) {
391
+ this.rpcList.save([...this.rpcList.value, item]);
392
+ this.refresh();
393
+ return;
394
+ }
395
+ this.rpcList.save([...defaultRPCList, item]);
396
+ this.refresh();
397
+ }
398
+ async addToMetamask(url) {
399
+ var _a;
400
+ try {
401
+ if (typeof window == "undefined")
402
+ return;
403
+ await ((_a = window == null ? void 0 : window.ethereum) == null ? void 0 : _a.request({
404
+ method: "wallet_addEthereumChain",
405
+ params: [{
406
+ chainId: `0x${4689 .toString(16)}`,
407
+ chainName: "IoTeX Mainnet",
408
+ nativeCurrency: {
409
+ name: "IoTeX",
410
+ symbol: "IOTX",
411
+ decimals: 18
412
+ },
413
+ rpcUrls: [url],
414
+ blockExplorerUrls: ["https://iotexscan.io"]
415
+ }]
416
+ }));
417
+ RootStore.Get(ToastPlugin).success("Network added");
418
+ console.log("Network added");
419
+ } catch (error) {
420
+ console.error("Failed to add network", error);
421
+ }
422
+ }
423
+ async switchOrAddChain(chainId) {
424
+ return new Promise(async (resolve, reject) => {
425
+ try {
426
+ await window.ethereum.request({
427
+ method: "wallet_switchEthereumChain",
428
+ params: [{ chainId: toHex(chainId) }]
429
+ });
430
+ resolve(true);
431
+ } catch (switchError) {
432
+ if (switchError.code === 4902) {
433
+ try {
434
+ await this.addToMetamaskById(chainId);
435
+ } catch (addError) {
436
+ reject(addError);
437
+ }
438
+ } else {
439
+ reject(switchError);
440
+ }
441
+ }
442
+ });
443
+ }
444
+ async addToMetamaskById(id) {
445
+ return new Promise(async (resolve, reject) => {
446
+ try {
447
+ if (typeof window == "undefined")
448
+ return;
449
+ const chain = RootStore.Get(WalletConfigStore).supportedChains.find((i) => i.id == id);
450
+ const res = await window.ethereum.request({
451
+ method: "wallet_addEthereumChain",
452
+ params: [{
453
+ "chainId": toHex(chain.id),
454
+ "chainName": chain.name,
455
+ "nativeCurrency": {
456
+ "name": chain.nativeCurrency.name,
457
+ "symbol": chain.nativeCurrency.symbol,
458
+ "decimals": chain.nativeCurrency.decimals
459
+ },
460
+ "rpcUrls": JSON.parse(JSON.stringify(chain.rpcUrls.default.http)),
461
+ "blockExplorerUrls": [chain.blockExplorers.default.url]
462
+ }]
463
+ });
464
+ console.log(res);
465
+ resolve(res);
466
+ } catch (switchError) {
467
+ reject(false);
468
+ }
469
+ });
470
+ }
471
+ refresh() {
472
+ this.showCustomRpc = false;
473
+ this.customRpc = "";
474
+ setTimeout(() => {
475
+ this.testRpc();
476
+ }, 500);
477
+ }
478
+ latencyColor(latency) {
479
+ if (latency < 0) {
480
+ return "text-red-500";
481
+ }
482
+ if (latency < 1) {
483
+ return "text-green-500";
484
+ }
485
+ if (latency < 2) {
486
+ return "text-yellow-500";
487
+ }
488
+ return "text-red-500";
489
+ }
490
+ async testRpcFunction(url) {
491
+ const start = performance.now();
492
+ try {
493
+ const response = await fetch(url, {
494
+ method: "POST",
495
+ headers: {
496
+ "Content-Type": "application/json"
497
+ },
498
+ body: JSON.stringify({
499
+ jsonrpc: "2.0",
500
+ method: "eth_getBlockByNumber",
501
+ params: ["latest", false],
502
+ id: 1
503
+ })
504
+ });
505
+ if (!response.ok) {
506
+ throw new Error(`Error from server: ${response.status}`);
507
+ }
508
+ const res = await response.json();
509
+ console.log(res);
510
+ const end = performance.now();
511
+ return { url, lentency: Number(helper.number.numberFormat((end - start) / 1e3, "0.000", { fallback: "-1" })), height: parseInt(res.result.number, 16) };
512
+ } catch (error) {
513
+ console.error("RPC Latency Test Failed:", error);
514
+ return { url, lentency: -1, height: -1 };
515
+ }
516
+ }
517
+ testRpc() {
518
+ var _a;
519
+ (_a = this.rpcList) == null ? void 0 : _a.value.forEach((i) => {
520
+ this.testRpcFunction(i.name).then((res) => {
521
+ i.latency = res.lentency;
522
+ i.height = res.height;
523
+ });
524
+ });
525
+ this.rpcList.save(this.rpcList.value);
526
+ }
527
+ removeRpc(name) {
528
+ this.rpcList.save(this.rpcList.value.filter((i) => i.name !== name));
529
+ }
530
+ scoreIcon(score) {
531
+ if (score < 0) {
532
+ return /* @__PURE__ */ React3.createElement(Icon, { icon: "codicon:error", width: "18", height: "18", style: { color: "#FF0000" } });
533
+ }
534
+ if (score < 1) {
535
+ return /* @__PURE__ */ React3.createElement(Icon, { icon: "icon-park-solid:check-one", width: "18", height: "18", style: { color: "#289726" } });
536
+ }
537
+ if (score < 2) {
538
+ return /* @__PURE__ */ React3.createElement(Icon, { icon: "bxs:error", width: "18", height: "18", style: { color: "#FFA500" } });
539
+ }
540
+ return /* @__PURE__ */ React3.createElement(Icon, { icon: "codicon:error", width: "18", height: "18", style: { color: "#FF0000" } });
541
+ }
542
+ get wallet() {
543
+ return RootStore.Get(WalletStore);
544
+ }
545
+ // debounceAutoSelectRpc = pDebounce(this.autoSelectRpc, 3000)
546
+ async autoSelectRpc() {
547
+ console.log("autoSelectRpc");
548
+ for (let i = 0; i < this.rpcList.value.length; i++) {
549
+ const item = this.rpcList.value[i];
550
+ const res = await this.testRpcFunction(item.name);
551
+ if (res.lentency != -1 || res.height > 0) {
552
+ this.curRpc.save(item.name);
553
+ break;
554
+ }
555
+ }
556
+ }
557
+ };
558
+ var WalletHistoryStore = class {
559
+ constructor() {
560
+ this.sid = "WalletHistoryStore";
561
+ this.isRender = false;
562
+ this.autoObservable = true;
563
+ this.history = new StorageState({ value: [], key: "history" });
564
+ }
565
+ set(params) {
566
+ Object.assign(this, params);
567
+ }
568
+ get historyList() {
569
+ if (this.isRender) {
570
+ return this.history.value;
571
+ }
572
+ return [];
573
+ }
574
+ recordHistory(item) {
575
+ let value = this.history.load();
576
+ if (!value) {
577
+ value = [item];
578
+ } else {
579
+ value = [...value, item];
580
+ }
581
+ this.history.setValue(value);
582
+ }
583
+ updateHistoryStatusByTx(tx, status) {
584
+ let value = this.history.load();
585
+ if (!value) {
586
+ return;
587
+ }
588
+ value = value.map((i) => {
589
+ if (i.tx == tx) {
590
+ i.status = status;
591
+ return i;
592
+ }
593
+ if (!tx) {
594
+ i.status = status;
595
+ }
596
+ return i;
597
+ });
598
+ this.history.setValue(value);
599
+ }
600
+ clearHistory() {
601
+ this.history.setValue(null);
602
+ }
603
+ };
604
+ var SuccessTxDialog = observer((props) => {
605
+ return /* @__PURE__ */ React3.createElement("div", { className: "flex-col gap-4 py-10" }, /* @__PURE__ */ React3.createElement("div", { className: "w-full flex items-center justify-center" }, /* @__PURE__ */ React3.createElement(Icon, { icon: "icon-park-solid:check-one", width: "48", height: "48", className: "text-green-500" })), /* @__PURE__ */ React3.createElement("div", { className: "text-2xl font-[900] text-center mt-4" }, props.msg), /* @__PURE__ */ React3.createElement(
606
+ "div",
607
+ {
608
+ className: "flex items-center justify-center text-green-500 text-sm mt-6 gap-2 cursor-pointer hover:text-green-600 transition",
609
+ onClick: (e) => window.open(`https://iotexscan.io/tx/${props.hash}`, "_blank")
610
+ },
611
+ "View on IoTeXScan ",
612
+ /* @__PURE__ */ React3.createElement(Icon, { icon: "material-symbols:chip-extraction-rounded", width: "18", height: "18" })
613
+ ));
614
+ });
615
+ var ShowSuccessTxDialog = ({ msg, hash }) => {
616
+ RootStore.Get(DialogStore).setData({
617
+ title: "",
618
+ content: /* @__PURE__ */ React3.createElement(SuccessTxDialog, { msg, hash }),
619
+ isOpen: true
620
+ });
621
+ };
622
+ var _transport = null;
623
+ var _signer = null;
624
+ async function createTransport() {
625
+ if (_transport) {
626
+ return _transport;
627
+ }
628
+ try {
629
+ const res = await TransportWebUSB.create();
630
+ console.log("createTransport res", res);
631
+ _transport = res;
632
+ return res;
633
+ } catch (error) {
634
+ console.error("Error creating transport", error);
635
+ throw error;
636
+ }
637
+ }
638
+ function waiter(duration) {
639
+ return new Promise((resolve) => {
640
+ setTimeout(resolve, duration);
641
+ });
642
+ }
643
+ var GlobalLedgerProvider = ObjectPool.get("provider", async () => {
644
+ return new ethers.providers.JsonRpcProvider("https://babel-api.mainnet.iotex.io");
645
+ });
646
+ var GlobalLedgerSigner = async () => {
647
+ var _a;
648
+ try {
649
+ if (_signer) {
650
+ return _signer;
651
+ }
652
+ const transport = await createTransport();
653
+ _signer = new LedgerSigner(transport, await GlobalLedgerProvider, "44'/304'/0'/0/0");
654
+ return _signer;
655
+ } catch (error) {
656
+ console.error("Error creating ledger signer", error);
657
+ RootStore.Get(ToastPlugin).error((_a = error.message) != null ? _a : "Failed to connect to Ledger");
658
+ RootStore.Get(WalletStore).isLedger = false;
659
+ return null;
660
+ }
661
+ };
662
+ var ConnectLedger = async () => {
663
+ RootStore.Get(WalletStore).isLedger = true;
664
+ console.log("ConnectLedger");
665
+ const signer = await GlobalLedgerSigner();
666
+ console.log("signer", signer);
667
+ const interval = setInterval(async () => {
668
+ try {
669
+ const address = await (signer == null ? void 0 : signer.getAddress());
670
+ if (address) {
671
+ RootStore.Get(WalletStore).set({
672
+ account: address,
673
+ isConnect: true
674
+ });
675
+ clearInterval(interval);
676
+ return signer;
677
+ }
678
+ } catch (error) {
679
+ console.error("Error getting address", error);
680
+ }
681
+ }, 1e3);
682
+ };
683
+ var DisconnectLedger = () => {
684
+ RootStore.Get(WalletStore).set({
685
+ isConnect: false,
686
+ isLedger: false
687
+ });
688
+ };
689
+ var LedgerSigner = class _LedgerSigner extends ethers.Signer {
690
+ constructor(transport, provider, path) {
691
+ super();
692
+ ethers.utils.defineReadOnly(this, "path", path || "44'/304'/0'/0/0");
693
+ ethers.utils.defineReadOnly(this, "provider", provider || null);
694
+ const eth = new Eth(transport);
695
+ const _eth = eth.getAppConfiguration().then((config) => {
696
+ return eth;
697
+ }, (error) => {
698
+ return Promise.reject(error);
699
+ });
700
+ ethers.utils.defineReadOnly(this, "_eth", _eth);
701
+ }
702
+ _retry(callback, timeout) {
703
+ return new Promise(async (resolve, reject) => {
704
+ if (timeout && timeout > 0) {
705
+ setTimeout(() => {
706
+ reject(new Error("timeout"));
707
+ }, timeout);
708
+ }
709
+ const eth = await this._eth;
710
+ for (let i = 0; i < 50; i++) {
711
+ try {
712
+ const result = await callback(eth);
713
+ return resolve(result);
714
+ } catch (error) {
715
+ if (error.id !== "TransportLocked") {
716
+ return reject(error);
717
+ }
718
+ }
719
+ await waiter(100);
720
+ }
721
+ return reject(new Error("timeout"));
722
+ });
723
+ }
724
+ async getAddress() {
725
+ const account = await this._retry((eth) => eth.getAddress(this.path));
726
+ return ethers.utils.getAddress(account.address);
727
+ }
728
+ async signMessage(message) {
729
+ if (typeof message === "string") {
730
+ message = ethers.utils.toUtf8Bytes(message);
731
+ }
732
+ const messageHex = ethers.utils.hexlify(message).substring(2);
733
+ const sig = await this._retry((eth) => eth.signPersonalMessage(this.path, messageHex));
734
+ sig.r = "0x" + sig.r;
735
+ sig.s = "0x" + sig.s;
736
+ return ethers.utils.joinSignature(sig);
737
+ }
738
+ async signTransaction(transaction) {
739
+ const tx = await ethers.utils.resolveProperties(transaction);
740
+ const baseTx = {
741
+ chainId: tx.chainId || void 0,
742
+ data: tx.data || void 0,
743
+ gasLimit: tx.gasLimit || void 0,
744
+ gasPrice: tx.gasPrice || void 0,
745
+ nonce: tx.nonce ? ethers.BigNumber.from(tx.nonce).toNumber() : void 0,
746
+ to: tx.to || void 0,
747
+ value: tx.value || void 0
748
+ };
749
+ const unsignedTx = ethers.utils.serializeTransaction(baseTx).substring(2);
750
+ const sig = await this._retry((eth) => eth.signTransaction(this.path, unsignedTx));
751
+ return ethers.utils.serializeTransaction(baseTx, {
752
+ v: ethers.BigNumber.from("0x" + sig.v).toNumber(),
753
+ r: "0x" + sig.r,
754
+ s: "0x" + sig.s
755
+ });
756
+ }
757
+ connect(provider) {
758
+ return new _LedgerSigner(provider, this.path);
759
+ }
760
+ };
761
+
762
+ // module/Wallet/index.tsx
763
+ var WalletStore = class _WalletStore {
764
+ constructor(args) {
765
+ this.sid = "wallet";
766
+ this.autoObservable = true;
767
+ this.account = null;
768
+ this.isSuccessDialogOpen = false;
769
+ this.isLedger = false;
770
+ this.isConnect = false;
771
+ this.event = new EventEmitter();
772
+ this.updateTicker = 0;
773
+ this.addressMode = "0x";
774
+ this.isIoTeXChain = false;
775
+ this.balance = PromiseHook.wrap({
776
+ func: async () => {
777
+ var _a;
778
+ if (!this.publicClient || !this.account)
779
+ return helper.number.warpBigNumber("0");
780
+ const balance = await this.publicClient.getBalance({
781
+ address: this.account
782
+ });
783
+ if (balance) {
784
+ return helper.number.warpBigNumber((_a = balance == null ? void 0 : balance.toString()) != null ? _a : "0");
785
+ }
786
+ }
787
+ });
788
+ Object.assign(this, args);
789
+ }
790
+ // isInSafeApp = false;
791
+ get isInSafeApp() {
792
+ return RootStore.Get(WalletConfigStore).isInSafeApp;
793
+ }
794
+ setAddressMode(mode) {
795
+ this.addressMode = mode;
796
+ localStorage.setItem("addressMode", mode);
797
+ }
798
+ get accountFormat() {
799
+ return this.account ? helper.address.convertAddress(this.addressMode, this.account) : "-";
800
+ }
801
+ get connectAccountEllipsisFormat() {
802
+ return this.account ? helper.string.truncate(helper.address.convertAddress(this.addressMode, this.account), 11, "...") : "-";
803
+ }
804
+ get accountEllipsisFormat() {
805
+ return this.account ? helper.string.truncate(helper.address.convertAddress(this.addressMode, this.account), 16, "...") : "-";
806
+ }
807
+ get supportedChains() {
808
+ return RootStore.Get(WalletConfigStore).supportedChains;
809
+ }
810
+ use() {
811
+ const { chain, address, isConnected } = useAccount();
812
+ const { switchChainAsync } = useSwitchChain();
813
+ const { openConnectModal } = useConnectModal();
814
+ const { connect } = useConnect();
815
+ const { disconnect } = useDisconnect();
816
+ const walletConfigStore = RootStore.Get(WalletConfigStore);
817
+ this.set({
818
+ //@ts-ignore
819
+ connect,
820
+ // @ts-ignore
821
+ // walletClient,
822
+ openConnectModal,
823
+ switchChain: switchChainAsync,
824
+ disconnect
825
+ });
826
+ useEffect(() => {
827
+ RootStore.Get(WalletHistoryStore).set({ isRender: true });
828
+ this.set({
829
+ isConnect: isConnected,
830
+ account: address,
831
+ chain
832
+ });
833
+ if ((chain == null ? void 0 : chain.id) == 4689) {
834
+ this.isIoTeXChain = true;
835
+ } else {
836
+ this.isIoTeXChain = false;
837
+ }
838
+ walletConfigStore.set({
839
+ isConnect: isConnected
840
+ });
841
+ if (this.account) {
842
+ this.updateTicker++;
843
+ walletConfigStore.set({
844
+ walletUpdateTick: this.updateTicker
845
+ });
846
+ this.event.emit("walletAccount:ready");
847
+ }
848
+ }, [address, isConnected, chain]);
849
+ useEffect(() => {
850
+ setTimeout(() => {
851
+ this.balance.call();
852
+ }, 1500);
853
+ }, [this.updateTicker]);
854
+ }
855
+ useWalletClientWithCompatibleMode() {
856
+ if (RootStore.Get(WalletConfigStore).compatibleMode) {
857
+ if (this.account) {
858
+ this.walletClient = createWalletClient({
859
+ account: this.account,
860
+ chain: this.chain,
861
+ transport: custom(window.ethereum),
862
+ pollingInterval: 2500
863
+ }).extend(publicActions);
864
+ }
865
+ console.log(this.walletClient, "this.walletClientxxx");
866
+ }
867
+ }
868
+ useWalletClientWithoutCompatibleMode() {
869
+ const { data: walletClient, isSuccess } = useWalletClient({
870
+ query: {
871
+ refetchInterval: 2500
872
+ }
873
+ });
874
+ useEffect(() => {
875
+ if (isSuccess && walletClient) {
876
+ this.set({ walletClient });
877
+ }
878
+ }, [walletClient, isSuccess]);
879
+ }
880
+ //always return or return default chain
881
+ get publicClient() {
882
+ if (this.chain && this.supportedChains.some((i) => i.id === this.chain.id)) {
883
+ if (this.chain.id == 4689) {
884
+ return AIem.PubClient("4689", {
885
+ rpcUrls: { default: { http: [RootStore.Get(WalletRpcStore).curRpc.value] } },
886
+ multicall: true,
887
+ pollingInterval: 2500
888
+ });
889
+ }
890
+ return AIem.PubClient(this.chain.id.toString(), { pollingInterval: 2500 });
891
+ } else {
892
+ return AIem.PubClient("4689", { pollingInterval: 2500 });
893
+ }
894
+ }
895
+ set(args) {
896
+ Object.assign(this, args);
897
+ }
898
+ toJSON() {
899
+ const { account } = this;
900
+ return { account };
901
+ }
902
+ async prepare(chainId) {
903
+ RootStore.Get(WalletRpcStore);
904
+ return new Promise(async (res, rej) => {
905
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
906
+ try {
907
+ if (this.account) {
908
+ if (this.isLedger) {
909
+ res(this);
910
+ }
911
+ if ((!chainId || Number((_a = this.chain) == null ? void 0 : _a.id) == Number(chainId)) && this.walletClient) {
912
+ res(this);
913
+ }
914
+ const interval = setInterval(() => {
915
+ var _a2;
916
+ if (((_a2 = this.chain) == null ? void 0 : _a2.id) == chainId) {
917
+ try {
918
+ this.useWalletClientWithCompatibleMode();
919
+ res(this);
920
+ } catch (error) {
921
+ console.log(error, "myerror");
922
+ rej(error);
923
+ }
924
+ clearInterval(interval);
925
+ }
926
+ }, 1e3);
927
+ if (chainId != ((_b = this.chain) == null ? void 0 : _b.id)) {
928
+ try {
929
+ await ((_c = this.walletClient) == null ? void 0 : _c.switchChain({ id: chainId }));
930
+ } catch (error) {
931
+ console.log(error.message);
932
+ if ((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("wallet_addEthereumChain")) {
933
+ const chain = RootStore.Get(WalletConfigStore).supportedChains.find((i) => i.id == chainId);
934
+ try {
935
+ await RootStore.Get(WalletRpcStore).addToMetamaskById(chainId);
936
+ await this.walletClient.switchChain({ id: chainId });
937
+ } catch (error2) {
938
+ RootStore.Get(DialogStore).setData({
939
+ isOpen: true,
940
+ title: "Chain Addition Failed",
941
+ size: "2xl",
942
+ content: /* @__PURE__ */ React3.createElement("div", null, /* @__PURE__ */ React3.createElement(Card, { className: "p-2" }, /* @__PURE__ */ React3.createElement("div", { className: "p-2 flex items-center justify-center gap-4" }, /* @__PURE__ */ React3.createElement("div", { className: "text-yellow-500 text-sm" }, "We encountered an issue while adding the chain. This might be caused by a compatibility issue with your current plugin. Please try adding the chain manually or review your plugin settings to ensure compatibility."))), /* @__PURE__ */ React3.createElement("div", { className: "flex flex-col gap-4 my-4" }, /* @__PURE__ */ React3.createElement(
943
+ Input,
944
+ {
945
+ label: "Network Name",
946
+ value: chain.name,
947
+ startContent: /* @__PURE__ */ React3.createElement(Icon, { icon: "fluent:rename-24-filled", width: "20", height: "20" })
948
+ }
949
+ ), /* @__PURE__ */ React3.createElement(
950
+ Input,
951
+ {
952
+ label: "Network RPC",
953
+ value: (_f = (_e = chain.rpcUrls.default) == null ? void 0 : _e.http) == null ? void 0 : _f[0],
954
+ startContent: /* @__PURE__ */ React3.createElement(Icon, { icon: "material-symbols:link", width: "20", height: "20" })
955
+ }
956
+ ), /* @__PURE__ */ React3.createElement(
957
+ Input,
958
+ {
959
+ label: "Chain ID",
960
+ value: chain.id.toString(),
961
+ startContent: /* @__PURE__ */ React3.createElement(Icon, { icon: "f7:grid-circle-fill", width: "20", height: "20" })
962
+ }
963
+ ), /* @__PURE__ */ React3.createElement(
964
+ Input,
965
+ {
966
+ label: "Native Currency Symbol",
967
+ value: (_g = chain.nativeCurrency) == null ? void 0 : _g.symbol,
968
+ startContent: /* @__PURE__ */ React3.createElement(Icon, { icon: "mingcute:coin-fill", width: "20", height: "20" })
969
+ }
970
+ ), /* @__PURE__ */ React3.createElement(
971
+ Input,
972
+ {
973
+ label: "Block Explorer URL",
974
+ value: (_i = (_h = chain.blockExplorers) == null ? void 0 : _h.default) == null ? void 0 : _i.url,
975
+ startContent: /* @__PURE__ */ React3.createElement(Icon, { icon: "material-symbols:explore", width: "20", height: "20" })
976
+ }
977
+ )))
978
+ });
979
+ console.log(error2.message);
980
+ }
981
+ } else {
982
+ rej(error);
983
+ }
984
+ }
985
+ }
986
+ } else {
987
+ this.openConnectModal();
988
+ const interval = setInterval(() => {
989
+ if (this.account) {
990
+ clearInterval(interval);
991
+ res(this);
992
+ }
993
+ }, 1e3);
994
+ }
995
+ } catch (error) {
996
+ rej(error);
997
+ }
998
+ });
999
+ }
1000
+ async waitForTransactionReceipt({ hash }) {
1001
+ if (this.isInSafeApp) {
1002
+ const sdk = new SafeAppsSDK();
1003
+ while (true) {
1004
+ const queued = await sdk.txs.getBySafeTxHash(hash);
1005
+ if (queued.txStatus === TransactionStatus.AWAITING_CONFIRMATIONS || queued.txStatus === TransactionStatus.AWAITING_EXECUTION || queued.txStatus === TransactionStatus.CANCELLED) {
1006
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
1007
+ } else {
1008
+ return this.publicClient.waitForTransactionReceipt({ hash: queued.txHash });
1009
+ }
1010
+ }
1011
+ } else {
1012
+ return this.publicClient.waitForTransactionReceipt({ hash });
1013
+ }
1014
+ }
1015
+ static async SendTx(...args) {
1016
+ return RootStore.Get(_WalletStore).sendTx(...args);
1017
+ }
1018
+ static async SendRawTx(...args) {
1019
+ return RootStore.Get(_WalletStore).sendRawTx(...args);
1020
+ }
1021
+ async sendTx({
1022
+ chainId,
1023
+ tx,
1024
+ autoAlert = true,
1025
+ loadingText,
1026
+ successText,
1027
+ onError,
1028
+ historyItem,
1029
+ showSuccessDialog = false
1030
+ }) {
1031
+ var _a, _b, _c;
1032
+ const toast = RootStore.Get(ToastPlugin);
1033
+ let hash;
1034
+ const historyStore = RootStore.Get(WalletHistoryStore);
1035
+ try {
1036
+ if (loadingText)
1037
+ toast.loading(loadingText);
1038
+ if (!chainId)
1039
+ throw new Error("chainId, address, data is required");
1040
+ await RootStore.Get(_WalletStore).prepare(Number(chainId));
1041
+ hash = await tx();
1042
+ if (historyItem) {
1043
+ historyStore.recordHistory(__spreadProps(__spreadValues({}, historyItem), { tx: hash, timestamp: Date.now(), status: "loading", chainId: Number(chainId) }));
1044
+ }
1045
+ const receipt = await this.waitForTransactionReceipt({ hash });
1046
+ if (receipt.status == "success") {
1047
+ toast.dismiss();
1048
+ toast.success("The transaction was successful");
1049
+ if (historyItem) {
1050
+ if (showSuccessDialog) {
1051
+ ShowSuccessTxDialog({ msg: historyItem.msg, hash });
1052
+ }
1053
+ historyStore.updateHistoryStatusByTx(hash, "success");
1054
+ }
1055
+ } else {
1056
+ toast.dismiss();
1057
+ toast.error("The transaction failed");
1058
+ historyStore.updateHistoryStatusByTx(hash, "fail");
1059
+ }
1060
+ if (successText)
1061
+ toast.success(successText);
1062
+ this.updateTicker++;
1063
+ return receipt;
1064
+ } catch (error) {
1065
+ console.log(error);
1066
+ toast.dismiss();
1067
+ if (autoAlert) {
1068
+ const msg = /reason="[A-Za-z0-9_ :"]*/g.exec(error == null ? void 0 : error.message);
1069
+ console.log("sendTx", error == null ? void 0 : error.message);
1070
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("rejected")) || String(error).toLowerCase().includes("rejected") || String(error).toLowerCase().includes("denied")) {
1071
+ toast.error("User rejected transaction");
1072
+ return;
1073
+ }
1074
+ if (((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.includes("The Transaction may not be processed on a block yet")) || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("could not be found"))) {
1075
+ if (historyItem) {
1076
+ historyStore.updateHistoryStatusByTx(hash, "success");
1077
+ }
1078
+ toast.success("The transaction was successful");
1079
+ return;
1080
+ }
1081
+ if (msg) {
1082
+ onError == null ? void 0 : onError(new Error(msg || "Transaction failed"));
1083
+ } else {
1084
+ if (error == null ? void 0 : error.message.includes("viem")) {
1085
+ const messageArr = error == null ? void 0 : error.message.split("\n");
1086
+ console.log("messageArr---", messageArr);
1087
+ if (messageArr.length > 0) {
1088
+ onError == null ? void 0 : onError(new Error(messageArr[0] || "Transaction failed"));
1089
+ }
1090
+ } else {
1091
+ onError == null ? void 0 : onError(new Error((error == null ? void 0 : error.message) || "Transaction failed"));
1092
+ }
1093
+ }
1094
+ } else {
1095
+ onError == null ? void 0 : onError(error);
1096
+ throw error;
1097
+ }
1098
+ }
1099
+ }
1100
+ async sendRawTx({
1101
+ chainId,
1102
+ address,
1103
+ data,
1104
+ value = "0",
1105
+ autoAlert = true,
1106
+ onSended,
1107
+ onSuccess,
1108
+ onError,
1109
+ historyItem,
1110
+ loadingText,
1111
+ showSuccessDialog = false
1112
+ }) {
1113
+ var _a, _b, _c, _d;
1114
+ chainId = Number(chainId);
1115
+ const toast = RootStore.Get(ToastPlugin);
1116
+ try {
1117
+ if (!chainId || !address)
1118
+ throw new Error("chainId, address, is required");
1119
+ await RootStore.Get(_WalletStore).prepare(chainId);
1120
+ if (loadingText)
1121
+ toast.loading(loadingText);
1122
+ const historyStore = RootStore.Get(WalletHistoryStore);
1123
+ let hash;
1124
+ if (this.isLedger) {
1125
+ const ledger = await GlobalLedgerSigner();
1126
+ console.log(ledger, "ledger signer");
1127
+ const tx = await ledger.sendTransaction({
1128
+ to: address,
1129
+ data,
1130
+ value: value ? BigInt(value) : void 0,
1131
+ from: this.account,
1132
+ type: 0
1133
+ });
1134
+ hash = tx == null ? void 0 : tx.hash;
1135
+ } else {
1136
+ hash = await this.walletClient.sendTransaction({
1137
+ account: this.account,
1138
+ to: address,
1139
+ data,
1140
+ value: value ? BigInt(value) : void 0
1141
+ });
1142
+ }
1143
+ let receipt = await this.waitForTransactionReceipt({ hash });
1144
+ if (historyItem) {
1145
+ historyStore.recordHistory(__spreadProps(__spreadValues({}, historyItem), { tx: receipt.transactionHash, timestamp: Date.now(), status: "loading", chainId: Number(chainId) }));
1146
+ }
1147
+ this.updateTicker++;
1148
+ onSended ? onSended({ res: receipt }) : null;
1149
+ if (receipt.status == "success") {
1150
+ if (historyItem) {
1151
+ if (showSuccessDialog) {
1152
+ ShowSuccessTxDialog({ msg: historyItem.msg, hash });
1153
+ }
1154
+ historyStore.updateHistoryStatusByTx(receipt.transactionHash, "success");
1155
+ }
1156
+ onSuccess && onSuccess({ res: receipt });
1157
+ toast.dismiss();
1158
+ toast.success("The transaction was successful");
1159
+ } else {
1160
+ if (historyItem) {
1161
+ historyStore.updateHistoryStatusByTx(receipt.transactionHash, "fail");
1162
+ }
1163
+ onError && (onError == null ? void 0 : onError(new Error("The transaction failed")));
1164
+ toast.dismiss();
1165
+ toast.error("The transaction failed");
1166
+ }
1167
+ return receipt;
1168
+ } catch (error) {
1169
+ toast.dismiss();
1170
+ onError == null ? void 0 : onError(error);
1171
+ console.log(error);
1172
+ /reason="[A-Za-z0-9_ :"]*/g.exec(error == null ? void 0 : error.message);
1173
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("rejected")) || ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.includes("cancel")) || String(error).toLowerCase().includes("cancel") || String(error).toLowerCase().includes("rejected") || String(error).toLowerCase().includes("user denied")) {
1174
+ autoAlert && toast.error("User rejected transaction");
1175
+ onError == null ? void 0 : onError(error);
1176
+ return;
1177
+ }
1178
+ if ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("Price slippage check")) {
1179
+ autoAlert && toast.error("The latest pool price has changed, please try to increase the slippage tolerance or reload the page.");
1180
+ onError == null ? void 0 : onError(error);
1181
+ return;
1182
+ }
1183
+ if (error == null ? void 0 : error.message.includes("viem")) {
1184
+ const messageArr = error == null ? void 0 : error.message.split("\n");
1185
+ console.log("messageArr---", messageArr);
1186
+ if (messageArr.length > 0) {
1187
+ onError == null ? void 0 : onError(new Error((_d = messageArr[0]) != null ? _d : "Transaction failed"));
1188
+ return;
1189
+ }
1190
+ }
1191
+ if (!autoAlert) {
1192
+ onError == null ? void 0 : onError(error);
1193
+ throw error;
1194
+ }
1195
+ }
1196
+ }
1197
+ async signMessage(message) {
1198
+ if (this.isLedger) {
1199
+ const ledger = await GlobalLedgerSigner();
1200
+ return ledger.signMessage(message);
1201
+ }
1202
+ return this.walletClient.signMessage(message);
1203
+ }
1204
+ };
1205
+ var AutoMan = class {
1206
+ constructor() {
1207
+ this.sid = "AutoMan";
1208
+ this.stype = "Plugin";
1209
+ this.provider = observer(() => {
1210
+ const wallet = RootStore.Get(WalletStore);
1211
+ const router = useRouter();
1212
+ useEffect(() => {
1213
+ console.log("automan proverider");
1214
+ const stores = Object.values(rootStore.instance).filter((i) => i._active > 0);
1215
+ const promise = stores.reduce((p, c) => {
1216
+ const promise2 = Object.values(c).filter((i) => !!(i == null ? void 0 : i.call));
1217
+ return [...p, ...promise2];
1218
+ }, []);
1219
+ const autoUpdate = promise.filter((i) => i.autoUpdate);
1220
+ console.log({ autoUpdate });
1221
+ autoUpdate.forEach((i) => !i.loading.value && i.call());
1222
+ }, [wallet.updateTicker, router.asPath]);
1223
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null);
1224
+ });
1225
+ }
1226
+ static use(stores, promises) {
1227
+ useEffect(() => {
1228
+ Object.keys(stores).forEach((storeName) => {
1229
+ const store = stores[storeName];
1230
+ Object.keys(store).forEach((key) => {
1231
+ const i = store[key];
1232
+ if (!!(i == null ? void 0 : i.getOrCall) && (i.autoInit || !!(promises == null ? void 0 : promises[storeName][key]))) {
1233
+ if (!store._active)
1234
+ store._active = 0;
1235
+ store._active += 1;
1236
+ i.getOrCall();
1237
+ }
1238
+ });
1239
+ });
1240
+ return () => {
1241
+ Object.values(stores).forEach((store) => {
1242
+ if (!store._active)
1243
+ store._active = 0;
1244
+ store._active -= 1;
1245
+ if (store.autoClean !== false && !store._active > 0) {
1246
+ Object.entries(store).filter(([key, i]) => !!(i == null ? void 0 : i.value)).forEach(([key, i]) => {
1247
+ console.log("clean", key);
1248
+ i.value = null;
1249
+ });
1250
+ }
1251
+ });
1252
+ if (!!promises) {
1253
+ Object.entries(promises).forEach(([storaName, promise]) => {
1254
+ const store = stores[storaName];
1255
+ Object.keys(promise).forEach((key) => {
1256
+ const promise2 = store[key];
1257
+ console.log("clean", key);
1258
+ if (!promise2)
1259
+ return;
1260
+ if (!promise2._active)
1261
+ promise2._active = 0;
1262
+ promise2._active -= 1;
1263
+ if (!promise2._active > 0) {
1264
+ promise2.value = null;
1265
+ }
1266
+ });
1267
+ });
1268
+ }
1269
+ };
1270
+ }, []);
1271
+ return stores;
1272
+ }
1273
+ };
1274
+ var AppProvider = observer(({ children }) => {
1275
+ const rootStore2 = RootStore.init();
1276
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, rootStore2.providers.map((store) => {
1277
+ const Component = store.provider;
1278
+ return /* @__PURE__ */ React3.createElement(Component, { rootStore: rootStore2, key: store.sid });
1279
+ }), children && children);
1280
+ });
1281
+
1282
+ export { AppProvider, AutoMan, BigNumberInputState, BigNumberState, ConnectLedger, DisconnectLedger, ObjectPool, PromiseHook, StorageListState, StorageState, WalletConfigStore, WalletHistoryStore, WalletRpcStore, WalletStore };
1283
+ //# sourceMappingURL=out.js.map
1284
+ //# sourceMappingURL=chunk-BR7IWH2E.mjs.map