@tomo-inc/social-account-sdk 0.0.4 → 0.0.5

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/CHANGELOG.md CHANGED
@@ -5,3 +5,7 @@
5
5
  ## 0.0.3
6
6
 
7
7
  1. passkey in RN
8
+
9
+ ## 0.0.4
10
+
11
+ 1. x oidcToken exchange in relay
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomo-inc/social-account-sdk",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "author": "tomo.inc",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -25,23 +25,16 @@
25
25
  "access": "public"
26
26
  },
27
27
  "dependencies": {
28
- "viem": "^2.21.54",
29
- "axios": "^1.11.0",
30
- "crypto-js": "^4.2.0",
31
- "bignumber.js": "^9.1.2",
32
- "@cubist-labs/cubesigner-sdk": "^0.4.98-0",
33
- "@tomo-inc/cubist-sig-sdk": "^1.1.0"
28
+ "@tomo-inc/cubist-sig-sdk": "^1.1.0",
29
+ "@tomo-inc/chains-service": "0.0.3",
30
+ "@tomo-inc/cubist-wallet-sdk": "0.0.4",
31
+ "@tomo-inc/wallet-utils": "0.0.2"
34
32
  },
35
33
  "devDependencies": {
36
- "@types/crypto-js": "^4.2.2",
37
34
  "@types/node": "^20.11.19",
38
- "@types/supertest": "^2.0.12",
39
- "supertest": "^6.3.0",
40
35
  "tsup": "^8.3.5",
41
36
  "tsx": "^4.19.2",
42
37
  "typescript": "^5.3.3",
43
- "@vitest/browser": "^3.2.4",
44
- "playwright": "^1.44.1",
45
38
  "vitest": "^3.0.8"
46
39
  }
47
- }
40
+ }
package/dist/index.cjs DELETED
@@ -1,2 +0,0 @@
1
- 'use strict';var bignumber_js=require('bignumber.js'),viem=require('viem'),j=require('axios'),Tt=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 j__default=/*#__PURE__*/_interopDefault(j);var Tt__default=/*#__PURE__*/_interopDefault(Tt);var xt=Object.defineProperty;var i=(n,t)=>xt(n,"name",{value:t,configurable:true});var Ot=Object.defineProperty,At=i((n,t)=>{for(var e in t)Ot(n,e,{get:t[e],enumerable:true});},"__export"),Nt={};At(Nt,{clear:i(()=>Bt,"clear"),get:i(()=>Pt,"get"),remove:i(()=>Ut,"remove"),set:i(()=>Mt,"set"),setKeyNS:i(()=>Ft,"setKeyNS")});var A="tomo-";function Pt(n){let t=A+n;if(!Rt(t))return null;let e=null;try{let r=window.localStorage.getItem(t)||window.sessionStorage.getItem(t);e=JSON.parse(r);}catch(r){console.error(r);}return e!==null&&Object.prototype.hasOwnProperty.call(e,"type")&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:null}i(Pt,"get");function Mt(n,t,e){let r;e?r=window.sessionStorage:r=window.localStorage;let s=JSON.stringify({data:t,time:new Date().getTime(),type:typeof t});try{return r.setItem(A+n,s),!0}catch(a){a?.name?.toUpperCase().indexOf("QUOTA")>=0&&(window.localStorage.clear(),r.setItem(A+n,s));}}i(Mt,"set");function Ut(n){let t=A+n;window.localStorage.removeItem(t),window.sessionStorage.removeItem(t);}i(Ut,"remove");function Bt(){window?.localStorage?.clear(),window?.sessionStorage?.clear();}i(Bt,"clear");function Rt(n){return Object.prototype.hasOwnProperty.call(window.localStorage,n)||Object.prototype.hasOwnProperty.call(window.sessionStorage,n)}i(Rt,"isKeyExist");function Ft(n){typeof n=="string"&&n!==""&&(A=n);}i(Ft,"setKeyNS");var T=(n=>(n.BTC="btc",n.DOGE="doge",n.EVM="evm",n.SOL="sol",n.SUI="sui",n.TON="ton",n.TRON="tron",n.COSMOS="cosmos",n.APTOS="aptos",n))(T||{}),O={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 Dt(n,t,e){Object.prototype.toString.call(t)!=="[object Array]"&&(t=[t]);let r=[];for(let a=0,o=t.length;a<o;a++)r.push(s(t[a]));return r.join("");function s(a){return n.replace(/\\?\{([^}]+)\}/g,function(o,c){return o.charAt(0)=="\\"?o.slice(1):a[c]!=null?a[c]:""})}}i(Dt,"subs");function $t(n,t){let e={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}"},r=n.toString(),s=e[r]||"";if(s==="")throw new Error(`chainIndex ${n} tpl not found`);return Dt(s,t)}i($t,"getExplorerUrl");var Ht={prod:"https://wallet-pro.tomo.inc",pre:"https://wallet-pre-wlfi.tomo.inc",dev:"https://wallet-test.tomo.inc"},_t=class{static{i(this,"Networks");}chainType;networkAPIs;constructor(n,t){this.chainType=t||"",this.networkAPIs=n;}setChainType(n){this.chainType=n;}async getNetworks(n){return this.networkAPIs.getAllNetworks(n||"")}async getNetworkByChainId(n){let t=await this.networkAPIs.getNetworkByChainId(n);if(!t)throw new Error("Network not found");return t}async getNetworkByChainIndex(n){let t=await this.networkAPIs.getNetworkByChainIndex(n);if(!t)throw new Error("Network not found");return t}async getCurrentNetwork(){let n=this.chainType,t=await this.networkAPIs.getCurrentNetwork(n);return t===""&&(t=O?.[n]?.chainId||""),this.getNetworkByChainId(t)}async setCurrentNetwork(n){let t=this.chainType||"";return await this.networkAPIs.setCurrentNetwork(t,n),true}},Gt=class{static{i(this,"Tokens");}tokenAPIs;constructor(n){this.tokenAPIs=n;}async searchTokens({chainIndex:n,query:t}){let{data:e=[]}=await this.tokenAPIs.queryRemoteTokens({keyword:t||"",chainIndex:n});return e}async getTokenInfo({address:n,chainIndex:t}){let{data:{data:e}}=await this.tokenAPIs.getTokenInfo({address:n,chainIndex:t});return e}async getTokenRiskInfo(n){let{data:t}=await this.tokenAPIs.getTokenRisk(n);return t}async getTokenDetail(n){let{data:t}=await this.tokenAPIs.getTokenDetail(n);return t}};T.BTC+"",T.COSMOS+"",T.DOGE+"";var Kt=class{static{i(this,"Transactions");}transactionAPIs;constructor(n){this.transactionAPIs=n;}async queryGasInfo({chainType:n,params:t}){try{let e=await this.transactionAPIs.queryGasInfo(n,t);return {success:e?.code===0,data:e?.result||{}}}catch(e){return {success:false,message:e?.message||"Failed to query gas info"}}}async getTransactions(n){let t=await this.transactionAPIs.getTransactions(n),{cursor:e="",transactionList:r=[]}=t||{};return {cursor:e,transactionList:r}}async getTransaction(n){return (await this.transactionAPIs.getTransaction(n))?.data||{}}};function Y(n){let t=Ht[n];if(!t)throw new Error("Invalid tomo stage");return {rpcBaseUrl:`${t}`,walletBaseUrl:`${t}/wallet`,txBaseUrl:`${t}/quote`,tokenBaseUrl:`${t}/token`,userBaseUrl:`${t}/user/api`}}i(Y,"getConfig");var at={prod:Y("prod"),pre:Y("pre"),dev:Y("dev")};function qt(n){let t=Math.floor(Date.now()/1e3).toString(),e=n.method.toUpperCase(),r=n.data?n.data:{};e==="GET"?r=JSON.stringify({key:"value"}):typeof r!="string"&&(r=JSON.stringify(r));let s=[e,n.url,t,r,n.apiKey,n.apiSecret,n.salt].join("");return {signature:Tt__default.default.SHA256(s).toString(),timestamp:t}}i(qt,"generateSignature");var Vt=i(n=>`Bearer ${n}`,"formatJwtToken");function Lt(n,t,e){if(typeof e=="string"){let u=e;return Object.assign(n.headers??{},{"client-id":t,Authorization:Vt(u)}),n}let{apiKey:r,apiSecret:s,salt:a}=e,{signature:o,timestamp:c}=qt({method:n.method,url:n.url,data:n.data,apiKey:r,apiSecret:s,salt:a});return Object.assign(n.headers??{},{"X-APP-Key":r,"X-Signature":o,"X-Timestamp":c,"client-id":t}),n}i(Lt,"signRequest");var D=class{static{i(this,"BasePublicService");}tokenApi=j__default.default.create();txApi=j__default.default.create();walletApi=j__default.default.create();apiBase;tomoAppInfo;constructor(n,t){this.apiBase=n,this.tomoAppInfo=t,[this.tokenApi,this.txApi,this.walletApi].map((e,r)=>e.interceptors.request.use(s=>{let{tokenBaseUrl:a,txBaseUrl:o,walletBaseUrl:c}=n;return s.baseURL=[a,o,c][r],Lt(s,t.tomoClientId,t)}));}getSignConfig(){return this.tomoAppInfo}},zt=class ct extends D{static{i(this,"_TokenAPIs");}static instance;constructor(t,e){super(t,e);}static getInstance(t,e){return this.instance||(this.instance=new ct(t,e)),this.instance}async getTokenInfo(t){try{let e=await this.walletApi.get("/v1/balance/getTokenInfo",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to get token info:",e),e}}async getTokenRisk(t){if(typeof t.chainIndex!="number"||!t.tokenAddress)throw new Error("chainName or tokenAddress is required");let e=await this.tokenApi.post("/v1/market/risk/details",[t]);return {success:e?.data?.code==="0",message:e?.data?.msg,data:e?.data?.data?.[0]||null}}async addCustomToken(t){try{let e=await this.walletApi.post("/v1/customTokens/addCustomToken",t,{});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to add custom token:",e),e}}async deleteCustomToken(t){try{let e=await this.walletApi.get("/v1/customTokens/delete",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to delete custom token:",e),e}}async addMultiToken(t){try{let e=await this.walletApi.post("/v1/customTokens/addTokenWithMulti",t,{});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to add multi token:",e),e}}async removeMultiToken(t){try{let e=await this.walletApi.get("/v1/customTokens/hideTokenWithMulti",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to delete multi token:",e),e}}async syncCustomToken(t){try{return (await this.walletApi.post("/v1/customTokens/sync",t,{}))?.data||{}}catch(e){throw console.error("Failed to sync custom token:",e),e}}async getTokenBalance(t){try{let e=await this.walletApi.get("/v1/balance/getTokenBalanceWithDetail",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data||null}}catch(e){throw console.error("Failed to get token balance:",e),e}}async getTokenDetail(t){let{chainIndex:e,tokenAddress:r}=t,s=await this.tokenApi.get("/v1/market/token/detail",{params:{tokenAddress:r,chainIndex:e}});return {success:s?.data?.code==="0",message:s?.data?.msg,data:s?.data?.data||null}}async queryRemoteTokens(t){let{keyword:e="",chainIndex:r}=t||{};if(!e)throw new Error("Params is required");let s=await this.tokenApi.get("/v1/market/token/search",{params:{content:e,chainIndex:r}});return {success:s?.data?.code==="0",message:s?.data?.msg,data:s?.data?.data||[]}}},jt=class ut extends D{static{i(this,"_TransactionAPIs");}static instance;constructor(t,e){super(t,e);}static getInstance(t,e){return this.instance||(this.instance=new ut(t,e)),this.instance}async queryGasInfo(t,e){try{return (await this.txApi.post("/api/v1/quote/queryGasInfo",e))?.data||{}}catch(r){throw console.error("Failed to get gas info:",r),r}}async getTransactions(t){try{return (await this.walletApi.get("/v1/transaction/list",{params:t}))?.data?.data||{}}catch(e){throw console.error("Failed to get transactions:",e),e}}async getTransaction(t){try{return (await this.walletApi.get("/v1/transaction/detail",{params:t}))?.data?.data||{}}catch(e){throw console.error("Failed to get transaction:",e),e}}},Yt=class pt extends D{static{i(this,"_WalletAPIs");}static instance;constructor(t,e){super(t,e);}static getInstance(t,e){return this.instance||(this.instance=new pt(t,e)),this.instance}async createWallet(t){try{if(!t)throw new Error("Params is required");return (await this.walletApi.post("/v1/wallet/create",t,{}))?.data||{}}catch(e){if(e?.response?.data?.code==="60003")return {success:false,message:"Wallet already exists",data:null};throw console.error("Failed to create wallet:",e),e}}async syncWallet(t){try{return (await this.walletApi.post("/v1/wallet/sync",t,{}))?.data||{}}catch(e){throw console.error("Failed to sync wallet:",e),e}}async deleteWallet(t){try{return (await this.walletApi.post("/v1/wallet/delete",t,{}))?.data||{}}catch(e){throw console.error("Failed to sync wallet:",e),e}}},Jt=i(n=>[{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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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"),Xt=class lt extends D{static{i(this,"_NetworkAPIs");}static instance;chains=[];currentChainId="";constructor(t,e){super(t,e);let r=Jt(t.rpcBaseUrl);this.chains=r.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(t,e){return this.instance||(this.instance=new lt(t,e)),this.instance}getAllNetworks(t){return t===""?this.chains:this.chains.filter(e=>e.platformType===t.toUpperCase())}async getCurrentNetwork(t){if(!O?.[t])throw new Error(`Chain ${t} is not supported`);return this.currentChainId||O?.[t]?.chainId||""}async setCurrentNetwork(t,e){if(t&&!O?.[t])throw new Error(`Chain ${t} is not supported`);this.currentChainId=e;}getNetworkByChainId(t){return this.chains.find(e=>e.chainId===Number(t))}getNetworkByChainIndex(t){return this.chains.find(e=>e.chainIndex===t)}};function Wt(n,t){return {tokenAPIs:zt.getInstance(n,t),transactionAPIs:jt.getInstance(n,t),networkAPIs:Xt.getInstance(n,t),walletAPIs:Yt.getInstance(n,t)}}i(Wt,"tomoPublicApiService");var dt=class{static{i(this,"BaseService");}isDappConnected;approveParams;accountInfo;networks;tokens;transactions;constructor(n,t){if(!n.tomoStage||!at[n.tomoStage])throw new Error("Tomo stage is required");let e=at[n.tomoStage],{tokenAPIs:r,transactionAPIs:s,networkAPIs:a}=Wt(e,n);this.accountInfo=t,this.networks=new _t(a),this.tokens=new Gt(r),this.transactions=new Kt(s),this.isDappConnected=false;}async setApproveParams(n){this.approveParams=n;}};function Zt(n){let{chainId:t,name:e,rpcUrls:r,nativeCurrencyDecimals:s,nativeCurrencyName:a,nativeCurrencySymbol:o}=n,c={id:Number(t)||t,name:e,nativeCurrency:{name:a,symbol:o,decimals:s},rpcUrls:{default:{http:r,webSocket:[]},public:{http:r,webSocket:[]}},blockExplorers:{default:{name:"Explorer",url:r[0]}}};return {rpcClient:viem.createPublicClient({chain:c,pollingInterval:1e4,cacheTime:1e4,transport:viem.http()})}}i(Zt,"getRPCClient");var Q=(n=>(n.EOA="EOA",n.SOCIAL="SOCIAL",n))(Q||{}),ht=(n=>(n[n.swap=1]="swap",n[n.bridge=2]="bridge",n[n.receive=31]="receive",n[n.send=32]="send",n[n.approve=4]="approve",n[n.contractInteraction=5]="contractInteraction",n[n.redPocket=6]="redPocket",n))(ht||{}),Qt=i(n=>n&&n?.platformType==="EVM","isEvmChain"),J=i(({chainId:n,chainType:t})=>{if(viem.isHex(n)){let r=n;return n=viem.fromHex(n,"number").toString(),{chainId:n,chainIdHex:r,chainUid:`${t}:${n}`}}let e=viem.toHex(Number(n));return {chainId:n,chainIdHex:e,chainUid:`${t}:${n}`}},"getAllTypeChainIds"),te=class k extends dt{static{i(this,"_EvmService");}static instance;chainType;constructor(t,e,r){super(r,e),this.chainType=t;}static getInstance(t,e,r){return k.instance||(k.instance=new k(t,e,r)),k.instance}async eth_requestAccounts(){return await this.eth_accounts()}async eth_accounts(){return (await this.accountInfo.getCurrent()).map(e=>e.address)}async eth_chainId(){let t=this.chainType,e=await this.getCurrentChain(),{chainIdHex:r}=J({chainId:e?.chainId,chainType:t});return r}async getCurrentChain(){return this.networks.setChainType(this.chainType),await this.networks.getCurrentNetwork()}async wallet_switchEthereumChain(t){let{chainId:e}=t[0];if(!await this.isChainSupported(e))throw new Error(`Chain ${e} is not supported`);return await this.networks.setCurrentNetwork(e)}async isChainSupported(t){let e=this.chainType,r=J({chainId:t,chainType:e});if(!r.chainId)return false;let s=await this.networks.getNetworkByChainId(r.chainId);return s?Qt(s):false}async personal_sign([t,e]){if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");return await this.accountInfo.signMessage(t)}async eth_signTypedData_v4([t,e]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");return await this.accountInfo.signTypedData(e)}async eth_getBalance([t,e]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");if(e!=="latest")throw new Error("type is not supported");let s=await this.getCurrentChain(),{rpcClient:a}=Zt(s);try{return (await a.getBalance({address:t}))?.toString()||"0"}catch(o){return console.error(o),"0"}}async eth_estimateGas(t){let{from:e,to:r,value:s="0x1"}=t[0]||{};if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");if(!r)throw new Error("to is not set");let o=t[0]?.chainId||await this.eth_chainId(),c={chainIndex:Number(o),callData:"0x",gasLimitParam:{from:e,to:r,value:s},addressList:[e]},u=this.chainType,{data:l,success:m,message:h}=await this.transactions.queryGasInfo({chainType:u,params:c});if(!m){console.error("queryGasInfo evm",t,h,l);let{gasFee:f}=O[u];return f.toString()}let y=J({chainId:o,chainType:u}),{nativeCurrencyDecimals:v}=await this.networks.getNetworkByChainId(y.chainId),{baseFee:d=1,gasLimit:g=0}=l,b=new bignumber_js.BigNumber(d);return i(f=>{let V=b.plus(l[f]||0).times(g);return viem.toHex(BigInt(V.toNumber()),v)},"calcFee")("priorityFeeMedium")}async createPublicClient({chainId:t,rpcUrl:e}){if(e)return viem.createPublicClient({transport:viem.http(e)});if(t?(this.networks.setChainType(this.chainType),e=(await this.networks.getNetworkByChainId(t)).rpcUrls[0]):e=(await this.getCurrentChain()).rpcUrls[0],!e)throw new Error("rpcUrl is not set");return viem.createPublicClient({transport:viem.http(e)})}async eth_getTransactionCount([t,e]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");if(e!=="latest"&&e!=="pending")throw new Error("type is not supported");try{return await(await this.createPublicClient({})).getTransactionCount({address:t})}catch(s){throw console.error("Failed to get nonce:",s),new Error(`Failed to get nonce: ${s}`)}}async eth_signTransaction(t){let e={chainId:"number",to:"string",value:"bigint",data:"string",nonce:"number",maxPriorityFeePerGas:"bigint",maxFeePerGas:"bigint",gasLimit:"bigint",gas:"bigint"},r=t?.[0],s=r?.gas||r?.gasLimit;r={...r,gas:s,gasLimit:s},r.data=r.data||"0x";let o=(await this.accountInfo.getCurrent())[0].address;if(r?.from&&r?.from!==o)throw console.error("eth_signTransaction error data: from is not the current account",r),new Error("eth_signTransaction error data: from is not the current account");delete r?.from;let c={type:"eip1559",gas:r?.gasLimit,account:o};for(let u in e){if(!r?.[u]||!viem.isHex(r?.[u]))throw new Error(`${u}: no data or wrong type`);c[u]=e[u]==="number"?viem.fromHex(r[u],"number"):r[u];}try{let u=await this.accountInfo.signTransaction(JSON.stringify({data:c,types:e}));if(u==="")throw new Error(`eth_signTransaction error data: ${JSON.stringify(t)}`);return viem.parseTransaction(u)}catch(u){throw new Error("eth_signTransaction error"+u)}}async eth_sendRawTransaction([t],e){try{return await(await this.createPublicClient({rpcUrl:e})).sendRawTransaction({serializedTransaction:t})}catch(r){throw console.error("Failed to send transaction via RPC:",r,e),r}}async getTransaction(t){if(!t||!viem.isHex(t))throw new Error("txId is not valid");try{return await(await this.createPublicClient({})).getTransaction({hash:t})}catch(e){throw console.error("Failed to send transaction via RPC:",e,t),e}}},ee=class E extends dt{static{i(this,"_TomoWallet");}static instance;walletId;constructor(t,e){super(e),this.walletId=t;}getInstance(t,e){return E.instance||(E.instance=new E(t,e)),new E(t,e)}async supportedChains(t){return await this.networks.getNetworks(t||"")}async getChainInfo(t,e){return this.networks.setChainType(t),await this.networks.getNetworkByChainId(e)}async isChainSupported(t,e){this.networks.setChainType(t);let r=await this.networks.getNetworkByChainId(e);return r?!!r.chainId:false}async getTransactions({tokenAddress:t="",chainId:e="",typeList:r=[],pageLimit:s=20,cursor:a}){if(!this.walletId)throw new Error("walletId is required");try{let o={tokenAddress:t,pageLimit:s+1,walletId:this.walletId,cursor:a};if(r.length>0&&(o.typeList=r.join(",")),e){let y=(await this.networks.getNetworkByChainId(e)).chainIndex;o.chainIndex=y;}let{cursor:c="",transactionList:u}=await this.transactions.getTransactions(o),l=u.map(async h=>{let y=h.chainIndex,v=await this.networks.getNetworkByChainIndex(y);return {chainType:v.platformType.toLowerCase(),chainInfo:{chainId:v.chainId.toString(),name:v.name,icon:v.icon},nativeCurrency:v?.nativeCurrency,tokenInfo:h.tokenInfo,txHash:h.txHash,txDetail:h,txDetailLink:$t(y,{txId:h.txHash}),txTime:h.txTime}}),m=await Promise.all(l);return {cursor:c,transactionList:m}}catch(o){throw console.error("Failed to send transaction via RPC:",o),o}}},mt={[T.EVM]:te};var re=Object.defineProperty,ne=i((n,t)=>{for(var e in t)re(n,e,{get:t[e],enumerable:true});},"__export"),P={};ne(P,{clear:i(()=>ie,"clear"),get:i(()=>se,"get"),remove:i(()=>oe,"remove"),set:i(()=>ae,"set"),setKeyNS:i(()=>ue,"setKeyNS")});var N="tomo-";function se(n){let t=N+n;if(!ce(t))return null;let e=null;try{let r=window.localStorage.getItem(t)||window.sessionStorage.getItem(t);e=JSON.parse(r);}catch(r){console.error(r);}return e!==null&&Object.prototype.hasOwnProperty.call(e,"type")&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:null}i(se,"get");function ae(n,t,e){let r;e?r=window.sessionStorage:r=window.localStorage;let s=JSON.stringify({data:t,time:new Date().getTime(),type:typeof t});try{return r.setItem(N+n,s),!0}catch(a){a?.name?.toUpperCase().indexOf("QUOTA")>=0&&(window.localStorage.clear(),r.setItem(N+n,s));}}i(ae,"set");function oe(n){let t=N+n;window.localStorage.removeItem(t),window.sessionStorage.removeItem(t);}i(oe,"remove");function ie(){window?.localStorage?.clear(),window?.sessionStorage?.clear();}i(ie,"clear");function ce(n){return Object.prototype.hasOwnProperty.call(window.localStorage,n)||Object.prototype.hasOwnProperty.call(window.sessionStorage,n)}i(ce,"isKeyExist");function ue(n){typeof n=="string"&&n!==""&&(N=n);}i(ue,"setKeyNS");var $=i(n=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"isEmail"),p=(n=>(n.BTC="btc",n.DOGE="doge",n.EVM="evm",n.SOL="sol",n.SUI="sui",n.TON="ton",n.TRON="tron",n.COSMOS="cosmos",n.APTOS="aptos",n))(p||{});var M={prod:"prod",pre:"prod",dev:"gamma"},H={prod:"Org#49944bce-9daf-423f-a982-269f6d0d301b",pre:"Org#71c13f6d-b992-4660-874d-2ae0fadc789f",dev:"Org#3d07a75a-1188-4bd0-acfa-671a198b83eb"},S={prod:"https://social-relay.tomo.inc",pre:"https://social-relay.tomo.inc",dev:"https://social-relay-dev.tomo.inc"},tt={prod:"https://wallet-pro.tomo.inc",pre:"https://wallet-pre-wlfi.tomo.inc",dev:"https://wallet-test.tomo.inc"};var G=30*24*60*60,gt={auth:G,refresh:G*2},_=["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"],Ae="Key#Mnemonic_",Ne={"https://accounts.google.com":"google","https://shim.oauth2.cubist.dev/twitter":"x"},Pe={prod:"xnPWRJT5XG2WyevuydMjMpZq",pre:"xnPWRJT5XG2WyevuydMjMpZq",dev:"dev@tomo"},Me=i(n=>{let e={Login:["Fido","EmailOtp","Totp"],RegisterMfa:["Fido",`EmailOtp#${n==="prod"?172800:300}`,"Totp"],Export:["Fido","Totp"]};return {createSession:{method:"POST",path:"/session/",_allowed_mfa_types:e.Login},addFido:{method:"POST",path:"/user/me/fido/",_allowed_mfa_types:e.RegisterMfa},deleteFido:{method:"DELETE",path:"/user/me/fido/",_allowed_mfa_types:e.RegisterMfa},registerTotp:{method:"POST",path:"/user/me/totp/",_allowed_mfa_types:e.RegisterMfa},deleteTotp:{method:"DELETE",path:"/user/me/totp/",_allowed_mfa_types:e.RegisterMfa},registerEmailOtp:{method:"POST",path:"/user/me/email/",_allowed_mfa_types:e.RegisterMfa},initExport:{method:"POST",path:"/user/me/export/",_allowed_mfa_types:e.Export},completeExport:{method:"PATCH",path:"/user/me/export/",_allowed_mfa_types:e.Export}}},"getMfaInfoConfig"),Ue=class U{static{i(this,"_CubeExportService");}constructor(){this.seedPhraseKey="",this.cubeAccountService=null,this.cubeSignerClient=null,this.exportKey=null,cubesignerSdk.userExportKeygen().then(t=>{this.exportKey=t;});}static getInstance(){return U.instance||(U.instance=new U),U.instance}init(t){return this.cubeAccountService=t,this.cubeSignerClient=t.cubeSignerClient,this}async getExportKey(){if(this.seedPhraseKey)return this.seedPhraseKey;let e=(await this.cubeSignerClient?.sessionKeys()||[]).find(r=>r?.id.indexOf(Ae)===0);return this.seedPhraseKey=e?.id||"",this.seedPhraseKey}async getExportInfo(){if(!this.cubeSignerClient)return null;let t=await this.getExportKey(),r=await this.cubeSignerClient?.org()?.exports(t)?.fetch();if(r?.length===0)return {ready:true};let{valid_epoch:s=0,exp_epoch:a=0}=r[0],o=s-Date.now()/1e3;o=Math.max(Math.ceil(o),0);let c=a-s;return {ready:true,keyId:t,lastTime:o,duration:c,valid_epoch:s,exp_epoch:a}}async initExport(t){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");let e=await this.getExportKey(),r=await this.cubeSignerClient.org().initExport(e,t);return r.requiresMfa()?await this.cubeAccountService?.cubeMfaService?.getMfaInfo("initExport")||null:r.data()}async completeExport(t){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");let e=await this.getExportKey(),r=await this.cubeSignerClient.org().completeExport(e,this.exportKey.publicKey,t);if(r.requiresMfa())return await this.cubeAccountService?.cubeMfaService?.getMfaInfo("completeExport")||null;let s=r.data();return await cubesignerSdk.userExportDecrypt(this.exportKey.privateKey,s)}async deleteExport(){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");try{let t=await this.getExportKey();return {success:!0,data:await this.cubeSignerClient.org().deleteExport(t)}}catch(t){return {success:false,message:t?.message||"delete export error",error:t}}}},K="passkey-relay",Be="cubist-sdk",C=null,Re=i(({url:n,name:t,width:e,height:r})=>{let s=window.ReactNativeWebView;if(s){let c={url:n,name:t};return s.postMessage(JSON.stringify({type:"OPEN_PASSKEY_RELAY",message:c})),{closed:false,postMessage:i(u=>{s.postMessage(JSON.stringify({type:"PASSKEY_RELAY_MESSAGE",message:u}));},"postMessage")}}let a=(window.innerHeight-r)/2+window.screenY,o=(window.innerWidth-e)/2+window.screenX;try{let c=window.open(n,t,`dialog=yes,top=${a}px,left=${o},width=${e!==void 0?e:400}px,height=${r!==void 0?r:600}px`);return c||null}catch(c){return console.error("Failed to open window:",c),null}},"openWindow"),Fe=i(()=>{try{C&&!C.closed&&C.close();}catch(n){console.error("Failed to close window:",n);}finally{C=null;}},"closeWindow"),et=i(async(n,t)=>{if(C===null)throw new Error("Failed to open relay window");let e=S[t]||S.dev;C.postMessage({...n,from:Be},e);},"sendPasskeyMessage"),ft=i(async n=>new Promise((t,e)=>{if(n=n||P.get("cubeConfig"),!n.oidcToken||!n.tomoClientId){e({message:"oidcToken/tomoClientId is required"});return}let r=S[n.tomoStage];if(!r){e({message:"tomoStage must be dev/pre/prod."});return}C=Re({url:`${r}/passkey?origin=${window.location.origin}`,name:"relay-passkey",width:400,height:600});let s=i(a=>{let{type:o,data:c,from:u,error:l}=a.data;o==="passkey-relay-loaded"&&u===K&&et({type:"init",params:n},n.tomoStage),o==="passkey-relay-init"&&u===K&&(window.removeEventListener("message",s),t(c));},"handleMessage");window.addEventListener("message",s);}),"initPasskeyPage"),De=i(async(n,t)=>(C||await ft(t),new Promise((e,r)=>{let s=i(a=>{let{type:o,data:c,from:u,error:l}=a.data;o==="passkey-relay-addFido"&&u===K&&(window.removeEventListener("message",s),e(c));},"handleMessage");window.addEventListener("message",s),et({type:"addFido",params:n},t.tomoStage);})),"addPasskey"),$e=i(async(n,t)=>(C||await ft(t),new Promise((e,r)=>{let s=i(a=>{let{type:o,data:c,from:u,error:l}=a.data;o==="passkey-relay-verify"&&u===K&&(window.removeEventListener("message",s),e(c));},"handleMessage");window.addEventListener("message",s),et({type:"verify",params:n},t.tomoStage);})),"verifyPasskey"),wt=i((n,t,{userId:e,rpId:r,fidoName:s})=>{r=r||window.location.hostname;let{host:a,protocol:o}=window.location,c=o!=="https:"&&o!=="http:",u=a.indexOf("localhost:")===0;t.options=t?.options||{},t.options.rp=t.options.rp||{},t.options.rp.id=r,t.options.rpId=r,(c||u)&&(t?.options?.rp?.id&&delete t.options.rp.id,t?.options?.rpId&&delete t.options.rpId),t.options.timeout=6e4,t.options.attestation="none";let l=t.options?.user||{};return n==="add"&&(l.id=l.id||new TextEncoder().encode(e),l.name=s,l.displayName=s),t.options.user=l,t},"applyLocalDevFixes"),He=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(t){return this.cubeSignerClient=t.cubeSignerClient,this.apiClient=t.apiClient,this.cubeAccountService=t,this}setMfaType(t){if(!t)throw new Error("mfaType is required");this.mfaType=t;}setMfaAnswer(t){this.mfaAnswer=t;}async getMfaInfo(t){if(!t)throw new Error("mfaRequestType is required");let r=Me(this.cubeAccountService?.config?.cubeStage||"gamma")[t];if(!r)throw new Error("mfaRequestType is not supported");let{method:s,path:a}=r,c=(await this.apiClient.mfaList()).find(d=>{let g=d?.request.method,b=d?.request.path+"/";return g===s&&b.indexOf(a)>-1});if(!c)return null;let u=null,l=c?.status?.allowed_mfa_types||[];for(let d of l){u=u||{};let g=d.toLowerCase().split("#");u[g[0]]=g[1]?Number(g[1]):true;}let{receipt:m,created_at:h}=c,y=0;if(typeof u.emailOtp=="number"){let d=u.emailOtp-(Date.now()/1e3-h);y=Math.max(0,Math.ceil(d));}return u.emailOtp&&(u.emailOtpRemainTime=y),{...c,verifyStatus:m!==null?"approved":"pending",mfaRequired:u}}async answerRegister(t){let e=this.registerChallenge;if(!e)throw new Error("challenge is required");try{let r=await e.answer(t)||null;return this.registerChallenge=null,{success:!0,data:r}}catch(r){return {success:false,message:r?.message||"answer error",error:r}}}async executeBizWithMfa(t,e){if(!t)throw new Error("bizType is required");if(e||(e=await this.getMfaInfo(t)||null),!e?.id)throw new Error("mfa not exists, please create mfa first");let{success:r,data:s}=await this.approvalMfa(e?.id||"")||{};if(!r)return {success:false,message:`approval with ${this.mfaType} error.`};if(t==="createSession"){let o=await this.cubeAccountService?.createSession(s);return {success:!!o,message:o?"":"create session error",data:o}}if(t==="addFido"){let o=e.request?.body?.name,c=await this.addFido(o,s);return {success:!!c,message:c?"":"addFido error",data:c}}if(t==="deleteFido"){let c=(e?.request?.path||"").split("/user/me/fido/")[1]||"";if(!c)throw new Error("fidoId is required");let u=await this.deleteFido(decodeURIComponent(c),s);return {success:!!u,message:u?"":"deleteFido error",data:u}}if(t==="registerTotp"){let o=e.request?.body?.issuer,c=await this.registerTotp(o,s);return {success:!!c,message:c?"":"registerTotp error",data:c}}if(t==="deleteTotp"){let o=await this.deleteTotp(s);return {success:!!o,message:o?"":"deleteTotp error",data:o}}if(t==="registerEmailOtp"){let o=e.request?.body?.email,c=await this.registerEmailOtp(o,s);return {success:!!c,message:c?"":"registerEmailOtp error",data:c}}let a=this.cubeAccountService?.cubeExportService;if(t==="initExport"){let o=await a?.initExport(s);return {success:!!o,message:o?"":"init export error",data:o}}if(t==="completeExport"){let o=await a?.completeExport(s);return {success:!!o,message:o?"":"complete export error",data:o}}return {success:false,message:"bizType is not supported"}}async approvalMfa(t){let e={totp:"approvalTotp",emailOtp:"approvalEmailOtp",fido:"approvalFido"},r=this.mfaType;if(!r||!e[r])return {success:false,message:"mfaType is required"};let s=null;try{switch(r){case "totp":s=await this.approvalTotp(t);break;case "emailOtp":s=await this.approvalEmailOtp(t);break;case "fido":s=await this.approvalFido(t);break;default:return {success:!1,message:"Unsupported MFA type"}}}catch(a){return {success:false,message:`approval ${r} error: ${a instanceof Error?a.message:"Unknown error"}`}}return s?{success:true,data:s}:{success:false,message:`approval ${r} error.`}}getPasskeyConfig(){let{config:t}=this.cubeAccountService||{};return delete t?.cubeSalt,delete t?.jwtToken,t}passkeyClear(){Fe();}async addFido(t,e){let r=this.getPasskeyConfig();return await De({fidoName:t,receipt:e},r)}async addFidoLocal(t,e){if(!t||typeof t!="string")throw new Error("name is required");try{let r=await this.cubeAccountService?.getMfaConfig();if((r?.fido?.data||[]).find(m=>m?.name===t))throw new Error(`FIDO key with name "${t}" already exists`);let c=await this.cubeSignerClient?.addFido(t,e);if(c.requiresMfa())return await this.getMfaInfo("addFido");let u={userId:r?.account?.userId,rpId:this.cubeAccountService?.config?.rpId||window.location.hostname,fidoName:t};return await wt("add",c.data(),u).createCredentialAndAnswer(),!0}catch(r){return console.error("addFido error",r),false}}async deleteFido(t,e){try{let s=await this.cubeSignerClient?.deleteFido(t,e);return s.requiresMfa()?await this.getMfaInfo("deleteFido"):s.data()}catch{return null}}async approvalFido(t){let e=this.getPasskeyConfig();return await $e({mfaId:t},e)}async approvalFidoLocal(t){let e=this.apiClient,r=await this.cubeAccountService?.getMfaConfig(),s=await e.mfaFidoInit(t),a={userId:r?.account?.userId,rpId:this.cubeAccountService?.config?.rpId||window.location.hostname,fidoName:""};return s=wt("approval",s,a),await(await s.createCredentialAndAnswer("approve")).receipt()}async registerTotp(t,e){if(t==="")throw new Error("issuer are required");let r=await this.apiClient.userTotpResetInit(t,e);if(r.requiresMfa())return await this.getMfaInfo("registerTotp");let s=r.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")||t}}async deleteTotp(t){let e=await this.apiClient.userTotpDelete(t);return e.requiresMfa()?await this.getMfaInfo("deleteTotp"):e.data()}async approvalTotp(t){if(!t)throw new Error("MFA ID not found");let e=this.mfaAnswer?.totpCode;if(!e||!/^\d{6}$/.test(e))throw console.error("TOTP code is required"),new Error("TOTP code is required");let r=await this.apiClient.mfaVoteTotp(t,e,"approve"),s=this.cubeSignerClient?.org()?.id||this.cubeAccountService?.cubeOrgId||"";return {mfaId:r.id,mfaConf:r?.receipt?.confirmation,mfaOrgId:s}}async registerEmailOtp(t,e){if(!t||!$(t))throw new Error("email is required");let s=(await this.cubeAccountService?.getOidcClient()).apiClient,a={email:t,allow_otp_login:true},o=await s.userEmailResetInit(a,e);return o.requiresMfa()?await this.getMfaInfo("registerEmailOtp"):(this.registerChallenge=o.data(),this.registerChallenge)}async approvalEmailOtp(t){if(!t)throw new Error("MFA ID not found");if(!this.mfaChallenge){let r=await this.apiClient.mfaVoteEmailInit(t,"approve");return this.mfaChallenge=r,null}let e=this.mfaAnswer?.emailCode||"";if(e=e.split(/\s/).join(""),!e)throw new Error("emailCode is required");try{let r=await this.mfaChallenge.answer(e),s=this.cubeSignerClient?.org()?.id||this.cubeAccountService?.cubeOrgId||"",a={mfaId:r.id,mfaConf:r?.receipt?.confirmation,mfaOrgId:s};return this.mfaChallenge=null,a}catch(r){return console.warn("approvalEmailOtp error",r),null}}async sendEmailCode(t){if(!t)throw new Error("mfaId is required");try{let e=await this.apiClient.mfaVoteEmailInit(t,"approve");return this.mfaChallenge=e,!0}catch{return false}}},_e=i((n,t)=>{try{let{data:e,types:r}=JSON.parse(n);for(let s in r)r[s]==="bigint"&&(e[s]=BigInt(e[s]),t==="string"&&(e[s]=e[s].toString()));return e}catch{throw new Error("Invalid unsigned transaction")}},"recoverEVMTxData"),rt=class R{static{i(this,"_CubeSignService");}async init({cubeSession:t}){this.cubeSession=t,this.services||(this.services=await cubistSigSdk.getKeys(t));}static getInstance(){return R.instance||(R.instance=new R),R.instance}async getServiceByChainAndAddress(t,e){this.services||(this.services=await cubistSigSdk.getKeys(this.cubeSession));let r=this.buildKeyId(t,e),s=this.services.find(a=>a.id===r);return s||(console.warn(`service not found for chainType: ${t}`),null)}buildKeyId(t,e){switch(t){case p.EVM:return `Key#${e}`;case p.TRON:return `Key#Tron_${e}`;case p.SOL:return `Key#Solana_${e}`;case p.DOGE:return `Key#Doge_${e}`;default:return `Key#${e}`}}async signTransaction(t,e,r){let s=this?.cubeSession,a=await this.getServiceByChainAndAddress(t,e);if(!a)throw new Error(`service not found for chain ${t}`);let o=typeof r=="string"?JSON.parse(r):r;switch(t){case p.EVM:{let c=_e(r,"string");return await cubistSigSdk.signEvmTransaction(a,c,c.chainId,s)}case p.SOL:return await cubistSigSdk.signSolanaTransaction(a,o.rawTransaction,s);case p.DOGE:return await cubistSigSdk.signDogePsbt(a,o.psbtBase64,s);case p.TRON:{let c=o.data?.rawTransaction||o.rawTransaction;return await cubistSigSdk.signTronRawTransaction(a,c,s)}default:throw new Error(`Unsupported chain type: ${t}`)}}async signMessage(t,e,r){let s=this?.cubeSession,a=await this.getServiceByChainAndAddress(t,e);if(!a)throw new Error(`service not found for chain ${t}`);switch(t){case p.EVM:return await cubistSigSdk.signEvmMessage(a,r,s);case p.SOL:return await cubistSigSdk.signSolanaMessage(a,r,s);case p.DOGE:return (await cubistSigSdk.signDogeMessage(a,r,s)).signature;case p.TRON:return await cubistSigSdk.signTronMessage(a,r,s);default:throw new Error(`Unsupported chain type: ${t}`)}}async signTypedData(t,e,r){let s=this?.cubeSession,a=await this.getServiceByChainAndAddress(t,e);if(!a)throw new Error(`service not found for chain ${t}`);switch(t){case p.EVM:return await cubistSigSdk.signEvmTypedData(a,r,s);case p.TRON:return await cubistSigSdk.signTronTypeDaya(a,r.message,s);default:throw new Error(`Unsupported chain type: ${t}`)}}},Ge=i(async(n,t)=>{if(!t)throw new Error("salt is required");let e=Date.now().toString(),r={...n,timestamp:e},s=JSON.stringify(r),a=Tt__default.default.SHA256(s+t).toString();return {timestamp:e,signature:a}},"generateCubeSignature");function vt(n){let{tomoStage:t="dev",tomoClientId:e,jwtToken:r}=n,s=j__default.default.create({baseURL:`${tt[t]||tt.dev}/user`,timeout:2e4});return s.interceptors.request.use(async a=>(a.headers["client-id"]=e,r&&(a.headers.Authorization=`Bearer ${r}`),a),a=>{if(a?.response?.status===401)return Promise.reject(a)}),s}i(vt,"getTomoApi");var Ke=i(async(n,t)=>{let{iss:e,sub:r}=n,s=t.cubeSalt||"";if(!s)throw new Error("tomoStage error.");let{timestamp:a,signature:o}=await Ge({iss:e,sub:r},s),c={...n,timestamp:a,signature:o};return (await vt(t).post("/api/login/loginByCubistV2",c))?.data?.data||{}},"addUserToCube"),qe=i(async(n,t)=>{let e=vt(t),s=(await e.post("/api/user/getUserInfo"))?.data?.data.user||{},a=n.nickname.trim();return n={...s,...n,nickname:a,username:a},!!(await e.post("/api/setting/updateUserInfo",n,{headers:{}}))?.data?.success},"updateUserInfo"),nt=class I{static{i(this,"_CubeAccountService");}constructor(t){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=t,this.cubeEnv=null;}static getInstance(t){if(I.instance)return I.instance;if(!t?.tomoStage||!M[t?.tomoStage])throw new Error("tomoStage not 'dev' or 'pre' or 'prod'");let e=Pe[t?.tomoStage];if(!e)throw new Error("cubeSalt is required");let r=M[t?.tomoStage],s=cubesignerSdk.envs[r],a=H[t?.tomoStage];return I.instance=new I({...t,cubeSalt:e,cubeStage:r}),I.instance.cubeEnv=s,I.instance.cubeOrgId=a,I.instance}async getCubeIdentity(){let t=this?.config?.oidcToken;if(!t){let s=await P.get("cubeIdentity");return s?(this.cubeIdentity=s,this.cubeIdentity):(console.warn("oidcToken is required"),null)}let e=this.cubeOrgId,r=await cubistSigSdk.proof(t,this.cubeEnv,e);return await P.set("cubeIdentity",r,false),this.cubeIdentity=r,r}async loginOrRegister(t,e){this.config={...this.config,oidcToken:t};let r=await this.getCubeIdentity(),s={cubistUserID:r?.user_info?.user_id,aud:r?.aud,email:r?.email||e?.email||null,iss:r?.identity?.iss,sub:r?.identity?.sub,initialized:r?.user_info?.initialized},a=await Ke(s,this.config),{userToken:o,user:c,accountBaseInfo:u,accountWallet:l}=a;return this.accountData=a,this.accountWallet=l,this.jwtToken=o.accessToken,{user:{userId:c.userID,nickname:c.nickname,avatar:c.avatar},accountBaseInfo:u,accountWallet:l,walletId:l?.walletID}}async updateUserInfo(t){let e=t.nickname.trim();if(e.length<6||e.length>20)throw new Error("name length 6~20");let r={...this.config,jwtToken:this.jwtToken};return await qe(t,r)}async createSessionByOidcToken(t){if(t=t||this?.config?.oidcToken||"",!t)return console.warn("oidcToken is required"),false;let e=_,s=(await cubistSigSdk.getOidcResp(t,this.cubeEnv,this.cubeOrgId,G,e)).data();return this.setCubeSession(s),!!s}async createSession(t){let r=await this.apiClient.sessionCreateExtended("wallet_operations",_,gt,t);if(r.requiresMfa())return await this.cubeMfaService?.getMfaInfo("createSession")||null;let s=r.data();return this.setCubeSession(s),!!s}async refreshSession(){let r=(await this.apiClient.sessionCreate("wallet_operations",_,gt)).data();return this.setCubeSession(r),!!r}getCubeSession(){return this.cubeSession}setCubeSession(t){this.cubeSession=t;}sessionRevoke(){let t=this.apiClient;this.cubeSession=null,t?.sessionRevoke();}async refreshCubeClient(t){try{await this.createCubeSignerClient(t),this.initSubServices();}catch(e){console.error("refreshCubeClient error",e);}}async createCubeSignerClient(t){let e=await cubesignerSdk.CubeSignerClient.create(t);return this.cubeSignerClient=e,this.apiClient=this.cubeSignerClient.apiClient,e}async getOidcClient(t){let e=this?.config?.oidcToken||"";if(!e){console.warn("oidcToken is required");return}let r=_;return await cubistSigSdk.getOidcClient(e,this.cubeEnv,this.cubeOrgId,G,r,t)}async autoLogin(t){await this.refreshCubeClient(t),await this.setCubeSession(t);}async init(t){if(t=t||this?.config?.oidcToken||"",!t)return console.warn("oidcToken is required"),false;try{this.config={...this.config,oidcToken:t};let e=await this.getOidcClient();if(this.cubeSignerClient=e,this.apiClient=this.cubeSignerClient.apiClient,!await this.createSessionByOidcToken(t))throw new Error("create session by oidc token failed");return this.initSubServices(),!0}catch(e){throw console.error("init error",e),e}}async initSubServices(){let t=He.getInstance();this.cubeMfaService=t.init(this);let e=Ue.getInstance();this.cubeExportService=e.init(this);}async initCubeSignService(){let t=this.getCubeSession(),e=rt.getInstance();return await e.init({cubeSession:t}),e}async getCubeUserInfo(){try{let t=await this.apiClient?.userGet();return this.cubeUserInfo=t,t}catch{return null}}async getMfaConfig(){let[t,e]=await Promise.all([this.getCubeUserInfo(),this.getCubeIdentity()]),r=t?.name||e?.preferred_username||"",s=e?.identity?.iss||"",a=Ne?.[s]||"email",o=t?.verified_email?.email||"",c=t?.email||"",u=o!==""||c!=="",l=t?.mfa||[],m=l.filter(y=>y.type==="fido"),h=l.filter(y=>y.type==="totp");return {noMfa:!u&&m.length===0&&h.length===0,hasMfa:u||m.length>0||h.length>0,account:{name:r,email:c,otpEmail:o,accountType:a,userId:t?.user_id||""},emailOtp:{data:c||o,enabled:u},fido:{data:m,enabled:m.length>0},totp:{data:h[0],enabled:h.length>0}}}},Ve=i(async n=>{let t=nt.getInstance(n);if(!n.oidcToken)throw new Error("oidcToken is required");await t.loginOrRegister(n.oidcToken),await t.init(n.oidcToken);let e=t.cubeMfaService,r=t.cubeExportService;return {cubeAccount:t,cubeMfa:e,cubeExport:r}},"CubeConnect");var q=class{static{i(this,"CubeSocialAccount");}chainType;chainId;cubeSignService;accountData;userAPIs;constructor({chainType:t,chainId:e},r){this.chainType=t,this.chainId=e,this.accountData=r,this.cubeSignService=rt.getInstance();}async getAllAccounts(){let{accountWallet:t,user:e}=this.accountData||{},r={[p.EVM]:[{address:t?.ethereumAddress,publicKey:"",subType:p.EVM,path:""}],[p.DOGE]:[{address:t?.dogeAddress,publicKey:"",subType:p.DOGE,path:""}],[p.SOL]:[{address:t?.solanaAddress,publicKey:"",subType:p.SOL,path:""}],[p.TRON]:[{address:t?.tronAddress,publicKey:"",subType:p.TRON,path:""}],[p.BTC]:[{address:t?.bitcoinP2trAddressMain,publicKey:t?.bitcoinP2trPubKeyMain,subType:"TAPROOT",stage:"MAIN",path:"m/86'/0'/0'/0/0"},{address:t?.bitcoinP2trAddressTest,publicKey:t?.bitcoinP2trPubKeyTest,subType:"TAPROOT",stage:"TEST",path:"m/86'/1'/0'/0/0"},{address:t?.bitcoinP2shAddressMain,publicKey:t?.bitcoinP2shPubKeyMain,subType:"NESTED_SEGWIT",stage:"MAIN",path:"m/49'/0'/0'/0/0"},{address:t?.bitcoinP2shAddressTest,publicKey:t?.bitcoinP2shPubKeyTest,subType:"NESTED_SEGWIT",stage:"TEST",path:"m/49'/1'/0'/0/0"},{address:t?.bitcoinP2wpkhAddressMain,publicKey:t?.bitcoinP2wpkhPubKeyMain,subType:"NATIVE_SEGWIT",stage:"MAIN",path:"m/84'/0'/0'/0/0"},{address:t?.bitcoinP2wpkhAddressTest,publicKey:t?.bitcoinP2wpkhPubKeyTest,subType:"NATIVE_SEGWIT",stage:"TEST",path:"m/84'/0'/0'/0/0"},{address:t?.bitcoinP2pkhAddressMain,publicKey:t?.bitcoinP2pkhPubKeyMain,subType:"LEGACY",stage:"MAIN",path:"m/44'/0'/0'/0/0"},{address:t?.bitcoinP2pkhAddressTest,publicKey:t?.bitcoinP2pkhPubKeyTest,subType:"LEGACY",stage:"TEST",path:"m/44'/1'/0'/0/0"}],[p.SUI]:[{address:t?.suiAddress,publicKey:"",subType:p.SUI,path:""}],[p.TON]:[{address:t?.tonAddress,publicKey:"",subType:p.TON,path:""}],[p.COSMOS]:[{address:t?.cosmosAddress,publicKey:"",subType:p.COSMOS,path:""}],[p.APTOS]:[{address:t?.aptosAddress,publicKey:"",subType:p.APTOS,path:""}]};return {id:e.accountID,name:e.nickname,type:Q.SOCIAL,lastUsedTime:e.lastUsedTime,addresses:r,mnemonic:null,addressIndex:0,isImported:false,isBackedUp:false,isLocked:false,isFrozen:false}}async getCurrent(){let t=this.chainType,e=await this.getAllAccounts(),{address:r,publicKey:s,path:a,subType:o}=e?.addresses?.[t]?.[0]||{};return [{subType:o,address:r,path:a,publicKey:s,type:e.type,id:e.id}]}async signMessage(t){let e=await this.getCurrent(),r=this.chainType;try{let s=e[0].address;return await this.cubeSignService.signMessage(r,s,t)}catch(s){throw console.error("Error signing message with CubeSignService:",s),s}}async signTypedData(t){let e=await this.getCurrent(),r=this.chainType;try{let s=e[0].address;return await this.cubeSignService.signTypedData(r,s,t)}catch(s){throw console.error("Error signing typed data with CubeSignService:",s),s}}async signTransaction(t){let e=await this.getCurrent(),r=this.chainType,s=e[0].address;try{return await this.cubeSignService.signTransaction(r,s,t)}catch(a){throw console.error("Error signing transaction with CubeSignService:",a),a}}};var Ct={googleAuth:"tomo-google-authorized",xAuth:"tomo-twitter-authorized",kakaoAuth:"tomo-kakao-authorized",telegramAuth:"tomo-telegram-authorized"},ze=60,It=i(({url:n,name:t,width:e,height:r})=>{let s=(window.innerHeight-(r||400))/2+window.screenY,a=(window.innerWidth-(e||400))/2+window.screenX;try{let o=window.open(n,t,`dialog=yes,top=${s}px,left=${a},width=${e!==void 0?e:400}px,height=${r!==void 0?r:600}px`);return o||null}catch(o){return console.error("Failed to open window:",o),null}},"openWindow"),je=i(({tomoStage:n,xClientId:t,googleClientId:e})=>{let r=S[n];if(!r)throw new Error("Invalid tomo stage");let s=`${r}/x/loader`,a=`${r}/google`,o=M[n],c=H[n];if(!c)throw new Error("Invalid cube stage");let u=cubesignerSdk.envs[o]||cubesignerSdk.envs.gamma,l="https://accounts.google.com/o/oauth2/v2/auth",m=i((d,g=12e4)=>new Promise((b,w)=>{if(!d){w(new Error("Popup window is null"));return}let f=setTimeout(()=>{d.close(),w(new Error("Login timeout"));},g),x=i(async L=>{if(L.origin!==r||L.data.action!=="login")return;let{data:z,type:st}=L.data,F="";try{st===Ct.googleAuth?F=z.code:st===Ct.xAuth&&(F=z?.oidcToken||""),F&&(clearTimeout(f),window.removeEventListener("message",x),d.close(),b(F));}catch(St){clearTimeout(f),window.removeEventListener("message",x),d.close(),w(St);}},"messageHandler");window.addEventListener("message",x);let V=setInterval(()=>{d.closed&&(clearTimeout(f),clearInterval(V),window.removeEventListener("message",x),w(new Error("Login cancelled by user")));},400);}),"waitForOidcToken");return {loginByGoogle:i(async()=>{let d=window.location.origin,g=JSON.stringify({origin:d,action:"login",loadImg:""}),b={client_id:e,state:encodeURIComponent(g),redirect_uri:a,response_type:"id_token",scope:"openid",access_type:"offline",nonce:Date.now().toString(),prompt:"select_account"},w=`${l}?${new URLSearchParams(b).toString()}`,f=It({url:w,name:"Google login"});if(!f)throw new Error("Failed to open popup");return await m(f)},"loginByGoogle"),loginByX:i(async()=>{let g={target:window.location.origin,tomoStage:n,eventId:Date.now().toString(),action:"login",clientId:t},b=`${s}?${new URLSearchParams(g).toString()}`,w=It({url:b,name:"X login"});if(!w)throw new Error("Failed to open popup");return await m(w)},"loginByX"),loginByEmail:i(async d=>{if(!$(d))throw new Error("Invalid email");return {partialOidcToken:await cubistSigSdk.emailLogin(d,u,c),lifeTime:ze}},"loginByEmail")}},"OidcAuth");var Ar=i((n,t,e)=>{let{chainType:r,chainId:s}=t;nt.getInstance().initCubeSignService();let o=new q(t,n),c=mt[r];if(!c)throw new Error(`ChainTypeServices not found for chainType: ${r}`);let u=c.getInstance(r,o,e);return u.wallet_switchEthereumChain([{chainId:s}]),u},"SocialAccount");
2
- exports.ChainTypes=p;exports.CubeConnect=Ve;exports.OidcAuth=je;exports.SocialAccount=Ar;exports.TomoWallet=ee;exports.TxTypes=ht;
package/dist/index.d.cts DELETED
@@ -1,14 +0,0 @@
1
- import { TomoAppInfo } from '@tomo-inc/chains-service';
2
- export { TomoAppInfo as TomoAppConfig, TomoWallet, TransactionItem, TransactionsParams, TransactionsResponse, TxTypes } from '@tomo-inc/chains-service';
3
- import { CubeConnectResult } from '@tomo-inc/cubist-wallet-sdk';
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
- export { EmailLoginResult, LoginType, OidcAuth } from '@tomo-inc/oidc-auth';
8
-
9
- declare const SocialAccount: (accountData: CubeConnectResult, chainConfig: {
10
- chainType: ChainTypes;
11
- chainId: string;
12
- }, tomoAppConfig: TomoAppInfo) => any;
13
-
14
- export { SocialAccount };
package/dist/index.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import { TomoAppInfo } from '@tomo-inc/chains-service';
2
- export { TomoAppInfo as TomoAppConfig, TomoWallet, TransactionItem, TransactionsParams, TransactionsResponse, TxTypes } from '@tomo-inc/chains-service';
3
- import { CubeConnectResult } from '@tomo-inc/cubist-wallet-sdk';
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
- export { EmailLoginResult, LoginType, OidcAuth } from '@tomo-inc/oidc-auth';
8
-
9
- declare const SocialAccount: (accountData: CubeConnectResult, chainConfig: {
10
- chainType: ChainTypes;
11
- chainId: string;
12
- }, tomoAppConfig: TomoAppInfo) => any;
13
-
14
- export { SocialAccount };
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- import {BigNumber}from'bignumber.js';import {createPublicClient,http,isHex,fromHex,parseTransaction,toHex}from'viem';import j from'axios';import Tt from'crypto-js';import {userExportKeygen,userExportDecrypt,envs,CubeSignerClient}from'@cubist-labs/cubesigner-sdk';import {getKeys,signTronRawTransaction,signDogePsbt,signSolanaTransaction,signEvmTransaction,signTronMessage,signDogeMessage,signSolanaMessage,signEvmMessage,signTronTypeDaya,signEvmTypedData,proof,getOidcResp,getOidcClient,emailLogin}from'@tomo-inc/cubist-sig-sdk';var xt=Object.defineProperty;var i=(n,t)=>xt(n,"name",{value:t,configurable:true});var Ot=Object.defineProperty,At=i((n,t)=>{for(var e in t)Ot(n,e,{get:t[e],enumerable:true});},"__export"),Nt={};At(Nt,{clear:i(()=>Bt,"clear"),get:i(()=>Pt,"get"),remove:i(()=>Ut,"remove"),set:i(()=>Mt,"set"),setKeyNS:i(()=>Ft,"setKeyNS")});var A="tomo-";function Pt(n){let t=A+n;if(!Rt(t))return null;let e=null;try{let r=window.localStorage.getItem(t)||window.sessionStorage.getItem(t);e=JSON.parse(r);}catch(r){console.error(r);}return e!==null&&Object.prototype.hasOwnProperty.call(e,"type")&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:null}i(Pt,"get");function Mt(n,t,e){let r;e?r=window.sessionStorage:r=window.localStorage;let s=JSON.stringify({data:t,time:new Date().getTime(),type:typeof t});try{return r.setItem(A+n,s),!0}catch(a){a?.name?.toUpperCase().indexOf("QUOTA")>=0&&(window.localStorage.clear(),r.setItem(A+n,s));}}i(Mt,"set");function Ut(n){let t=A+n;window.localStorage.removeItem(t),window.sessionStorage.removeItem(t);}i(Ut,"remove");function Bt(){window?.localStorage?.clear(),window?.sessionStorage?.clear();}i(Bt,"clear");function Rt(n){return Object.prototype.hasOwnProperty.call(window.localStorage,n)||Object.prototype.hasOwnProperty.call(window.sessionStorage,n)}i(Rt,"isKeyExist");function Ft(n){typeof n=="string"&&n!==""&&(A=n);}i(Ft,"setKeyNS");var T=(n=>(n.BTC="btc",n.DOGE="doge",n.EVM="evm",n.SOL="sol",n.SUI="sui",n.TON="ton",n.TRON="tron",n.COSMOS="cosmos",n.APTOS="aptos",n))(T||{}),O={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 Dt(n,t,e){Object.prototype.toString.call(t)!=="[object Array]"&&(t=[t]);let r=[];for(let a=0,o=t.length;a<o;a++)r.push(s(t[a]));return r.join("");function s(a){return n.replace(/\\?\{([^}]+)\}/g,function(o,c){return o.charAt(0)=="\\"?o.slice(1):a[c]!=null?a[c]:""})}}i(Dt,"subs");function $t(n,t){let e={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}"},r=n.toString(),s=e[r]||"";if(s==="")throw new Error(`chainIndex ${n} tpl not found`);return Dt(s,t)}i($t,"getExplorerUrl");var Ht={prod:"https://wallet-pro.tomo.inc",pre:"https://wallet-pre-wlfi.tomo.inc",dev:"https://wallet-test.tomo.inc"},_t=class{static{i(this,"Networks");}chainType;networkAPIs;constructor(n,t){this.chainType=t||"",this.networkAPIs=n;}setChainType(n){this.chainType=n;}async getNetworks(n){return this.networkAPIs.getAllNetworks(n||"")}async getNetworkByChainId(n){let t=await this.networkAPIs.getNetworkByChainId(n);if(!t)throw new Error("Network not found");return t}async getNetworkByChainIndex(n){let t=await this.networkAPIs.getNetworkByChainIndex(n);if(!t)throw new Error("Network not found");return t}async getCurrentNetwork(){let n=this.chainType,t=await this.networkAPIs.getCurrentNetwork(n);return t===""&&(t=O?.[n]?.chainId||""),this.getNetworkByChainId(t)}async setCurrentNetwork(n){let t=this.chainType||"";return await this.networkAPIs.setCurrentNetwork(t,n),true}},Gt=class{static{i(this,"Tokens");}tokenAPIs;constructor(n){this.tokenAPIs=n;}async searchTokens({chainIndex:n,query:t}){let{data:e=[]}=await this.tokenAPIs.queryRemoteTokens({keyword:t||"",chainIndex:n});return e}async getTokenInfo({address:n,chainIndex:t}){let{data:{data:e}}=await this.tokenAPIs.getTokenInfo({address:n,chainIndex:t});return e}async getTokenRiskInfo(n){let{data:t}=await this.tokenAPIs.getTokenRisk(n);return t}async getTokenDetail(n){let{data:t}=await this.tokenAPIs.getTokenDetail(n);return t}};T.BTC+"",T.COSMOS+"",T.DOGE+"";var Kt=class{static{i(this,"Transactions");}transactionAPIs;constructor(n){this.transactionAPIs=n;}async queryGasInfo({chainType:n,params:t}){try{let e=await this.transactionAPIs.queryGasInfo(n,t);return {success:e?.code===0,data:e?.result||{}}}catch(e){return {success:false,message:e?.message||"Failed to query gas info"}}}async getTransactions(n){let t=await this.transactionAPIs.getTransactions(n),{cursor:e="",transactionList:r=[]}=t||{};return {cursor:e,transactionList:r}}async getTransaction(n){return (await this.transactionAPIs.getTransaction(n))?.data||{}}};function Y(n){let t=Ht[n];if(!t)throw new Error("Invalid tomo stage");return {rpcBaseUrl:`${t}`,walletBaseUrl:`${t}/wallet`,txBaseUrl:`${t}/quote`,tokenBaseUrl:`${t}/token`,userBaseUrl:`${t}/user/api`}}i(Y,"getConfig");var at={prod:Y("prod"),pre:Y("pre"),dev:Y("dev")};function qt(n){let t=Math.floor(Date.now()/1e3).toString(),e=n.method.toUpperCase(),r=n.data?n.data:{};e==="GET"?r=JSON.stringify({key:"value"}):typeof r!="string"&&(r=JSON.stringify(r));let s=[e,n.url,t,r,n.apiKey,n.apiSecret,n.salt].join("");return {signature:Tt.SHA256(s).toString(),timestamp:t}}i(qt,"generateSignature");var Vt=i(n=>`Bearer ${n}`,"formatJwtToken");function Lt(n,t,e){if(typeof e=="string"){let u=e;return Object.assign(n.headers??{},{"client-id":t,Authorization:Vt(u)}),n}let{apiKey:r,apiSecret:s,salt:a}=e,{signature:o,timestamp:c}=qt({method:n.method,url:n.url,data:n.data,apiKey:r,apiSecret:s,salt:a});return Object.assign(n.headers??{},{"X-APP-Key":r,"X-Signature":o,"X-Timestamp":c,"client-id":t}),n}i(Lt,"signRequest");var D=class{static{i(this,"BasePublicService");}tokenApi=j.create();txApi=j.create();walletApi=j.create();apiBase;tomoAppInfo;constructor(n,t){this.apiBase=n,this.tomoAppInfo=t,[this.tokenApi,this.txApi,this.walletApi].map((e,r)=>e.interceptors.request.use(s=>{let{tokenBaseUrl:a,txBaseUrl:o,walletBaseUrl:c}=n;return s.baseURL=[a,o,c][r],Lt(s,t.tomoClientId,t)}));}getSignConfig(){return this.tomoAppInfo}},zt=class ct extends D{static{i(this,"_TokenAPIs");}static instance;constructor(t,e){super(t,e);}static getInstance(t,e){return this.instance||(this.instance=new ct(t,e)),this.instance}async getTokenInfo(t){try{let e=await this.walletApi.get("/v1/balance/getTokenInfo",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to get token info:",e),e}}async getTokenRisk(t){if(typeof t.chainIndex!="number"||!t.tokenAddress)throw new Error("chainName or tokenAddress is required");let e=await this.tokenApi.post("/v1/market/risk/details",[t]);return {success:e?.data?.code==="0",message:e?.data?.msg,data:e?.data?.data?.[0]||null}}async addCustomToken(t){try{let e=await this.walletApi.post("/v1/customTokens/addCustomToken",t,{});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to add custom token:",e),e}}async deleteCustomToken(t){try{let e=await this.walletApi.get("/v1/customTokens/delete",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to delete custom token:",e),e}}async addMultiToken(t){try{let e=await this.walletApi.post("/v1/customTokens/addTokenWithMulti",t,{});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to add multi token:",e),e}}async removeMultiToken(t){try{let e=await this.walletApi.get("/v1/customTokens/hideTokenWithMulti",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data}}catch(e){throw console.error("Failed to delete multi token:",e),e}}async syncCustomToken(t){try{return (await this.walletApi.post("/v1/customTokens/sync",t,{}))?.data||{}}catch(e){throw console.error("Failed to sync custom token:",e),e}}async getTokenBalance(t){try{let e=await this.walletApi.get("/v1/balance/getTokenBalanceWithDetail",{params:t});return {success:e?.data?.code==="00000",message:e?.data?.msg,data:e?.data?.data||null}}catch(e){throw console.error("Failed to get token balance:",e),e}}async getTokenDetail(t){let{chainIndex:e,tokenAddress:r}=t,s=await this.tokenApi.get("/v1/market/token/detail",{params:{tokenAddress:r,chainIndex:e}});return {success:s?.data?.code==="0",message:s?.data?.msg,data:s?.data?.data||null}}async queryRemoteTokens(t){let{keyword:e="",chainIndex:r}=t||{};if(!e)throw new Error("Params is required");let s=await this.tokenApi.get("/v1/market/token/search",{params:{content:e,chainIndex:r}});return {success:s?.data?.code==="0",message:s?.data?.msg,data:s?.data?.data||[]}}},jt=class ut extends D{static{i(this,"_TransactionAPIs");}static instance;constructor(t,e){super(t,e);}static getInstance(t,e){return this.instance||(this.instance=new ut(t,e)),this.instance}async queryGasInfo(t,e){try{return (await this.txApi.post("/api/v1/quote/queryGasInfo",e))?.data||{}}catch(r){throw console.error("Failed to get gas info:",r),r}}async getTransactions(t){try{return (await this.walletApi.get("/v1/transaction/list",{params:t}))?.data?.data||{}}catch(e){throw console.error("Failed to get transactions:",e),e}}async getTransaction(t){try{return (await this.walletApi.get("/v1/transaction/detail",{params:t}))?.data?.data||{}}catch(e){throw console.error("Failed to get transaction:",e),e}}},Yt=class pt extends D{static{i(this,"_WalletAPIs");}static instance;constructor(t,e){super(t,e);}static getInstance(t,e){return this.instance||(this.instance=new pt(t,e)),this.instance}async createWallet(t){try{if(!t)throw new Error("Params is required");return (await this.walletApi.post("/v1/wallet/create",t,{}))?.data||{}}catch(e){if(e?.response?.data?.code==="60003")return {success:false,message:"Wallet already exists",data:null};throw console.error("Failed to create wallet:",e),e}}async syncWallet(t){try{return (await this.walletApi.post("/v1/wallet/sync",t,{}))?.data||{}}catch(e){throw console.error("Failed to sync wallet:",e),e}}async deleteWallet(t){try{return (await this.walletApi.post("/v1/wallet/delete",t,{}))?.data||{}}catch(e){throw console.error("Failed to sync wallet:",e),e}}},Jt=i(n=>[{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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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:[`${n}/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"),Xt=class lt extends D{static{i(this,"_NetworkAPIs");}static instance;chains=[];currentChainId="";constructor(t,e){super(t,e);let r=Jt(t.rpcBaseUrl);this.chains=r.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(t,e){return this.instance||(this.instance=new lt(t,e)),this.instance}getAllNetworks(t){return t===""?this.chains:this.chains.filter(e=>e.platformType===t.toUpperCase())}async getCurrentNetwork(t){if(!O?.[t])throw new Error(`Chain ${t} is not supported`);return this.currentChainId||O?.[t]?.chainId||""}async setCurrentNetwork(t,e){if(t&&!O?.[t])throw new Error(`Chain ${t} is not supported`);this.currentChainId=e;}getNetworkByChainId(t){return this.chains.find(e=>e.chainId===Number(t))}getNetworkByChainIndex(t){return this.chains.find(e=>e.chainIndex===t)}};function Wt(n,t){return {tokenAPIs:zt.getInstance(n,t),transactionAPIs:jt.getInstance(n,t),networkAPIs:Xt.getInstance(n,t),walletAPIs:Yt.getInstance(n,t)}}i(Wt,"tomoPublicApiService");var dt=class{static{i(this,"BaseService");}isDappConnected;approveParams;accountInfo;networks;tokens;transactions;constructor(n,t){if(!n.tomoStage||!at[n.tomoStage])throw new Error("Tomo stage is required");let e=at[n.tomoStage],{tokenAPIs:r,transactionAPIs:s,networkAPIs:a}=Wt(e,n);this.accountInfo=t,this.networks=new _t(a),this.tokens=new Gt(r),this.transactions=new Kt(s),this.isDappConnected=false;}async setApproveParams(n){this.approveParams=n;}};function Zt(n){let{chainId:t,name:e,rpcUrls:r,nativeCurrencyDecimals:s,nativeCurrencyName:a,nativeCurrencySymbol:o}=n,c={id:Number(t)||t,name:e,nativeCurrency:{name:a,symbol:o,decimals:s},rpcUrls:{default:{http:r,webSocket:[]},public:{http:r,webSocket:[]}},blockExplorers:{default:{name:"Explorer",url:r[0]}}};return {rpcClient:createPublicClient({chain:c,pollingInterval:1e4,cacheTime:1e4,transport:http()})}}i(Zt,"getRPCClient");var Q=(n=>(n.EOA="EOA",n.SOCIAL="SOCIAL",n))(Q||{}),ht=(n=>(n[n.swap=1]="swap",n[n.bridge=2]="bridge",n[n.receive=31]="receive",n[n.send=32]="send",n[n.approve=4]="approve",n[n.contractInteraction=5]="contractInteraction",n[n.redPocket=6]="redPocket",n))(ht||{}),Qt=i(n=>n&&n?.platformType==="EVM","isEvmChain"),J=i(({chainId:n,chainType:t})=>{if(isHex(n)){let r=n;return n=fromHex(n,"number").toString(),{chainId:n,chainIdHex:r,chainUid:`${t}:${n}`}}let e=toHex(Number(n));return {chainId:n,chainIdHex:e,chainUid:`${t}:${n}`}},"getAllTypeChainIds"),te=class k extends dt{static{i(this,"_EvmService");}static instance;chainType;constructor(t,e,r){super(r,e),this.chainType=t;}static getInstance(t,e,r){return k.instance||(k.instance=new k(t,e,r)),k.instance}async eth_requestAccounts(){return await this.eth_accounts()}async eth_accounts(){return (await this.accountInfo.getCurrent()).map(e=>e.address)}async eth_chainId(){let t=this.chainType,e=await this.getCurrentChain(),{chainIdHex:r}=J({chainId:e?.chainId,chainType:t});return r}async getCurrentChain(){return this.networks.setChainType(this.chainType),await this.networks.getCurrentNetwork()}async wallet_switchEthereumChain(t){let{chainId:e}=t[0];if(!await this.isChainSupported(e))throw new Error(`Chain ${e} is not supported`);return await this.networks.setCurrentNetwork(e)}async isChainSupported(t){let e=this.chainType,r=J({chainId:t,chainType:e});if(!r.chainId)return false;let s=await this.networks.getNetworkByChainId(r.chainId);return s?Qt(s):false}async personal_sign([t,e]){if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");return await this.accountInfo.signMessage(t)}async eth_signTypedData_v4([t,e]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");return await this.accountInfo.signTypedData(e)}async eth_getBalance([t,e]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");if(e!=="latest")throw new Error("type is not supported");let s=await this.getCurrentChain(),{rpcClient:a}=Zt(s);try{return (await a.getBalance({address:t}))?.toString()||"0"}catch(o){return console.error(o),"0"}}async eth_estimateGas(t){let{from:e,to:r,value:s="0x1"}=t[0]||{};if((await this.accountInfo.getCurrent())[0].address!==e)throw new Error("address is not the current account");if(!r)throw new Error("to is not set");let o=t[0]?.chainId||await this.eth_chainId(),c={chainIndex:Number(o),callData:"0x",gasLimitParam:{from:e,to:r,value:s},addressList:[e]},u=this.chainType,{data:l,success:m,message:h}=await this.transactions.queryGasInfo({chainType:u,params:c});if(!m){console.error("queryGasInfo evm",t,h,l);let{gasFee:f}=O[u];return f.toString()}let y=J({chainId:o,chainType:u}),{nativeCurrencyDecimals:v}=await this.networks.getNetworkByChainId(y.chainId),{baseFee:d=1,gasLimit:g=0}=l,b=new BigNumber(d);return i(f=>{let V=b.plus(l[f]||0).times(g);return toHex(BigInt(V.toNumber()),v)},"calcFee")("priorityFeeMedium")}async createPublicClient({chainId:t,rpcUrl:e}){if(e)return createPublicClient({transport:http(e)});if(t?(this.networks.setChainType(this.chainType),e=(await this.networks.getNetworkByChainId(t)).rpcUrls[0]):e=(await this.getCurrentChain()).rpcUrls[0],!e)throw new Error("rpcUrl is not set");return createPublicClient({transport:http(e)})}async eth_getTransactionCount([t,e]){if((await this.accountInfo.getCurrent())[0].address!==t)throw new Error("address is not the current account");if(e!=="latest"&&e!=="pending")throw new Error("type is not supported");try{return await(await this.createPublicClient({})).getTransactionCount({address:t})}catch(s){throw console.error("Failed to get nonce:",s),new Error(`Failed to get nonce: ${s}`)}}async eth_signTransaction(t){let e={chainId:"number",to:"string",value:"bigint",data:"string",nonce:"number",maxPriorityFeePerGas:"bigint",maxFeePerGas:"bigint",gasLimit:"bigint",gas:"bigint"},r=t?.[0],s=r?.gas||r?.gasLimit;r={...r,gas:s,gasLimit:s},r.data=r.data||"0x";let o=(await this.accountInfo.getCurrent())[0].address;if(r?.from&&r?.from!==o)throw console.error("eth_signTransaction error data: from is not the current account",r),new Error("eth_signTransaction error data: from is not the current account");delete r?.from;let c={type:"eip1559",gas:r?.gasLimit,account:o};for(let u in e){if(!r?.[u]||!isHex(r?.[u]))throw new Error(`${u}: no data or wrong type`);c[u]=e[u]==="number"?fromHex(r[u],"number"):r[u];}try{let u=await this.accountInfo.signTransaction(JSON.stringify({data:c,types:e}));if(u==="")throw new Error(`eth_signTransaction error data: ${JSON.stringify(t)}`);return parseTransaction(u)}catch(u){throw new Error("eth_signTransaction error"+u)}}async eth_sendRawTransaction([t],e){try{return await(await this.createPublicClient({rpcUrl:e})).sendRawTransaction({serializedTransaction:t})}catch(r){throw console.error("Failed to send transaction via RPC:",r,e),r}}async getTransaction(t){if(!t||!isHex(t))throw new Error("txId is not valid");try{return await(await this.createPublicClient({})).getTransaction({hash:t})}catch(e){throw console.error("Failed to send transaction via RPC:",e,t),e}}},ee=class E extends dt{static{i(this,"_TomoWallet");}static instance;walletId;constructor(t,e){super(e),this.walletId=t;}getInstance(t,e){return E.instance||(E.instance=new E(t,e)),new E(t,e)}async supportedChains(t){return await this.networks.getNetworks(t||"")}async getChainInfo(t,e){return this.networks.setChainType(t),await this.networks.getNetworkByChainId(e)}async isChainSupported(t,e){this.networks.setChainType(t);let r=await this.networks.getNetworkByChainId(e);return r?!!r.chainId:false}async getTransactions({tokenAddress:t="",chainId:e="",typeList:r=[],pageLimit:s=20,cursor:a}){if(!this.walletId)throw new Error("walletId is required");try{let o={tokenAddress:t,pageLimit:s+1,walletId:this.walletId,cursor:a};if(r.length>0&&(o.typeList=r.join(",")),e){let y=(await this.networks.getNetworkByChainId(e)).chainIndex;o.chainIndex=y;}let{cursor:c="",transactionList:u}=await this.transactions.getTransactions(o),l=u.map(async h=>{let y=h.chainIndex,v=await this.networks.getNetworkByChainIndex(y);return {chainType:v.platformType.toLowerCase(),chainInfo:{chainId:v.chainId.toString(),name:v.name,icon:v.icon},nativeCurrency:v?.nativeCurrency,tokenInfo:h.tokenInfo,txHash:h.txHash,txDetail:h,txDetailLink:$t(y,{txId:h.txHash}),txTime:h.txTime}}),m=await Promise.all(l);return {cursor:c,transactionList:m}}catch(o){throw console.error("Failed to send transaction via RPC:",o),o}}},mt={[T.EVM]:te};var re=Object.defineProperty,ne=i((n,t)=>{for(var e in t)re(n,e,{get:t[e],enumerable:true});},"__export"),P={};ne(P,{clear:i(()=>ie,"clear"),get:i(()=>se,"get"),remove:i(()=>oe,"remove"),set:i(()=>ae,"set"),setKeyNS:i(()=>ue,"setKeyNS")});var N="tomo-";function se(n){let t=N+n;if(!ce(t))return null;let e=null;try{let r=window.localStorage.getItem(t)||window.sessionStorage.getItem(t);e=JSON.parse(r);}catch(r){console.error(r);}return e!==null&&Object.prototype.hasOwnProperty.call(e,"type")&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:null}i(se,"get");function ae(n,t,e){let r;e?r=window.sessionStorage:r=window.localStorage;let s=JSON.stringify({data:t,time:new Date().getTime(),type:typeof t});try{return r.setItem(N+n,s),!0}catch(a){a?.name?.toUpperCase().indexOf("QUOTA")>=0&&(window.localStorage.clear(),r.setItem(N+n,s));}}i(ae,"set");function oe(n){let t=N+n;window.localStorage.removeItem(t),window.sessionStorage.removeItem(t);}i(oe,"remove");function ie(){window?.localStorage?.clear(),window?.sessionStorage?.clear();}i(ie,"clear");function ce(n){return Object.prototype.hasOwnProperty.call(window.localStorage,n)||Object.prototype.hasOwnProperty.call(window.sessionStorage,n)}i(ce,"isKeyExist");function ue(n){typeof n=="string"&&n!==""&&(N=n);}i(ue,"setKeyNS");var $=i(n=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"isEmail"),p=(n=>(n.BTC="btc",n.DOGE="doge",n.EVM="evm",n.SOL="sol",n.SUI="sui",n.TON="ton",n.TRON="tron",n.COSMOS="cosmos",n.APTOS="aptos",n))(p||{});var M={prod:"prod",pre:"prod",dev:"gamma"},H={prod:"Org#49944bce-9daf-423f-a982-269f6d0d301b",pre:"Org#71c13f6d-b992-4660-874d-2ae0fadc789f",dev:"Org#3d07a75a-1188-4bd0-acfa-671a198b83eb"},S={prod:"https://social-relay.tomo.inc",pre:"https://social-relay.tomo.inc",dev:"https://social-relay-dev.tomo.inc"},tt={prod:"https://wallet-pro.tomo.inc",pre:"https://wallet-pre-wlfi.tomo.inc",dev:"https://wallet-test.tomo.inc"};var G=30*24*60*60,gt={auth:G,refresh:G*2},_=["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"],Ae="Key#Mnemonic_",Ne={"https://accounts.google.com":"google","https://shim.oauth2.cubist.dev/twitter":"x"},Pe={prod:"xnPWRJT5XG2WyevuydMjMpZq",pre:"xnPWRJT5XG2WyevuydMjMpZq",dev:"dev@tomo"},Me=i(n=>{let e={Login:["Fido","EmailOtp","Totp"],RegisterMfa:["Fido",`EmailOtp#${n==="prod"?172800:300}`,"Totp"],Export:["Fido","Totp"]};return {createSession:{method:"POST",path:"/session/",_allowed_mfa_types:e.Login},addFido:{method:"POST",path:"/user/me/fido/",_allowed_mfa_types:e.RegisterMfa},deleteFido:{method:"DELETE",path:"/user/me/fido/",_allowed_mfa_types:e.RegisterMfa},registerTotp:{method:"POST",path:"/user/me/totp/",_allowed_mfa_types:e.RegisterMfa},deleteTotp:{method:"DELETE",path:"/user/me/totp/",_allowed_mfa_types:e.RegisterMfa},registerEmailOtp:{method:"POST",path:"/user/me/email/",_allowed_mfa_types:e.RegisterMfa},initExport:{method:"POST",path:"/user/me/export/",_allowed_mfa_types:e.Export},completeExport:{method:"PATCH",path:"/user/me/export/",_allowed_mfa_types:e.Export}}},"getMfaInfoConfig"),Ue=class U{static{i(this,"_CubeExportService");}constructor(){this.seedPhraseKey="",this.cubeAccountService=null,this.cubeSignerClient=null,this.exportKey=null,userExportKeygen().then(t=>{this.exportKey=t;});}static getInstance(){return U.instance||(U.instance=new U),U.instance}init(t){return this.cubeAccountService=t,this.cubeSignerClient=t.cubeSignerClient,this}async getExportKey(){if(this.seedPhraseKey)return this.seedPhraseKey;let e=(await this.cubeSignerClient?.sessionKeys()||[]).find(r=>r?.id.indexOf(Ae)===0);return this.seedPhraseKey=e?.id||"",this.seedPhraseKey}async getExportInfo(){if(!this.cubeSignerClient)return null;let t=await this.getExportKey(),r=await this.cubeSignerClient?.org()?.exports(t)?.fetch();if(r?.length===0)return {ready:true};let{valid_epoch:s=0,exp_epoch:a=0}=r[0],o=s-Date.now()/1e3;o=Math.max(Math.ceil(o),0);let c=a-s;return {ready:true,keyId:t,lastTime:o,duration:c,valid_epoch:s,exp_epoch:a}}async initExport(t){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");let e=await this.getExportKey(),r=await this.cubeSignerClient.org().initExport(e,t);return r.requiresMfa()?await this.cubeAccountService?.cubeMfaService?.getMfaInfo("initExport")||null:r.data()}async completeExport(t){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");let e=await this.getExportKey(),r=await this.cubeSignerClient.org().completeExport(e,this.exportKey.publicKey,t);if(r.requiresMfa())return await this.cubeAccountService?.cubeMfaService?.getMfaInfo("completeExport")||null;let s=r.data();return await userExportDecrypt(this.exportKey.privateKey,s)}async deleteExport(){if(!this.cubeSignerClient||!this.cubeAccountService)throw new Error("cubeSignerClient is not initialized");try{let t=await this.getExportKey();return {success:!0,data:await this.cubeSignerClient.org().deleteExport(t)}}catch(t){return {success:false,message:t?.message||"delete export error",error:t}}}},K="passkey-relay",Be="cubist-sdk",C=null,Re=i(({url:n,name:t,width:e,height:r})=>{let s=window.ReactNativeWebView;if(s){let c={url:n,name:t};return s.postMessage(JSON.stringify({type:"OPEN_PASSKEY_RELAY",message:c})),{closed:false,postMessage:i(u=>{s.postMessage(JSON.stringify({type:"PASSKEY_RELAY_MESSAGE",message:u}));},"postMessage")}}let a=(window.innerHeight-r)/2+window.screenY,o=(window.innerWidth-e)/2+window.screenX;try{let c=window.open(n,t,`dialog=yes,top=${a}px,left=${o},width=${e!==void 0?e:400}px,height=${r!==void 0?r:600}px`);return c||null}catch(c){return console.error("Failed to open window:",c),null}},"openWindow"),Fe=i(()=>{try{C&&!C.closed&&C.close();}catch(n){console.error("Failed to close window:",n);}finally{C=null;}},"closeWindow"),et=i(async(n,t)=>{if(C===null)throw new Error("Failed to open relay window");let e=S[t]||S.dev;C.postMessage({...n,from:Be},e);},"sendPasskeyMessage"),ft=i(async n=>new Promise((t,e)=>{if(n=n||P.get("cubeConfig"),!n.oidcToken||!n.tomoClientId){e({message:"oidcToken/tomoClientId is required"});return}let r=S[n.tomoStage];if(!r){e({message:"tomoStage must be dev/pre/prod."});return}C=Re({url:`${r}/passkey?origin=${window.location.origin}`,name:"relay-passkey",width:400,height:600});let s=i(a=>{let{type:o,data:c,from:u,error:l}=a.data;o==="passkey-relay-loaded"&&u===K&&et({type:"init",params:n},n.tomoStage),o==="passkey-relay-init"&&u===K&&(window.removeEventListener("message",s),t(c));},"handleMessage");window.addEventListener("message",s);}),"initPasskeyPage"),De=i(async(n,t)=>(C||await ft(t),new Promise((e,r)=>{let s=i(a=>{let{type:o,data:c,from:u,error:l}=a.data;o==="passkey-relay-addFido"&&u===K&&(window.removeEventListener("message",s),e(c));},"handleMessage");window.addEventListener("message",s),et({type:"addFido",params:n},t.tomoStage);})),"addPasskey"),$e=i(async(n,t)=>(C||await ft(t),new Promise((e,r)=>{let s=i(a=>{let{type:o,data:c,from:u,error:l}=a.data;o==="passkey-relay-verify"&&u===K&&(window.removeEventListener("message",s),e(c));},"handleMessage");window.addEventListener("message",s),et({type:"verify",params:n},t.tomoStage);})),"verifyPasskey"),wt=i((n,t,{userId:e,rpId:r,fidoName:s})=>{r=r||window.location.hostname;let{host:a,protocol:o}=window.location,c=o!=="https:"&&o!=="http:",u=a.indexOf("localhost:")===0;t.options=t?.options||{},t.options.rp=t.options.rp||{},t.options.rp.id=r,t.options.rpId=r,(c||u)&&(t?.options?.rp?.id&&delete t.options.rp.id,t?.options?.rpId&&delete t.options.rpId),t.options.timeout=6e4,t.options.attestation="none";let l=t.options?.user||{};return n==="add"&&(l.id=l.id||new TextEncoder().encode(e),l.name=s,l.displayName=s),t.options.user=l,t},"applyLocalDevFixes"),He=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(t){return this.cubeSignerClient=t.cubeSignerClient,this.apiClient=t.apiClient,this.cubeAccountService=t,this}setMfaType(t){if(!t)throw new Error("mfaType is required");this.mfaType=t;}setMfaAnswer(t){this.mfaAnswer=t;}async getMfaInfo(t){if(!t)throw new Error("mfaRequestType is required");let r=Me(this.cubeAccountService?.config?.cubeStage||"gamma")[t];if(!r)throw new Error("mfaRequestType is not supported");let{method:s,path:a}=r,c=(await this.apiClient.mfaList()).find(d=>{let g=d?.request.method,b=d?.request.path+"/";return g===s&&b.indexOf(a)>-1});if(!c)return null;let u=null,l=c?.status?.allowed_mfa_types||[];for(let d of l){u=u||{};let g=d.toLowerCase().split("#");u[g[0]]=g[1]?Number(g[1]):true;}let{receipt:m,created_at:h}=c,y=0;if(typeof u.emailOtp=="number"){let d=u.emailOtp-(Date.now()/1e3-h);y=Math.max(0,Math.ceil(d));}return u.emailOtp&&(u.emailOtpRemainTime=y),{...c,verifyStatus:m!==null?"approved":"pending",mfaRequired:u}}async answerRegister(t){let e=this.registerChallenge;if(!e)throw new Error("challenge is required");try{let r=await e.answer(t)||null;return this.registerChallenge=null,{success:!0,data:r}}catch(r){return {success:false,message:r?.message||"answer error",error:r}}}async executeBizWithMfa(t,e){if(!t)throw new Error("bizType is required");if(e||(e=await this.getMfaInfo(t)||null),!e?.id)throw new Error("mfa not exists, please create mfa first");let{success:r,data:s}=await this.approvalMfa(e?.id||"")||{};if(!r)return {success:false,message:`approval with ${this.mfaType} error.`};if(t==="createSession"){let o=await this.cubeAccountService?.createSession(s);return {success:!!o,message:o?"":"create session error",data:o}}if(t==="addFido"){let o=e.request?.body?.name,c=await this.addFido(o,s);return {success:!!c,message:c?"":"addFido error",data:c}}if(t==="deleteFido"){let c=(e?.request?.path||"").split("/user/me/fido/")[1]||"";if(!c)throw new Error("fidoId is required");let u=await this.deleteFido(decodeURIComponent(c),s);return {success:!!u,message:u?"":"deleteFido error",data:u}}if(t==="registerTotp"){let o=e.request?.body?.issuer,c=await this.registerTotp(o,s);return {success:!!c,message:c?"":"registerTotp error",data:c}}if(t==="deleteTotp"){let o=await this.deleteTotp(s);return {success:!!o,message:o?"":"deleteTotp error",data:o}}if(t==="registerEmailOtp"){let o=e.request?.body?.email,c=await this.registerEmailOtp(o,s);return {success:!!c,message:c?"":"registerEmailOtp error",data:c}}let a=this.cubeAccountService?.cubeExportService;if(t==="initExport"){let o=await a?.initExport(s);return {success:!!o,message:o?"":"init export error",data:o}}if(t==="completeExport"){let o=await a?.completeExport(s);return {success:!!o,message:o?"":"complete export error",data:o}}return {success:false,message:"bizType is not supported"}}async approvalMfa(t){let e={totp:"approvalTotp",emailOtp:"approvalEmailOtp",fido:"approvalFido"},r=this.mfaType;if(!r||!e[r])return {success:false,message:"mfaType is required"};let s=null;try{switch(r){case "totp":s=await this.approvalTotp(t);break;case "emailOtp":s=await this.approvalEmailOtp(t);break;case "fido":s=await this.approvalFido(t);break;default:return {success:!1,message:"Unsupported MFA type"}}}catch(a){return {success:false,message:`approval ${r} error: ${a instanceof Error?a.message:"Unknown error"}`}}return s?{success:true,data:s}:{success:false,message:`approval ${r} error.`}}getPasskeyConfig(){let{config:t}=this.cubeAccountService||{};return delete t?.cubeSalt,delete t?.jwtToken,t}passkeyClear(){Fe();}async addFido(t,e){let r=this.getPasskeyConfig();return await De({fidoName:t,receipt:e},r)}async addFidoLocal(t,e){if(!t||typeof t!="string")throw new Error("name is required");try{let r=await this.cubeAccountService?.getMfaConfig();if((r?.fido?.data||[]).find(m=>m?.name===t))throw new Error(`FIDO key with name "${t}" already exists`);let c=await this.cubeSignerClient?.addFido(t,e);if(c.requiresMfa())return await this.getMfaInfo("addFido");let u={userId:r?.account?.userId,rpId:this.cubeAccountService?.config?.rpId||window.location.hostname,fidoName:t};return await wt("add",c.data(),u).createCredentialAndAnswer(),!0}catch(r){return console.error("addFido error",r),false}}async deleteFido(t,e){try{let s=await this.cubeSignerClient?.deleteFido(t,e);return s.requiresMfa()?await this.getMfaInfo("deleteFido"):s.data()}catch{return null}}async approvalFido(t){let e=this.getPasskeyConfig();return await $e({mfaId:t},e)}async approvalFidoLocal(t){let e=this.apiClient,r=await this.cubeAccountService?.getMfaConfig(),s=await e.mfaFidoInit(t),a={userId:r?.account?.userId,rpId:this.cubeAccountService?.config?.rpId||window.location.hostname,fidoName:""};return s=wt("approval",s,a),await(await s.createCredentialAndAnswer("approve")).receipt()}async registerTotp(t,e){if(t==="")throw new Error("issuer are required");let r=await this.apiClient.userTotpResetInit(t,e);if(r.requiresMfa())return await this.getMfaInfo("registerTotp");let s=r.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")||t}}async deleteTotp(t){let e=await this.apiClient.userTotpDelete(t);return e.requiresMfa()?await this.getMfaInfo("deleteTotp"):e.data()}async approvalTotp(t){if(!t)throw new Error("MFA ID not found");let e=this.mfaAnswer?.totpCode;if(!e||!/^\d{6}$/.test(e))throw console.error("TOTP code is required"),new Error("TOTP code is required");let r=await this.apiClient.mfaVoteTotp(t,e,"approve"),s=this.cubeSignerClient?.org()?.id||this.cubeAccountService?.cubeOrgId||"";return {mfaId:r.id,mfaConf:r?.receipt?.confirmation,mfaOrgId:s}}async registerEmailOtp(t,e){if(!t||!$(t))throw new Error("email is required");let s=(await this.cubeAccountService?.getOidcClient()).apiClient,a={email:t,allow_otp_login:true},o=await s.userEmailResetInit(a,e);return o.requiresMfa()?await this.getMfaInfo("registerEmailOtp"):(this.registerChallenge=o.data(),this.registerChallenge)}async approvalEmailOtp(t){if(!t)throw new Error("MFA ID not found");if(!this.mfaChallenge){let r=await this.apiClient.mfaVoteEmailInit(t,"approve");return this.mfaChallenge=r,null}let e=this.mfaAnswer?.emailCode||"";if(e=e.split(/\s/).join(""),!e)throw new Error("emailCode is required");try{let r=await this.mfaChallenge.answer(e),s=this.cubeSignerClient?.org()?.id||this.cubeAccountService?.cubeOrgId||"",a={mfaId:r.id,mfaConf:r?.receipt?.confirmation,mfaOrgId:s};return this.mfaChallenge=null,a}catch(r){return console.warn("approvalEmailOtp error",r),null}}async sendEmailCode(t){if(!t)throw new Error("mfaId is required");try{let e=await this.apiClient.mfaVoteEmailInit(t,"approve");return this.mfaChallenge=e,!0}catch{return false}}},_e=i((n,t)=>{try{let{data:e,types:r}=JSON.parse(n);for(let s in r)r[s]==="bigint"&&(e[s]=BigInt(e[s]),t==="string"&&(e[s]=e[s].toString()));return e}catch{throw new Error("Invalid unsigned transaction")}},"recoverEVMTxData"),rt=class R{static{i(this,"_CubeSignService");}async init({cubeSession:t}){this.cubeSession=t,this.services||(this.services=await getKeys(t));}static getInstance(){return R.instance||(R.instance=new R),R.instance}async getServiceByChainAndAddress(t,e){this.services||(this.services=await getKeys(this.cubeSession));let r=this.buildKeyId(t,e),s=this.services.find(a=>a.id===r);return s||(console.warn(`service not found for chainType: ${t}`),null)}buildKeyId(t,e){switch(t){case p.EVM:return `Key#${e}`;case p.TRON:return `Key#Tron_${e}`;case p.SOL:return `Key#Solana_${e}`;case p.DOGE:return `Key#Doge_${e}`;default:return `Key#${e}`}}async signTransaction(t,e,r){let s=this?.cubeSession,a=await this.getServiceByChainAndAddress(t,e);if(!a)throw new Error(`service not found for chain ${t}`);let o=typeof r=="string"?JSON.parse(r):r;switch(t){case p.EVM:{let c=_e(r,"string");return await signEvmTransaction(a,c,c.chainId,s)}case p.SOL:return await signSolanaTransaction(a,o.rawTransaction,s);case p.DOGE:return await signDogePsbt(a,o.psbtBase64,s);case p.TRON:{let c=o.data?.rawTransaction||o.rawTransaction;return await signTronRawTransaction(a,c,s)}default:throw new Error(`Unsupported chain type: ${t}`)}}async signMessage(t,e,r){let s=this?.cubeSession,a=await this.getServiceByChainAndAddress(t,e);if(!a)throw new Error(`service not found for chain ${t}`);switch(t){case p.EVM:return await signEvmMessage(a,r,s);case p.SOL:return await signSolanaMessage(a,r,s);case p.DOGE:return (await signDogeMessage(a,r,s)).signature;case p.TRON:return await signTronMessage(a,r,s);default:throw new Error(`Unsupported chain type: ${t}`)}}async signTypedData(t,e,r){let s=this?.cubeSession,a=await this.getServiceByChainAndAddress(t,e);if(!a)throw new Error(`service not found for chain ${t}`);switch(t){case p.EVM:return await signEvmTypedData(a,r,s);case p.TRON:return await signTronTypeDaya(a,r.message,s);default:throw new Error(`Unsupported chain type: ${t}`)}}},Ge=i(async(n,t)=>{if(!t)throw new Error("salt is required");let e=Date.now().toString(),r={...n,timestamp:e},s=JSON.stringify(r),a=Tt.SHA256(s+t).toString();return {timestamp:e,signature:a}},"generateCubeSignature");function vt(n){let{tomoStage:t="dev",tomoClientId:e,jwtToken:r}=n,s=j.create({baseURL:`${tt[t]||tt.dev}/user`,timeout:2e4});return s.interceptors.request.use(async a=>(a.headers["client-id"]=e,r&&(a.headers.Authorization=`Bearer ${r}`),a),a=>{if(a?.response?.status===401)return Promise.reject(a)}),s}i(vt,"getTomoApi");var Ke=i(async(n,t)=>{let{iss:e,sub:r}=n,s=t.cubeSalt||"";if(!s)throw new Error("tomoStage error.");let{timestamp:a,signature:o}=await Ge({iss:e,sub:r},s),c={...n,timestamp:a,signature:o};return (await vt(t).post("/api/login/loginByCubistV2",c))?.data?.data||{}},"addUserToCube"),qe=i(async(n,t)=>{let e=vt(t),s=(await e.post("/api/user/getUserInfo"))?.data?.data.user||{},a=n.nickname.trim();return n={...s,...n,nickname:a,username:a},!!(await e.post("/api/setting/updateUserInfo",n,{headers:{}}))?.data?.success},"updateUserInfo"),nt=class I{static{i(this,"_CubeAccountService");}constructor(t){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=t,this.cubeEnv=null;}static getInstance(t){if(I.instance)return I.instance;if(!t?.tomoStage||!M[t?.tomoStage])throw new Error("tomoStage not 'dev' or 'pre' or 'prod'");let e=Pe[t?.tomoStage];if(!e)throw new Error("cubeSalt is required");let r=M[t?.tomoStage],s=envs[r],a=H[t?.tomoStage];return I.instance=new I({...t,cubeSalt:e,cubeStage:r}),I.instance.cubeEnv=s,I.instance.cubeOrgId=a,I.instance}async getCubeIdentity(){let t=this?.config?.oidcToken;if(!t){let s=await P.get("cubeIdentity");return s?(this.cubeIdentity=s,this.cubeIdentity):(console.warn("oidcToken is required"),null)}let e=this.cubeOrgId,r=await proof(t,this.cubeEnv,e);return await P.set("cubeIdentity",r,false),this.cubeIdentity=r,r}async loginOrRegister(t,e){this.config={...this.config,oidcToken:t};let r=await this.getCubeIdentity(),s={cubistUserID:r?.user_info?.user_id,aud:r?.aud,email:r?.email||e?.email||null,iss:r?.identity?.iss,sub:r?.identity?.sub,initialized:r?.user_info?.initialized},a=await Ke(s,this.config),{userToken:o,user:c,accountBaseInfo:u,accountWallet:l}=a;return this.accountData=a,this.accountWallet=l,this.jwtToken=o.accessToken,{user:{userId:c.userID,nickname:c.nickname,avatar:c.avatar},accountBaseInfo:u,accountWallet:l,walletId:l?.walletID}}async updateUserInfo(t){let e=t.nickname.trim();if(e.length<6||e.length>20)throw new Error("name length 6~20");let r={...this.config,jwtToken:this.jwtToken};return await qe(t,r)}async createSessionByOidcToken(t){if(t=t||this?.config?.oidcToken||"",!t)return console.warn("oidcToken is required"),false;let e=_,s=(await getOidcResp(t,this.cubeEnv,this.cubeOrgId,G,e)).data();return this.setCubeSession(s),!!s}async createSession(t){let r=await this.apiClient.sessionCreateExtended("wallet_operations",_,gt,t);if(r.requiresMfa())return await this.cubeMfaService?.getMfaInfo("createSession")||null;let s=r.data();return this.setCubeSession(s),!!s}async refreshSession(){let r=(await this.apiClient.sessionCreate("wallet_operations",_,gt)).data();return this.setCubeSession(r),!!r}getCubeSession(){return this.cubeSession}setCubeSession(t){this.cubeSession=t;}sessionRevoke(){let t=this.apiClient;this.cubeSession=null,t?.sessionRevoke();}async refreshCubeClient(t){try{await this.createCubeSignerClient(t),this.initSubServices();}catch(e){console.error("refreshCubeClient error",e);}}async createCubeSignerClient(t){let e=await CubeSignerClient.create(t);return this.cubeSignerClient=e,this.apiClient=this.cubeSignerClient.apiClient,e}async getOidcClient(t){let e=this?.config?.oidcToken||"";if(!e){console.warn("oidcToken is required");return}let r=_;return await getOidcClient(e,this.cubeEnv,this.cubeOrgId,G,r,t)}async autoLogin(t){await this.refreshCubeClient(t),await this.setCubeSession(t);}async init(t){if(t=t||this?.config?.oidcToken||"",!t)return console.warn("oidcToken is required"),false;try{this.config={...this.config,oidcToken:t};let e=await this.getOidcClient();if(this.cubeSignerClient=e,this.apiClient=this.cubeSignerClient.apiClient,!await this.createSessionByOidcToken(t))throw new Error("create session by oidc token failed");return this.initSubServices(),!0}catch(e){throw console.error("init error",e),e}}async initSubServices(){let t=He.getInstance();this.cubeMfaService=t.init(this);let e=Ue.getInstance();this.cubeExportService=e.init(this);}async initCubeSignService(){let t=this.getCubeSession(),e=rt.getInstance();return await e.init({cubeSession:t}),e}async getCubeUserInfo(){try{let t=await this.apiClient?.userGet();return this.cubeUserInfo=t,t}catch{return null}}async getMfaConfig(){let[t,e]=await Promise.all([this.getCubeUserInfo(),this.getCubeIdentity()]),r=t?.name||e?.preferred_username||"",s=e?.identity?.iss||"",a=Ne?.[s]||"email",o=t?.verified_email?.email||"",c=t?.email||"",u=o!==""||c!=="",l=t?.mfa||[],m=l.filter(y=>y.type==="fido"),h=l.filter(y=>y.type==="totp");return {noMfa:!u&&m.length===0&&h.length===0,hasMfa:u||m.length>0||h.length>0,account:{name:r,email:c,otpEmail:o,accountType:a,userId:t?.user_id||""},emailOtp:{data:c||o,enabled:u},fido:{data:m,enabled:m.length>0},totp:{data:h[0],enabled:h.length>0}}}},Ve=i(async n=>{let t=nt.getInstance(n);if(!n.oidcToken)throw new Error("oidcToken is required");await t.loginOrRegister(n.oidcToken),await t.init(n.oidcToken);let e=t.cubeMfaService,r=t.cubeExportService;return {cubeAccount:t,cubeMfa:e,cubeExport:r}},"CubeConnect");var q=class{static{i(this,"CubeSocialAccount");}chainType;chainId;cubeSignService;accountData;userAPIs;constructor({chainType:t,chainId:e},r){this.chainType=t,this.chainId=e,this.accountData=r,this.cubeSignService=rt.getInstance();}async getAllAccounts(){let{accountWallet:t,user:e}=this.accountData||{},r={[p.EVM]:[{address:t?.ethereumAddress,publicKey:"",subType:p.EVM,path:""}],[p.DOGE]:[{address:t?.dogeAddress,publicKey:"",subType:p.DOGE,path:""}],[p.SOL]:[{address:t?.solanaAddress,publicKey:"",subType:p.SOL,path:""}],[p.TRON]:[{address:t?.tronAddress,publicKey:"",subType:p.TRON,path:""}],[p.BTC]:[{address:t?.bitcoinP2trAddressMain,publicKey:t?.bitcoinP2trPubKeyMain,subType:"TAPROOT",stage:"MAIN",path:"m/86'/0'/0'/0/0"},{address:t?.bitcoinP2trAddressTest,publicKey:t?.bitcoinP2trPubKeyTest,subType:"TAPROOT",stage:"TEST",path:"m/86'/1'/0'/0/0"},{address:t?.bitcoinP2shAddressMain,publicKey:t?.bitcoinP2shPubKeyMain,subType:"NESTED_SEGWIT",stage:"MAIN",path:"m/49'/0'/0'/0/0"},{address:t?.bitcoinP2shAddressTest,publicKey:t?.bitcoinP2shPubKeyTest,subType:"NESTED_SEGWIT",stage:"TEST",path:"m/49'/1'/0'/0/0"},{address:t?.bitcoinP2wpkhAddressMain,publicKey:t?.bitcoinP2wpkhPubKeyMain,subType:"NATIVE_SEGWIT",stage:"MAIN",path:"m/84'/0'/0'/0/0"},{address:t?.bitcoinP2wpkhAddressTest,publicKey:t?.bitcoinP2wpkhPubKeyTest,subType:"NATIVE_SEGWIT",stage:"TEST",path:"m/84'/0'/0'/0/0"},{address:t?.bitcoinP2pkhAddressMain,publicKey:t?.bitcoinP2pkhPubKeyMain,subType:"LEGACY",stage:"MAIN",path:"m/44'/0'/0'/0/0"},{address:t?.bitcoinP2pkhAddressTest,publicKey:t?.bitcoinP2pkhPubKeyTest,subType:"LEGACY",stage:"TEST",path:"m/44'/1'/0'/0/0"}],[p.SUI]:[{address:t?.suiAddress,publicKey:"",subType:p.SUI,path:""}],[p.TON]:[{address:t?.tonAddress,publicKey:"",subType:p.TON,path:""}],[p.COSMOS]:[{address:t?.cosmosAddress,publicKey:"",subType:p.COSMOS,path:""}],[p.APTOS]:[{address:t?.aptosAddress,publicKey:"",subType:p.APTOS,path:""}]};return {id:e.accountID,name:e.nickname,type:Q.SOCIAL,lastUsedTime:e.lastUsedTime,addresses:r,mnemonic:null,addressIndex:0,isImported:false,isBackedUp:false,isLocked:false,isFrozen:false}}async getCurrent(){let t=this.chainType,e=await this.getAllAccounts(),{address:r,publicKey:s,path:a,subType:o}=e?.addresses?.[t]?.[0]||{};return [{subType:o,address:r,path:a,publicKey:s,type:e.type,id:e.id}]}async signMessage(t){let e=await this.getCurrent(),r=this.chainType;try{let s=e[0].address;return await this.cubeSignService.signMessage(r,s,t)}catch(s){throw console.error("Error signing message with CubeSignService:",s),s}}async signTypedData(t){let e=await this.getCurrent(),r=this.chainType;try{let s=e[0].address;return await this.cubeSignService.signTypedData(r,s,t)}catch(s){throw console.error("Error signing typed data with CubeSignService:",s),s}}async signTransaction(t){let e=await this.getCurrent(),r=this.chainType,s=e[0].address;try{return await this.cubeSignService.signTransaction(r,s,t)}catch(a){throw console.error("Error signing transaction with CubeSignService:",a),a}}};var Ct={googleAuth:"tomo-google-authorized",xAuth:"tomo-twitter-authorized",kakaoAuth:"tomo-kakao-authorized",telegramAuth:"tomo-telegram-authorized"},ze=60,It=i(({url:n,name:t,width:e,height:r})=>{let s=(window.innerHeight-(r||400))/2+window.screenY,a=(window.innerWidth-(e||400))/2+window.screenX;try{let o=window.open(n,t,`dialog=yes,top=${s}px,left=${a},width=${e!==void 0?e:400}px,height=${r!==void 0?r:600}px`);return o||null}catch(o){return console.error("Failed to open window:",o),null}},"openWindow"),je=i(({tomoStage:n,xClientId:t,googleClientId:e})=>{let r=S[n];if(!r)throw new Error("Invalid tomo stage");let s=`${r}/x/loader`,a=`${r}/google`,o=M[n],c=H[n];if(!c)throw new Error("Invalid cube stage");let u=envs[o]||envs.gamma,l="https://accounts.google.com/o/oauth2/v2/auth",m=i((d,g=12e4)=>new Promise((b,w)=>{if(!d){w(new Error("Popup window is null"));return}let f=setTimeout(()=>{d.close(),w(new Error("Login timeout"));},g),x=i(async L=>{if(L.origin!==r||L.data.action!=="login")return;let{data:z,type:st}=L.data,F="";try{st===Ct.googleAuth?F=z.code:st===Ct.xAuth&&(F=z?.oidcToken||""),F&&(clearTimeout(f),window.removeEventListener("message",x),d.close(),b(F));}catch(St){clearTimeout(f),window.removeEventListener("message",x),d.close(),w(St);}},"messageHandler");window.addEventListener("message",x);let V=setInterval(()=>{d.closed&&(clearTimeout(f),clearInterval(V),window.removeEventListener("message",x),w(new Error("Login cancelled by user")));},400);}),"waitForOidcToken");return {loginByGoogle:i(async()=>{let d=window.location.origin,g=JSON.stringify({origin:d,action:"login",loadImg:""}),b={client_id:e,state:encodeURIComponent(g),redirect_uri:a,response_type:"id_token",scope:"openid",access_type:"offline",nonce:Date.now().toString(),prompt:"select_account"},w=`${l}?${new URLSearchParams(b).toString()}`,f=It({url:w,name:"Google login"});if(!f)throw new Error("Failed to open popup");return await m(f)},"loginByGoogle"),loginByX:i(async()=>{let g={target:window.location.origin,tomoStage:n,eventId:Date.now().toString(),action:"login",clientId:t},b=`${s}?${new URLSearchParams(g).toString()}`,w=It({url:b,name:"X login"});if(!w)throw new Error("Failed to open popup");return await m(w)},"loginByX"),loginByEmail:i(async d=>{if(!$(d))throw new Error("Invalid email");return {partialOidcToken:await emailLogin(d,u,c),lifeTime:ze}},"loginByEmail")}},"OidcAuth");var Ar=i((n,t,e)=>{let{chainType:r,chainId:s}=t;nt.getInstance().initCubeSignService();let o=new q(t,n),c=mt[r];if(!c)throw new Error(`ChainTypeServices not found for chainType: ${r}`);let u=c.getInstance(r,o,e);return u.wallet_switchEthereumChain([{chainId:s}]),u},"SocialAccount");
2
- export{p as ChainTypes,Ve as CubeConnect,je as OidcAuth,Ar as SocialAccount,ee as TomoWallet,ht as TxTypes};