@tomo-inc/social-account-sdk 0.0.2-alpha.0 → 0.0.2-alpha.2

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/README.md CHANGED
@@ -1 +1,34 @@
1
1
  # @tomo-inc/social-account-sdk
2
+
3
+ for wallet developers
4
+
5
+ demo: https://github.com/tomo-inc/tomo-wallet-demo
6
+
7
+ cookbook: https://github.com/tomo-inc/tomo-wallet-demo/blob/main/src/social-wallet-demo.md
8
+
9
+ ## features
10
+
11
+ 1. support x(twitter) + google login
12
+ 2. support emai login
13
+ 3. only support evm
14
+
15
+ ## wallet api
16
+
17
+ 1. supportedChains: support chains
18
+ 2. getChainInfo
19
+ 3. isChainSupported
20
+ 4. getTransactions(transaction history)
21
+
22
+ ## evm api
23
+
24
+ 1. eth_accounts https://docs.metamask.io/wallet/reference/json-rpc-methods/eth_accounts/
25
+ 2. eth_chainId https://docs.metamask.io/wallet/reference/json-rpc-methods/eth_chainid/
26
+ 3. wallet_switchEthereumChain https://docs.metamask.io/wallet/reference/json-rpc-methods/wallet_switchethereumchain/
27
+ 4. personal_sign https://docs.metamask.io/wallet/reference/json-rpc-methods/personal_sign/
28
+ 5. eth_signTypedData_v4 https://docs.metamask.io/wallet/reference/json-rpc-methods/eth_signtypeddata_v4/
29
+ 6. eth_getTransactionCount(nonce) https://docs.metamask.io/wallet/reference/json-rpc-methods/eth_gettransactioncount/
30
+ 7. eth_getBalance https://docs.metamask.io/wallet/reference/json-rpc-methods/eth_getbalance/
31
+ 8. eth_estimateGas https://docs.metamask.io/wallet/reference/json-rpc-methods/eth_estimategas/
32
+ 9. eth_signTransaction https://docs.metamask.io/snaps/reference/keyring-api/chain-methods/#eth_signtransaction
33
+ 10. sendTransaction https://docs.metamask.io/services/reference/solana/json-rpc-methods/sendtransaction/
34
+ 11. getTransaction https://docs.metamask.io/services/reference/solana/json-rpc-methods/gettransaction/
package/dist/index.cjs CHANGED
@@ -1,248 +1,2 @@
1
- 'use strict';
2
-
3
- var walletUtils = require('@tomo-inc/wallet-utils');
4
- var chainsService = require('@tomo-inc/chains-service');
5
- var cubistWalletSdk = require('@tomo-inc/cubist-wallet-sdk');
6
- var oidcAuth = require('@tomo-inc/oidc-auth');
7
-
8
- var __defProp = Object.defineProperty;
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
11
- var CubeSocialAccount = class {
12
- constructor({ chainType, chainId }, accountData) {
13
- __publicField(this, "chainType");
14
- __publicField(this, "chainId");
15
- __publicField(this, "cubeSignService");
16
- __publicField(this, "accountData");
17
- __publicField(this, "userAPIs");
18
- this.chainType = chainType;
19
- this.chainId = chainId;
20
- this.accountData = accountData;
21
- this.cubeSignService = cubistWalletSdk.CubeSignService.getInstance();
22
- }
23
- async getAllAccounts() {
24
- const { accountWallet, user } = this.accountData || {};
25
- const addresses = {
26
- [walletUtils.ChainTypes.EVM]: [
27
- {
28
- address: accountWallet == null ? void 0 : accountWallet.ethereumAddress,
29
- publicKey: "",
30
- subType: walletUtils.ChainTypes.EVM,
31
- path: ""
32
- }
33
- ],
34
- [walletUtils.ChainTypes.DOGE]: [
35
- {
36
- address: accountWallet == null ? void 0 : accountWallet.dogeAddress,
37
- publicKey: "",
38
- subType: walletUtils.ChainTypes.DOGE,
39
- path: ""
40
- }
41
- ],
42
- [walletUtils.ChainTypes.SOL]: [
43
- {
44
- address: accountWallet == null ? void 0 : accountWallet.solanaAddress,
45
- publicKey: "",
46
- subType: walletUtils.ChainTypes.SOL,
47
- path: ""
48
- }
49
- ],
50
- [walletUtils.ChainTypes.TRON]: [
51
- {
52
- address: accountWallet == null ? void 0 : accountWallet.tronAddress,
53
- publicKey: "",
54
- subType: walletUtils.ChainTypes.TRON,
55
- path: ""
56
- }
57
- ],
58
- [walletUtils.ChainTypes.BTC]: [
59
- {
60
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2trAddressMain,
61
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2trPubKeyMain,
62
- subType: "TAPROOT",
63
- stage: "MAIN",
64
- path: "m/86'/0'/0'/0/0"
65
- },
66
- {
67
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2trAddressTest,
68
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2trPubKeyTest,
69
- subType: "TAPROOT",
70
- stage: "TEST",
71
- path: "m/86'/1'/0'/0/0"
72
- },
73
- {
74
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2shAddressMain,
75
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2shPubKeyMain,
76
- subType: "NESTED_SEGWIT",
77
- stage: "MAIN",
78
- path: "m/49'/0'/0'/0/0"
79
- },
80
- {
81
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2shAddressTest,
82
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2shPubKeyTest,
83
- subType: "NESTED_SEGWIT",
84
- stage: "TEST",
85
- path: "m/49'/1'/0'/0/0"
86
- },
87
- {
88
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2wpkhAddressMain,
89
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2wpkhPubKeyMain,
90
- subType: "NATIVE_SEGWIT",
91
- stage: "MAIN",
92
- path: "m/84'/0'/0'/0/0"
93
- },
94
- {
95
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2wpkhAddressTest,
96
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2wpkhPubKeyTest,
97
- subType: "NATIVE_SEGWIT",
98
- stage: "TEST",
99
- path: "m/84'/0'/0'/0/0"
100
- },
101
- {
102
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2pkhAddressMain,
103
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2pkhPubKeyMain,
104
- subType: "LEGACY",
105
- stage: "MAIN",
106
- path: "m/44'/0'/0'/0/0"
107
- },
108
- {
109
- address: accountWallet == null ? void 0 : accountWallet.bitcoinP2pkhAddressTest,
110
- publicKey: accountWallet == null ? void 0 : accountWallet.bitcoinP2pkhPubKeyTest,
111
- subType: "LEGACY",
112
- stage: "TEST",
113
- path: "m/44'/1'/0'/0/0"
114
- }
115
- ],
116
- [walletUtils.ChainTypes.SUI]: [
117
- {
118
- address: accountWallet == null ? void 0 : accountWallet.suiAddress,
119
- publicKey: "",
120
- subType: walletUtils.ChainTypes.SUI,
121
- path: ""
122
- }
123
- ],
124
- [walletUtils.ChainTypes.TON]: [
125
- {
126
- address: accountWallet == null ? void 0 : accountWallet.tonAddress,
127
- publicKey: "",
128
- subType: walletUtils.ChainTypes.TON,
129
- path: ""
130
- }
131
- ],
132
- [walletUtils.ChainTypes.COSMOS]: [
133
- {
134
- address: accountWallet == null ? void 0 : accountWallet.cosmosAddress,
135
- publicKey: "",
136
- subType: walletUtils.ChainTypes.COSMOS,
137
- path: ""
138
- }
139
- ],
140
- [walletUtils.ChainTypes.APTOS]: [
141
- {
142
- address: accountWallet == null ? void 0 : accountWallet.aptosAddress,
143
- publicKey: "",
144
- subType: walletUtils.ChainTypes.APTOS,
145
- path: ""
146
- }
147
- ]
148
- };
149
- return {
150
- id: user.accountID,
151
- name: user.nickname,
152
- type: chainsService.AccountType.SOCIAL,
153
- lastUsedTime: user.lastUsedTime,
154
- addresses,
155
- mnemonic: null,
156
- addressIndex: 0,
157
- isImported: false,
158
- isBackedUp: false,
159
- isLocked: false,
160
- isFrozen: false
161
- };
162
- }
163
- async getCurrent() {
164
- var _a, _b;
165
- const chainType = this.chainType;
166
- const account = await this.getAllAccounts();
167
- const { address, publicKey, path, subType } = ((_b = (_a = account == null ? void 0 : account.addresses) == null ? void 0 : _a[chainType]) == null ? void 0 : _b[0]) || {};
168
- return [
169
- {
170
- subType,
171
- address,
172
- path,
173
- publicKey,
174
- type: account.type,
175
- id: account.id
176
- }
177
- ];
178
- }
179
- async signMessage(message) {
180
- const currentAccounts = await this.getCurrent();
181
- const chainType = this.chainType;
182
- try {
183
- const address = currentAccounts[0].address;
184
- return await this.cubeSignService.signMessage(chainType, address, message);
185
- } catch (error) {
186
- console.error("Error signing message with CubeSignService:", error);
187
- throw error;
188
- }
189
- }
190
- async signTypedData(typedData) {
191
- const currentAccounts = await this.getCurrent();
192
- const chainType = this.chainType;
193
- try {
194
- const address = currentAccounts[0].address;
195
- return await this.cubeSignService.signTypedData(chainType, address, typedData);
196
- } catch (error) {
197
- console.error("Error signing typed data with CubeSignService:", error);
198
- throw error;
199
- }
200
- }
201
- //VersionedTransaction cannot through entirely to background by sendMessage
202
- async signTransaction(unsignedTx) {
203
- const currentAccounts = await this.getCurrent();
204
- const chainType = this.chainType;
205
- const address = currentAccounts[0].address;
206
- try {
207
- return await this.cubeSignService.signTransaction(chainType, address, unsignedTx);
208
- } catch (error) {
209
- console.error("Error signing transaction with CubeSignService:", error);
210
- throw error;
211
- }
212
- }
213
- };
214
- var SocialAccount = (accountData, chainConfig, tomoAppConfig) => {
215
- const { chainType, chainId } = chainConfig;
216
- const cubeAccountService = cubistWalletSdk.CubeAccountService.getInstance();
217
- cubeAccountService.initCubeSignService();
218
- const socialAccount = new CubeSocialAccount(chainConfig, accountData);
219
- const CurrentService = chainsService.ChainTypeServices[chainType];
220
- if (!CurrentService) {
221
- throw new Error(`ChainTypeServices not found for chainType: ${chainType}`);
222
- }
223
- const currentService = CurrentService.getInstance(chainType, socialAccount, tomoAppConfig);
224
- currentService.wallet_switchEthereumChain([{ chainId }]);
225
- return currentService;
226
- };
227
-
228
- Object.defineProperty(exports, "ChainTypes", {
229
- enumerable: true,
230
- get: function () { return walletUtils.ChainTypes; }
231
- });
232
- Object.defineProperty(exports, "TomoWallet", {
233
- enumerable: true,
234
- get: function () { return chainsService.TomoWallet; }
235
- });
236
- Object.defineProperty(exports, "TxTypes", {
237
- enumerable: true,
238
- get: function () { return chainsService.TxTypes; }
239
- });
240
- Object.defineProperty(exports, "CubeConnect", {
241
- enumerable: true,
242
- get: function () { return cubistWalletSdk.CubeConnect; }
243
- });
244
- Object.defineProperty(exports, "OidcAuth", {
245
- enumerable: true,
246
- get: function () { return oidcAuth.OidcAuth; }
247
- });
248
- exports.SocialAccount = SocialAccount;
1
+ 'use strict';var bignumber_js=require('bignumber.js'),viem=require('viem'),X=require('axios'),$e=require('crypto-js'),cubesignerSdk=require('@cubist-labs/cubesigner-sdk'),cubistSigSdk=require('@tomo-inc/cubist-sig-sdk');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var X__default=/*#__PURE__*/_interopDefault(X);var $e__default=/*#__PURE__*/_interopDefault($e);var Re=Object.defineProperty;var i=(r,e)=>Re(r,"name",{value:e,configurable:true});var He=Object.defineProperty,Ge=i((r,e)=>{for(var t in e)He(r,t,{get:e[t],enumerable:true});},"__export"),Ke={};Ge(Ke,{clear:i(()=>je,"clear"),get:i(()=>qe,"get"),remove:i(()=>Le,"remove"),set:i(()=>Ve,"set"),setKeyNS:i(()=>Xe,"setKeyNS")});var M="tomo-";function qe(r){let e=M+r;if(!ze(e))return null;let t=null;try{let n=window.localStorage.getItem(e)||window.sessionStorage.getItem(e);t=JSON.parse(n);}catch(n){console.error(n);}return t!==null&&Object.prototype.hasOwnProperty.call(t,"type")&&Object.prototype.hasOwnProperty.call(t,"data")?t.data:null}i(qe,"get");function Ve(r,e,t){var n;let s;t?s=window.sessionStorage:s=window.localStorage;let a=JSON.stringify({data:e,time:new Date().getTime(),type:typeof e});try{return s.setItem(M+r,a),!0}catch(o){((n=o?.name)==null?void 0:n.toUpperCase().indexOf("QUOTA"))>=0&&(window.localStorage.clear(),s.setItem(M+r,a));}}i(Ve,"set");function Le(r){let e=M+r;window.localStorage.removeItem(e),window.sessionStorage.removeItem(e);}i(Le,"remove");function je(){var r,e;(r=window?.localStorage)==null||r.clear(),(e=window?.sessionStorage)==null||e.clear();}i(je,"clear");function ze(r){return Object.prototype.hasOwnProperty.call(window.localStorage,r)||Object.prototype.hasOwnProperty.call(window.sessionStorage,r)}i(ze,"isKeyExist");function Xe(r){typeof r=="string"&&r!==""&&(M=r);}i(Xe,"setKeyNS");var N=(r=>(r.BTC="btc",r.DOGE="doge",r.EVM="evm",r.SOL="sol",r.SUI="sui",r.TON="ton",r.TRON="tron",r.COSMOS="cosmos",r.APTOS="aptos",r))(N||{}),A={doge:{chainId:"3",chainIndex:300,support:true,gasFee:.5,dust:1e-4},evm:{chainId:"1",chainIndex:100,support:true,gasFee:1e-5,dust:0},sol:{chainId:"501",chainIndex:50100,support:true,gasFee:1e-4,dust:0,reserve:9e-4},tron:{chainId:"19484",chainIndex:1948400,support:true,gasFee:.5,dust:0},btc:{chainId:"0",chainIndex:0,support:false,gasFee:1e-5,dust:1e-4},sui:{support:false,gasFee:0,dust:0},ton:{support:false,gasFee:0,dust:0},cosmos:{support:false,gasFee:0,dust:0},aptos:{support:false,gasFee:0,dust:0}};function Je(r,e,t){Object.prototype.toString.call(e)!=="[object Array]"&&(e=[e]);let n=[];for(let a=0,o=e.length;a<o;a++)n.push(s(e[a]));return n.join("");function s(a){return r.replace(/\\?\{([^}]+)\}/g,function(o,c){return o.charAt(0)=="\\"?o.slice(1):a[c]!=null?a[c]:""})}}i(Je,"subs");function Ye(r,e){let t={0:"",100:"https://etherscan.io/tx/{txId}",300:"https://dogechain.info/tx/{txId}",400:"",1e3:"https://optimistic.etherscan.io/tx/{txId}",5600:"https://bscscan.com/tx/{txId}",12600:"https://explorer.movementnetwork.xyz/txn/{txId}?network=mainnet",13700:"https://polygonscan.com/tx/{txId}",20400:"https://opbnb.bscscan.com/tx/{txId}",22300:"https://explorer.bsquared.network/tx/{txId}",22700:"https://promscan.io/tx/{txId}",32400:"https://mainnet.era.zksync.io/tx/{txId}",48e3:"https://worldchain-mainnet.explorer.alchemy.com/tx/{txId}",50100:"https://solscan.io/tx/{txId}",78400:"",11e4:"",132900:"https://seitrace.com/tx/{txId}",151400:"https://mainnet.storyscan.xyz/tx/{txId}",162500:"https://explorer.gravity.xyz/tx/{txId}",264900:"https://mainnet-explorer.ailayer.xyz/tx/{txId}",42e4:"https://scan.merlinchain.io/tx/{txId}",554500:"https://scan.duckchain.io/tx/{txId}",833300:"https://mainnet-rpc.b3.fun/http/tx/{txId}",845300:"https://base.blockscout.com/tx/{txId}",1948400:"https://tronscan.org/#/transaction/{txId}",4216100:"https://arbiscan.io/tx/{txId}",4311400:"https://snowtrace.io/tx/{txId}",4776300:"https://neotube.io/transaction/{txId}",5914400:"https://lineascan.build/tx/{txId}",6080800:"https://rpc.gobob.xyz/tx/{txId}",8009400:"https://berascan.com/tx/{txId}",8145700:"https://blastscan.io/tx/{txId}",20090100:"https://rpc.bitlayer.org/tx/{txId}",53435200:"https://scrollscan.com/tx/{txId}",221122420:"https://blockscout.devnet.doge.xyz/tx/{txId}",21e8:"https://maizenet-explorer.usecorn.com/tx/{txId}"},n=r.toString(),s=t[n]||"";if(s==="")throw new Error(`chainIndex ${r} tpl not found`);return Je(s,e)}i(Ye,"getExplorerUrl");var We={prod:"https://wallet-pro.tomo.inc",pre:"https://wallet-pre-wlfi.tomo.inc",dev:"https://wallet-test.tomo.inc"},Ze=class{static{i(this,"Networks");}chainType;networkAPIs;constructor(r,e){this.chainType=e||"",this.networkAPIs=r;}setChainType(r){this.chainType=r;}async getNetworks(r){return this.networkAPIs.getAllNetworks(r||"")}async getNetworkByChainId(r){let e=await this.networkAPIs.getNetworkByChainId(r);if(!e)throw new Error("Network not found");return e}async getNetworkByChainIndex(r){let e=await this.networkAPIs.getNetworkByChainIndex(r);if(!e)throw new Error("Network not found");return e}async getCurrentNetwork(){let r=this.chainType,e=await this.networkAPIs.getCurrentNetwork(r);return e===""&&(e=A?.[r]?.chainId||""),this.getNetworkByChainId(e)}async setCurrentNetwork(r){let e=this.chainType||"";return await this.networkAPIs.setCurrentNetwork(e,r),true}},Qe=class{static{i(this,"Tokens");}tokenAPIs;constructor(r){this.tokenAPIs=r;}async searchTokens({chainIndex:r,query:e}){let{data:t=[]}=await this.tokenAPIs.queryRemoteTokens({keyword:e||"",chainIndex:r});return t}async getTokenInfo({address:r,chainIndex:e}){let{data:{data:t}}=await this.tokenAPIs.getTokenInfo({address:r,chainIndex:e});return t}async getTokenRiskInfo(r){let{data:e}=await this.tokenAPIs.getTokenRisk(r);return e}async getTokenDetail(r){let{data:e}=await this.tokenAPIs.getTokenDetail(r);return e}};N.BTC+"",N.COSMOS+"",N.DOGE+"";var et=class{static{i(this,"Transactions");}transactionAPIs;constructor(r){this.transactionAPIs=r;}async queryGasInfo({chainType:r,params:e}){try{let t=await this.transactionAPIs.queryGasInfo(r,e);return {success:t?.code===0,data:t?.result||{}}}catch(t){return {success:false,message:t?.message||"Failed to query gas info"}}}async getTransactions(r){let e=await this.transactionAPIs.getTransactions(r),{cursor:t="",transactionList:n=[]}=e||{};return {cursor:t,transactionList:n}}async getTransaction(r){return (await this.transactionAPIs.getTransaction(r))?.data||{}}};function J(r){let e=We[r];if(!e)throw new Error("Invalid tomo stage");return {rpcBaseUrl:`${e}`,walletBaseUrl:`${e}/wallet`,txBaseUrl:`${e}/quote`,tokenBaseUrl:`${e}/token`,userBaseUrl:`${e}/user/api`}}i(J,"getConfig");var ie={prod:J("prod"),pre:J("pre"),dev:J("dev")};function tt(r){let e=Math.floor(Date.now()/1e3).toString(),t=r.method.toUpperCase(),n=r.data?r.data:{};t==="GET"?n=JSON.stringify({key:"value"}):typeof n!="string"&&(n=JSON.stringify(n));let s=[t,r.url,e,n,r.apiKey,r.apiSecret,r.salt].join("");return {signature:$e__default.default.SHA256(s).toString(),timestamp:e}}i(tt,"generateSignature");var rt=i(r=>`Bearer ${r}`,"formatJwtToken");function nt(r,e,t){if(typeof t=="string"){let l=t;return Object.assign(r.headers??{},{"client-id":e,Authorization:rt(l)}),r}let{apiKey:n,apiSecret:s,salt:a}=t,{signature:o,timestamp:c}=tt({method:r.method,url:r.url,data:r.data,apiKey:n,apiSecret:s,salt:a});return Object.assign(r.headers??{},{"X-APP-Key":n,"X-Signature":o,"X-Timestamp":c,"client-id":e}),r}i(nt,"signRequest");var K=class{static{i(this,"BasePublicService");}tokenApi=X__default.default.create();txApi=X__default.default.create();walletApi=X__default.default.create();apiBase;tomoAppInfo;constructor(r,e){this.apiBase=r,this.tomoAppInfo=e,[this.tokenApi,this.txApi,this.walletApi].map((t,n)=>t.interceptors.request.use(s=>{let{tokenBaseUrl:a,txBaseUrl:o,walletBaseUrl:c}=r;return s.baseURL=[a,o,c][n],nt(s,e.tomoClientId,e)}));}getSignConfig(){return this.tomoAppInfo}},st=class ue extends K{static{i(this,"_TokenAPIs");}static instance;constructor(e,t){super(e,t);}static getInstance(e,t){return this.instance||(this.instance=new ue(e,t)),this.instance}async getTokenInfo(e){try{let t=await this.walletApi.get("/v1/balance/getTokenInfo",{params:e});return {success:t?.data?.code==="00000",message:t?.data?.msg,data:t?.data?.data}}catch(t){throw console.error("Failed to get token info:",t),t}}async getTokenRisk(e){if(typeof e.chainIndex!="number"||!e.tokenAddress)throw new Error("chainName or tokenAddress is required");let t=await this.tokenApi.post("/v1/market/risk/details",[e]);return {success:t?.data?.code==="0",message:t?.data?.msg,data:t?.data?.data?.[0]||null}}async addCustomToken(e){try{let t=await this.walletApi.post("/v1/customTokens/addCustomToken",e,{});return {success:t?.data?.code==="00000",message:t?.data?.msg,data:t?.data?.data}}catch(t){throw console.error("Failed to add custom token:",t),t}}async deleteCustomToken(e){try{let t=await this.walletApi.get("/v1/customTokens/delete",{params:e});return {success:t?.data?.code==="00000",message:t?.data?.msg,data:t?.data?.data}}catch(t){throw console.error("Failed to delete custom token:",t),t}}async addMultiToken(e){try{let t=await this.walletApi.post("/v1/customTokens/addTokenWithMulti",e,{});return {success:t?.data?.code==="00000",message:t?.data?.msg,data:t?.data?.data}}catch(t){throw console.error("Failed to add multi token:",t),t}}async removeMultiToken(e){try{let t=await this.walletApi.get("/v1/customTokens/hideTokenWithMulti",{params:e});return {success:t?.data?.code==="00000",message:t?.data?.msg,data:t?.data?.data}}catch(t){throw console.error("Failed to delete multi token:",t),t}}async syncCustomToken(e){try{return (await this.walletApi.post("/v1/customTokens/sync",e,{}))?.data||{}}catch(t){throw console.error("Failed to sync custom token:",t),t}}async getTokenBalance(e){try{let t=await this.walletApi.get("/v1/balance/getTokenBalanceWithDetail",{params:e});return {success:t?.data?.code==="00000",message:t?.data?.msg,data:t?.data?.data||null}}catch(t){throw console.error("Failed to get token balance:",t),t}}async getTokenDetail(e){let{chainIndex:t,tokenAddress:n}=e,s=await this.tokenApi.get("/v1/market/token/detail",{params:{tokenAddress:n,chainIndex:t}});return {success:s?.data?.code==="0",message:s?.data?.msg,data:s?.data?.data||null}}async queryRemoteTokens(e){let{keyword:t="",chainIndex:n}=e||{};if(!t)throw new Error("Params is required");let s=await this.tokenApi.get("/v1/market/token/search",{params:{content:t,chainIndex:n}});return {success:s?.data?.code==="0",message:s?.data?.msg,data:s?.data?.data||[]}}},at=class pe extends K{static{i(this,"_TransactionAPIs");}static instance;constructor(e,t){super(e,t);}static getInstance(e,t){return this.instance||(this.instance=new pe(e,t)),this.instance}async queryGasInfo(e,t){try{return (await this.txApi.post("/api/v1/quote/queryGasInfo",t))?.data||{}}catch(n){throw console.error("Failed to get gas info:",n),n}}async getTransactions(e){try{return (await this.walletApi.get("/v1/transaction/list",{params:e}))?.data?.data||{}}catch(t){throw console.error("Failed to get transactions:",t),t}}async getTransaction(e){try{return (await this.walletApi.get("/v1/transaction/detail",{params:e}))?.data?.data||{}}catch(t){throw console.error("Failed to get transaction:",t),t}}},ot=class de extends K{static{i(this,"_WalletAPIs");}static instance;constructor(e,t){super(e,t);}static getInstance(e,t){return this.instance||(this.instance=new de(e,t)),this.instance}async createWallet(e){try{if(!e)throw new Error("Params is required");return (await this.walletApi.post("/v1/wallet/create",e,{}))?.data||{}}catch(t){if(t?.response?.data?.code==="60003")return {success:false,message:"Wallet already exists",data:null};throw console.error("Failed to create wallet:",t),t}}async syncWallet(e){try{return (await this.walletApi.post("/v1/wallet/sync",e,{}))?.data||{}}catch(t){throw console.error("Failed to sync wallet:",t),t}}async deleteWallet(e){try{return (await this.walletApi.post("/v1/wallet/delete",e,{}))?.data||{}}catch(t){throw console.error("Failed to sync wallet:",t),t}}},it=i(r=>[{chainId:0,chainIndex:0,name:"BITCOIN",chainName:"Bitcoin",nativeCurrencyName:"BTC",nativeCurrencySymbol:"BTC",nativeCurrencyDecimals:8,platformType:"BTC",icon:"https://static.tomo.inc/token/btc.svg",supportSwap:true,supportGift:false,supportHistory:true},{chainId:3,chainIndex:300,name:"DOGECOIN",chainName:"Dogecoin",nativeCurrencyName:"DOGE",nativeCurrencySymbol:"DOGE",nativeCurrencyDecimals:8,blockExplorerUrl:"https://dogechain.info",platformType:"DOGE",icon:"https://static.tomo.inc/token/doge.svg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:221122420,chainIndex:22112242e3,name:"DOGEOS_DEVNET",chainName:"DogeOS Devnet",rpcUrls:[`${r}/rpc/v1/doge_test`],blockExplorerUrl:"https://blockscout.devnet.doge.xyz",platformType:"EVM",isTestnet:true,icon:"/assets/dogeos.svg",supportSwap:true,supportGift:false,supportHistory:false},{chainId:1,chainIndex:100,name:"ETH",chainName:"Ethereum",nativeCurrencyName:"ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/eth`],blockExplorerUrl:"https://etherscan.io",platformType:"EVM",icon:"https://static.tomo.inc/token/eth_new.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:501,chainIndex:50100,name:"SOLANA",chainName:"Solana",nativeCurrencyName:"SOL",nativeCurrencySymbol:"SOL",nativeCurrencyDecimals:9,rpcUrls:["https://FLORAL-YOLO-DAYLIGHT.solana-mainnet.quiknode.pro/78b0cda5969b12967ac69cde74e0937ed285d6e5","https://mainnet.helius-rpc.com/?api-key=ac6f0298-d53b-4a04-8389-7966584a67d1","https://empty-smart-wildflower.solana-mainnet.quiknode.pro/ebfb8013883fffdaf5a64952fd6c8b2b2bf3cea8"],blockExplorerUrl:"https://solscan.io",platformType:"SOLANA",icon:"https://static.tomo.inc/token/sol.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:56,chainIndex:5600,name:"BSC",chainName:"BNB Chain",nativeCurrencyName:"BNB",nativeCurrencySymbol:"BNB",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/bsc`],blockExplorerUrl:"https://bscscan.com",platformType:"EVM",icon:"https://static.tomo.inc/token/bsc_new.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:8453,chainIndex:845300,name:"BASE",chainName:"Base",nativeCurrencyName:"BASE_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/base`],blockExplorerUrl:"https://base.blockscout.com",platformType:"EVM",icon:"https://static.tomo.inc/token/base.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:1100,chainIndex:11e4,name:"TON",chainName:"TON",nativeCurrencyName:"TON",nativeCurrencySymbol:"TON",nativeCurrencyDecimals:9,platformType:"TON",icon:"https://static.tomo.inc/token/ton.svg",supportSwap:true,supportGift:true,supportHistory:false},{chainId:784,chainIndex:78400,name:"SUI",chainName:"SUI",nativeCurrencyName:"SUI",nativeCurrencySymbol:"SUI",nativeCurrencyDecimals:9,platformType:"SUI",icon:"https://static.tomo.inc/token/sui.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:42161,chainIndex:4216100,name:"ARBITRUM",chainName:"Arbitrum One",nativeCurrencyName:"ARB_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/arbitrum_one`],blockExplorerUrl:"https://arbiscan.io",platformType:"EVM",icon:"https://static.tomo.inc/token/arb.jpeg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:59144,chainIndex:5914400,name:"LINEA",chainName:"Linea",nativeCurrencyName:"LINEA_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/linea`],blockExplorerUrl:"https://lineascan.build",platformType:"EVM",icon:"https://static.tomo.inc/token/linea.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:10,chainIndex:1e3,name:"OPTIMISM",chainName:"Optimism",nativeCurrencyName:"OP_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/optimism`],blockExplorerUrl:"https://optimistic.etherscan.io",platformType:"EVM",icon:"https://static.tomo.inc/token/op.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:137,chainIndex:13700,name:"POLYGON_POS",chainName:"Polygon",nativeCurrencyName:"POL",nativeCurrencySymbol:"POL",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/polygon`],blockExplorerUrl:"https://polygonscan.com",platformType:"EVM",icon:"https://static.tomo.inc/token/polygon.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:81457,chainIndex:8145700,name:"BLAST",chainName:"Blast",nativeCurrencyName:"BLAST_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/blast`],blockExplorerUrl:"https://blastscan.io",platformType:"EVM",icon:"https://static.tomo.inc/token/blast.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:534352,chainIndex:53435200,name:"SCROLL",chainName:"Scroll",nativeCurrencyName:"SCROLL_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/scroll`],blockExplorerUrl:"https://scrollscan.com",platformType:"EVM",icon:"https://static.tomo.inc/token/scroll.svg",supportSwap:true,supportGift:true,supportHistory:true},{chainId:43114,chainIndex:4311400,name:"AVAX",chainName:"Avalanche C",nativeCurrencyName:"AVAX",nativeCurrencySymbol:"AVAX",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/avalanche`],blockExplorerUrl:"https://snowtrace.io",platformType:"EVM",icon:"https://static.tomo.inc/token/avalanche.svg",supportSwap:true,supportGift:false,supportHistory:true},{chainId:324,chainIndex:32400,name:"ZKSYNC",chainName:"zkSync Era",nativeCurrencyName:"ZKSYNC_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/zk_sync`],blockExplorerUrl:"https://mainnet.era.zksync.io",platformType:"EVM",icon:"https://static.tomo.inc/token/zksync.png",supportSwap:false,supportGift:false,supportHistory:true},{chainId:60808,chainIndex:6080800,name:"BOB",chainName:"BOB",nativeCurrencyName:"BOB_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/bob`],blockExplorerUrl:"https://rpc.gobob.xyz",platformType:"EVM",icon:"https://static.tomo.inc/token/bob.png",supportSwap:false,supportGift:false,supportHistory:true},{chainId:8333,chainIndex:833300,name:"B3",chainName:"B3 Mainnet",nativeCurrencyName:"B3_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/b3`],blockExplorerUrl:"https://mainnet-rpc.b3.fun/http",platformType:"EVM",icon:"https://static.tomo.inc/token/b3.svg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:223,chainIndex:22300,name:"B2",chainName:"B\xB2 Network",nativeCurrencyName:"B2_BTC",nativeCurrencySymbol:"BTC",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/b2`],blockExplorerUrl:"https://explorer.bsquared.network",platformType:"EVM",icon:"https://static.tomo.inc/token/b2.svg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:200901,chainIndex:20090100,name:"BITLAYER",chainName:"Bitlayer",nativeCurrencyName:"BITLAYER_BTC",nativeCurrencySymbol:"BTC",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/bit_layer`],blockExplorerUrl:"https://rpc.bitlayer.org",platformType:"EVM",icon:"https://static.tomo.inc/token/bitlayer.svg",supportSwap:false,supportGift:true,supportHistory:true},{chainId:19484,chainIndex:1948400,name:"TRON",chainName:"Tron",nativeCurrencyName:"TRX",nativeCurrencySymbol:"TRX",nativeCurrencyDecimals:6,platformType:"TRON",blockExplorerUrl:"https://tronscan.org",icon:"https://static.tomo.inc/token/tron.svg",supportSwap:true,supportGift:false,supportHistory:true},{chainId:4,chainIndex:400,name:"COSMOS_HUB",chainName:"Cosmos Hub",nativeCurrencyName:"ATOM",nativeCurrencySymbol:"ATOM",nativeCurrencyDecimals:6,platformType:"COSMOS",icon:"https://static.tomo.inc/token/cosmos.png",supportSwap:false,supportGift:false,supportHistory:false},{chainId:5545,chainIndex:554500,name:"DUCKCHAIN",chainName:"DuckChain Mainnet",nativeCurrencyName:"DUCKCHAIN_TON",nativeCurrencySymbol:"TON",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/duck`],blockExplorerUrl:"https://scan.duckchain.io",platformType:"EVM",icon:"https://static.tomo.inc/token/duckchain.svg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:47763,chainIndex:4776300,name:"NEOX",chainName:"Neo X Mainnet",nativeCurrencyName:"GAS",nativeCurrencySymbol:"GAS",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/neox`],blockExplorerUrl:"https://neotube.io",platformType:"EVM",icon:"https://static.tomo.inc/token/neo.jpg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:4200,chainIndex:42e4,name:"MERLIN",chainName:"Merlin Chain",nativeCurrencyName:"MERLIN_BTC",nativeCurrencySymbol:"BTC",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/merlin`],blockExplorerUrl:"https://scan.merlinchain.io",platformType:"EVM",icon:"https://static.tomo.inc/token/merlin.png",supportSwap:false,supportGift:true,supportHistory:true},{chainId:1329,chainIndex:132900,name:"SEI",chainName:"Sei EVM",nativeCurrencyName:"SEI",nativeCurrencySymbol:"SEI",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/sei`],blockExplorerUrl:"https://seitrace.com",platformType:"EVM",icon:"https://static.tomo.inc/token/sei.svg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:480,chainIndex:48e3,name:"WORLD_CHAIN",chainName:"World Chain",nativeCurrencyName:"WORLDCHAIN_ETH",nativeCurrencySymbol:"ETH",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/world`],blockExplorerUrl:"https://worldchain-mainnet.explorer.alchemy.com",platformType:"EVM",icon:"https://static.tomo.inc/token/world-chain.jpg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:2649,chainIndex:264900,name:"AILAYER",chainName:"AILayer",nativeCurrencyName:"AILAYER_BTC",nativeCurrencySymbol:"BTC",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/ai_layer`],blockExplorerUrl:"https://mainnet-explorer.ailayer.xyz",platformType:"EVM",icon:"https://static.tomo.inc/token/ailayer.svg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:227,chainIndex:22700,name:"PROM",chainName:"Prom",nativeCurrencyName:"PROM",nativeCurrencySymbol:"PROM",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/prom_test`],blockExplorerUrl:"https://promscan.io",platformType:"EVM",icon:"https://static.tomo.inc/token/prom-testnet.svg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:1625,chainIndex:162500,name:"GRAVITY",chainName:"Gravity Alpha",nativeCurrencyName:"G",nativeCurrencySymbol:"G",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/gravity`],blockExplorerUrl:"https://explorer.gravity.xyz",platformType:"EVM",icon:"https://static.tomo.inc/token/gravity.jpg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:204,chainIndex:20400,name:"OPBNB",chainName:"opBNB",nativeCurrencyName:"OP_BNB",nativeCurrencySymbol:"BNB",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/op_bnb`],blockExplorerUrl:"https://opbnb.bscscan.com",platformType:"EVM",icon:"https://static.tomo.inc/token/opbnb.svg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:21e6,chainIndex:21e8,name:"CORN",chainName:"Corn",nativeCurrencyName:"BTCN",nativeCurrencySymbol:"BTCN",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/corn`],blockExplorerUrl:"https://maizenet-explorer.usecorn.com",platformType:"EVM",icon:"https://static.tomo.inc/token/corn-logo.svg",supportSwap:false,supportGift:true,supportHistory:false},{chainId:126,chainIndex:12600,name:"MOVEMENT_MAINNET",chainName:"Movement Mainnet",nativeCurrencyName:"MOVE",nativeCurrencySymbol:"MOVE",nativeCurrencyDecimals:8,rpcUrls:["https://mainnet.movementnetwork.xyz/v1"],blockExplorerUrl:"https://explorer.movementnetwork.xyz",platformType:"APTOS",icon:"https://static.tomo.inc/token/movement.svg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:80094,chainIndex:8009400,name:"BERACHAIN_MAINNET",chainName:"Berachain Mainnet",nativeCurrencyName:"BERA Token",nativeCurrencySymbol:"BERA",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/bera`],blockExplorerUrl:"https://berascan.com",platformType:"EVM",icon:"https://static.tomo.inc/token/berachain.svg",supportSwap:false,supportGift:false,supportHistory:false},{chainId:1514,chainIndex:151400,name:"STORY_MAINNET",chainName:"Story Mainnet",nativeCurrencyName:"IP",nativeCurrencySymbol:"IP",nativeCurrencyDecimals:18,rpcUrls:[`${r}/rpc/v1/story`],blockExplorerUrl:"https://mainnet.storyscan.xyz",platformType:"EVM",icon:"https://static.tomo.inc/token/story.jpg",supportSwap:false,supportGift:false,supportHistory:false}],"loadNetworks"),ct=class he extends K{static{i(this,"_NetworkAPIs");}static instance;chains=[];currentChainId="";constructor(e,t){super(e,t);let n=it(e.rpcBaseUrl);this.chains=n.map(s=>{let a={symbol:s.nativeCurrencySymbol||"",decimals:s.nativeCurrencyDecimals||18,name:s.nativeCurrencyName||""};return delete s.nativeCurrencySymbol,delete s.nativeCurrencyDecimals,delete s.nativeCurrencyName,{...s,nativeCurrency:a}}),this.currentChainId="1";}static getInstance(e,t){return this.instance||(this.instance=new he(e,t)),this.instance}getAllNetworks(e){return e===""?this.chains:this.chains.filter(t=>t.platformType===e.toUpperCase())}async getCurrentNetwork(e){if(!A?.[e])throw new Error(`Chain ${e} is not supported`);return this.currentChainId||A?.[e]?.chainId||""}async setCurrentNetwork(e,t){if(e&&!A?.[e])throw new Error(`Chain ${e} is not supported`);this.currentChainId=t;}getNetworkByChainId(e){return this.chains.find(t=>t.chainId===Number(e))}getNetworkByChainIndex(e){return this.chains.find(t=>t.chainIndex===e)}};function lt(r,e){return {tokenAPIs:st.getInstance(r,e),transactionAPIs:at.getInstance(r,e),networkAPIs:ct.getInstance(r,e),walletAPIs:ot.getInstance(r,e)}}i(lt,"tomoPublicApiService");var me=class{static{i(this,"BaseService");}isDappConnected;approveParams;accountInfo;networks;tokens;transactions;constructor(r,e){if(!r.tomoStage||!ie[r.tomoStage])throw new Error("Tomo stage is required");let t=ie[r.tomoStage],{tokenAPIs:n,transactionAPIs:s,networkAPIs:a}=lt(t,r);this.accountInfo=e,this.networks=new Ze(a),this.tokens=new Qe(n),this.transactions=new et(s),this.isDappConnected=false;}async setApproveParams(r){this.approveParams=r;}};function ut(r){let{chainId:e,name:t,rpcUrls:n,nativeCurrencyDecimals:s,nativeCurrencyName:a,nativeCurrencySymbol:o}=r,c={id:Number(e)||e,name:t,nativeCurrency:{name:a,symbol:o,decimals:s},rpcUrls:{default:{http:n,webSocket:[]},public:{http:n,webSocket:[]}},blockExplorers:{default:{name:"Explorer",url:n[0]}}};return {rpcClient:viem.createPublicClient({chain:c,pollingInterval:1e4,cacheTime:1e4,transport:viem.http()})}}i(ut,"getRPCClient");var ee=(r=>(r.EOA="EOA",r.SOCIAL="SOCIAL",r))(ee||{}),we=(r=>(r[r.swap=1]="swap",r[r.bridge=2]="bridge",r[r.receive=31]="receive",r[r.send=32]="send",r[r.approve=4]="approve",r[r.contractInteraction=5]="contractInteraction",r[r.redPocket=6]="redPocket",r))(we||{}),pt=i(r=>r&&r?.platformType==="EVM","isEvmChain"),Y=i(({chainId:r,chainType:e})=>{if(viem.isHex(r)){let n=r;return r=viem.fromHex(r,"number").toString(),{chainId:r,chainIdHex:n,chainUid:`${e}:${r}`}}let t=viem.toHex(Number(r));return {chainId:r,chainIdHex:t,chainUid:`${e}:${r}`}},"getAllTypeChainIds"),dt=class P extends me{static{i(this,"_EvmService");}static instance;chainType;constructor(e,t,n){super(n,t),this.chainType=e;}static getInstance(e,t,n){return P.instance||(P.instance=new P(e,t,n)),P.instance}async eth_requestAccounts(){return await this.eth_accounts()}async eth_accounts(){return (await this.accountInfo.getCurrent()).map(t=>t.address)}async eth_chainId(){let e=this.chainType,t=await this.getCurrentChain(),{chainIdHex:n}=Y({chainId:t?.chainId,chainType:e});return n}async getCurrentChain(){return this.networks.setChainType(this.chainType),await this.networks.getCurrentNetwork()}async wallet_switchEthereumChain(e){let{chainId:t}=e[0];if(!await this.isChainSupported(t))throw new Error(`Chain ${t} is not supported`);return await this.networks.setCurrentNetwork(t)}async isChainSupported(e){let t=this.chainType,n=Y({chainId:e,chainType:t});if(!n.chainId)return false;let s=await this.networks.getNetworkByChainId(n.chainId);return s?pt(s):false}async personal_sign([e,t]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");return await this.accountInfo.signMessage(e)}async eth_signTypedData_v4([e,t]){if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");return await this.accountInfo.signTypedData(t)}async eth_getBalance([e,t]){if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");if(t!=="latest")throw new Error("type is not supported");let s=await this.getCurrentChain(),{rpcClient:a}=ut(s);try{return (await a.getBalance({address:e}))?.toString()||"0"}catch(o){return console.error(o),"0"}}async eth_estimateGas(e){let{from:t,to:n,value:s="0x1"}=e[0]||{};if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");if(!n)throw new Error("to is not set");let o=e[0]?.chainId||await this.eth_chainId(),c={chainIndex:Number(o),callData:"0x",gasLimitParam:{from:t,to:n,value:s},addressList:[t]},l=this.chainType,{data:h,success:m,message:u}=await this.transactions.queryGasInfo({chainType:l,params:c});if(!m){console.error("queryGasInfo evm",e,u,h);let{gasFee:b}=A[l];return b.toString()}let y=Y({chainId:o,chainType:l}),{nativeCurrencyDecimals:p}=await this.networks.getNetworkByChainId(y.chainId),{baseFee:v=1,gasLimit:d=0}=h,w=new bignumber_js.BigNumber(v);return i(b=>{let E=w.plus(h[b]||0).times(d);return viem.toHex(BigInt(E.toNumber()),p)},"calcFee")("priorityFeeMedium")}async createPublicClient({chainId:e,rpcUrl:t}){if(t)return viem.createPublicClient({transport:viem.http(t)});if(e?(this.networks.setChainType(this.chainType),t=(await this.networks.getNetworkByChainId(e)).rpcUrls[0]):t=(await this.getCurrentChain()).rpcUrls[0],!t)throw new Error("rpcUrl is not set");return viem.createPublicClient({transport:viem.http(t)})}async eth_getTransactionCount([e,t]){if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");if(t!=="latest"&&t!=="pending")throw new Error("type is not supported");try{return await(await this.createPublicClient({})).getTransactionCount({address:e})}catch(s){throw console.error("Failed to get nonce:",s),new Error(`Failed to get nonce: ${s}`)}}async eth_signTransaction(e){let t={chainId:"number",to:"string",value:"bigint",data:"string",nonce:"number",maxPriorityFeePerGas:"bigint",maxFeePerGas:"bigint",gasLimit:"bigint",gas:"bigint"},n=e?.[0],s=n?.gas||n?.gasLimit;n={...n,gas:s,gasLimit:s},n.data=n.data||"0x";let o=(await this.accountInfo.getCurrent())[0].address;if(n?.from&&n?.from!==o)throw console.error("eth_signTransaction error data: from is not the current account",n),new Error("eth_signTransaction error data: from is not the current account");delete n?.from;let c={type:"eip1559",gas:n?.gasLimit,account:o};for(let l in t){if(!n?.[l]||!viem.isHex(n?.[l]))throw new Error(`${l}: no data or wrong type`);c[l]=t[l]==="number"?viem.fromHex(n[l],"number"):n[l];}try{let l=await this.accountInfo.signTransaction(JSON.stringify({data:c,types:t}));if(l==="")throw new Error(`eth_signTransaction error data: ${JSON.stringify(e)}`);return viem.parseTransaction(l)}catch(l){throw new Error("eth_signTransaction error"+l)}}async eth_sendRawTransaction([e],t){try{return await(await this.createPublicClient({rpcUrl:t})).sendRawTransaction({serializedTransaction:e})}catch(n){throw console.error("Failed to send transaction via RPC:",n,t),n}}async getTransaction(e){if(!e||!viem.isHex(e))throw new Error("txId is not valid");try{return await(await this.createPublicClient({})).getTransaction({hash:e})}catch(t){throw console.error("Failed to send transaction via RPC:",t,e),t}}},ht=class _ extends me{static{i(this,"_TomoWallet");}static instance;walletId;constructor(e,t){super(t),this.walletId=e;}getInstance(e,t){return _.instance||(_.instance=new _(e,t)),new _(e,t)}async supportedChains(e){return await this.networks.getNetworks(e||"")}async getChainInfo(e,t){return this.networks.setChainType(e),await this.networks.getNetworkByChainId(t)}async isChainSupported(e,t){this.networks.setChainType(e);let n=await this.networks.getNetworkByChainId(t);return n?!!n.chainId:false}async getTransactions({tokenAddress:e="",chainId:t="",typeList:n=[],pageLimit:s=20,cursor:a}){if(!this.walletId)throw new Error("walletId is required");try{let o={tokenAddress:e,pageLimit:s+1,walletId:this.walletId,cursor:a};if(n.length>0&&(o.typeList=n.join(",")),t){let y=(await this.networks.getNetworkByChainId(t)).chainIndex;o.chainIndex=y;}let{cursor:c="",transactionList:l}=await this.transactions.getTransactions(o),h=l.map(async u=>{let y=u.chainIndex,p=await this.networks.getNetworkByChainIndex(y);return {chainType:p.platformType.toLowerCase(),chainInfo:{chainId:p.chainId.toString(),name:p.name,icon:p.icon},nativeCurrency:p?.nativeCurrency,tokenInfo:u.tokenInfo,txHash:u.txHash,txDetail:u,txDetailLink:Ye(y,{txId:u.txHash}),txTime:u.txTime}}),m=await Promise.all(h);return {cursor:c,transactionList:m}}catch(o){throw console.error("Failed to send transaction via RPC:",o),o}}},ye={[N.EVM]:dt};var Mt=Object.defineProperty,Ut=Object.defineProperties,Bt=Object.getOwnPropertyDescriptors,fe=Object.getOwnPropertySymbols,Rt=Object.prototype.hasOwnProperty,Ft=Object.prototype.propertyIsEnumerable,ve=i((r,e,t)=>e in r?Mt(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t,"__defNormalProp"),k=i((r,e)=>{for(var t in e||(e={}))Rt.call(e,t)&&ve(r,t,e[t]);if(fe)for(var t of fe(e))Ft.call(e,t)&&ve(r,t,e[t]);return r},"__spreadValues"),O=i((r,e)=>Ut(r,Bt(e)),"__spreadProps"),Dt=Object.defineProperty,$t=i((r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:true});},"__export"),V={};$t(V,{clear:i(()=>qt,"clear"),get:i(()=>Ht,"get"),remove:i(()=>Kt,"remove"),set:i(()=>Gt,"set"),setKeyNS:i(()=>Lt,"setKeyNS")});var F="tomo-";function Ht(r){let e=F+r;if(!Vt(e))return null;let t=null;try{let n=window.localStorage.getItem(e)||window.sessionStorage.getItem(e);t=JSON.parse(n);}catch(n){console.error(n);}return t!==null&&Object.prototype.hasOwnProperty.call(t,"type")&&Object.prototype.hasOwnProperty.call(t,"data")?t.data:null}i(Ht,"get");function Gt(r,e,t){var n;let s;t?s=window.sessionStorage:s=window.localStorage;let a=JSON.stringify({data:e,time:new Date().getTime(),type:typeof e});try{return s.setItem(F+r,a),!0}catch(o){((n=o?.name)==null?void 0:n.toUpperCase().indexOf("QUOTA"))>=0&&(window.localStorage.clear(),s.setItem(F+r,a));}}i(Gt,"set");function Kt(r){let e=F+r;window.localStorage.removeItem(e),window.sessionStorage.removeItem(e);}i(Kt,"remove");function qt(){var r,e;(r=window?.localStorage)==null||r.clear(),(e=window?.sessionStorage)==null||e.clear();}i(qt,"clear");function Vt(r){return Object.prototype.hasOwnProperty.call(window.localStorage,r)||Object.prototype.hasOwnProperty.call(window.sessionStorage,r)}i(Vt,"isKeyExist");function Lt(r){typeof r=="string"&&r!==""&&(F=r);}i(Lt,"setKeyNS");var jt=i(r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r),"isEmail"),S=(r=>(r.BTC="btc",r.DOGE="doge",r.EVM="evm",r.SOL="sol",r.SUI="sui",r.TON="ton",r.TRON="tron",r.COSMOS="cosmos",r.APTOS="aptos",r))(S||{}),be={prod:"prod",pre:"prod",dev:"gamma"},zt={prod:"Org#49944bce-9daf-423f-a982-269f6d0d301b",pre:"Org#71c13f6d-b992-4660-874d-2ae0fadc789f",dev:"Org#3d07a75a-1188-4bd0-acfa-671a198b83eb"},te={prod:"https://social-relay.tomo.inc",pre:"https://social-relay.tomo.inc",dev:"https://social-relay-dev.tomo.inc"},Se={prod:"https://wallet-pro.tomo.inc",pre:"https://wallet-pre-wlfi.tomo.inc",dev:"https://wallet-test.tomo.inc"},L=30*24*60*60,Ie={auth:L,refresh:L*2},q=["sign:*","export:*","manage:session:extend","manage:mfa:*","manage:mfa:register:email","manage:mfa:register:fido","manage:mfa:unregister:fido","manage:mfa:register:totp","manage:mfa:unregister:totp","manage:export:user:delete","manage:export:user:list"],Xt="Key#Mnemonic_",Jt={"https://accounts.google.com":"google","https://shim.oauth2.cubist.dev/twitter":"x"},Yt={prod:"xnPWRJT5XG2WyevuydMjMpZq",pre:"xnPWRJT5XG2WyevuydMjMpZq",dev:"dev@tomo"},Wt=i(r=>{let t={Login:["Fido","EmailOtp","Totp"],RegisterMfa:["Fido",`EmailOtp#${r==="prod"?172800:300}`,"Totp"],Export:["Fido","Totp"]};return {createSession:{method:"POST",path:"/session/",_allowed_mfa_types:t.Login},addFido:{method:"POST",path:"/user/me/fido/",_allowed_mfa_types:t.RegisterMfa},deleteFido:{method:"DELETE",path:"/user/me/fido/",_allowed_mfa_types:t.RegisterMfa},registerTotp:{method:"POST",path:"/user/me/totp/",_allowed_mfa_types:t.RegisterMfa},deleteTotp:{method:"DELETE",path:"/user/me/totp/",_allowed_mfa_types:t.RegisterMfa},registerEmailOtp:{method:"POST",path:"/user/me/email/",_allowed_mfa_types:t.RegisterMfa},initExport:{method:"POST",path:"/user/me/export/",_allowed_mfa_types:t.Export},completeExport:{method:"PATCH",path:"/user/me/export/",_allowed_mfa_types:t.Export}}},"getMfaInfoConfig"),Zt=class U{static{i(this,"_CubeExportService");}constructor(){this.seedPhraseKey="",this.cubeAccountService=null,this.cubeSignerClient=null,this.exportKey=null,cubesignerSdk.userExportKeygen().then(e=>{this.exportKey=e;});}static getInstance(){return U.instance||(U.instance=new U),U.instance}init(e){return this.cubeAccountService=e,this.cubeSignerClient=e.cubeSignerClient,this}async getExportKey(){var e;if(this.seedPhraseKey)return this.seedPhraseKey;let n=(await((e=this.cubeSignerClient)==null?void 0:e.sessionKeys())||[]).find(s=>s?.id.indexOf(Xt)===0);return this.seedPhraseKey=n?.id||"",this.seedPhraseKey}async getExportInfo(){var e,t;if(!this.cubeSignerClient)return null;let n=await this.getExportKey(),s=(t=(e=this.cubeSignerClient)==null?void 0:e.org())==null?void 0:t.exports(n),a=await s?.fetch();if(a?.length===0)return {ready:true};let{valid_epoch:o=0,exp_epoch:c=0}=a[0],l=o-Date.now()/1e3;l=Math.max(Math.ceil(l),0);let h=c-o;return {ready:true,keyId:n,lastTime:l,duration:h,valid_epoch:o,exp_epoch:c}}async initExport(e){var t,n;if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");let s=await this.getExportKey(),a=await this.cubeSignerClient.org().initExport(s,e);return a.requiresMfa()?await((n=(t=this.cubeAccountService)==null?void 0:t.cubeMfaService)==null?void 0:n.getMfaInfo("initExport"))||null:a.data()}async completeExport(e){var t,n;if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");let s=await this.getExportKey(),a=await this.cubeSignerClient.org().completeExport(s,this.exportKey.publicKey,e);if(a.requiresMfa())return await((n=(t=this.cubeAccountService)==null?void 0:t.cubeMfaService)==null?void 0:n.getMfaInfo("completeExport"))||null;let o=a.data();return await cubesignerSdk.userExportDecrypt(this.exportKey.privateKey,o)}async deleteExport(){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");try{let e=await this.getExportKey();return {success:!0,data:await this.cubeSignerClient.org().deleteExport(e)}}catch(e){return {success:false,message:e?.message||"delete export error",error:e}}}},x=null,C=null,Qt=i(({url:r,name:e,width:t,height:n})=>{let s=(window.innerHeight-n)/2+window.screenY,a=(window.innerWidth-t)/2+window.screenX;try{let o=window.open(r,e,`dialog=yes,top=${s}px,left=${a},width=${t!==void 0?t:400}px,height=${n!==void 0?n:600}px`);return o||null}catch(o){return console.error("Failed to open window:",o),null}},"openWindow"),er=i(()=>{try{x&&!x.closed&&x.close();}catch(r){console.error("Failed to close window:",r);}finally{x=null,C&&(clearInterval(C),C=null);}},"closeWindow"),re=i(r=>{C&&clearInterval(C),C=setInterval(()=>{x&&x.closed&&(console.log("Passkey window was closed by user"),r(),C&&(clearInterval(C),C=null),x=null);},1e3);},"addWindowCloseListener"),xe=i(()=>{C&&(clearInterval(C),C=null);},"removeWindowCloseListener"),ne=i(async(r,e)=>{if(x===null)throw new Error("Failed to open relay window");let t=te[e]||te.dev;x.postMessage(r,t);},"sendPasskeyMessage"),ke=i(async r=>{if(r=r||V.get("cubeConfig"),!r.oidcToken)throw new Error("oidcToken is required");let e=te[r.tomoStage];return new Promise((t,n)=>{x=Qt({url:`${e}/passkey`,name:"relay-passkey",width:400,height:600});let s=i(a=>{let{type:o,data:c,error:l}=a.data;o==="loaded"&&ne({type:"init",params:r},r.tomoStage),o==="init"&&(window.removeEventListener("message",s),t(c));},"handleMessage");re(()=>{window.removeEventListener("message",s),n(new Error("Passkey window was closed by user"));}),window.addEventListener("message",s);})},"initPasskeyPage"),tr=i(async(r,e)=>(x||await ke(e),new Promise((t,n)=>{let s=i(a=>{let{type:o,data:c,error:l}=a.data;o==="addFido"&&(window.removeEventListener("message",s),xe(),t(c));},"handleMessage");re(()=>{window.removeEventListener("message",s),n(new Error("Add passkey window was closed by user"));}),window.addEventListener("message",s),ne({type:"addFido",params:r},e.tomoStage);})),"addPasskey"),rr=i(async(r,e)=>(x||await ke(e),new Promise((t,n)=>{let s=i(a=>{let{type:o,data:c}=a.data;o==="verify"&&(window.removeEventListener("message",s),xe(),t(c));},"handleMessage");re(()=>{window.removeEventListener("message",s),n(new Error("Verify passkey window was closed by user"));}),window.addEventListener("message",s),ne({type:"verify",params:r},e.tomoStage);})),"verifyPasskey"),Ce=i((r,e,{userId:t,rpId:n,fidoName:s})=>{var a,o,c,l;n=n||window.location.hostname;let{host:h,protocol:m}=window.location,u=m!=="https:"&&m!=="http:",y=h.indexOf("localhost:")===0;e.options=e?.options||{},e.options.rp=e.options.rp||{},e.options.rp.id=n,e.options.rpId=n,(u||y)&&((o=(a=e?.options)==null?void 0:a.rp)!=null&&o.id&&delete e.options.rp.id,(c=e?.options)!=null&&c.rpId&&delete e.options.rpId),e.options.timeout=6e4,e.options.attestation="none";let p=((l=e.options)==null?void 0:l.user)||{};return r==="add"&&(p.id=p.id||new TextEncoder().encode(t),p.name=s,p.displayName=s),e.options.user=p,e},"applyLocalDevFixes"),nr=class B{static{i(this,"_CubeMfaService");}constructor(){this.mfaType="fido",this.cubeAccountService=null,this.cubeSignerClient=null,this.apiClient=null,this.mfaAnswer=null,this.mfaChallenge=null,this.registerChallenge=null;}static getInstance(){return B.instance||(B.instance=new B),B.instance}init(e){return this.cubeSignerClient=e.cubeSignerClient,this.apiClient=e.apiClient,this.cubeAccountService=e,this}setMfaType(e){if(!e)throw new Error("mfaType is required");this.mfaType=e;}setMfaAnswer(e){this.mfaAnswer=e;}async getMfaInfo(e){var t,n,s;if(!e)throw new Error("mfaRequestType is required");let o=Wt(((n=(t=this.cubeAccountService)==null?void 0:t.config)==null?void 0:n.cubeStage)||"gamma")[e];if(!o)throw new Error("mfaRequestType is not supported");let{method:c,path:l}=o,m=(await this.apiClient.mfaList()).find(g=>{let b=g?.request.method,I=g?.request.path+"/";return b===c&&I.indexOf(l)>-1});if(!m)return null;let u=null,y=((s=m?.status)==null?void 0:s.allowed_mfa_types)||[];for(let g of y){u=u||{};let b=g.toLowerCase().split("#");u[b[0]]=b[1]?Number(b[1]):true;}let{receipt:p,created_at:v}=m,d=0;if(typeof u.emailOtp=="number"){let g=u.emailOtp-(Date.now()/1e3-v);d=Math.max(0,Math.ceil(g));}u.emailOtp&&(u.emailOtpRemainTime=d);let w=p!==null?"approved":"pending";return O(k({},m),{verifyStatus:w,mfaRequired:u})}async answerRegister(e){let t=this.registerChallenge;if(!t)throw new Error("challenge is required");try{let n=await t.answer(e)||null;return this.registerChallenge=null,{success:!0,data:n}}catch(n){return {success:false,message:n?.message||"answer error",error:n}}}async executeBizWithMfa(e,t){var n,s,a,o,c,l,h,m,u;if(!e)throw new Error("bizType is required");if(t||(t=await this.getMfaInfo(e)||null),!t?.id)throw new Error("mfa not exists, please create mfa first");let{success:y,data:p}=await this.approvalMfa(t?.id||"")||{};if(!y)return {success:false,message:`approval with ${this.mfaType} error.`};if(e==="createSession"){let d=await((n=this.cubeAccountService)==null?void 0:n.createSession(p));return {success:!!d,message:d?"":"create session error",data:d}}if(e==="addFido"){let d=(a=(s=t.request)==null?void 0:s.body)==null?void 0:a.name,w=await this.addFido(d,p);return {success:!!w,message:w?"":"addFido error",data:w}}if(e==="deleteFido"){let w=(((o=t?.request)==null?void 0:o.path)||"").split("/user/me/fido/")[1]||"";if(!w)throw new Error("fidoId is required");let g=await this.deleteFido(decodeURIComponent(w),p);return {success:!!g,message:g?"":"deleteFido error",data:g}}if(e==="registerTotp"){let d=(l=(c=t.request)==null?void 0:c.body)==null?void 0:l.issuer,w=await this.registerTotp(d,p);return {success:!!w,message:w?"":"registerTotp error",data:w}}if(e==="deleteTotp"){let d=await this.deleteTotp(p);return {success:!!d,message:d?"":"deleteTotp error",data:d}}if(e==="registerEmailOtp"){let d=(m=(h=t.request)==null?void 0:h.body)==null?void 0:m.email,w=await this.registerEmailOtp(d,p);return {success:!!w,message:w?"":"registerEmailOtp error",data:w}}let v=(u=this.cubeAccountService)==null?void 0:u.cubeExportService;if(e==="initExport"){let d=await v?.initExport(p);return {success:!!d,message:d?"":"init export error",data:d}}if(e==="completeExport"){let d=await v?.completeExport(p);return {success:!!d,message:d?"":"complete export error",data:d}}return {success:false,message:"bizType is not supported"}}async approvalMfa(e){let t={totp:"approvalTotp",emailOtp:"approvalEmailOtp",fido:"approvalFido"},n=this.mfaType;if(!n||!t[n])return {success:false,message:"mfaType is required"};let s=null;try{switch(n){case "totp":s=await this.approvalTotp(e);break;case "emailOtp":s=await this.approvalEmailOtp(e);break;case "fido":s=await this.approvalFido(e);break;default:return {success:!1,message:"Unsupported MFA type"}}}catch(a){return {success:false,message:`approval ${n} error: ${a instanceof Error?a.message:"Unknown error"}`}}return s?{success:true,data:s}:{success:false,message:`approval ${n} error.`}}getPasskeyConfig(){let{config:e}=this.cubeAccountService||{};return e==null||delete e.cubeSalt,e==null||delete e.jwtToken,e}passkeyRelayClose(){er();}async addFido(e,t){let n=this.getPasskeyConfig();return await tr({fidoName:e,receipt:t},n)}async _addFido(e,t){var n,s,a,o,c;if(!e||typeof e!="string")throw new Error("name is required");try{let l=await((n=this.cubeAccountService)==null?void 0:n.getMfaConfig());if((((s=l?.fido)==null?void 0:s.data)||[]).find(d=>d?.name===e))throw new Error(`FIDO key with name "${e}" already exists`);let u=this.cubeSignerClient,y=await u?.addFido(e,t);if(y.requiresMfa())return await this.getMfaInfo("addFido");let p={userId:(a=l?.account)==null?void 0:a.userId,rpId:((c=(o=this.cubeAccountService)==null?void 0:o.config)==null?void 0:c.rpId)||window.location.hostname,fidoName:e};return await Ce("add",y.data(),p).createCredentialAndAnswer(),!0}catch(l){return console.error("addFido error",l),false}}async deleteFido(e,t){try{let n=this.cubeSignerClient,s=await n?.deleteFido(e,t);return s.requiresMfa()?await this.getMfaInfo("deleteFido"):s.data()}catch{return null}}async approvalFido(e){let t=this.getPasskeyConfig();return await rr({mfaId:e},t)}async _approvalFido(e){var t,n,s,a;let o=this.apiClient,c=await((t=this.cubeAccountService)==null?void 0:t.getMfaConfig()),l=await o.mfaFidoInit(e),h={userId:(n=c?.account)==null?void 0:n.userId,rpId:((a=(s=this.cubeAccountService)==null?void 0:s.config)==null?void 0:a.rpId)||window.location.hostname,fidoName:""};return l=Ce("approval",l,h),await(await l.createCredentialAndAnswer("approve")).receipt()}async registerTotp(e,t){if(e==="")throw new Error("issuer are required");let n=await this.apiClient.userTotpResetInit(e,t);if(n.requiresMfa())return await this.getMfaInfo("registerTotp");let s=n.data();this.registerChallenge=s;let a=new URL(s?.url).searchParams;return {id:s?.id,url:s?.url,secret:a.get("secret")||"",issuer:a.get("issuer")||e}}async deleteTotp(e){let t=await this.apiClient.userTotpDelete(e);return t.requiresMfa()?await this.getMfaInfo("deleteTotp"):t.data()}async approvalTotp(e){var t,n,s,a,o;if(!e)throw new Error("MFA ID not found");let c=(t=this.mfaAnswer)==null?void 0:t.totpCode;if(!c||!/^\d{6}$/.test(c))throw console.error("TOTP code is required"),new Error("TOTP code is required");let l=await this.apiClient.mfaVoteTotp(e,c,"approve"),h=((s=(n=this.cubeSignerClient)==null?void 0:n.org())==null?void 0:s.id)||((a=this.cubeAccountService)==null?void 0:a.cubeOrgId)||"";return {mfaId:l.id,mfaConf:(o=l?.receipt)==null?void 0:o.confirmation,mfaOrgId:h}}async registerEmailOtp(e,t){var n;if(!e||!jt(e))throw new Error("email is required");let a=(await((n=this.cubeAccountService)==null?void 0:n.getOidcClient())).apiClient,o={email:e,allow_otp_login:true},c=await a.userEmailResetInit(o,t);return c.requiresMfa()?await this.getMfaInfo("registerEmailOtp"):(this.registerChallenge=c.data(),this.registerChallenge)}async approvalEmailOtp(e){var t,n,s,a,o;if(!e)throw new Error("MFA ID not found");if(!this.mfaChallenge){let l=await this.apiClient.mfaVoteEmailInit(e,"approve");return this.mfaChallenge=l,null}let c=((t=this.mfaAnswer)==null?void 0:t.emailCode)||"";if(c=c.split(/\s/).join(""),!c)throw new Error("emailCode is required");try{let l=await this.mfaChallenge.answer(c),h=((s=(n=this.cubeSignerClient)==null?void 0:n.org())==null?void 0:s.id)||((a=this.cubeAccountService)==null?void 0:a.cubeOrgId)||"",m={mfaId:l.id,mfaConf:(o=l?.receipt)==null?void 0:o.confirmation,mfaOrgId:h};return this.mfaChallenge=null,m}catch(l){return console.warn("approvalEmailOtp error",l),null}}async sendEmailCode(e){if(!e)throw new Error("mfaId is required");try{let t=await this.apiClient.mfaVoteEmailInit(e,"approve");return this.mfaChallenge=t,!0}catch{return false}}},sr=i((r,e)=>{try{let{data:t,types:n}=JSON.parse(r);for(let s in n)n[s]==="bigint"&&(t[s]=BigInt(t[s]),e==="string"&&(t[s]=t[s].toString()));return t}catch{throw new Error("Invalid unsigned transaction")}},"recoverEVMTxData"),se=class R{static{i(this,"_CubeSignService");}async init({cubeSession:e}){this.cubeSession=e,this.services||(this.services=await cubistSigSdk.getKeys(e));}static getInstance(){return R.instance||(R.instance=new R),R.instance}async getServiceByChainAndAddress(e,t){this.services||(this.services=await cubistSigSdk.getKeys(this.cubeSession));let n=this.buildKeyId(e,t),s=this.services.find(a=>a.id===n);return s||(console.warn(`service not found for chainType: ${e}`),null)}buildKeyId(e,t){switch(e){case S.EVM:return `Key#${t}`;case S.TRON:return `Key#Tron_${t}`;case S.SOL:return `Key#Solana_${t}`;case S.DOGE:return `Key#Doge_${t}`;default:return `Key#${t}`}}async signTransaction(e,t,n){var s;let a=this==null?void 0:this.cubeSession,o=await this.getServiceByChainAndAddress(e,t);if(!o)throw new Error(`service not found for chain ${e}`);let c=typeof n=="string"?JSON.parse(n):n;switch(e){case S.EVM:{let l=sr(n,"string");return await cubistSigSdk.signEvmTransaction(o,l,l.chainId,a)}case S.SOL:return await cubistSigSdk.signSolanaTransaction(o,c.rawTransaction,a);case S.DOGE:return await cubistSigSdk.signDogePsbt(o,c.psbtBase64,a);case S.TRON:{let l=((s=c.data)==null?void 0:s.rawTransaction)||c.rawTransaction;return await cubistSigSdk.signTronRawTransaction(o,l,a)}default:throw new Error(`Unsupported chain type: ${e}`)}}async signMessage(e,t,n){let s=this==null?void 0:this.cubeSession,a=await this.getServiceByChainAndAddress(e,t);if(!a)throw new Error(`service not found for chain ${e}`);switch(e){case S.EVM:return await cubistSigSdk.signEvmMessage(a,n,s);case S.SOL:return await cubistSigSdk.signSolanaMessage(a,n,s);case S.DOGE:return (await cubistSigSdk.signDogeMessage(a,n,s)).signature;case S.TRON:return await cubistSigSdk.signTronMessage(a,n,s);default:throw new Error(`Unsupported chain type: ${e}`)}}async signTypedData(e,t,n){let s=this==null?void 0:this.cubeSession,a=await this.getServiceByChainAndAddress(e,t);if(!a)throw new Error(`service not found for chain ${e}`);switch(e){case S.EVM:return await cubistSigSdk.signEvmTypedData(a,n,s);case S.TRON:return await cubistSigSdk.signTronTypeDaya(a,n.message,s);default:throw new Error(`Unsupported chain type: ${e}`)}}},ar=i(async(r,e)=>{if(!e)throw new Error("salt is required");let t=Date.now().toString(),n=O(k({},r),{timestamp:t}),s=JSON.stringify(n),a=$e__default.default.SHA256(s+e).toString();return {timestamp:t,signature:a}},"generateCubeSignature");function Ee(r){let{tomoStage:e="dev",tomoClientId:t,jwtToken:n}=r,s=X__default.default.create({baseURL:`${Se[e]||Se.dev}/user`,timeout:2e4});return s.interceptors.request.use(async a=>(a.headers["client-id"]=t,n&&(a.headers.Authorization=`Bearer ${n}`),a),a=>{var o;if(((o=a?.response)==null?void 0:o.status)===401)return Promise.reject(a)}),s}i(Ee,"getTomoApi");var or=i(async(r,e)=>{var t;let{iss:n,sub:s}=r,a=e.cubeSalt||"";if(!a)throw new Error("tomoStage error.");let{timestamp:o,signature:c}=await ar({iss:n,sub:s},a),l=O(k({},r),{timestamp:o,signature:c}),m=await Ee(e).post("/api/login/loginByCubistV2",l);return ((t=m?.data)==null?void 0:t.data)||{}},"addUserToCube"),ir=i(async(r,e)=>{var t,n;let s=Ee(e),a=await s.post("/api/user/getUserInfo"),o=((t=a?.data)==null?void 0:t.data.user)||{},c=r.nickname.trim();r=O(k(k({},o),r),{nickname:c,username:c});let l=await s.post("/api/setting/updateUserInfo",r,{headers:{}});return !!((n=l?.data)!=null&&n.success)},"updateUserInfo"),ae=class T{static{i(this,"_CubeAccountService");}constructor(e){this.jwtToken="",this.accountData=null,this.cubeUserInfo=null,this.cubeIdentity=null,this.cubeSession=null,this.cubeSignerClient=null,this.apiClient=null,this.cubeMfaService=null,this.cubeExportService=null,this.cubeOrgId="",this.config=e,this.cubeEnv=null;}static getInstance(e){if(T.instance)return T.instance;if(!e?.tomoStage||!be[e?.tomoStage])throw new Error("tomoStage not 'dev' or 'pre' or 'prod'");let t=Yt[e?.tomoStage];if(!t)throw new Error("cubeSalt is required");let n=be[e?.tomoStage],s=cubesignerSdk.envs[n],a=zt[e?.tomoStage];return T.instance=new T(O(k({},e),{cubeSalt:t,cubeStage:n})),T.instance.cubeEnv=s,T.instance.cubeOrgId=a,T.instance}async getCubeIdentity(){var e;let t=(e=this==null?void 0:this.config)==null?void 0:e.oidcToken;if(!t){let a=await V.get("cubeIdentity");return a?(this.cubeIdentity=a,this.cubeIdentity):(console.warn("oidcToken is required"),null)}let n=this.cubeOrgId,s=await cubistSigSdk.proof(t,this.cubeEnv,n);return await V.set("cubeIdentity",s,false),this.cubeIdentity=s,s}async loginOrRegister(e,t){var n,s,a,o;this.config=O(k({},this.config),{oidcToken:e});let c=await this.getCubeIdentity(),l={cubistUserID:(n=c?.user_info)==null?void 0:n.user_id,aud:c?.aud,email:c?.email||t?.email||null,iss:(s=c?.identity)==null?void 0:s.iss,sub:(a=c?.identity)==null?void 0:a.sub,initialized:(o=c?.user_info)==null?void 0:o.initialized},h=await or(l,this.config),{userToken:m,user:u,accountBaseInfo:y,accountWallet:p}=h;return this.accountData=h,this.accountWallet=p,this.jwtToken=m.accessToken,{user:{userId:u.userID,nickname:u.nickname,avatar:u.avatar},accountBaseInfo:y,accountWallet:p,walletId:p?.walletID}}async updateUserInfo(e){let t=e.nickname.trim();if(t.length<6||t.length>20)throw new Error("name length 6~20");let n=O(k({},this.config),{jwtToken:this.jwtToken});return await ir(e,n)}async createSessionByOidcToken(e){var t;if(e=e||((t=this==null?void 0:this.config)==null?void 0:t.oidcToken)||"",!e)return console.warn("oidcToken is required"),false;let n=q,a=(await cubistSigSdk.getOidcResp(e,this.cubeEnv,this.cubeOrgId,L,n)).data();return this.setCubeSession(a),!!a}async createSession(e){var t;let s=await this.apiClient.sessionCreateExtended("wallet_operations",q,Ie,e);if(s.requiresMfa())return await((t=this.cubeMfaService)==null?void 0:t.getMfaInfo("createSession"))||null;let a=s.data();return this.setCubeSession(a),!!a}async refreshSession(){let n=(await this.apiClient.sessionCreate("wallet_operations",q,Ie)).data();return this.setCubeSession(n),!!n}getCubeSession(){return this.cubeSession}setCubeSession(e){this.cubeSession=e;}sessionRevoke(){let e=this.apiClient;this.cubeSession=null,e?.sessionRevoke();}async refreshCubeClient(e){try{await this.createCubeSignerClient(e),this.initSubServices();}catch(t){console.error("refreshCubeClient error",t);}}async createCubeSignerClient(e){let t=await cubesignerSdk.CubeSignerClient.create(e);return this.cubeSignerClient=t,this.apiClient=this.cubeSignerClient.apiClient,t}async getOidcClient(e){var t;let n=((t=this==null?void 0:this.config)==null?void 0:t.oidcToken)||"";if(!n){console.warn("oidcToken is required");return}let s=q;return await cubistSigSdk.getOidcClient(n,this.cubeEnv,this.cubeOrgId,L,s,e)}async autoLogin(e){await this.refreshCubeClient(e),await this.setCubeSession(e);}async init(e){var t;if(e=e||((t=this==null?void 0:this.config)==null?void 0:t.oidcToken)||"",!e)return console.warn("oidcToken is required"),false;try{this.config=O(k({},this.config),{oidcToken:e});let n=await this.getOidcClient();if(this.cubeSignerClient=n,this.apiClient=this.cubeSignerClient.apiClient,!await this.createSessionByOidcToken(e))throw new Error("create session by oidc token failed");return this.initSubServices(),!0}catch(n){throw console.error("init error",n),n}}async initSubServices(){let e=nr.getInstance();this.cubeMfaService=e.init(this);let t=Zt.getInstance();this.cubeExportService=t.init(this);}async initCubeSignService(){let e=this.getCubeSession(),t=se.getInstance();return await t.init({cubeSession:e}),t}async getCubeUserInfo(){var e;try{let t=await((e=this.apiClient)==null?void 0:e.userGet());return this.cubeUserInfo=t,t}catch{return null}}async getMfaConfig(){var e,t,n;let[s,a]=await Promise.all([this.getCubeUserInfo(),this.getCubeIdentity()]),o=s?.name||a?.preferred_username||"",c=((e=a?.identity)==null?void 0:e.iss)||"",l=((t=Jt)==null?void 0:t[c])||"email",h=((n=s?.verified_email)==null?void 0:n.email)||"",m=s?.email||"",u=h!==""||m!=="",y=s?.mfa||[],p=y.filter(d=>d.type==="fido"),v=y.filter(d=>d.type==="totp");return {noMfa:!u&&p.length===0&&v.length===0,hasMfa:u||p.length>0||v.length>0,account:{name:o,email:m,otpEmail:h,accountType:l,userId:s?.user_id||""},emailOtp:{data:m||h,enabled:u},fido:{data:p,enabled:p.length>0},totp:{data:v[0],enabled:v.length>0}}}},cr=i(async r=>{let e=ae.getInstance(r);if(!r.oidcToken)throw new Error("oidcToken is required");await e.loginOrRegister(r.oidcToken),await e.init(r.oidcToken);let t=e.cubeMfaService,n=e.cubeExportService;return {cubeAccount:e,cubeMfa:t,cubeExport:n}},"CubeConnect");var lr=Object.defineProperty,ur=i((r,e)=>{for(var t in e)lr(r,t,{get:e[t],enumerable:true});},"__export"),pr={};ur(pr,{clear:i(()=>wr,"clear"),get:i(()=>dr,"get"),remove:i(()=>mr,"remove"),set:i(()=>hr,"set"),setKeyNS:i(()=>gr,"setKeyNS")});var D="tomo-";function dr(r){let e=D+r;if(!yr(e))return null;let t=null;try{let n=window.localStorage.getItem(e)||window.sessionStorage.getItem(e);t=JSON.parse(n);}catch(n){console.error(n);}return t!==null&&Object.prototype.hasOwnProperty.call(t,"type")&&Object.prototype.hasOwnProperty.call(t,"data")?t.data:null}i(dr,"get");function hr(r,e,t){var n;let s;t?s=window.sessionStorage:s=window.localStorage;let a=JSON.stringify({data:e,time:new Date().getTime(),type:typeof e});try{return s.setItem(D+r,a),!0}catch(o){((n=o?.name)==null?void 0:n.toUpperCase().indexOf("QUOTA"))>=0&&(window.localStorage.clear(),s.setItem(D+r,a));}}i(hr,"set");function mr(r){let e=D+r;window.localStorage.removeItem(e),window.sessionStorage.removeItem(e);}i(mr,"remove");function wr(){var r,e;(r=window?.localStorage)==null||r.clear(),(e=window?.sessionStorage)==null||e.clear();}i(wr,"clear");function yr(r){return Object.prototype.hasOwnProperty.call(window.localStorage,r)||Object.prototype.hasOwnProperty.call(window.sessionStorage,r)}i(yr,"isKeyExist");function gr(r){typeof r=="string"&&r!==""&&(D=r);}i(gr,"setKeyNS");var Te=i(r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r),"isEmail"),f=(r=>(r.BTC="btc",r.DOGE="doge",r.EVM="evm",r.SOL="sol",r.SUI="sui",r.TON="ton",r.TRON="tron",r.COSMOS="cosmos",r.APTOS="aptos",r))(f||{});var Oe={prod:"prod",pre:"prod",dev:"gamma"},Pe={prod:"Org#49944bce-9daf-423f-a982-269f6d0d301b",pre:"Org#71c13f6d-b992-4660-874d-2ae0fadc789f",dev:"Org#3d07a75a-1188-4bd0-acfa-671a198b83eb"},_e={prod:"https://social-relay.tomo.inc",pre:"https://social-relay.tomo.inc",dev:"https://social-relay-dev.tomo.inc"};var j=class{static{i(this,"CubeSocialAccount");}chainType;chainId;cubeSignService;accountData;userAPIs;constructor({chainType:e,chainId:t},n){this.chainType=e,this.chainId=t,this.accountData=n,this.cubeSignService=se.getInstance();}async getAllAccounts(){let{accountWallet:e,user:t}=this.accountData||{},n={[f.EVM]:[{address:e?.ethereumAddress,publicKey:"",subType:f.EVM,path:""}],[f.DOGE]:[{address:e?.dogeAddress,publicKey:"",subType:f.DOGE,path:""}],[f.SOL]:[{address:e?.solanaAddress,publicKey:"",subType:f.SOL,path:""}],[f.TRON]:[{address:e?.tronAddress,publicKey:"",subType:f.TRON,path:""}],[f.BTC]:[{address:e?.bitcoinP2trAddressMain,publicKey:e?.bitcoinP2trPubKeyMain,subType:"TAPROOT",stage:"MAIN",path:"m/86'/0'/0'/0/0"},{address:e?.bitcoinP2trAddressTest,publicKey:e?.bitcoinP2trPubKeyTest,subType:"TAPROOT",stage:"TEST",path:"m/86'/1'/0'/0/0"},{address:e?.bitcoinP2shAddressMain,publicKey:e?.bitcoinP2shPubKeyMain,subType:"NESTED_SEGWIT",stage:"MAIN",path:"m/49'/0'/0'/0/0"},{address:e?.bitcoinP2shAddressTest,publicKey:e?.bitcoinP2shPubKeyTest,subType:"NESTED_SEGWIT",stage:"TEST",path:"m/49'/1'/0'/0/0"},{address:e?.bitcoinP2wpkhAddressMain,publicKey:e?.bitcoinP2wpkhPubKeyMain,subType:"NATIVE_SEGWIT",stage:"MAIN",path:"m/84'/0'/0'/0/0"},{address:e?.bitcoinP2wpkhAddressTest,publicKey:e?.bitcoinP2wpkhPubKeyTest,subType:"NATIVE_SEGWIT",stage:"TEST",path:"m/84'/0'/0'/0/0"},{address:e?.bitcoinP2pkhAddressMain,publicKey:e?.bitcoinP2pkhPubKeyMain,subType:"LEGACY",stage:"MAIN",path:"m/44'/0'/0'/0/0"},{address:e?.bitcoinP2pkhAddressTest,publicKey:e?.bitcoinP2pkhPubKeyTest,subType:"LEGACY",stage:"TEST",path:"m/44'/1'/0'/0/0"}],[f.SUI]:[{address:e?.suiAddress,publicKey:"",subType:f.SUI,path:""}],[f.TON]:[{address:e?.tonAddress,publicKey:"",subType:f.TON,path:""}],[f.COSMOS]:[{address:e?.cosmosAddress,publicKey:"",subType:f.COSMOS,path:""}],[f.APTOS]:[{address:e?.aptosAddress,publicKey:"",subType:f.APTOS,path:""}]};return {id:t.accountID,name:t.nickname,type:ee.SOCIAL,lastUsedTime:t.lastUsedTime,addresses:n,mnemonic:null,addressIndex:0,isImported:false,isBackedUp:false,isLocked:false,isFrozen:false}}async getCurrent(){let e=this.chainType,t=await this.getAllAccounts(),{address:n,publicKey:s,path:a,subType:o}=t?.addresses?.[e]?.[0]||{};return [{subType:o,address:n,path:a,publicKey:s,type:t.type,id:t.id}]}async signMessage(e){let t=await this.getCurrent(),n=this.chainType;try{let s=t[0].address;return await this.cubeSignService.signMessage(n,s,e)}catch(s){throw console.error("Error signing message with CubeSignService:",s),s}}async signTypedData(e){let t=await this.getCurrent(),n=this.chainType;try{let s=t[0].address;return await this.cubeSignService.signTypedData(n,s,e)}catch(s){throw console.error("Error signing typed data with CubeSignService:",s),s}}async signTransaction(e){let t=await this.getCurrent(),n=this.chainType,s=t[0].address;try{return await this.cubeSignService.signTransaction(n,s,e)}catch(a){throw console.error("Error signing transaction with CubeSignService:",a),a}}};var Ae={googleAuth:"tomo-google-authorized",xAuth:"tomo-twitter-authorized",kakaoAuth:"tomo-kakao-authorized",telegramAuth:"tomo-telegram-authorized"},vr=60,Me=i(({url:r,name:e,width:t,height:n})=>{let s=(window.innerHeight-(n||400))/2+window.screenY,a=(window.innerWidth-(t||400))/2+window.screenX;try{let o=window.open(r,e,`dialog=yes,top=${s}px,left=${a},width=${t!==void 0?t:400}px,height=${n!==void 0?n:600}px`);return o||null}catch(o){return console.error("Failed to open window:",o),null}},"openWindow"),br=i(async(r,e,t,n)=>{let a=await(await fetch(e,{method:"POST",body:new URLSearchParams({code:r,grant_type:"authorization_code",client_id:t,redirect_uri:n,code_verifier:"challenge"})})).json();return a?.id_token||""},"getXOidcToken"),Sr=i(({tomoStage:r,xClientId:e,googleClientId:t})=>{let n=_e[r];if(!n)throw new Error("Invalid tomo stage");let s=`${n}/x`,a=`${n}/x/loader`,o=`${n}/google`,c=Oe[r],l=Pe[r];if(!l)throw new Error("Invalid cube stage");let h=cubesignerSdk.envs[c]||cubesignerSdk.envs.gamma,m=`${h.SignerApiRoot}/v0/org/${encodeURIComponent(l)}/oauth2/twitter`,u="https://accounts.google.com/o/oauth2/v2/auth",y=i((w,g=12e4)=>new Promise((b,I)=>{if(!w){I(new Error("Popup window is null"));return}let E=setTimeout(()=>{w.close(),I(new Error("Login timeout"));},g),$=i(async z=>{if(z.origin!==n||z.data.action!=="login")return;let{data:H,type:oe}=z.data,G="";try{oe===Ae.googleAuth?G=H.code:oe===Ae.xAuth&&H?.code&&(G=await br(H.code,m,e,s)),G&&(clearTimeout(E),window.removeEventListener("message",$),w.close(),b(G));}catch(Be){clearTimeout(E),window.removeEventListener("message",$),w.close(),I(Be);}},"messageHandler");window.addEventListener("message",$);let Ue=setInterval(()=>{w.closed&&(clearTimeout(E),clearInterval(Ue),window.removeEventListener("message",$),I(new Error("Login cancelled by user")));},400);}),"waitForOidcToken");return {loginByGoogle:i(async()=>{let w=window.location.origin,g=JSON.stringify({origin:w,action:"login",loadImg:""}),b={client_id:t,state:encodeURIComponent(g),redirect_uri:o,response_type:"id_token",scope:"openid",access_type:"offline",nonce:Date.now().toString(),prompt:"select_account"},I=`${u}?${new URLSearchParams(b).toString()}`,E=Me({url:I,name:"Google login"});if(!E)throw new Error("Failed to open popup");return await y(E)},"loginByGoogle"),loginByX:i(async()=>{let g={target:window.location.origin,eventId:Date.now().toString(),action:"login",clientId:e},b=`${a}?${new URLSearchParams(g).toString()}`,I=Me({url:b,name:"X login"});if(!I)throw new Error("Failed to open popup");return await y(I)},"loginByX"),loginByEmail:i(async w=>{if(!Te(w))throw new Error("Invalid email");return {partialOidcToken:await cubistSigSdk.emailLogin(w,h,l),lifeTime:vr}},"loginByEmail")}},"OidcAuth");var rn=i((r,e,t)=>{let{chainType:n,chainId:s}=e;ae.getInstance().initCubeSignService();let o=new j(e,r),c=ye[n];if(!c)throw new Error(`ChainTypeServices not found for chainType: ${n}`);let l=c.getInstance(n,o,t);return l.wallet_switchEthereumChain([{chainId:s}]),l},"SocialAccount");
2
+ exports.ChainTypes=f;exports.CubeConnect=cr;exports.OidcAuth=Sr;exports.SocialAccount=rn;exports.TomoWallet=ht;exports.TxTypes=we;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- import { ChainTypes } from '@tomo-inc/wallet-utils';
2
- export { ChainTypes } from '@tomo-inc/wallet-utils';
3
1
  import { TomoAppInfo } from '@tomo-inc/chains-service';
4
2
  export { TomoAppInfo as TomoAppConfig, TomoWallet, TransactionItem, TransactionsParams, TransactionsResponse, TxTypes } from '@tomo-inc/chains-service';
5
3
  import { CubeConnectResult } from '@tomo-inc/cubist-wallet-sdk';
6
4
  export { CubeConfig, CubeConnect, CubeConnectResult, MfaConfig, TotpInfo } from '@tomo-inc/cubist-wallet-sdk';
5
+ import { ChainTypes } from '@tomo-inc/wallet-utils';
6
+ export { ChainTypes } from '@tomo-inc/wallet-utils';
7
7
  export { EmailLoginResult, LoginType, OidcAuth } from '@tomo-inc/oidc-auth';
8
8
 
9
9
  declare const SocialAccount: (accountData: CubeConnectResult, chainConfig: {
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { ChainTypes } from '@tomo-inc/wallet-utils';
2
- export { ChainTypes } from '@tomo-inc/wallet-utils';
3
1
  import { TomoAppInfo } from '@tomo-inc/chains-service';
4
2
  export { TomoAppInfo as TomoAppConfig, TomoWallet, TransactionItem, TransactionsParams, TransactionsResponse, TxTypes } from '@tomo-inc/chains-service';
5
3
  import { CubeConnectResult } from '@tomo-inc/cubist-wallet-sdk';
6
4
  export { CubeConfig, CubeConnect, CubeConnectResult, MfaConfig, TotpInfo } from '@tomo-inc/cubist-wallet-sdk';
5
+ import { ChainTypes } from '@tomo-inc/wallet-utils';
6
+ export { ChainTypes } from '@tomo-inc/wallet-utils';
7
7
  export { EmailLoginResult, LoginType, OidcAuth } from '@tomo-inc/oidc-auth';
8
8
 
9
9
  declare const SocialAccount: (accountData: CubeConnectResult, chainConfig: {