@dappworks/kit 0.4.229 → 0.4.231

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/dist/wallet.mjs CHANGED
@@ -1,696 +1,26 @@
1
- import { AIem } from './chunk-NPQ7GCFM.mjs';
2
- import './chunk-7MDKCI65.mjs';
3
- import { ObjectPool, StorageState, PromiseHook } from './chunk-DRTTNPZI.mjs';
1
+ import { WalletConfigStore, WalletStore, WalletRpcStore } from './chunk-NO4O46V2.mjs';
2
+ export { WalletConfigStore, WalletHistoryStore, WalletRpcStore, WalletStore } from './chunk-NO4O46V2.mjs';
4
3
  import './chunk-TSUKTLY3.mjs';
5
- import { DialogStore } from './chunk-GT4R5SDI.mjs';
4
+ import './chunk-NPQ7GCFM.mjs';
5
+ import './chunk-7MDKCI65.mjs';
6
+ import './chunk-GT4R5SDI.mjs';
6
7
  import { ToastPlugin } from './chunk-IMOLRP7I.mjs';
7
8
  import './chunk-K73JTEJQ.mjs';
8
9
  import { RootStore } from './chunk-XSGTWROT.mjs';
9
- import { helper } from './chunk-R4N52NI2.mjs';
10
+ import './chunk-R4N52NI2.mjs';
10
11
  import './chunk-ONVPCAMQ.mjs';
11
12
  import './chunk-K7LFG5BA.mjs';
12
- import { __spreadValues, __spreadProps } from './chunk-R4SQKVDQ.mjs';
13
- import { RainbowKitProvider, darkTheme, lightTheme, getDefaultConfig, useConnectModal } from '@rainbow-me/rainbowkit';
13
+ import { __spreadValues } from './chunk-R4SQKVDQ.mjs';
14
+ import { RainbowKitProvider, darkTheme, lightTheme } from '@rainbow-me/rainbowkit';
14
15
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
15
- import React5, { useEffect } from 'react';
16
- import { WagmiProvider, useAccount, useSwitchChain, useConnect, useDisconnect, useWalletClient } from 'wagmi';
17
- import { toHex, createWalletClient, custom, publicActions } from 'viem';
18
- import EventEmitter from 'events';
19
- import { Icon } from '@iconify/react';
20
- import { iopayWallet, metaMaskWallet, walletConnectWallet, okxWallet, binanceWallet, safeWallet } from '@rainbow-me/rainbowkit/wallets';
21
- import SafeAppsSDK, { TransactionStatus } from '@safe-global/safe-apps-sdk';
22
- import { observer } from 'mobx-react-lite';
16
+ import React2, { useEffect } from 'react';
17
+ import { WagmiProvider } from 'wagmi';
23
18
  import { iotex as iotex$1, iotexTestnet as iotexTestnet$1 } from 'viem/chains';
19
+ import SafeAppsSDK from '@safe-global/safe-apps-sdk';
20
+ import { observer } from 'mobx-react-lite';
21
+ import { Icon } from '@iconify/react';
24
22
  import { Checkbox, Tooltip, Button, Popover, PopoverTrigger, PopoverContent, Input, Table, TableHeader, TableColumn, TableBody, TableRow, TableCell } from '@nextui-org/react';
25
23
 
26
- var WalletConfigStore = class {
27
- constructor(args) {
28
- this.sid = "WalletConfigStore";
29
- this.autoObservable = true;
30
- this.appName = "Dappkit";
31
- this.projectId = "b69e844f38265667350efd78e3e1a5fb";
32
- this.defaultChainId = 4689;
33
- this.updateTicker = 1;
34
- this.walletUpdateTick = 0;
35
- this.isConnect = false;
36
- this.isInSafeApp = false;
37
- // This mode to resolve and walletClient and nextui in some extreme cases cause page infinite redraw bugs
38
- this.compatibleMode = true;
39
- Object.assign(this, args);
40
- }
41
- set(params) {
42
- Object.assign(this, params);
43
- this.updateTicker += 1;
44
- }
45
- get reconnectOnMount() {
46
- if (!this.compatibleMode)
47
- return true;
48
- if (!this.isConnect && this.walletUpdateTick == 0) {
49
- return true;
50
- }
51
- if (!this.isConnect && this.walletUpdateTick != 0) {
52
- return false;
53
- }
54
- if (this.isConnect) {
55
- return true;
56
- }
57
- }
58
- get rainbowKitConfig() {
59
- var _a;
60
- return ObjectPool.get(`rainbowKitConfig-${(_a = this.supportedChains) == null ? void 0 : _a.map((i) => i.id).join("-")}`, () => {
61
- return getDefaultConfig({
62
- appName: this.appName,
63
- projectId: this.projectId,
64
- //@ts-ignore
65
- chains: this.supportedChains,
66
- wallets: [
67
- {
68
- groupName: "Recommended",
69
- wallets: [iopayWallet, metaMaskWallet]
70
- },
71
- {
72
- groupName: "Others",
73
- wallets: [metaMaskWallet, walletConnectWallet, iopayWallet, okxWallet, binanceWallet, safeWallet]
74
- }
75
- ]
76
- });
77
- });
78
- }
79
- };
80
-
81
- // module/Wallet/walletPluginStore.tsx
82
- var defaultRPCList = [
83
- { name: "https://babel-api.fastblocks.io", latency: 0, height: 0, custom: false },
84
- { name: "https://babel-api.mainnet.iotex.one", latency: 0, height: 0 },
85
- { name: "https://babel-api.mainnet.iotex.io", latency: 0, height: 0 },
86
- { name: "https://iotex-network.rpc.thirdweb.com", latency: 0, height: 0 },
87
- { name: "https://iotexrpc.com", latency: 0, height: 0 },
88
- { name: "https://iotex.api.onfinality.io/public", latency: 0, height: 0 },
89
- { name: "https://rpc.ankr.com/iotex", latency: 0, height: 0 }
90
- ];
91
- var WalletRpcStore = class {
92
- constructor() {
93
- this.sid = "WalletPluginStore";
94
- this.autoObservable = true;
95
- this.curRpc = new StorageState({ default: "https://babel-api.mainnet.iotex.one", key: "curRPC-v2", value: "https://babel-api.mainnet.iotex.one" });
96
- this.isAutoSelectRpc = new StorageState({ key: "isAutoSelectRpc", default: true });
97
- this.customRpc = "";
98
- this.rpcList = new StorageState({ key: "customRpcList-v2", default: defaultRPCList, value: [] });
99
- this.showCustomRpc = false;
100
- }
101
- get currentRpc() {
102
- var _a, _b;
103
- console.log((_a = this.rpcList.value) == null ? void 0 : _a.find((i) => i.name == this.curRpc));
104
- return ((_b = this.rpcList.value) == null ? void 0 : _b.find((i) => i.name == this.curRpc.value)) || null;
105
- }
106
- addCustomRpc() {
107
- const item = { name: this.customRpc, latency: 0, height: 0, custom: true };
108
- if (defaultRPCList.find((i) => i.name === item.name)) {
109
- return RootStore.Get(ToastPlugin).error("Rpc already exists");
110
- }
111
- if (this.rpcList.value) {
112
- this.rpcList.save([...this.rpcList.value, item]);
113
- this.refresh();
114
- return;
115
- }
116
- this.rpcList.save([...defaultRPCList, item]);
117
- this.refresh();
118
- }
119
- async addToMetamask(url) {
120
- var _a;
121
- try {
122
- if (typeof window == "undefined")
123
- return;
124
- await ((_a = window == null ? void 0 : window.ethereum) == null ? void 0 : _a.request({
125
- method: "wallet_addEthereumChain",
126
- params: [{
127
- chainId: `0x${4689 .toString(16)}`,
128
- chainName: "IoTeX Mainnet",
129
- nativeCurrency: {
130
- name: "IoTeX",
131
- symbol: "IOTX",
132
- decimals: 18
133
- },
134
- rpcUrls: [url],
135
- blockExplorerUrls: ["https://iotexscan.io"]
136
- }]
137
- }));
138
- RootStore.Get(ToastPlugin).success("Network added");
139
- console.log("Network added");
140
- } catch (error) {
141
- console.error("Failed to add network", error);
142
- }
143
- }
144
- async switchOrAddChain(chainId) {
145
- return new Promise(async (resolve, reject) => {
146
- try {
147
- await window.ethereum.request({
148
- method: "wallet_switchEthereumChain",
149
- params: [{ chainId: toHex(chainId) }]
150
- });
151
- resolve(true);
152
- } catch (switchError) {
153
- if (switchError.code === 4902) {
154
- try {
155
- await this.addToMetamaskById(chainId);
156
- } catch (addError) {
157
- reject(addError);
158
- }
159
- } else {
160
- reject(switchError);
161
- }
162
- }
163
- });
164
- }
165
- async addToMetamaskById(id) {
166
- return new Promise(async (resolve, reject) => {
167
- try {
168
- if (typeof window == "undefined")
169
- return;
170
- const chain = RootStore.Get(WalletConfigStore).supportedChains.find((i) => i.id == id);
171
- const res = await window.ethereum.request({
172
- method: "wallet_addEthereumChain",
173
- params: [{
174
- "chainId": toHex(chain.id),
175
- "chainName": chain.name,
176
- "nativeCurrency": {
177
- "name": chain.nativeCurrency.name,
178
- "symbol": chain.nativeCurrency.symbol,
179
- "decimals": chain.nativeCurrency.decimals
180
- },
181
- "rpcUrls": JSON.parse(JSON.stringify(chain.rpcUrls.default.http)),
182
- "blockExplorerUrls": [chain.blockExplorers.default.url]
183
- }]
184
- });
185
- console.log(res);
186
- resolve(res);
187
- } catch (switchError) {
188
- reject(false);
189
- }
190
- });
191
- }
192
- refresh() {
193
- this.showCustomRpc = false;
194
- this.customRpc = "";
195
- setTimeout(() => {
196
- this.testRpc();
197
- }, 500);
198
- }
199
- latencyColor(latency) {
200
- if (latency < 0) {
201
- return "text-red-500";
202
- }
203
- if (latency < 1) {
204
- return "text-green-500";
205
- }
206
- if (latency < 2) {
207
- return "text-yellow-500";
208
- }
209
- return "text-red-500";
210
- }
211
- async testRpcFunction(url) {
212
- const start = performance.now();
213
- try {
214
- const response = await fetch(url, {
215
- method: "POST",
216
- headers: {
217
- "Content-Type": "application/json"
218
- },
219
- body: JSON.stringify({
220
- jsonrpc: "2.0",
221
- method: "eth_getBlockByNumber",
222
- params: ["latest", false],
223
- id: 1
224
- })
225
- });
226
- if (!response.ok) {
227
- throw new Error(`Error from server: ${response.status}`);
228
- }
229
- const res = await response.json();
230
- console.log(res);
231
- const end = performance.now();
232
- return { url, lentency: Number(helper.number.numberFormat((end - start) / 1e3, "0.000", { fallback: "-1" })), height: parseInt(res.result.number, 16) };
233
- } catch (error) {
234
- console.error("RPC Latency Test Failed:", error);
235
- return { url, lentency: -1, height: -1 };
236
- }
237
- }
238
- testRpc() {
239
- var _a;
240
- (_a = this.rpcList) == null ? void 0 : _a.value.forEach((i) => {
241
- this.testRpcFunction(i.name).then((res) => {
242
- i.latency = res.lentency;
243
- i.height = res.height;
244
- });
245
- });
246
- this.rpcList.save(this.rpcList.value);
247
- }
248
- removeRpc(name) {
249
- this.rpcList.save(this.rpcList.value.filter((i) => i.name !== name));
250
- }
251
- scoreIcon(score) {
252
- if (score < 0) {
253
- return /* @__PURE__ */ React5.createElement(Icon, { icon: "codicon:error", width: "18", height: "18", style: { color: "#FF0000" } });
254
- }
255
- if (score < 1) {
256
- return /* @__PURE__ */ React5.createElement(Icon, { icon: "icon-park-solid:check-one", width: "18", height: "18", style: { color: "#289726" } });
257
- }
258
- if (score < 2) {
259
- return /* @__PURE__ */ React5.createElement(Icon, { icon: "bxs:error", width: "18", height: "18", style: { color: "#FFA500" } });
260
- }
261
- return /* @__PURE__ */ React5.createElement(Icon, { icon: "codicon:error", width: "18", height: "18", style: { color: "#FF0000" } });
262
- }
263
- get wallet() {
264
- return RootStore.Get(WalletStore);
265
- }
266
- // debounceAutoSelectRpc = pDebounce(this.autoSelectRpc, 3000)
267
- async autoSelectRpc() {
268
- console.log("autoSelectRpc");
269
- for (let i = 0; i < this.rpcList.value.length; i++) {
270
- const item = this.rpcList.value[i];
271
- const res = await this.testRpcFunction(item.name);
272
- if (res.lentency != -1 || res.height > 0) {
273
- this.curRpc.save(item.name);
274
- break;
275
- }
276
- }
277
- }
278
- };
279
- var WalletHistoryStore = class {
280
- constructor() {
281
- this.sid = "WalletHistoryStore";
282
- this.isRender = false;
283
- this.autoObservable = true;
284
- this.history = new StorageState({ value: [], key: "history" });
285
- }
286
- set(params) {
287
- Object.assign(this, params);
288
- }
289
- get historyList() {
290
- if (this.isRender) {
291
- return this.history.value;
292
- }
293
- return [];
294
- }
295
- recordHistory(item) {
296
- let value = this.history.load();
297
- if (!value) {
298
- value = [item];
299
- } else {
300
- value = [...value, item];
301
- }
302
- this.history.setValue(value);
303
- }
304
- updateHistoryStatusByTx(tx, status) {
305
- let value = this.history.load();
306
- if (!value) {
307
- return;
308
- }
309
- value = value.map((i) => {
310
- if (i.tx == tx) {
311
- i.status = status;
312
- return i;
313
- }
314
- if (!tx) {
315
- i.status = status;
316
- }
317
- return i;
318
- });
319
- this.history.setValue(value);
320
- }
321
- clearHistory() {
322
- this.history.setValue(null);
323
- }
324
- };
325
- var SuccessTxDialog = observer((props) => {
326
- return /* @__PURE__ */ React5.createElement("div", { className: "flex-col gap-4 py-10" }, /* @__PURE__ */ React5.createElement("div", { className: "w-full flex items-center justify-center" }, /* @__PURE__ */ React5.createElement(Icon, { icon: "icon-park-solid:check-one", width: "48", height: "48", className: "text-green-500" })), /* @__PURE__ */ React5.createElement("div", { className: "text-2xl font-[900] text-center mt-4" }, props.msg), /* @__PURE__ */ React5.createElement(
327
- "div",
328
- {
329
- className: "flex items-center justify-center text-green-500 text-sm mt-6 gap-2 cursor-pointer hover:text-green-600 transition",
330
- onClick: (e) => window.open(`https://iotexscan.io/tx/${props.hash}`, "_blank")
331
- },
332
- "View on IoTeXScan ",
333
- /* @__PURE__ */ React5.createElement(Icon, { icon: "material-symbols:chip-extraction-rounded", width: "18", height: "18" })
334
- ));
335
- });
336
- var ShowSuccessTxDialog = ({ msg, hash }) => {
337
- RootStore.Get(DialogStore).setData({
338
- title: "",
339
- content: /* @__PURE__ */ React5.createElement(SuccessTxDialog, { msg, hash }),
340
- isOpen: true
341
- });
342
- };
343
-
344
- // module/Wallet/index.tsx
345
- var WalletStore = class _WalletStore {
346
- constructor(args) {
347
- this.sid = "wallet";
348
- this.autoObservable = true;
349
- this.account = null;
350
- this.isSuccessDialogOpen = false;
351
- this.isConnect = false;
352
- this.event = new EventEmitter();
353
- this.updateTicker = 0;
354
- this.addressMode = "0x";
355
- this.isIoTeXChain = false;
356
- this.balance = PromiseHook.wrap({
357
- func: async () => {
358
- var _a;
359
- if (!this.publicClient || !this.account)
360
- return helper.number.warpBigNumber("0");
361
- const balance = await this.publicClient.getBalance({
362
- address: this.account
363
- });
364
- if (balance) {
365
- return helper.number.warpBigNumber((_a = balance == null ? void 0 : balance.toString()) != null ? _a : "0");
366
- }
367
- }
368
- });
369
- Object.assign(this, args);
370
- }
371
- // isInSafeApp = false;
372
- get isInSafeApp() {
373
- return RootStore.Get(WalletConfigStore).isInSafeApp;
374
- }
375
- setAddressMode(mode) {
376
- this.addressMode = mode;
377
- localStorage.setItem("addressMode", mode);
378
- }
379
- get accountFormat() {
380
- return this.account ? helper.address.convertAddress(this.addressMode, this.account) : "-";
381
- }
382
- get connectAccountEllipsisFormat() {
383
- return this.account ? helper.string.truncate(helper.address.convertAddress(this.addressMode, this.account), 11, "...") : "-";
384
- }
385
- get accountEllipsisFormat() {
386
- return this.account ? helper.string.truncate(helper.address.convertAddress(this.addressMode, this.account), 16, "...") : "-";
387
- }
388
- get supportedChains() {
389
- return RootStore.Get(WalletConfigStore).supportedChains;
390
- }
391
- use() {
392
- const { chain, address, isConnected } = useAccount();
393
- const { switchChainAsync } = useSwitchChain();
394
- const { openConnectModal } = useConnectModal();
395
- const { connect } = useConnect();
396
- const { disconnect } = useDisconnect();
397
- const walletConfigStore = RootStore.Get(WalletConfigStore);
398
- this.set({
399
- //@ts-ignore
400
- connect,
401
- // @ts-ignore
402
- // walletClient,
403
- openConnectModal,
404
- switchChain: switchChainAsync,
405
- disconnect
406
- });
407
- useEffect(() => {
408
- RootStore.Get(WalletHistoryStore).set({ isRender: true });
409
- this.set({
410
- isConnect: isConnected,
411
- account: address,
412
- chain
413
- });
414
- if ((chain == null ? void 0 : chain.id) == 4689) {
415
- this.isIoTeXChain = true;
416
- } else {
417
- this.isIoTeXChain = false;
418
- }
419
- walletConfigStore.set({
420
- isConnect: isConnected
421
- });
422
- if (this.account) {
423
- this.updateTicker++;
424
- walletConfigStore.set({
425
- walletUpdateTick: this.updateTicker
426
- });
427
- this.event.emit("walletAccount:ready");
428
- }
429
- this.useWalletClientWithCompatibleMode();
430
- }, [address, isConnected, chain]);
431
- useEffect(() => {
432
- setTimeout(() => {
433
- this.balance.call();
434
- }, 1500);
435
- }, [this.updateTicker]);
436
- }
437
- useWalletClientWithCompatibleMode() {
438
- if (RootStore.Get(WalletConfigStore).compatibleMode) {
439
- if (this.account && this.account) {
440
- this.walletClient = createWalletClient({
441
- account: this.account,
442
- chain: this.chain,
443
- transport: custom(window.ethereum)
444
- }).extend(publicActions);
445
- }
446
- }
447
- }
448
- useWalletClientWithoutCompatibleMode() {
449
- const { data: walletClient } = useWalletClient();
450
- this.set({
451
- walletClient
452
- });
453
- }
454
- //always return or return default chain
455
- get publicClient() {
456
- if (this.chain && this.supportedChains.some((i) => i.id === this.chain.id)) {
457
- if (this.chain.id == 4689) {
458
- return AIem.PubClient("4689", { rpcUrls: { default: { http: [RootStore.Get(WalletRpcStore).curRpc.value] } }, multicall: true });
459
- }
460
- return AIem.PubClient(this.chain.id.toString());
461
- } else {
462
- return AIem.PubClient("4689");
463
- }
464
- }
465
- set(args) {
466
- Object.assign(this, args);
467
- }
468
- toJSON() {
469
- const { account } = this;
470
- return { account };
471
- }
472
- async prepare(chainId) {
473
- const walletRpcStore = RootStore.Get(WalletRpcStore);
474
- return new Promise(async (res, rej) => {
475
- var _a, _b;
476
- try {
477
- if (this.account) {
478
- console.log((_a = this.chain) == null ? void 0 : _a.id, "this.chain?.id");
479
- if (!chainId || Number((_b = this.chain) == null ? void 0 : _b.id) == Number(chainId)) {
480
- res(this);
481
- }
482
- const interval = setInterval(() => {
483
- var _a2;
484
- if (((_a2 = this.chain) == null ? void 0 : _a2.id) == chainId) {
485
- try {
486
- this.useWalletClientWithCompatibleMode();
487
- res(this);
488
- } catch (error) {
489
- }
490
- clearInterval(interval);
491
- }
492
- }, 1e3);
493
- try {
494
- await walletRpcStore.switchOrAddChain(chainId != null ? chainId : 4689);
495
- } catch (error) {
496
- rej(error);
497
- }
498
- } else {
499
- this.openConnectModal();
500
- const interval = setInterval(() => {
501
- if (this.account) {
502
- clearInterval(interval);
503
- res(this);
504
- }
505
- }, 1e3);
506
- }
507
- } catch (error) {
508
- rej(error);
509
- }
510
- });
511
- }
512
- async waitForTransactionReceipt({ hash }) {
513
- if (this.isInSafeApp) {
514
- const sdk = new SafeAppsSDK();
515
- while (true) {
516
- const queued = await sdk.txs.getBySafeTxHash(hash);
517
- if (queued.txStatus === TransactionStatus.AWAITING_CONFIRMATIONS || queued.txStatus === TransactionStatus.AWAITING_EXECUTION || queued.txStatus === TransactionStatus.CANCELLED) {
518
- await new Promise((resolve) => setTimeout(resolve, 2e3));
519
- } else {
520
- return this.publicClient.waitForTransactionReceipt({ hash: queued.txHash });
521
- }
522
- }
523
- } else {
524
- return this.publicClient.waitForTransactionReceipt({ hash });
525
- }
526
- }
527
- static async SendTx(...args) {
528
- return RootStore.Get(_WalletStore).sendTx(...args);
529
- }
530
- static async SendRawTx(...args) {
531
- return RootStore.Get(_WalletStore).sendRawTx(...args);
532
- }
533
- async sendTx({
534
- chainId,
535
- tx,
536
- autoAlert = true,
537
- loadingText,
538
- successText,
539
- onError,
540
- historyItem,
541
- showSuccessDialog = false
542
- }) {
543
- var _a, _b, _c;
544
- const toast = RootStore.Get(ToastPlugin);
545
- let hash;
546
- const historyStore = RootStore.Get(WalletHistoryStore);
547
- try {
548
- if (loadingText)
549
- toast.loading(loadingText);
550
- if (!chainId)
551
- throw new Error("chainId, address, data is required");
552
- await RootStore.Get(_WalletStore).prepare(Number(chainId));
553
- hash = await tx();
554
- if (historyItem) {
555
- historyStore.recordHistory(__spreadProps(__spreadValues({}, historyItem), { tx: hash, timestamp: Date.now(), status: "loading", chainId: Number(chainId) }));
556
- }
557
- const receipt = await this.waitForTransactionReceipt({ hash });
558
- if (receipt.status == "success") {
559
- toast.dismiss();
560
- toast.success("The transaction was successful");
561
- if (historyItem) {
562
- if (showSuccessDialog) {
563
- ShowSuccessTxDialog({ msg: historyItem.msg, hash });
564
- }
565
- historyStore.updateHistoryStatusByTx(hash, "success");
566
- }
567
- } else {
568
- toast.dismiss();
569
- toast.error("The transaction failed");
570
- historyStore.updateHistoryStatusByTx(hash, "fail");
571
- }
572
- if (successText)
573
- toast.success(successText);
574
- this.updateTicker++;
575
- return receipt;
576
- } catch (error) {
577
- console.log(error);
578
- toast.dismiss();
579
- if (autoAlert) {
580
- const msg = /reason="[A-Za-z0-9_ :"]*/g.exec(error == null ? void 0 : error.message);
581
- console.log("sendTx", error == null ? void 0 : error.message);
582
- if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("rejected")) || String(error).toLowerCase().includes("rejected") || String(error).toLowerCase().includes("denied")) {
583
- toast.error("User rejected transaction");
584
- return;
585
- }
586
- 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"))) {
587
- if (historyItem) {
588
- historyStore.updateHistoryStatusByTx(hash, "success");
589
- }
590
- toast.success("The transaction was successful");
591
- return;
592
- }
593
- if (msg) {
594
- onError == null ? void 0 : onError(new Error(msg || "Transaction failed"));
595
- } else {
596
- if (error == null ? void 0 : error.message.includes("viem")) {
597
- const messageArr = error == null ? void 0 : error.message.split("\n");
598
- console.log("messageArr---", messageArr);
599
- if (messageArr.length > 0) {
600
- onError == null ? void 0 : onError(new Error(messageArr[0] || "Transaction failed"));
601
- }
602
- } else {
603
- onError == null ? void 0 : onError(new Error((error == null ? void 0 : error.message) || "Transaction failed"));
604
- }
605
- }
606
- } else {
607
- onError == null ? void 0 : onError(error);
608
- throw error;
609
- }
610
- }
611
- }
612
- async sendRawTx({
613
- chainId,
614
- address,
615
- data,
616
- value = "0",
617
- autoAlert = true,
618
- onSended,
619
- onSuccess,
620
- onError,
621
- historyItem,
622
- loadingText,
623
- showSuccessDialog = false
624
- }) {
625
- var _a, _b, _c, _d;
626
- chainId = Number(chainId);
627
- const toast = RootStore.Get(ToastPlugin);
628
- try {
629
- if (!chainId || !address)
630
- throw new Error("chainId, address, is required");
631
- await RootStore.Get(_WalletStore).prepare(chainId);
632
- if (loadingText)
633
- toast.loading(loadingText);
634
- const historyStore = RootStore.Get(WalletHistoryStore);
635
- const hash = await this.walletClient.sendTransaction({
636
- account: this.account,
637
- to: address,
638
- data,
639
- value: value ? BigInt(value) : void 0
640
- });
641
- let receipt = await this.waitForTransactionReceipt({ hash });
642
- console.log(receipt);
643
- if (historyItem) {
644
- historyStore.recordHistory(__spreadProps(__spreadValues({}, historyItem), { tx: receipt.transactionHash, timestamp: Date.now(), status: "loading", chainId: Number(chainId) }));
645
- }
646
- onSended ? onSended({ res: receipt }) : null;
647
- if (receipt.status == "success") {
648
- if (historyItem) {
649
- if (showSuccessDialog) {
650
- ShowSuccessTxDialog({ msg: historyItem.msg, hash });
651
- }
652
- historyStore.updateHistoryStatusByTx(receipt.transactionHash, "success");
653
- }
654
- onSuccess && onSuccess({ res: receipt });
655
- toast.dismiss();
656
- toast.success("The transaction was successful");
657
- } else {
658
- if (historyItem) {
659
- historyStore.updateHistoryStatusByTx(receipt.transactionHash, "fail");
660
- }
661
- onError && (onError == null ? void 0 : onError(new Error("The transaction failed")));
662
- toast.dismiss();
663
- toast.error("The transaction failed");
664
- }
665
- return receipt;
666
- } catch (error) {
667
- toast.dismiss();
668
- onError == null ? void 0 : onError(error);
669
- console.log(error.message);
670
- /reason="[A-Za-z0-9_ :"]*/g.exec(error == null ? void 0 : error.message);
671
- 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")) {
672
- autoAlert && toast.error("User rejected transaction");
673
- return;
674
- }
675
- if ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("Price slippage check")) {
676
- autoAlert && toast.error("The latest pool price has changed, please try to increase the slippage tolerance or reload the page.");
677
- return;
678
- }
679
- if (error == null ? void 0 : error.message.includes("viem")) {
680
- const messageArr = error == null ? void 0 : error.message.split("\n");
681
- console.log("messageArr---", messageArr);
682
- if (messageArr.length > 0) {
683
- onError == null ? void 0 : onError(new Error((_d = messageArr[0]) != null ? _d : "Transaction failed"));
684
- return;
685
- }
686
- }
687
- if (!autoAlert) {
688
- onError == null ? void 0 : onError(error);
689
- throw error;
690
- }
691
- }
692
- }
693
- };
694
24
  var iotex = __spreadValues({
695
25
  iconUrl: "https://cdn-dapp-works.s3.us-east-1.amazonaws.com/1dd84d927ae959c508392be62e6eb549.png"
696
26
  }, iotex$1);
@@ -722,18 +52,18 @@ var WalletProvider = observer(({
722
52
  }
723
53
  });
724
54
  }, []);
725
- return /* @__PURE__ */ React5.createElement(WagmiProvider, { config: walletConfig.rainbowKitConfig, reconnectOnMount: walletConfig.reconnectOnMount }, /* @__PURE__ */ React5.createElement(QueryClientProvider, { client: queryClient }, /* @__PURE__ */ React5.createElement(RainbowKitProvider, { locale: "en", theme: theme == "dark" ? darkTheme() : lightTheme() }, children, compatibleMode ? /* @__PURE__ */ React5.createElement(WalletConnectcompatibleMode, null) : /* @__PURE__ */ React5.createElement(WalletConnect, null))));
55
+ return /* @__PURE__ */ React2.createElement(WagmiProvider, { config: walletConfig.rainbowKitConfig, reconnectOnMount: walletConfig.reconnectOnMount }, /* @__PURE__ */ React2.createElement(QueryClientProvider, { client: queryClient }, /* @__PURE__ */ React2.createElement(RainbowKitProvider, { locale: "en", theme: theme == "dark" ? darkTheme() : lightTheme() }, children, compatibleMode ? /* @__PURE__ */ React2.createElement(WalletConnectcompatibleMode, null) : /* @__PURE__ */ React2.createElement(WalletConnect, null))));
726
56
  });
727
57
  var WalletConnectcompatibleMode = () => {
728
58
  const wallet = RootStore.Get(WalletStore);
729
59
  wallet.use();
730
- return /* @__PURE__ */ React5.createElement(React5.Fragment, null);
60
+ return /* @__PURE__ */ React2.createElement(React2.Fragment, null);
731
61
  };
732
62
  var WalletConnect = () => {
733
63
  const wallet = RootStore.Get(WalletStore);
734
64
  wallet.useWalletClientWithoutCompatibleMode();
735
65
  wallet.use();
736
- return /* @__PURE__ */ React5.createElement(React5.Fragment, null);
66
+ return /* @__PURE__ */ React2.createElement(React2.Fragment, null);
737
67
  };
738
68
  var RpcList = observer(() => {
739
69
  var _a, _b;
@@ -742,9 +72,9 @@ var RpcList = observer(() => {
742
72
  useEffect(() => {
743
73
  rpcStore.testRpc();
744
74
  }, []);
745
- return /* @__PURE__ */ React5.createElement("div", { className: "mb-3 mt-4" }, /* @__PURE__ */ React5.createElement("div", { className: "w-full flex mb-2 mt-2" }, /* @__PURE__ */ React5.createElement("div", { className: "flex items-center justify-center gap-2" }, /* @__PURE__ */ React5.createElement(Checkbox, { size: "sm", isSelected: rpcStore.isAutoSelectRpc.value, onValueChange: (e) => rpcStore.isAutoSelectRpc.save(e) }, "Auto select rpc"), /* @__PURE__ */ React5.createElement(Tooltip, { content: /* @__PURE__ */ React5.createElement("div", { className: "w-[300px]" }, "Once selected, if the current RPC cannot send a request, an available RPC will be automatically chosen.") }, /* @__PURE__ */ React5.createElement(Icon, { icon: "ph:question", width: "18", height: "18", className: "text-gray-500" }))), /* @__PURE__ */ React5.createElement(Button, { startContent: /* @__PURE__ */ React5.createElement(Icon, { icon: "tabler:test-pipe", width: "18", height: "18" }), className: "ml-auto", onClick: (e) => {
75
+ return /* @__PURE__ */ React2.createElement("div", { className: "mb-3 mt-4" }, /* @__PURE__ */ React2.createElement("div", { className: "w-full flex mb-2 mt-2" }, /* @__PURE__ */ React2.createElement("div", { className: "flex items-center justify-center gap-2" }, /* @__PURE__ */ React2.createElement(Checkbox, { size: "sm", isSelected: rpcStore.isAutoSelectRpc.value, onValueChange: (e) => rpcStore.isAutoSelectRpc.save(e) }, "Auto select rpc"), /* @__PURE__ */ React2.createElement(Tooltip, { content: /* @__PURE__ */ React2.createElement("div", { className: "w-[300px]" }, "Once selected, if the current RPC cannot send a request, an available RPC will be automatically chosen.") }, /* @__PURE__ */ React2.createElement(Icon, { icon: "ph:question", width: "18", height: "18", className: "text-gray-500" }))), /* @__PURE__ */ React2.createElement(Button, { startContent: /* @__PURE__ */ React2.createElement(Icon, { icon: "tabler:test-pipe", width: "18", height: "18" }), className: "ml-auto", onClick: (e) => {
746
76
  rpcStore.testRpc();
747
- } }, "Test"), /* @__PURE__ */ React5.createElement(Popover, { placement: "bottom", offset: 20, showArrow: true, isOpen: rpcStore.showCustomRpc, onOpenChange: (open) => rpcStore.showCustomRpc = open }, /* @__PURE__ */ React5.createElement(PopoverTrigger, null, /* @__PURE__ */ React5.createElement(Button, { color: "primary", startContent: /* @__PURE__ */ React5.createElement(Icon, { icon: "basil:add-solid", width: "18", height: "18" }), className: "ml-4" }, "Add custom rpc")), /* @__PURE__ */ React5.createElement(PopoverContent, null, /* @__PURE__ */ React5.createElement("div", { className: "px-1 py-2" }, /* @__PURE__ */ React5.createElement(
77
+ } }, "Test"), /* @__PURE__ */ React2.createElement(Popover, { placement: "bottom", offset: 20, showArrow: true, isOpen: rpcStore.showCustomRpc, onOpenChange: (open) => rpcStore.showCustomRpc = open }, /* @__PURE__ */ React2.createElement(PopoverTrigger, null, /* @__PURE__ */ React2.createElement(Button, { color: "primary", startContent: /* @__PURE__ */ React2.createElement(Icon, { icon: "basil:add-solid", width: "18", height: "18" }), className: "ml-4" }, "Add custom rpc")), /* @__PURE__ */ React2.createElement(PopoverContent, null, /* @__PURE__ */ React2.createElement("div", { className: "px-1 py-2" }, /* @__PURE__ */ React2.createElement(
748
78
  Input,
749
79
  {
750
80
  type: "url",
@@ -755,7 +85,7 @@ var RpcList = observer(() => {
755
85
  rpcStore.customRpc = value;
756
86
  }
757
87
  }
758
- ), /* @__PURE__ */ React5.createElement(Button, { color: "primary", isDisabled: !rpcStore.customRpc, onClick: (e) => rpcStore.addCustomRpc() }, "Save"))))), /* @__PURE__ */ React5.createElement(
88
+ ), /* @__PURE__ */ React2.createElement(Button, { color: "primary", isDisabled: !rpcStore.customRpc, onClick: (e) => rpcStore.addCustomRpc() }, "Save"))))), /* @__PURE__ */ React2.createElement(
759
89
  Table,
760
90
  {
761
91
  color: "success",
@@ -763,22 +93,22 @@ var RpcList = observer(() => {
763
93
  defaultSelectedKeys: [rpcStore.curRpc.value],
764
94
  "aria-label": "Example static collection table"
765
95
  },
766
- /* @__PURE__ */ React5.createElement(TableHeader, null, /* @__PURE__ */ React5.createElement(TableColumn, null, "RPC Server Address"), /* @__PURE__ */ React5.createElement(TableColumn, { align: "center" }, "Score"), /* @__PURE__ */ React5.createElement(TableColumn, { align: "center" }, "Height"), /* @__PURE__ */ React5.createElement(TableColumn, { align: "center" }, "Latency"), /* @__PURE__ */ React5.createElement(TableColumn, { align: "center" }, "Action")),
767
- /* @__PURE__ */ React5.createElement(TableBody, null, (_b = (_a = rpcStore.rpcList) == null ? void 0 : _a.value) == null ? void 0 : _b.map((item, index) => {
768
- return /* @__PURE__ */ React5.createElement(TableRow, { className: "cursor-pointer", key: item.name, onClick: (e) => {
96
+ /* @__PURE__ */ React2.createElement(TableHeader, null, /* @__PURE__ */ React2.createElement(TableColumn, null, "RPC Server Address"), /* @__PURE__ */ React2.createElement(TableColumn, { align: "center" }, "Score"), /* @__PURE__ */ React2.createElement(TableColumn, { align: "center" }, "Height"), /* @__PURE__ */ React2.createElement(TableColumn, { align: "center" }, "Latency"), /* @__PURE__ */ React2.createElement(TableColumn, { align: "center" }, "Action")),
97
+ /* @__PURE__ */ React2.createElement(TableBody, null, (_b = (_a = rpcStore.rpcList) == null ? void 0 : _a.value) == null ? void 0 : _b.map((item, index) => {
98
+ return /* @__PURE__ */ React2.createElement(TableRow, { className: "cursor-pointer", key: item.name, onClick: (e) => {
769
99
  rpcStore.curRpc.save(item.name);
770
100
  RootStore.Get(ToastPlugin).success("Set rpc success");
771
- } }, /* @__PURE__ */ React5.createElement(TableCell, null, item.name), /* @__PURE__ */ React5.createElement(TableCell, null, rpcStore.scoreIcon(item.latency)), /* @__PURE__ */ React5.createElement(TableCell, null, item.height), /* @__PURE__ */ React5.createElement(TableCell, { className: rpcStore.latencyColor(item.latency) }, item.latency, "s"), /* @__PURE__ */ React5.createElement(TableCell, null, /* @__PURE__ */ React5.createElement("div", { className: "relative flex items-center gap-2" }, /* @__PURE__ */ React5.createElement(Tooltip, { content: "Add to metamask" }, /* @__PURE__ */ React5.createElement("span", { className: "text-lg text-danger cursor-pointer active:opacity-50", onClick: (e) => {
101
+ } }, /* @__PURE__ */ React2.createElement(TableCell, null, item.name), /* @__PURE__ */ React2.createElement(TableCell, null, rpcStore.scoreIcon(item.latency)), /* @__PURE__ */ React2.createElement(TableCell, null, item.height), /* @__PURE__ */ React2.createElement(TableCell, { className: rpcStore.latencyColor(item.latency) }, item.latency, "s"), /* @__PURE__ */ React2.createElement(TableCell, null, /* @__PURE__ */ React2.createElement("div", { className: "relative flex items-center gap-2" }, /* @__PURE__ */ React2.createElement(Tooltip, { content: "Add to metamask" }, /* @__PURE__ */ React2.createElement("span", { className: "text-lg text-danger cursor-pointer active:opacity-50", onClick: (e) => {
772
102
  e.stopPropagation();
773
103
  rpcStore.addToMetamask(item.name);
774
- } }, /* @__PURE__ */ React5.createElement(Icon, { icon: "logos:metamask-icon", width: "18", height: "18" }))), item.custom && /* @__PURE__ */ React5.createElement(Tooltip, { content: "Remove" }, /* @__PURE__ */ React5.createElement("span", { className: "text-lg text-danger cursor-pointer active:opacity-50", onClick: (e) => {
104
+ } }, /* @__PURE__ */ React2.createElement(Icon, { icon: "logos:metamask-icon", width: "18", height: "18" }))), item.custom && /* @__PURE__ */ React2.createElement(Tooltip, { content: "Remove" }, /* @__PURE__ */ React2.createElement("span", { className: "text-lg text-danger cursor-pointer active:opacity-50", onClick: (e) => {
775
105
  e.stopPropagation();
776
106
  rpcStore.removeRpc(item.name);
777
- } }, /* @__PURE__ */ React5.createElement(Icon, { icon: "solar:trash-bin-minimalistic-broken", width: "20", height: "20" }))))));
107
+ } }, /* @__PURE__ */ React2.createElement(Icon, { icon: "solar:trash-bin-minimalistic-broken", width: "20", height: "20" }))))));
778
108
  }))
779
109
  ));
780
110
  });
781
111
 
782
- export { RpcList, WalletConfigStore, WalletHistoryStore, WalletProvider, WalletRpcStore, WalletStore, iotex, iotexTestnet };
112
+ export { RpcList, WalletProvider, iotex, iotexTestnet };
783
113
  //# sourceMappingURL=out.js.map
784
114
  //# sourceMappingURL=wallet.mjs.map