@dappworks/kit 0.5.7 → 0.5.9

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