@getpara/core-sdk 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/cjs/.!4420!index.js.br +0 -0
  2. package/dist/cjs/.!4422!index.js.gz +0 -0
  3. package/dist/cjs/index.js +2 -97
  4. package/dist/cjs/index.js.br +0 -0
  5. package/dist/cjs/index.js.gz +0 -0
  6. package/dist/esm/.!4417!index.js.br +0 -0
  7. package/dist/esm/.!4419!index.js.gz +0 -0
  8. package/dist/esm/index.js +2 -23
  9. package/dist/esm/index.js.br +0 -0
  10. package/dist/esm/index.js.gz +0 -0
  11. package/dist/types/ParaCore.d.ts +8 -1
  12. package/package.json +7 -7
  13. package/dist/cjs/ParaCore.js +0 -2606
  14. package/dist/cjs/PlatformUtils.js +0 -2
  15. package/dist/cjs/StorageUtils.js +0 -2
  16. package/dist/cjs/constants.js +0 -20
  17. package/dist/cjs/cryptography/utils.js +0 -251
  18. package/dist/cjs/errors.js +0 -27
  19. package/dist/cjs/external/mpcComputationClient.js +0 -33
  20. package/dist/cjs/external/userManagementClient.js +0 -66
  21. package/dist/cjs/package.json +0 -1
  22. package/dist/cjs/shares/KeyContainer.js +0 -84
  23. package/dist/cjs/shares/recovery.js +0 -62
  24. package/dist/cjs/shares/shareDistribution.js +0 -67
  25. package/dist/cjs/transmission/transmissionUtils.js +0 -73
  26. package/dist/cjs/types/config.js +0 -22
  27. package/dist/cjs/types/events.js +0 -17
  28. package/dist/cjs/types/index.js +0 -30
  29. package/dist/cjs/types/onRamps.js +0 -10
  30. package/dist/cjs/types/params.js +0 -2
  31. package/dist/cjs/types/popup.js +0 -12
  32. package/dist/cjs/types/recovery.js +0 -12
  33. package/dist/cjs/types/theme.js +0 -2
  34. package/dist/cjs/types/wallet.js +0 -9
  35. package/dist/cjs/utils/events.js +0 -9
  36. package/dist/cjs/utils/formatting.js +0 -81
  37. package/dist/cjs/utils/index.js +0 -22
  38. package/dist/cjs/utils/onRamps.js +0 -36
  39. package/dist/cjs/utils/polling.js +0 -25
  40. package/dist/cjs/utils/url.js +0 -74
  41. package/dist/cjs/utils/wallet.js +0 -74
  42. package/dist/esm/ParaCore.js +0 -2576
  43. package/dist/esm/PlatformUtils.js +0 -1
  44. package/dist/esm/StorageUtils.js +0 -1
  45. package/dist/esm/constants.js +0 -17
  46. package/dist/esm/cryptography/utils.js +0 -226
  47. package/dist/esm/errors.js +0 -21
  48. package/dist/esm/external/mpcComputationClient.js +0 -26
  49. package/dist/esm/external/userManagementClient.js +0 -56
  50. package/dist/esm/package.json +0 -1
  51. package/dist/esm/shares/KeyContainer.js +0 -57
  52. package/dist/esm/shares/recovery.js +0 -58
  53. package/dist/esm/shares/shareDistribution.js +0 -63
  54. package/dist/esm/transmission/transmissionUtils.js +0 -45
  55. package/dist/esm/types/config.js +0 -19
  56. package/dist/esm/types/events.js +0 -14
  57. package/dist/esm/types/index.js +0 -9
  58. package/dist/esm/types/onRamps.js +0 -7
  59. package/dist/esm/types/params.js +0 -1
  60. package/dist/esm/types/popup.js +0 -9
  61. package/dist/esm/types/recovery.js +0 -9
  62. package/dist/esm/types/theme.js +0 -1
  63. package/dist/esm/types/wallet.js +0 -6
  64. package/dist/esm/utils/events.js +0 -5
  65. package/dist/esm/utils/formatting.js +0 -66
  66. package/dist/esm/utils/index.js +0 -6
  67. package/dist/esm/utils/onRamps.js +0 -30
  68. package/dist/esm/utils/polling.js +0 -21
  69. package/dist/esm/utils/url.js +0 -66
  70. package/dist/esm/utils/wallet.js +0 -64
File without changes
File without changes
package/dist/cjs/index.js CHANGED
@@ -1,97 +1,2 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
19
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
20
- };
21
- var __importStar = (this && this.__importStar) || function (mod) {
22
- if (mod && mod.__esModule) return mod;
23
- var result = {};
24
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25
- __setModuleDefault(result, mod);
26
- return result;
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.paraVersion = exports.transmissionUtilsRetrieve = exports.getPortalBaseURL = exports.toAssetInfoArray = exports.getOnRampNetworks = exports.getOnRampAssets = exports.isWalletSupported = exports.publicKeyFromHex = exports.decryptPrivateKeyWithPassword = exports.encryptPrivateKeyWithPassword = exports.hashPasswordWithSalt = exports.decryptPrivateKeyAndDecryptShare = exports.decryptPrivateKey = exports.encryptPrivateKey = exports.getSHA256HashHex = exports.getPublicKeyFromSignature = exports.getDerivedPrivateKeyAndDecrypt = exports.encodePrivateKeyToPemHex = exports.encryptWithDerivedPublicKey = exports.getPublicKeyHex = exports.getAsymmetricKeyPair = exports.decryptWithPrivateKey = exports.decryptWithKeyPair = exports.mpcComputationClient = exports.initClient = exports.getBaseUrl = exports.KeyContainer = exports.distributeNewShare = exports.STORAGE_PREFIX = exports.entityToWallet = exports.stringToPhoneNumber = exports.getPortalDomain = exports.RecoveryStatus = exports.PregenIdentifierType = exports.PopupType = exports.OnRampMethod = exports.PREGEN_IDENTIFIER_TYPES = exports.NON_ED25519 = exports.OAuthMethod = exports.OnRampPurchaseStatus = exports.OnRampProvider = exports.OnRampPurchaseType = exports.OnRampAsset = exports.WalletScheme = exports.WalletType = exports.Network = exports.EmailTheme = exports.AuthMethod = void 0;
30
- const ParaCore_js_1 = require("./ParaCore.js");
31
- var user_management_client_1 = require("@getpara/user-management-client");
32
- Object.defineProperty(exports, "AuthMethod", { enumerable: true, get: function () { return user_management_client_1.AuthMethod; } });
33
- Object.defineProperty(exports, "EmailTheme", { enumerable: true, get: function () { return user_management_client_1.EmailTheme; } });
34
- Object.defineProperty(exports, "Network", { enumerable: true, get: function () { return user_management_client_1.Network; } });
35
- Object.defineProperty(exports, "WalletType", { enumerable: true, get: function () { return user_management_client_1.WalletType; } });
36
- Object.defineProperty(exports, "WalletScheme", { enumerable: true, get: function () { return user_management_client_1.WalletScheme; } });
37
- Object.defineProperty(exports, "OnRampAsset", { enumerable: true, get: function () { return user_management_client_1.OnRampAsset; } });
38
- Object.defineProperty(exports, "OnRampPurchaseType", { enumerable: true, get: function () { return user_management_client_1.OnRampPurchaseType; } });
39
- Object.defineProperty(exports, "OnRampProvider", { enumerable: true, get: function () { return user_management_client_1.OnRampProvider; } });
40
- Object.defineProperty(exports, "OnRampPurchaseStatus", { enumerable: true, get: function () { return user_management_client_1.OnRampPurchaseStatus; } });
41
- Object.defineProperty(exports, "OAuthMethod", { enumerable: true, get: function () { return user_management_client_1.OAuthMethod; } });
42
- Object.defineProperty(exports, "NON_ED25519", { enumerable: true, get: function () { return user_management_client_1.NON_ED25519; } });
43
- Object.defineProperty(exports, "PREGEN_IDENTIFIER_TYPES", { enumerable: true, get: function () { return user_management_client_1.PREGEN_IDENTIFIER_TYPES; } });
44
- var index_js_1 = require("./types/index.js");
45
- Object.defineProperty(exports, "OnRampMethod", { enumerable: true, get: function () { return index_js_1.OnRampMethod; } });
46
- Object.defineProperty(exports, "PopupType", { enumerable: true, get: function () { return index_js_1.PopupType; } });
47
- Object.defineProperty(exports, "PregenIdentifierType", { enumerable: true, get: function () { return index_js_1.PregenIdentifierType; } });
48
- Object.defineProperty(exports, "RecoveryStatus", { enumerable: true, get: function () { return index_js_1.RecoveryStatus; } });
49
- __exportStar(require("./types/events.js"), exports);
50
- __exportStar(require("./types/config.js"), exports);
51
- var index_js_2 = require("./utils/index.js");
52
- Object.defineProperty(exports, "getPortalDomain", { enumerable: true, get: function () { return index_js_2.getPortalDomain; } });
53
- Object.defineProperty(exports, "stringToPhoneNumber", { enumerable: true, get: function () { return index_js_2.stringToPhoneNumber; } });
54
- Object.defineProperty(exports, "entityToWallet", { enumerable: true, get: function () { return index_js_2.entityToWallet; } });
55
- var constants_js_1 = require("./constants.js");
56
- Object.defineProperty(exports, "STORAGE_PREFIX", { enumerable: true, get: function () { return constants_js_1.PREFIX; } });
57
- var shareDistribution_js_1 = require("./shares/shareDistribution.js");
58
- Object.defineProperty(exports, "distributeNewShare", { enumerable: true, get: function () { return shareDistribution_js_1.distributeNewShare; } });
59
- var KeyContainer_js_1 = require("./shares/KeyContainer.js");
60
- Object.defineProperty(exports, "KeyContainer", { enumerable: true, get: function () { return KeyContainer_js_1.KeyContainer; } });
61
- var userManagementClient_js_1 = require("./external/userManagementClient.js");
62
- Object.defineProperty(exports, "getBaseUrl", { enumerable: true, get: function () { return userManagementClient_js_1.getBaseUrl; } });
63
- Object.defineProperty(exports, "initClient", { enumerable: true, get: function () { return userManagementClient_js_1.initClient; } });
64
- exports.mpcComputationClient = __importStar(require("./external/mpcComputationClient.js"));
65
- var utils_js_1 = require("./cryptography/utils.js");
66
- Object.defineProperty(exports, "decryptWithKeyPair", { enumerable: true, get: function () { return utils_js_1.decryptWithKeyPair; } });
67
- Object.defineProperty(exports, "decryptWithPrivateKey", { enumerable: true, get: function () { return utils_js_1.decryptWithPrivateKey; } });
68
- Object.defineProperty(exports, "getAsymmetricKeyPair", { enumerable: true, get: function () { return utils_js_1.getAsymmetricKeyPair; } });
69
- Object.defineProperty(exports, "getPublicKeyHex", { enumerable: true, get: function () { return utils_js_1.getPublicKeyHex; } });
70
- Object.defineProperty(exports, "encryptWithDerivedPublicKey", { enumerable: true, get: function () { return utils_js_1.encryptWithDerivedPublicKey; } });
71
- Object.defineProperty(exports, "encodePrivateKeyToPemHex", { enumerable: true, get: function () { return utils_js_1.encodePrivateKeyToPemHex; } });
72
- Object.defineProperty(exports, "getDerivedPrivateKeyAndDecrypt", { enumerable: true, get: function () { return utils_js_1.getDerivedPrivateKeyAndDecrypt; } });
73
- Object.defineProperty(exports, "getPublicKeyFromSignature", { enumerable: true, get: function () { return utils_js_1.getPublicKeyFromSignature; } });
74
- Object.defineProperty(exports, "getSHA256HashHex", { enumerable: true, get: function () { return utils_js_1.getSHA256HashHex; } });
75
- Object.defineProperty(exports, "encryptPrivateKey", { enumerable: true, get: function () { return utils_js_1.encryptPrivateKey; } });
76
- Object.defineProperty(exports, "decryptPrivateKey", { enumerable: true, get: function () { return utils_js_1.decryptPrivateKey; } });
77
- Object.defineProperty(exports, "decryptPrivateKeyAndDecryptShare", { enumerable: true, get: function () { return utils_js_1.decryptPrivateKeyAndDecryptShare; } });
78
- Object.defineProperty(exports, "hashPasswordWithSalt", { enumerable: true, get: function () { return utils_js_1.hashPasswordWithSalt; } });
79
- Object.defineProperty(exports, "encryptPrivateKeyWithPassword", { enumerable: true, get: function () { return utils_js_1.encryptPrivateKeyWithPassword; } });
80
- Object.defineProperty(exports, "decryptPrivateKeyWithPassword", { enumerable: true, get: function () { return utils_js_1.decryptPrivateKeyWithPassword; } });
81
- Object.defineProperty(exports, "publicKeyFromHex", { enumerable: true, get: function () { return utils_js_1.publicKeyFromHex; } });
82
- __exportStar(require("./external/userManagementClient.js"), exports);
83
- __exportStar(require("./errors.js"), exports);
84
- __exportStar(require("./utils/formatting.js"), exports);
85
- __exportStar(require("./utils/polling.js"), exports);
86
- var wallet_js_1 = require("./utils/wallet.js");
87
- Object.defineProperty(exports, "isWalletSupported", { enumerable: true, get: function () { return wallet_js_1.isWalletSupported; } });
88
- var onRamps_js_1 = require("./utils/onRamps.js");
89
- Object.defineProperty(exports, "getOnRampAssets", { enumerable: true, get: function () { return onRamps_js_1.getOnRampAssets; } });
90
- Object.defineProperty(exports, "getOnRampNetworks", { enumerable: true, get: function () { return onRamps_js_1.getOnRampNetworks; } });
91
- Object.defineProperty(exports, "toAssetInfoArray", { enumerable: true, get: function () { return onRamps_js_1.toAssetInfoArray; } });
92
- var url_js_1 = require("./utils/url.js");
93
- Object.defineProperty(exports, "getPortalBaseURL", { enumerable: true, get: function () { return url_js_1.getPortalBaseURL; } });
94
- var transmissionUtils_js_1 = require("./transmission/transmissionUtils.js");
95
- Object.defineProperty(exports, "transmissionUtilsRetrieve", { enumerable: true, get: function () { return transmissionUtils_js_1.retrieve; } });
96
- exports.paraVersion = ParaCore_js_1.ParaCore.version;
97
- exports.default = ParaCore_js_1.ParaCore;
1
+ var wt=Object.create;var z=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var Ke=(i,e)=>{for(var t in e)z(i,t,{get:e[t],enumerable:!0})},ke=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pt(e))!Tt.call(i,s)&&s!==t&&z(i,s,{get:()=>e[s],enumerable:!(r=It(e,s))||r.enumerable});return i};var W=(i,e,t)=>(t=i!=null?wt(At(i)):{},ke(e||!i||!i.__esModule?z(t,"default",{value:i,enumerable:!0}):t,i)),Wt=i=>ke(z({},"__esModule",{value:!0}),i);var Yt={};Ke(Yt,{AuthMethod:()=>h.AuthMethod,EmailTheme:()=>h.EmailTheme,EnabledFlow:()=>je,Environment:()=>He,KeyContainer:()=>v,NON_ED25519:()=>h.NON_ED25519,Network:()=>h.Network,OAuthMethod:()=>h.OAuthMethod,OnRampAsset:()=>h.OnRampAsset,OnRampMethod:()=>Ie,OnRampProvider:()=>h.OnRampProvider,OnRampPurchaseStatus:()=>h.OnRampPurchaseStatus,OnRampPurchaseType:()=>h.OnRampPurchaseType,PREGEN_IDENTIFIER_TYPES:()=>h.PREGEN_IDENTIFIER_TYPES,ParaEvent:()=>g,PopupType:()=>ee,PregenIdentifierType:()=>we,RecoveryStatus:()=>Pe,STORAGE_PREFIX:()=>f,TransactionReviewDenied:()=>F,TransactionReviewError:()=>J,TransactionReviewTimeout:()=>V,WalletScheme:()=>h.WalletScheme,WalletType:()=>h.WalletType,decimalToHex:()=>Lt,decryptPrivateKey:()=>xe,decryptPrivateKeyAndDecryptShare:()=>nt,decryptPrivateKeyWithPassword:()=>Oe,decryptWithKeyPair:()=>st,decryptWithPrivateKey:()=>G,default:()=>Jt,distributeNewShare:()=>_,encodePrivateKeyToPemHex:()=>ie,encryptPrivateKey:()=>et,encryptPrivateKeyWithPassword:()=>ot,encryptWithDerivedPublicKey:()=>H,entityToWallet:()=>b,getAsymmetricKeyPair:()=>D,getBaseMPCNetworkUrl:()=>Ft,getBaseOAuthUrl:()=>be,getBaseUrl:()=>Le,getCosmosAddress:()=>Se,getDerivedPrivateKeyAndDecrypt:()=>it,getOnRampAssets:()=>$e,getOnRampNetworks:()=>Ve,getPortalBaseURL:()=>R,getPortalDomain:()=>Ae,getPublicKeyFromSignature:()=>tt,getPublicKeyHex:()=>L,getSHA256HashHex:()=>Re,hashPasswordWithSalt:()=>at,hexStringToBase64:()=>Rt,hexToDecimal:()=>bt,hexToSignature:()=>xt,hexToUint8Array:()=>Ot,initClient:()=>ne,isWalletSupported:()=>re,mpcComputationClient:()=>ae,normalizePhoneNumber:()=>Ee,paraVersion:()=>jt,publicKeyFromHex:()=>ze,stringToPhoneNumber:()=>K,toAssetInfoArray:()=>Z,transmissionUtilsRetrieve:()=>mt,truncateAddress:()=>Q,waitUntilTrue:()=>Ut});module.exports=Wt(Yt);var fe=require("buffer"),p=require("@getpara/user-management-client"),Et=W(require("node-forge"));var Xe=W(require("base64url")),w=W(require("node-forge"));function y(i,e,t){typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent(i,{detail:{data:e,...t&&{error:new Error(t)}}}))}var De=require("@cosmjs/encoding"),Ge=require("@noble/hashes/sha256"),Be=require("@noble/hashes/ripemd160"),Me=W(require("elliptic")),Fe=W(require("libphonenumber-js")),Ct=new Me.default.ec("secp256k1");function Rt(i){return i.substring(0,2)==="0x"&&(i=i.substring(2)),Buffer.from(i,"hex").toString("base64")}function xt(i){return{r:`0x${i.slice(2,66)}`,s:`0x${i.slice(66,130)}`,v:BigInt(i.slice(130,132))}}function Ot(i){return i.startsWith("0x")&&(i=i.slice(2)),new Uint8Array(Buffer.from(i,"hex"))}function bt(i){return i.startsWith("0x")&&(i=i.slice(2)),`${parseInt(i,16)}`}function Lt(i){return`0x${parseInt(i).toString(16)}`}function vt(i){switch(i.length){case 33:return i;case 65:return Uint8Array.from(Ct.keyFromPublic(i).getPublic(!0,"array"));default:throw new Error("Invalid pubkey length")}}function _t(i){if(i.length!==33)throw new Error(`Invalid Secp256k1 pubkey length (compressed): ${i.length}`);return(0,Be.ripemd160)((0,Ge.sha256)(i))}function Se(i,e){let t=new Uint8Array(Buffer.from(i.startsWith("0x")?i.slice(2):i,"hex")),r=vt(t);return(0,De.toBech32)(e,_t(r))}function Q(i,e,{prefix:t=e==="COSMOS"?"cosmos":void 0}={}){let r=(e==="COSMOS"?t.length:e==="SOLANA"?0:2)+4;return`${i.slice(0,r)}...${i.slice(-4)}`}function K(i){return(0,Fe.default)(i)?.formatInternational().replace(/[^\d+]/g,"")}function Ee(i,e){return K(`${i[0]!=="+"?"+":""}${i}${e}`)}function Z(i){let e=[];return Object.keys(i).forEach(t=>{let r=i[t];Object.keys(r).forEach(s=>{let n=r[s];Object.keys(n).forEach(o=>{let a=n[o];e.push([t,s,o,a])})})}),e}function Ve(i,{walletType:e,allowed:t}={}){return[...new Set(Z(i).filter(([r,s])=>(!e||r===e)&&(!t||t.includes(s))).map(([r,s])=>s))]}function $e(i,{walletType:e,network:t,allowed:r}={}){return[...new Set(Z(i).filter(([s,n,o])=>(!e||s===e)&&(!t||n===t)&&(!Array.isArray(r)||r.includes(o))).map(([,,s])=>s))]}async function Ut(i,e,t){let r=Date.now();for(;Date.now()-r<e;){if(await i())return!0;await new Promise(s=>setTimeout(s,t))}return!1}var He=(o=>(o.DEV="DEV",o.SANDBOX="SANDBOX",o.BETA="BETA",o.PROD="PROD",o.DEVELOPMENT="BETA",o.PRODUCTION="PROD",o))(He||{}),je=(r=>(r.BUY="BUY",r.RECEIVE="RECEIVE",r.WITHDRAW="WITHDRAW",r))(je||{});var we=(t=>(t.EMAIL="EMAIL",t.PHONE="PHONE",t))(we||{});var Ie=(s=>(s.ACH="ACH",s.DEBIT="Debit",s.CREDIT="Credit",s.APPLE_PAY="Apple Pay",s))(Ie||{});var ee=(o=>(o.SIGN_TRANSACTION_REVIEW="SIGN_TRANSACTION_REVIEW",o.SIGN_MESSAGE_REVIEW="SIGN_MESSAGE_REVIEW",o.LOGIN_PASSKEY="LOGIN_PASSKEY",o.CREATE_PASSKEY="CREATE_PASSKEY",o.OAUTH="OAUTH",o.ON_RAMP_TRANSACTION="ON_RAMP_TRANSACTION",o))(ee||{});var Pe=(n=>(n.INITIATED="INITIATED",n.READY="READY",n.EXPIRED="EXPIRED",n.FINISHED="FINISHED",n.CANCELLED="CANCELLED",n))(Pe||{});var C="para",g=(d=>(d.LOGIN_EVENT=`${C}Login`,d.ACCOUNT_CREATION_EVENT=`${C}AccountCreation`,d.ACCOUNT_SETUP_EVENT=`${C}AccountSetup`,d.LOGOUT_EVENT=`${C}Logout`,d.SIGN_MESSAGE_EVENT=`${C}SignMessage`,d.SIGN_TRANSACTION_EVENT=`${C}SignTransaction`,d.EXTERNAL_WALLET_CHANGE_EVENT=`${C}ExternalWalletChange`,d.WALLETS_CHANGE_EVENT=`${C}WalletsChange`,d.WALLET_CREATED=`${C}WalletCreated`,d.PREGEN_WALLET_CLAIMED=`${C}PregenWalletClaimed`,d))(g||{});function Ae(i,e){if(e)return"localhost";switch(i){case"DEV":return"localhost";case"SANDBOX":return"app.sandbox.usecapsule.com";case"BETA":return"app.beta.usecapsule.com";case"PROD":return"app.usecapsule.com";default:throw new Error(`env: ${i} not supported`)}}function R({env:i,isE2E:e},t,r){if(e)return r?"https://app.sandbox.usecapsule.com":"http://localhost:3003";let s=Ae(i);return i==="DEV"?t?"http://127.0.0.1:3003":`http://${s}:3003`:`https://${s}`}function Nt(i){switch(i){case"DEV":return"localhost";case"SANDBOX":return"connect.sandbox.getpara.com";case"BETA":return"connect.beta.getpara.com";case"PROD":return"connect.getpara.com";default:throw new Error(`env: ${i} not supported`)}}function Je({env:i},e){let t=Nt(i);return i==="DEV"?e?"http://127.0.0.1:3008":`http://${t}:3008`:`https://${t}`}function te({base:i,path:e,params:t={}}){let r=new URL(e,i);return Object.entries(t).forEach(([s,n])=>{n&&n!=="undefined"&&n!=="null"&&r.searchParams.set(s,n.toString())}),r.toString()}var E=require("@getpara/user-management-client");var x={[E.WalletScheme.DKLS]:{[E.WalletType.EVM]:!0,[E.WalletType.COSMOS]:!0},[E.WalletScheme.CGGMP]:{[E.WalletType.EVM]:!0,[E.WalletType.COSMOS]:!0},[E.WalletScheme.ED25519]:{[E.WalletType.SOLANA]:!0}};function Ye(i,e,t){if(!i||!e)return!1;switch(t){case"EMAIL":return i.toLowerCase()===e.toLowerCase();case"PHONE":return K(i)===K(e);case"CUSTOM_ID":return i===e;default:return i.replace(/^@/g,"").toLowerCase()===e.replace(/^@/g,"").toLowerCase()}}function re(i,e){return i.some(t=>!!x[e.scheme][t])}function Te(i){return Object.keys(x).filter(e=>e===E.WalletScheme.CGGMP?!1:(Array.isArray(i)?i:Object.keys(i)).some(t=>x[e][t]))}function Kt(i){return[...new Set(i.reduce((e,t)=>[...e,...Object.keys(x[t]).filter(r=>x[t][r])],[]))]}function We(i){return Kt(Te((Array.isArray(i)?i:[i]).map(e=>E.WalletType[e])))}function b(i){return{...i,scheme:i.scheme,type:i.type,pregenIdentifierType:i.pregenIdentifierType}}function k(i){return["USER","PREGEN"].includes(i.type)&&(i.isPregen=i.type==="PREGEN",i.type=i.scheme===E.WalletScheme.ED25519?E.WalletType.SOLANA:E.WalletType.EVM),i.scheme&&!i.type&&(i.type=i.scheme===E.WalletScheme.ED25519?E.WalletType.SOLANA:E.WalletType.EVM),i}var kt=w.default.pki.rsa,Ce="RSA-OAEP",qe="794241bc819a125a7b78ea313decc0bc",se=new Uint8Array([23,66,157,146,179,158,117,120,184,73,123,81]);function Re(i){let e=w.default.md.sha256.create();return e.update(i),e.digest().toHex()}function L(i){let e=w.default.pki.publicKeyToRSAPublicKeyPem(i.publicKey);return Buffer.from(e,"utf-8").toString("hex")}function ze(i){let e=Qe(i);return w.default.pki.publicKeyFromPem(e)}function Qe(i){return Buffer.from(i,"hex").toString("utf-8")}function ie(i){let e=w.default.pki.privateKeyToPem(i.privateKey);return Buffer.from(e,"utf-8").toString("hex")}function Ze(i){let e=Buffer.from(i,"hex").toString("utf-8");return w.default.pki.privateKeyFromPem(e)}async function et(i,e){let t=ie(i),r=await window.crypto.subtle.importKey("raw",Buffer.from(e,"base64"),{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),s=new TextEncoder().encode(t),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:se},r,s);return Buffer.from(n).toString("base64")}async function xe(i,e){let t=await crypto.subtle.importKey("raw",Buffer.from(e,"base64"),{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:se},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return Ze(s)}async function D(i,e){let t=w.default.random.createInstance();e&&(t.seedFileSync=s=>e,t.seedFile=(s,n)=>{n(null,e)});let r={bits:2048,e:65537,prng:t};if(!i.disableWorkers){r.workLoad=100,r.workers=e?1:-1;let s=await fetch(`${R(i)}/static/js/prime.worker.min.js`),n=new Blob([await s.text()],{type:"application/javascript"});r.workerScript=URL.createObjectURL(n)}return new Promise((s,n)=>kt.generateKeyPair(r,(o,a)=>{o&&n(o),s(a)}))}async function tt(i,e){let t=Xe.default.encode(e),r=await D(i,t);return L(r)}function Dt(i){let e=w.default.random.getBytesSync(16),t=w.default.cipher.createCipher("AES-CBC",e);t.start({iv:qe}),t.update(w.default.util.createBuffer(i)),t.finish();let r=t.output.toHex();return{key:e,encryptedMessageHex:r}}function rt(i,e){let t=w.default.cipher.createDecipher("AES-CBC",i);return t.start({iv:qe}),t.update(w.default.util.createBuffer(w.default.util.hexToBytes(e))),t.finish(),t.output.toString()}function st(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.privateKey.decrypt(r,Ce);return rt(s,e)}function G(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.decrypt(r,Ce);return rt(s,e)}async function Gt(i,{seedValue:e,encryptedMessageHex:t,encryptedKeyHex:r}){let s=await D(i,e);return G(s.privateKey,t,r)}async function it(i,e,t){return Promise.all(t.map(async r=>({walletId:r.walletId,walletScheme:r.walletScheme,partnerId:r.partnerId,signer:await Gt(i,{seedValue:e,encryptedMessageHex:r.encryptedShare,encryptedKeyHex:r.encryptedKey}),protocolId:r.protocolId})))}async function nt(i,e,t){let r;try{r=await xe(t,i)}catch{}try{r=await Oe(t,i)}catch{}if(!r)throw new Error("Could not decrypt private key");return e.map(s=>({walletId:s.walletId,walletScheme:s.walletScheme,partnerId:s.partnerId,signer:G(r,s.encryptedShare,s.encryptedKey),protocolId:s.protocolId}))}function H(i,e){let{key:t,encryptedMessageHex:r}=Dt(e),s=Qe(i),o=w.default.pki.publicKeyFromPem(s).encrypt(t,Ce),a=Buffer.from(o,"utf-8").toString("hex");return{encryptedMessageHex:r,encryptedKeyHex:a}}function at(i){let e=Bt(),t=e+i,r=Re(t);return{salt:e,hash:r}}function Bt(i=16){return w.default.util.bytesToHex(w.default.random.getBytesSync(i))}async function Mt(i){let e=Buffer.from(i,"hex");return await window.crypto.subtle.importKey("raw",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function ot(i,e){let t=await Mt(e),r=ie(i),s=new TextEncoder().encode(r),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:se},t,s);return Buffer.from(n).toString("base64")}async function Oe(i,e){let t=await crypto.subtle.importKey("raw",Buffer.from(e,"hex"),{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:se},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return Ze(s)}var lt=W(require("@getpara/user-management-client"));function be(i){switch(i){case"DEV":return"http://localhost:8080/";case"SANDBOX":return"https://api.sandbox.usecapsule.com/";case"BETA":return"https://api.beta.usecapsule.com/";case"PROD":return"https://api.usecapsule.com/";default:throw new Error(`unsupported env: ${i}`)}}function Le(i){switch(i){case"DEV":return"http://localhost:8080/";case"SANDBOX":return"https://api.sandbox.getpara.com/";case"BETA":return"https://api.beta.getpara.com/";case"PROD":return"https://api.getpara.com/";default:throw new Error(`unsupported env: ${i}`)}}function Ft(i,e){let t=e?"ws":"http";switch(i){case"DEV":return`${t}://localhost:3000`;case"SANDBOX":return`${t}s://mpc-network.sandbox.getpara.com`;case"BETA":return`${t}s://mpc-network.beta.getpara.com`;case"PROD":return`${t}s://mpc-network.prod.getpara.com`;default:throw new Error(`unsupported env: ${i}`)}}function ne({env:i,version:e,apiKey:t,partnerId:r,useFetchAdapter:s=!1,retrieveSessionCookie:n,persistSessionCookie:o}){return new lt.default({userManagementHost:Le(i),version:["DEV","SANDBOX"].includes(i)?"dev":e,apiKey:t,partnerId:r,opts:{useFetchAdapter:s},retrieveSessionCookie:n,persistSessionCookie:o})}var ae={};Ke(ae,{initClient:()=>ve});var ct=W(require("axios"));function ve(i,e){let t=ct.default.create({baseURL:i});return e&&(t.defaults.adapter=function(r){return fetch(r.baseURL+r.url,{method:r.method,headers:r.headers,body:r.data,credentials:r.withCredentials?"include":void 0}).then(s=>s.text().then(n=>({data:n,status:s.status,statusText:s.statusText,headers:s.headers,config:r,request:fetch}))).catch(function(s){throw s})}),t}var M=require("@getpara/user-management-client");var B=require("@getpara/user-management-client");var j=require("@celo/utils/lib/ecies.js"),pt=W(require("ethereumjs-util")),dt=W(require("node-forge")),v=class i{constructor(e,t,r){this.walletId=e,this.keyshare=t,this.address=r,this.backupDecryptionKey=Buffer.from(dt.random.getBytesSync(32),"binary").toString("hex")}static buildFrom(e){try{let t=JSON.parse(e);return Object.assign(new i("","",""),t)}catch{let r=new i("","","");return r.backupDecryptionKey=e.split("|")[0],r}}getPublicEncryptionKey(){return Buffer.from(pt.privateToPublic(Buffer.from(this.backupDecryptionKey,"hex")))}getPublicEncryptionKeyHex(){return this.getPublicEncryptionKey().toString("hex")}encryptForSelf(e){try{let t=this.getPublicEncryptionKey();return(0,j.Encrypt)(t,Buffer.from(e,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}static encryptWithPublicKey(e,t){try{return(0,j.Encrypt)(e,Buffer.from(t,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}decrypt(e){try{let t=Buffer.from(e,"base64"),r=(0,j.Decrypt)(Buffer.from(this.backupDecryptionKey,"hex"),t);return Buffer.from(r.buffer).toString("ucs2")}catch{throw Error("Error decrypting backup")}}};async function oe({ctx:i,userId:e,walletId:t,otherEncryptedShares:r=[],userSigner:s,ignoreRedistributingBackupEncryptedShare:n=!1,emailProps:o={},forceRefresh:a=!1}){if(n)return await i.client.uploadUserKeyShares(e,r.map(I=>({walletId:t,...I}))),"";let l,c,{recoveryPublicKeys:d}=await i.client.getRecoveryPublicKeys(e);if(a||!d?.length){c=new v(t,"","");let{recoveryPublicKeys:I}=await i.client.persistRecoveryPublicKeys(e,[c.getPublicEncryptionKeyHex()]),S=c.encryptForSelf(s);l=[{walletId:t,encryptedShare:S,type:B.KeyShareType.USER,encryptor:B.EncryptorType.RECOVERY,recoveryPublicKeyId:I[0].id}]}else l=d.map(I=>{let{id:S,publicKey:m}=I,A=v.encryptWithPublicKey(Buffer.from(m,"hex"),s);return{walletId:t,encryptedShare:A,type:B.KeyShareType.USER,encryptor:B.EncryptorType.RECOVERY,recoveryPublicKeyId:S}});return await i.client.uploadUserKeyShares(e,[...r.map(I=>({walletId:t,...I})),...n?[]:l]),await i.client.distributeParaShare({userId:e,walletId:t,useDKLS:i.useDKLS,...o}),c?JSON.stringify(c):""}async function _({ctx:i,userId:e,walletId:t,userShare:r,ignoreRedistributingBackupEncryptedShare:s=!1,emailProps:n={},partnerId:o,protocolId:a}){let c=(await i.client.getSessionPublicKeys(e)).data.keys.map(m=>{if(!m.publicKey)return;let{encryptedMessageHex:A,encryptedKeyHex:u}=H(m.sigDerivedPublicKey,r);return{encryptedShare:A,encryptedKey:u,type:M.KeyShareType.USER,encryptor:M.EncryptorType.BIOMETRICS,biometricPublicKey:m.sigDerivedPublicKey,partnerId:o,protocolId:a}}).filter(Boolean),I=(await i.client.getPasswords({userId:e})).map(m=>{if(m.status==="PENDING")return;let{encryptedMessageHex:A,encryptedKeyHex:u}=H(m.sigDerivedPublicKey,r);return{encryptedShare:A,encryptedKey:u,type:M.KeyShareType.USER,encryptor:M.EncryptorType.PASSWORD,passwordId:m.id,partnerId:o,protocolId:a}}).filter(Boolean),S=[...c,...I];return await oe({ctx:i,userId:e,walletId:t,otherEncryptedShares:S,userSigner:r,ignoreRedistributingBackupEncryptedShare:s,emailProps:n})}var le=require("@celo/utils/lib/ecies.js"),U=require("buffer"),ut=W(require("ethereumjs-util")),ht=require("crypto");async function gt(i,e){let t,r;for(;;)try{t=(0,ht.randomBytes)(32).toString("hex"),r=ut.privateToPublic(U.Buffer.from(t,"hex"));break}catch{continue}let s=U.Buffer.from(r),n=(0,le.Encrypt)(s,U.Buffer.from(i,"ucs2")).toString("base64"),{data:{id:o}}=await e.tempTrasmissionInit(n);return encodeURIComponent(o+"|"+t)}async function mt(i,e){let[t,r]=decodeURIComponent(i).split("|"),n=(await e.tempTrasmission(t)).data.message,o=U.Buffer.from(n,"base64");return U.Buffer.from((0,le.Decrypt)(U.Buffer.from(r,"hex"),o).buffer).toString("ucs2")}var J=class extends Error{constructor(e){super("transaction review error"),this.name="TransactionReviewError",this.transactionReviewUrl=e}},F=class extends Error{constructor(){super("transaction review has been denied by the user"),this.name="TransactionReviewDenied"}},V=class extends Error{constructor(e,t){super("transaction review has timed out"),this.name="TransactionReviewTimeout",this.transactionReviewUrl=e,this.pendingTransactionId=t}};var yt='1.3.0',f="@CAPSULE/",ce=`${f}e-mail`,pe=`${f}phone`,de=`${f}countryCode`,ft=`${f}farcasterUsername`,ue=`${f}telegramUserId`,he=`${f}userId`,Y=`${f}ed25519Wallets`,N=`${f}wallets`,ge=`${f}externalWallets`,me=`${f}currentWalletIds`,ye=`${f}currentExternalWalletAddresses`,$=`${f}sessionCookie`,X=`${f}loginEncryptionKeyPair`,O=2e3,_e=1e3;typeof global<"u"?global.Buffer=global.Buffer||fe.Buffer:typeof window<"u"?(window.Buffer=window.Buffer||fe.Buffer,window.global=window.global||window):(self.Buffer=self.Buffer||fe.Buffer,self.global=self.global||self);var{pki:St,jsbn:Ht}=Et.default,q=class i{constructor(e,t,r){this.isAwaitingAccountCreation=!1;this.isAwaitingLogin=!1;this.isAwaitingFarcaster=!1;this.isAwaitingOAuth=!1;this.currentWalletIds={};this.#e=void 0;this.#t=void 0;this.localStorageGetItem=e=>this.platformUtils.localStorage.get(e);this.localStorageSetItem=(e,t)=>this.platformUtils.localStorage.set(e,t);this.sessionStorageGetItem=e=>this.platformUtils.sessionStorage.get(e);this.sessionStorageSetItem=(e,t)=>this.platformUtils.sessionStorage.set(e,t);this.sessionStorageRemoveItem=e=>this.platformUtils.sessionStorage.removeItem(e);this.retrieveSessionCookie=()=>this.sessionCookie;this.clearStorage=async(e="all")=>{let t=e==="all";(t||e==="local")&&this.platformUtils.localStorage.clear(f),(t||e==="session")&&this.platformUtils.sessionStorage.clear(f),(t||e==="secure")&&this.platformUtils.secureStorage&&this.platformUtils.secureStorage.clear(f)};this.createWalletPerMissingType=this.createWalletPerType;r||(r={}),this.emailPrimaryColor=r.emailPrimaryColor,this.emailTheme=r.emailTheme,this.homepageUrl=r.homepageUrl,this.supportUrl=r.supportUrl,this.xUrl=r.xUrl,this.githubUrl=r.githubUrl,this.linkedinUrl=r.linkedinUrl,this.portalBackgroundColor=r.portalBackgroundColor,this.portalPrimaryButtonColor=r.portalPrimaryButtonColor,this.portalTextColor=r.portalTextColor,this.portalPrimaryButtonTextColor=r.portalPrimaryButtonTextColor,this.portalTheme=r.portalTheme,this.platformUtils=this.getPlatformUtils(),this.disableProviderModal=this.platformUtils.disableProviderModal,r.useStorageOverrides&&(this.localStorageGetItem=r.localStorageGetItemOverride,this.localStorageSetItem=r.localStorageSetItemOverride,this.sessionStorageGetItem=r.sessionStorageGetItemOverride,this.sessionStorageSetItem=r.sessionStorageSetItemOverride,this.sessionStorageRemoveItem=r.sessionStorageRemoveItemOverride,this.clearStorage=r.clearStorageOverride),r.useSessionStorage&&(this.localStorageGetItem=this.sessionStorageGetItem,this.localStorageSetItem=this.sessionStorageSetItem),this.persistSessionCookie=u=>{this.sessionCookie=u,(r.useSessionStorage?this.sessionStorageSetItem:this.localStorageSetItem)($,u)},this.ctx={env:e,apiKey:t,client:ne({env:e,version:i.version,apiKey:t,partnerId:this.isPortal(e)?r.portalPartnerId:void 0,useFetchAdapter:!!r.disableWorkers,retrieveSessionCookie:this.retrieveSessionCookie,persistSessionCookie:this.persistSessionCookie}),disableWorkers:r.disableWorkers,offloadMPCComputationURL:r.offloadMPCComputationURL,useLocalFiles:r.useLocalFiles,useDKLS:r.useDKLSForCreation||!r.offloadMPCComputationURL,disableWebSockets:!!r.disableWebSockets,wasmOverride:r.wasmOverride,cosmosPrefix:this.cosmosPrefix},r.offloadMPCComputationURL&&(this.ctx.mpcComputationClient=ve(r.offloadMPCComputationURL,r.disableWorkers));try{this.#e=r.supportedWalletTypes?(()=>{if(Object.values(r.supportedWalletTypes).every(u=>!!u&&typeof u=="object"&&u.optional))throw new Error("at least one wallet type must be non-optional");if(!Object.keys(r.supportedWalletTypes).every(u=>Object.values(p.WalletType).includes(u)))throw new Error("unsupported wallet type");return this.#t=r.supportedWalletTypes,Object.entries(r.supportedWalletTypes).reduce((u,[P,T])=>T?(P===p.WalletType.COSMOS&&typeof T=="object"&&T.prefix&&(this.cosmosPrefix=T.prefix),[...u,{type:P,optional:T===!0?!1:T.optional??!1}]):u,[])})():void 0}catch{this.#e=void 0}if(!this.platformUtils.isSyncStorage||r.useStorageOverrides)return;this.email=this.localStorageGetItem(ce)||void 0,this.countryCode=this.localStorageGetItem(de)||void 0,this.phone=this.localStorageGetItem(pe)||void 0,this.userId=this.localStorageGetItem(he)||void 0,this.telegramUserId=this.localStorageGetItem(ue)||void 0;let s=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(N):this.localStorageGetItem(N),n=JSON.parse(s||"{}"),o=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(Y):this.localStorageGetItem(Y),a=JSON.parse(o||"{}"),l={...Object.keys(n).reduce((u,P)=>({...u,[P]:k(n[P])}),{}),...Object.keys(a).reduce((u,P)=>({...u,...u[P]?{}:{[P]:k(a[P])}}),{})};this.setWallets(l);let c=this.localStorageGetItem(me)??void 0,d=[void 0,null,"undefined"].includes(c)?{}:(()=>{let u=JSON.parse(c);return Array.isArray(u)?Object.keys(p.WalletType).reduce((P,T)=>{let Ue=Object.values(this.wallets).find(Ne=>u.includes(Ne.id)&&x[Ne.scheme][T]);return{...P,...Ue&&!P[T]?{[T]:[Ue.id]}:{}}},{}):u})();this.setCurrentWalletIds(d),this.sessionCookie=this.localStorageGetItem($)||this.sessionStorageGetItem($)||void 0,Object.values(this.wallets).filter(u=>this.isWalletOwned(u)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0});let I=this.sessionStorageGetItem(X);I&&I!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(I)));let S=this.localStorageGetItem(ge),m=JSON.parse(S||"{}");this.setExternalWallets(m);let A=this.localStorageGetItem(ye)||void 0;this.currentExternalWalletAddresses=A?JSON.parse(A):void 0}static{this.version=yt}get isEmail(){return!!this.email&&!this.phone&&!this.countryCode&&!this.farcasterUsername&&!this.telegramUserId}get isPhone(){return!!this.phone&&!!this.countryCode&&!this.email&&!this.farcasterUsername&&!this.telegramUserId}get isFarcaster(){return!!this.farcasterUsername&&!this.email&&!this.phone&&!this.countryCode&&!this.telegramUserId}get isTelegram(){return!!this.telegramUserId&&!this.email&&!this.phone&&!this.countryCode&&!this.farcasterUsername}get currentWalletIdsArray(){return this.supportedWalletTypes.reduce((e,{type:t})=>[...e,...(this.currentWalletIds[t]??[]).map(r=>[r,t])],[])}get currentWalletIdsUnique(){return[...new Set(Object.values(this.currentWalletIds).flat())]}get pregenIds(){return{...Object.values(this.wallets).filter(e=>!this.userId||this.isPregenWalletClaimable(e)).reduce((e,t)=>(e[t.pregenIdentifierType]??[]).includes(t.pregenIdentifier)?e:{...e,[t.pregenIdentifierType]:[...new Set([...e[t.pregenIdentifierType]??[],t.pregenIdentifier])]},{})}}get isMultiWallet(){return this.currentWalletIdsArray.length>1}#e;#t;get supportedWalletTypes(){return this.#e??[]}get isWalletTypeEnabled(){return this.supportedWalletTypes.reduce((e,{type:t})=>({...e,[t]:!0}),{})}convertBigInt(e){let t=new Ht.BigInteger(null);return t.data=e.data,t.s=e.s,t.t=e.t,t}convertEncryptionKeyPair(e){return{privateKey:St.setRsaPrivateKey(this.convertBigInt(e.privateKey.n),this.convertBigInt(e.privateKey.e),this.convertBigInt(e.privateKey.d),this.convertBigInt(e.privateKey.p),this.convertBigInt(e.privateKey.q),this.convertBigInt(e.privateKey.dP),this.convertBigInt(e.privateKey.dQ),this.convertBigInt(e.privateKey.qInv)),publicKey:St.setRsaPublicKey(this.convertBigInt(e.publicKey.n),this.convertBigInt(e.publicKey.e))}}isPortal(e){return typeof window>"u"?!1:!!window.location?.host&&R(e?{env:e}:this.ctx).includes(window.location.host)}isParaConnect(){return typeof window>"u"?!1:!!window.location?.host&&Je(this.ctx).includes(window.location.host)}requireApiKey(){if(!this.ctx.apiKey)throw new Error(`in order to create a wallet or user with Para, you
2
+ must provide an API key to the Para instance`)}isWalletSupported(e){return!this.#e||re(this.supportedWalletTypes.map(({type:t})=>t)??[],e)}isWalletOwned(e){return this.isWalletSupported(e)&&!e.pregenIdentifier&&!e.pregenIdentifierType&&!!this.userId&&e.userId===this.userId}isPregenWalletUnclaimed(e){return this.isWalletSupported(e)&&(!e.userId||e.isPregen&&!!e.pregenIdentifier&&!!e.pregenIdentifierType)}isPregenWalletClaimable(e){return this.isWalletSupported(e)&&this.isPregenWalletUnclaimed(e)&&(!["EMAIL","PHONE","TELEGRAM"].includes(e.pregenIdentifierType)||Ye(e.pregenIdentifierType==="EMAIL"?this.email:e.pregenIdentifierType==="TELEGRAM"?this.telegramUserId:this.getPhoneNumber(),e.pregenIdentifier,e.pregenIdentifierType))}isWalletUsable(e,{type:t,scheme:r,forbidPregen:s=!1}={},n=!1){let o;if(!this.wallets[e])o=`wallet with id ${e} does not exist`;else{let a=this.wallets[e],[l,c]=[this.isPregenWalletUnclaimed(a),this.isWalletOwned(a)];s&&l?o=`pre-generated wallet with id ${a.id} cannot be selected`:!c&&!l?o=`wallet with id ${a.id} is not owned by the current user`:this.isWalletSupported(a)?t&&(!We(t).includes(a.type)||c&&!t.some(d=>(this.currentWalletIds[d]??[]).includes(e)))?o=`wallet with id ${a.id} and type ${a.type} cannot be selected`:r&&!r.includes(a.scheme)&&(o=`wallet with id ${a.id} and scheme ${a.scheme} cannot be selected`):o=`wallet with id ${a.id} and type ${a.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({type:d})=>d).join(", ")}`}if(o){if(n)throw new Error(o);return!1}return!0}getDisplayAddress(e,t={}){if(this.externalWallets[e]){let n=this.externalWallets[e];return t.truncate?Q(n.address,n.type,{prefix:this.cosmosPrefix}):n.address}let r=this.findWallet(e,t.addressType);if(!r)return;let s;switch(r.type){case p.WalletType.COSMOS:s=Se(r.publicKey,this.cosmosPrefix??"cosmos");break;default:s=r.address;break}return t.truncate?Q(s,r.type,{prefix:this.cosmosPrefix}):s}getIdenticonHash(e,t){if(this.externalWallets[e]){let s=this.externalWallets[e];return`${s.id}-${s.address}-${s.type}`}let r=this.findWallet(e,t);return r?`${r.id}-${r.address}-${r.type}`:void 0}getWallets(){return this.wallets}getAddress(e){return e?this.wallets[e].address:Object.values(this.wallets)?.[0]?.address}async constructPortalUrl(e,t={}){let r=e==="onRamp"?R(this.ctx):await this.getPortalURL(t.partnerId),s;switch(e){case"createPassword":{s=`/web/users/${this.userId}/passwords/${t.pathId}`;break}case"createAuth":{s=`/web/users/${this.userId}/biometrics/${t.pathId}`;break}case"loginPassword":{s="/web/passwords/login";break}case"loginAuth":{s="/web/biometrics/login";break}case"txReview":{s=`/web/users/${this.userId}/transaction-review/${t.pathId}`;break}case"onRamp":{s=`/web/users/${this.userId}/on-ramp-transaction/${t.pathId}`;break}default:throw new Error(`invalid URL type ${e}`)}let[n,o,a]=[["createAuth","createPassword"].includes(e),["loginAuth","loginPassword"].includes(e),e==="onRamp"],l=t.partnerId?(await this.ctx.client.getPartner(t.partnerId)).data?.partner:void 0,c={apiKey:this.ctx.apiKey,partnerId:t.partnerId,portalFont:t.theme?.font||l?.font||this.portalTheme?.font,portalBorderRadius:t.theme?.borderRadius||this.portalTheme?.borderRadius,portalThemeMode:t.theme?.mode||l?.themeMode||this.portalTheme?.mode,portalAccentColor:t.theme?.accentColor||l?.accentColor||this.portalTheme?.accentColor,portalForegroundColor:t.theme?.foregroundColor||l?.foregroundColor||this.portalTheme?.foregroundColor,portalBackgroundColor:t.theme?.backgroundColor||l?.backgroundColor||this.portalBackgroundColor||this.portalTheme?.backgroundColor,portalPrimaryButtonColor:this.portalPrimaryButtonColor,portalTextColor:this.portalTextColor,portalPrimaryButtonTextColor:this.portalPrimaryButtonTextColor,isForNewDevice:t.isForNewDevice?t.isForNewDevice.toString():void 0,supportedWalletTypes:this.#t?JSON.stringify(this.#t):void 0,...n||o?{...t.authType==="email"?{email:this.email}:{},...t.authType==="phone"?{phone:this.phone,countryCode:this.countryCode}:{},...t.authType==="farcaster"?{farcasterUsername:this.farcasterUsername}:{},...t.authType==="telegram"?{telegramUserId:this.telegramUserId}:{}}:{},...o||a?{sessionId:t.sessionId}:{},...o?{encryptionKey:t.loginEncryptionPublicKey,newDeviceSessionLookupId:t.newDeviceSessionId,newDeviceEncryptionKey:t.newDeviceEncryptionKey,pregenIds:JSON.stringify(this.pregenIds),displayName:t.displayName,pfpUrl:t.pfpUrl}:{},...t.params||{}};return te({base:r,path:s,params:c})}async touchSession(e=!1){let t=await this.ctx.client.touchSession(e);return this.setSupportedWalletTypes(t.data.supportedWalletTypes,t.data.cosmosPrefix),t}setSupportedWalletTypes(e,t){e&&!this.#e&&(this.#e=e,Object.keys(this.currentWalletIds).forEach(r=>{this.#e?.some(({type:s})=>s===r)||delete this.currentWalletIds[r]})),t&&!this.cosmosPrefix&&(this.cosmosPrefix=t)}getVerificationEmailProps(){return{brandColor:this.emailPrimaryColor,theme:this.emailTheme,supportUrl:this.supportUrl,homepageUrl:this.homepageUrl,xUrl:this.xUrl,githubUrl:this.githubUrl,linkedinUrl:this.linkedinUrl}}getBackupKitEmailProps(){return{brandColor:this.emailPrimaryColor,theme:this.emailTheme,homepageUrl:this.homepageUrl,xUrl:this.xUrl,linkedinUrl:this.linkedinUrl,githubUrl:this.githubUrl,supportUrl:this.supportUrl}}async init(){this.email=await this.localStorageGetItem(ce)||void 0,this.countryCode=await this.localStorageGetItem(de)||void 0,this.phone=await this.localStorageGetItem(pe)||void 0,this.userId=await this.localStorageGetItem(he)||void 0,this.telegramUserId=await this.localStorageGetItem(ue)||void 0;let e=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(N):await this.localStorageGetItem(N),t=JSON.parse(e||"{}"),r=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(Y):await this.localStorageGetItem(Y),s=JSON.parse(r||"{}"),n={...Object.keys(t).reduce((S,m)=>({...S,[m]:k(t[m])}),{}),...Object.keys(s).reduce((S,m)=>({...S,...S[m]?{}:{[m]:k(s[m])}}),{})};await this.setWallets(n);let o=await this.localStorageGetItem(me)??void 0,a=[void 0,null,"undefined","null"].includes(o)?{}:(()=>{let S=JSON.parse(o);return Array.isArray(S)?Object.keys(p.WalletType).reduce((m,A)=>{let u=Object.values(this.wallets).find(P=>S.includes(P.id)&&x[P.scheme][A]);return{...m,...u&&!m[A]?{[A]:[u.id]}:{}}},{}):S})();await this.setCurrentWalletIds(a),this.sessionCookie=await this.localStorageGetItem($)||await this.sessionStorageGetItem($)||void 0,Object.values(this.wallets).filter(S=>this.isWalletOwned(S)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0});let l=await this.sessionStorageGetItem(X);l&&l!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(l)));let c=await this.localStorageGetItem(ge),d=JSON.parse(c||"{}");await this.setExternalWallets(d);let I=await this.localStorageGetItem(ye)||void 0;this.currentExternalWalletAddresses=I?JSON.parse(I):void 0,await this.touchSession()}async setEmail(e){this.email=e,await this.localStorageSetItem(ce,e)}async setTelegramUserId(e){this.telegramUserId=e,await this.localStorageSetItem(ue,e)}async setPhoneNumber(e,t){this.phone=e,this.countryCode=t,await this.localStorageSetItem(pe,e),await this.localStorageSetItem(de,t)}async setFarcasterUsername(e){this.farcasterUsername=e,await this.localStorageSetItem(ft,e)}async setExternalWallet({address:e,type:t,provider:r,addressBech32:s}){this.externalWallets={[e]:{id:e,address:s??e,type:t,name:r,isExternal:!0,signer:""}},this.currentExternalWalletAddresses=[e],this.setCurrentExternalWalletAddresses(this.currentExternalWalletAddresses),this.setExternalWallets(this.externalWallets),y(g.EXTERNAL_WALLET_CHANGE_EVENT,null)}async setUserId(e){this.userId=e,await this.localStorageSetItem(he,e)}async setWallets(e){if(this.wallets=e,this.platformUtils.secureStorage){await this.platformUtils.secureStorage.set(N,JSON.stringify(e));return}await this.localStorageSetItem(N,JSON.stringify(e))}async setExternalWallets(e){this.externalWallets=e,await this.localStorageSetItem(ge,JSON.stringify(e))}async setCurrentExternalWalletAddresses(e){this.currentExternalWalletAddresses=e,await this.localStorageSetItem(ye,JSON.stringify(e))}async setLoginEncryptionKeyPair(e){e||(e=await D(this.ctx)),this.loginEncryptionKeyPair=e,await this.sessionStorageSetItem(X,JSON.stringify(e))}async deleteLoginEncryptionKeyPair(){this.loginEncryptionKeyPair=void 0,await this.sessionStorageRemoveItem(X)}getUserId(){return this.userId}getEmail(){return this.email}getPhone(){return{phone:this.phone,countryCode:this.countryCode}}getPhoneNumber(){if(!(!this.phone||!this.countryCode))return Ee(this.countryCode,this.phone)}getFarcasterUsername(){return this.farcasterUsername}async setCurrentWalletIds(e,{needsWallet:t=!1,sessionLookupId:r,newDeviceSessionLookupId:s}={}){this.currentWalletIds=e,await this.localStorageSetItem(me,JSON.stringify(this.currentWalletIds)),r&&await this.ctx.client.setCurrentWalletIds(this.getUserId(),this.currentWalletIds,t,r,s),y(g.WALLETS_CHANGE_EVENT,null)}findWalletId(e,t={}){if(e)this.assertIsValidWalletId(e,t);else{for(let r of[...this.currentWalletIdsUnique,...Object.keys(this.wallets)])if(this.isWalletUsable(r,t)){e=r;break}if(!e)throw new Error("no valid wallet id found")}return e}findWalletByAddress(e,t){if(this.externalWallets[e])return this.externalWallets[e];let r;if(Object.entries(this.currentWalletIds).forEach(([s,n])=>{let o=Object.keys(this.wallets).filter(a=>this.wallets[a].type===s&&this.isPregenWalletClaimable(this.wallets[a]));[...n,...o].forEach(a=>{e.toLowerCase()===this.getDisplayAddress(a,{addressType:s}).toLowerCase()&&(r=this.wallets[a])})}),!r)throw new Error(`wallet with address ${e} not found`);return this.assertIsValidWalletId(r.id,t),r}findWallet(e,t,r={}){if(!e&&Object.keys(this.externalWallets).length>0)return Object.values(this.externalWallets)[0];if(this.externalWallets[e])return this.externalWallets[e];try{let s=this.findWalletId(e,r);if(s&&this.wallets[s]){let{signer:n,...o}=this.wallets[s],a=t??this.currentWalletIdsArray.find(([l])=>l===s)?.[1]??o.type;return{...o,type:p.WalletType[a]}}}catch{return}}get availableWallets(){return[...this.currentWalletIdsArray.map(([e,t])=>[e,t,!1]).map(([e,t])=>{let r=this.findWallet(e,t);return r?{id:r.id,type:t,address:this.getDisplayAddress(e,{addressType:t}),name:r.name}:null}).filter(e=>e!==null),...Object.values(this.externalWallets??{})]}getWalletsByType(e){return Object.values(this.wallets).filter(t=>this.isWalletUsable(t.id,{type:[e]}))}assertIsValidWalletId(e,t={}){this.isWalletUsable(e,t,!0)}async assertIsValidWalletType(e,t){if(this.#e||await this.touchSession(),!e||!Object.values(p.WalletType).includes(e)||!(t??this.supportedWalletTypes.map(({type:r})=>r)).includes(e))throw new Error(`wallet type ${e} is not supported`);return e}async getMissingTypes(){return this.#e||await this.touchSession(),this.supportedWalletTypes.filter(({type:e,optional:t})=>!t&&Object.values(this.wallets).every(r=>!this.isWalletOwned(r)||!x[r.scheme][e])).map(({type:e})=>e)}async getTypesToCreate(e){return this.#e||await this.touchSession(),Te(e??await this.getMissingTypes()).map(t=>{switch(t){case p.WalletScheme.ED25519:return p.WalletType.SOLANA;default:return this.supportedWalletTypes.some(({type:r,optional:s})=>r===p.WalletType.COSMOS&&!s)?p.WalletType.COSMOS:p.WalletType.EVM}})}async getPartnerURL(e){return(await this.ctx.client.getPartner(e)).data.partner.portalUrl}async getPortalURL(e){return e&&await this.getPartnerURL(e)||R(this.ctx)}async getWebAuthURLForCreate({webAuthId:e,...t}){return this.constructPortalUrl("createAuth",{...t,pathId:e})}async getPasswordURLForCreate({passwordId:e,...t}){return this.constructPortalUrl("createPassword",{...t,pathId:e})}getShortUrl(e){return te({base:R(this.ctx),path:`/short/${e}`})}async shortenLoginLink(e){let t=await gt(e,this.ctx.client);return this.getShortUrl(t)}async getWebAuthURLForLogin(e){return this.constructPortalUrl("loginAuth",e)}async getPasswordURLForLogin(e){return this.constructPortalUrl("loginPassword",e)}async getWebAuthURLForLoginForPhone(e){return this.constructPortalUrl("loginAuth",{authType:"phone",...e})}async getPrivateKey(e){let t=Object.values(this.wallets),r=e?this.wallets[e]:t?.[0];if(!r)throw new Error("wallet not found");if(r.scheme!==p.WalletScheme.DKLS)throw new Error("invalid wallet scheme");return await this.platformUtils.getPrivateKey(this.ctx,this.userId,r.id,r.signer,this.retrieveSessionCookie())}async fetchWallets(){return(await(this.isPortal()||this.isParaConnect()?this.ctx.client.getAllWallets(this.userId):this.ctx.client.getWallets(this.userId,!0))).data.wallets.filter(t=>!!t.address&&(this.isParaConnect()||!this.isParaConnect()&&this.isWalletSupported(b(t))))}async populateWalletAddresses(){(await this.ctx.client.getWallets(this.userId,!0)).data.wallets.forEach(r=>{this.wallets[r.id]&&(this.wallets[r.id]={...b(r),...this.wallets[r.id]})}),await this.setWallets(this.wallets)}async populatePregenWalletAddresses(){(await this.getPregenWallets()).forEach(t=>{this.wallets[t.id]&&(this.wallets[t.id]={...b(t),...this.wallets[t.id]})}),await this.setWallets(this.wallets)}async checkIfUserExists({email:e}){return(await this.ctx.client.checkUserExists({email:e})).data.exists}async checkIfUserExistsByPhone({phone:e,countryCode:t}){return(await this.ctx.client.checkUserExists({phone:e,countryCode:t})).data.exists}async createUser({email:e}){this.requireApiKey(),await this.setEmail(e);let{userId:t}=await this.ctx.client.createUser({email:this.email,...this.getVerificationEmailProps()});await this.setUserId(t)}async createUserByPhone({phone:e,countryCode:t}){this.requireApiKey(),await this.setPhoneNumber(e,t);let{userId:r}=await this.ctx.client.createUser({phone:this.phone,countryCode:this.countryCode});await this.setUserId(r)}async externalWalletLogin(e){this.requireApiKey();let{userId:t}=await this.ctx.client.externalWalletLogin({externalAddress:e.address,type:e.type,externalWalletProvider:e.provider});await this.setExternalWallet(e),await this.setUserId(t)}isUsingExternalWallet(){return!!Object.keys(this.externalWallets).length}async verifyEmail({verificationCode:e}){return await this.ctx.client.verifyEmail(this.userId,{verificationCode:e}),this.getSetUpBiometricsURL()}async verifyPhone({verificationCode:e}){return await this.ctx.client.verifyPhone(this.userId,{verificationCode:e}),this.getSetUpBiometricsURLForPhone()}async verifyTelegram(e){let t=await this.ctx.client.verifyTelegram(e);return t.isValid&&(await this.setUserId(t.userId),await this.setTelegramUserId(t.telegramUserId),await this.touchSession(!0),this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair()),t}async verify2FA({email:e,verificationCode:t}){let r=await this.ctx.client.verify2FA(e,t);return{initiatedAt:r.data.initiatedAt,status:r.data.status,userId:r.data.userId,wallets:r.data.wallets}}async verify2FAForPhone({phone:e,countryCode:t,verificationCode:r}){let s=await this.ctx.client.verify2FAForPhone(e,t,r);return{initiatedAt:s.data.initiatedAt,status:s.data.status,userId:s.data.userId,wallets:s.data.wallets}}async setup2FA(){return{uri:(await this.ctx.client.setup2FA(this.userId)).data.uri}}async enable2FA({verificationCode:e}){await this.ctx.client.enable2FA(this.userId,e)}async check2FAStatus(){return this.userId?{isSetup:(await this.ctx.client.check2FAStatus(this.userId)).data.isSetup}:{isSetup:!1}}async resendVerificationCode(){await this.ctx.client.resendVerificationCode({userId:this.userId,...this.getVerificationEmailProps()})}async resendVerificationCodeByPhone(){await this.ctx.client.resendVerificationCodeByPhone({userId:this.userId})}async getSetUpBiometricsURL({authType:e="email",isForNewDevice:t=!1}={}){let r=await this.ctx.client.addSessionPublicKey(this.userId,{status:p.PublicKeyStatus.PENDING,type:p.PublicKeyType.WEB});return this.getWebAuthURLForCreate({authType:e,isForNewDevice:t,webAuthId:r.data.id,partnerId:r.data.partnerId})}async getSetUpBiometricsURLForPhone({isForNewDevice:e=!1}={}){let t=await this.ctx.client.addSessionPublicKey(this.userId,{status:p.PublicKeyStatus.PENDING,type:p.PublicKeyType.WEB});return this.getWebAuthURLForCreate({authType:"phone",isForNewDevice:e,webAuthId:t.data.id,partnerId:t.data.partnerId})}async getSetupPasswordURL({authType:e="email",isForNewDevice:t=!1,theme:r}={}){let s=await this.ctx.client.addSessionPasswordPublicKey(this.userId,{status:p.PasswordStatus.PENDING});return this.getPasswordURLForCreate({authType:e,isForNewDevice:t,passwordId:s.data.id,partnerId:s.data.partnerId,theme:r})}async isSessionActive(){return this.isUsingExternalWallet()?!0:!!(await this.touchSession()).data.isAuthenticated}async isFullyLoggedIn(){return this.isUsingExternalWallet()?!0:await this.isSessionActive()&&this.currentWalletIdsArray.length>0&&this.currentWalletIdsArray.reduce((t,[r])=>t&&!!this.wallets[r],!0)}async supportedAuthMethods(e){let{supportedAuthMethods:t}=await this.ctx.client.getSupportedAuthMethods(e),r=new Set;for(let s of t)switch(s){case"PASSWORD":r.add(p.AuthMethod.PASSWORD);break;case"BIOMETRIC":r.add(p.AuthMethod.PASSKEY);break}return r}async getUserBiometricLocationHints(){if(!this.email&&!this.phone&&!this.farcasterUsername&&!this.telegramUserId)throw new Error("one of email, phone or farcaster username are required to get biometric location hints");return await this.ctx.client.getBiometricLocationHints({email:this.email,phone:this.phone,countryCode:this.countryCode,farcasterUsername:this.farcasterUsername,telegramUserId:this.telegramUserId})}async setAuth(e){let t=(0,p.extractAuthInfo)(e);if(t){switch(t.authType){case"email":await this.setEmail(t.identifier);break;case"phone":await this.setPhoneNumber(t.auth.phone,t.auth.countryCode);break;case"farcaster":await this.setFarcasterUsername(t.identifier);break;case"telegram":await this.setTelegramUserId(t.identifier);break}return t}}async initiateUserLogin({useShortUrl:e=!1,...t}){let r=await this.setAuth(t);if(!r)return;let s=await this.touchSession(!0);this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair();let n=await this.getWebAuthURLForLogin({authType:r.authType,sessionId:s.data.sessionId,partnerId:s.data.partnerId,loginEncryptionPublicKey:L(this.loginEncryptionKeyPair)});return e?this.shortenLoginLink(n):n}async initiateUserLoginV2(e){let t=await this.setAuth(e);if(t)return await this.touchSession(!0),this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair(),await this.supportedAuthMethods(t.auth)}async initiateUserLoginForPhone({useShortUrl:e=!1,...t}){await this.setAuth(t);let r=await this.touchSession(!0);this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair();let s=await this.getWebAuthURLForLoginForPhone({sessionId:r.data.sessionId,loginEncryptionPublicKey:L(this.loginEncryptionKeyPair),partnerId:r.data.partnerId});return e?this.shortenLoginLink(s):s}async waitForAccountCreation(){for(await this.touchSession(),this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingAccountCreation=!0;this.isAwaitingAccountCreation;)try{if(await new Promise(e=>setTimeout(e,O)),await this.isSessionActive())return this.isAwaitingAccountCreation=!1,y(g.ACCOUNT_CREATION_EVENT,!0),!0}catch(e){console.error(e)}return!1}async waitForPasskeyAndCreateWallet(){await this.waitForAccountCreation();let e=await this.getPregenWallets(),t,r={};e.length>0&&(t=await this.claimPregenWallets(),r=this.supportedWalletTypes.reduce((o,{type:a})=>({...o,[a]:[e.find(l=>!!x[l.scheme][a])?.id]}),{}));let s=await this.createWalletPerType();t=t??s.recoverySecret,r={...r,...s.walletIds};let n={walletIds:r,recoverySecret:t};return y(g.ACCOUNT_SETUP_EVENT,n),n}async getFarcasterConnectURL(){await this.logout(),await this.touchSession(!0);let{data:{connect_uri:e}}=await this.ctx.client.initializeFarcasterLogin();return e}async waitForFarcasterStatus(){for(this.isAwaitingFarcaster=!0;this.isAwaitingFarcaster;)try{await new Promise(t=>setTimeout(t,O));let e=await this.ctx.client.getFarcasterAuthStatus();if(e.data.state==="completed"){let{userId:t,userExists:r,username:s,pfpUrl:n}=e.data;return await this.setUserId(t),await this.setFarcasterUsername(s),{userExists:r,username:s,pfpUrl:n}}}catch(e){console.error(e),this.isAwaitingFarcaster=!1}}async getOAuthURL({method:e,deeplinkUrl:t}){await this.logout();let r=await this.touchSession(!0);return te({base:e===p.OAuthMethod.TELEGRAM?R(this.ctx,!0):be(this.ctx.env),path:`/auth/${e.toLowerCase()}`,params:{apiKey:this.ctx.apiKey,sessionLookupId:r.data.sessionLookupId,deeplinkUrl:t}})}async waitForOAuth({popupWindow:e}={}){for(this.isAwaitingOAuth=!0;this.isAwaitingOAuth;)try{if(e?.closed)return{isError:!0,userExists:!1};if(await new Promise(t=>setTimeout(t,O)),this.isAwaitingOAuth){let t=await this.touchSession();if(t.data.userId){let{userId:r,email:s}=t.data;await this.setUserId(r),await this.setEmail(s);let n=await this.checkIfUserExists({email:s});return this.isAwaitingOAuth=!1,{userExists:n,email:s}}}}catch(t){console.error(t)}return{userExists:!1}}async waitForLoginAndSetup({popupWindow:e,skipSessionRefresh:t=!1}={}){for(this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingLogin=!0;this.isAwaitingLogin;)try{if(await new Promise(l=>setTimeout(l,O)),!await this.isSessionActive()){if(e?.closed){let l={isComplete:!1,isError:!0};return y(g.LOGIN_EVENT,l,"failed to setup user"),l}continue}let s=await this.userSetupAfterLogin(),n=s.data.needsWallet??!1;if(!n&&this.currentWalletIdsArray.length===0)if(e?.closed){let l={isComplete:!1,isError:!0};return y(g.LOGIN_EVENT,l,"failed to setup user"),l}else continue;let o=await this.fetchWallets(),a=await this.getTransmissionKeyShares();if(a.data.temporaryShares.length===o.length){await this.setupAfterLogin({temporaryShares:a.data.temporaryShares,skipSessionRefresh:t}),await this.claimPregenWallets();let l={isComplete:!0,needsWallet:n||Object.values(this.wallets).length===0,partnerId:s.data.partnerId};return y(g.LOGIN_EVENT,l),l}}catch(s){console.error(s)}let r={isComplete:!1};return y(g.LOGIN_EVENT,r,"exitted login without setting up user"),r}async refreshSession({shouldOpenPopup:e=!1}={}){let t=await this.touchSession(!0);this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair();let r=await this.getWebAuthURLForLogin({sessionId:t.data.sessionId,loginEncryptionPublicKey:L(this.loginEncryptionKeyPair)});return e&&this.platformUtils.openPopup(r),r}async userSetupAfterLogin(){let e=await this.touchSession();return await this.setUserId(e.data.userId),e.data.currentWalletIds&&e.data.currentWalletIds!==this.currentWalletIds&&await this.setCurrentWalletIds(e.data.currentWalletIds,{sessionLookupId:this.isPortal()?e.data.sessionLookupId:void 0}),e}async getTransmissionKeyShares({isForNewDevice:e=!1}={}){let t=await this.touchSession(),r=e?`${t.data.sessionLookupId}-new-device`:t.data.sessionLookupId;return this.ctx.client.getTransmissionKeyshares(this.userId,r)}async setupAfterLogin({temporaryShares:e,skipSessionRefresh:t=!1}={}){e||(e=(await this.getTransmissionKeyShares()).data.temporaryShares),e.forEach(r=>{let s=G(this.loginEncryptionKeyPair.privateKey,r.encryptedShare,r.encryptedKey);this.wallets[r.walletId]={id:r.walletId,signer:s}}),await this.deleteLoginEncryptionKeyPair(),await this.populateWalletAddresses(),await this.touchSession(!t)}async distributeNewWalletShare({walletId:e,userShare:t,skipBiometricShareCreation:r=!1,forceRefresh:s=!1}){let n=t;return n||(n=this.wallets[e].signer),r?await oe({ctx:this.ctx,userId:this.userId,walletId:e,userSigner:n,emailProps:this.getBackupKitEmailProps(),forceRefresh:s}):await _({ctx:this.ctx,userId:this.userId,walletId:e,userShare:n,emailProps:this.getBackupKitEmailProps()})}async waitForWalletAddress(e){let t=0;for(;;)try{if(t===10)break;++t;let s=(await this.ctx.client.getWallets(this.userId)).data.wallets.find(n=>n.id===e);if(s&&s.address)return;await new Promise(n=>setTimeout(n,_e))}catch(r){console.error(r)}throw new Error("timed out waiting for wallet address")}async waitForPregenWalletAddress(e){let t=0;for(;;)try{if(t===10)break;++t;let s=(await this.getPregenWallets()).find(n=>n.id===e);if(s&&s.address)return;await new Promise(n=>setTimeout(n,_e))}catch(r){console.error(r)}throw new Error("timed out waiting for wallet address")}async createWalletPerType({skipDistribute:e=!1,types:t}={}){let r=[],s={},n;for(let o of await this.getTypesToCreate(t)){let[a,l]=await this.createWallet({type:o,skipDistribute:e});r.push(a),We(o).filter(c=>!!this.isWalletTypeEnabled[c]).forEach(c=>{s[c]=[a.id]}),l&&(n=l)}return{wallets:r,walletIds:s,recoverySecret:n}}async refreshShare({walletId:e,share:t,oldPartnerId:r,newPartnerId:s,keyShareProtocolId:n,redistributeBackupEncryptedShares:o}){let{signer:a,protocolId:l}=await this.platformUtils.refresh(this.ctx,this.retrieveSessionCookie(),this.userId,e,t,r,s,n),c=await _({ctx:this.ctx,userId:this.userId,walletId:e,userShare:a,ignoreRedistributingBackupEncryptedShare:!o,emailProps:this.getBackupKitEmailProps(),partnerId:s,protocolId:l});return{signer:a,recoverySecret:c,protocolId:l}}async createWallet({type:e,skipDistribute:t=!1}={}){this.requireApiKey();let r=await this.assertIsValidWalletType(e??this.supportedWalletTypes.find(({optional:d})=>!d)?.type),s,n,o;switch(r){case p.WalletType.SOLANA:{o=await this.platformUtils.ed25519Keygen(this.ctx,this.userId,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}default:{o=await this.platformUtils.keygen(this.ctx,this.userId,r,null,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}}let a=o.walletId;s=o.signer,this.wallets[a]={id:a,signer:s,scheme:r===p.WalletType.SOLANA?p.WalletScheme.ED25519:p.WalletScheme.DKLS,type:r},n=this.wallets[a],await this.waitForWalletAddress(n.id),await this.populateWalletAddresses();let l=null;t||(l=await _({ctx:this.ctx,userId:this.userId,walletId:n.id,userShare:s,emailProps:this.getBackupKitEmailProps()})),await this.setCurrentWalletIds({...this.currentWalletIds,[r]:[...this.currentWalletIds[r]??[],a]});let c={...n};return delete c.signer,y(g.WALLET_CREATED,{wallet:c,recoverySecret:l}),[n,l]}async createPregenWallet(e){let{type:t=this.supportedWalletTypes.find(({optional:c})=>!c)?.type,pregenIdentifier:r,pregenIdentifierType:s="EMAIL"}=e;this.requireApiKey();let n=await this.assertIsValidWalletType(t??this.supportedWalletTypes.find(({optional:c})=>!c)?.type),o;switch(n){case p.WalletType.SOLANA:o=await this.platformUtils.ed25519PreKeygen(this.ctx,r,s,this.retrieveSessionCookie());break;default:o=await this.platformUtils.preKeygen(this.ctx,void 0,r,s,n,null,this.retrieveSessionCookie());break}let{signer:a,walletId:l}=o;return this.wallets[l]={id:l,signer:a,scheme:n===p.WalletType.SOLANA?p.WalletScheme.ED25519:p.WalletScheme.DKLS,type:n,isPregen:!0,pregenIdentifier:r,pregenIdentifierType:s},await this.waitForPregenWalletAddress(l),await this.populatePregenWalletAddresses(),this.wallets[l]}async createPregenWalletPerType({types:e,pregenIdentifier:t,pregenIdentifierType:r="EMAIL"}){let s=[];for(let n of await this.getTypesToCreate(e)){let o=await this.createPregenWallet({type:n,pregenIdentifier:t,pregenIdentifierType:r});s.push(o)}return s}async claimPregenWallets({pregenIdentifier:e,pregenIdentifierType:t=e?"EMAIL":void 0}={}){this.requireApiKey();let r=e&&t?await this.getPregenWallets({pregenIdentifier:e,pregenIdentifierType:t}):await this.getPregenWallets();if(r.length===0)return;let s,{walletIds:n}=await this.ctx.client.claimPregenWallets({userId:this.userId,walletIds:r.map(o=>o.id)});for(let o of n){let a=this.wallets[o],l;if(a.scheme===p.WalletScheme.ED25519){let d=await _({ctx:this.ctx,userId:this.userId,walletId:a.id,userShare:this.wallets[a.id].signer,emailProps:this.getBackupKitEmailProps(),partnerId:a.partnerId});d.length>0&&(s=d)}else l=await this.refreshShare({walletId:a.id,share:this.wallets[a.id].signer,oldPartnerId:a.partnerId,newPartnerId:a.partnerId,redistributeBackupEncryptedShares:!0}),l.recoverySecret&&(s=l.recoverySecret);this.wallets[a.id]={...this.wallets[a.id],signer:l?.signer??a.signer,userId:this.userId,pregenIdentifier:void 0,pregenIdentifierType:void 0};let c={...this.wallets[a.id]};delete c.signer,y(g.PREGEN_WALLET_CLAIMED,{wallet:c,recoverySecret:s})}return await this.setWallets(this.wallets),s}async updatePregenWalletIdentifier({walletId:e,newPregenIdentifier:t,newPregenIdentifierType:r}){this.requireApiKey(),await this.ctx.client.updatePregenWallet(e,{pregenIdentifier:t,pregenIdentifierType:r}),this.wallets[e]&&(this.wallets[e]={...this.wallets[e],pregenIdentifier:t,pregenIdentifierType:r},await this.setWallets(this.wallets))}async hasPregenWallet({pregenIdentifier:e,pregenIdentifierType:t}){return this.requireApiKey(),!!(await this.getPregenWallets({pregenIdentifier:e,pregenIdentifierType:t})).find(n=>n.pregenIdentifier===e&&n.pregenIdentifierType===t)}async getPregenWallets({pregenIdentifier:e,pregenIdentifierType:t=e?"EMAIL":void 0}={}){return this.requireApiKey(),(await this.ctx.client.getPregenWallets(e&&t?{[t]:[e]}:this.pregenIds,this.isPortal(),this.userId)).wallets.filter(s=>this.isWalletSupported(b(s)))}encodeWalletBase64(e){let t=JSON.stringify(e);return Buffer.from(t).toString("base64")}getUserShare(){return Object.values(this.wallets).length===0?null:Object.values(this.wallets).map(e=>this.encodeWalletBase64(e)).join("-")}async setUserShare(e){if(!e)return;let t=e.split("-");for(let r of t){let s=Buffer.from(r,"base64").toString(),n=k(JSON.parse(s));this.wallets[n.id]=n,await this.setWallets(this.wallets)}}async getTransactionReviewUrl(e,t){let r=await this.touchSession();return this.constructPortalUrl("txReview",{partnerId:r.data.partnerId,pathId:e,params:{email:this.email,timeoutMs:t?.toString()}})}async getOnRampTransactionUrl({purchaseId:e,providerKey:t,...r}){let s=await this.touchSession(),[n,o]=(0,p.extractWalletRef)(r);return this.constructPortalUrl("onRamp",{partnerId:s.data.partnerId,pathId:e,sessionId:s.data.sessionId,params:{[n]:o,providerKey:t,currentWalletIds:JSON.stringify(this.currentWalletIds)}})}async signMessage({walletId:e,messageBase64:t,timeoutMs:r=3e4,cosmosSignDocBase64:s}){this.assertIsValidWalletId(e);let n=this.wallets[e],o=this.userId;n.partnerId&&!n.userId&&(o=n.partnerId);let a=await this.signMessageInner({wallet:n,signerId:o,messageBase64:t,cosmosSignDocBase64:s}),l=Date.now();if(a.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(a.pendingTransactionId,r),{type:s?"SIGN_TRANSACTION_REVIEW":"SIGN_MESSAGE_REVIEW"});else return y(g.SIGN_MESSAGE_EVENT,a),a;for(await new Promise(c=>setTimeout(c,O));!(Date.now()-l>r);){try{await this.ctx.client.getPendingTransaction(this.userId,a.pendingTransactionId)}catch{let d=new F;throw y(g.SIGN_MESSAGE_EVENT,a,d.message),d}if(a=await this.signMessageInner({wallet:n,signerId:o,messageBase64:t,cosmosSignDocBase64:s}),a.pendingTransactionId)await new Promise(c=>setTimeout(c,O));else break}if(a.pendingTransactionId){let c=new V(await this.getTransactionReviewUrl(a.pendingTransactionId),a.pendingTransactionId);throw y(g.SIGN_MESSAGE_EVENT,a,c.message),c}return y(g.SIGN_MESSAGE_EVENT,a),a}async signMessageInner({wallet:e,signerId:t,messageBase64:r,cosmosSignDocBase64:s}){let n;switch(e.scheme){case p.WalletScheme.ED25519:n=await this.platformUtils.ed25519Sign(this.ctx,t,e.id,e.signer,r,this.retrieveSessionCookie());break;default:n=await this.platformUtils.signMessage(this.ctx,t,e.id,e.signer,r,this.retrieveSessionCookie(),e.scheme===p.WalletScheme.DKLS,s);break}return n}async signTransaction({walletId:e,rlpEncodedTxBase64:t,chainId:r,timeoutMs:s=3e4}){this.assertIsValidWalletId(e);let n=this.wallets[e],o=this.userId;n.partnerId&&!n.userId&&(o=n.partnerId);let a=await this.platformUtils.signTransaction(this.ctx,o,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===p.WalletScheme.DKLS),l=Date.now();if(a.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(a.pendingTransactionId,s),{type:"SIGN_TRANSACTION_REVIEW"});else return y(g.SIGN_TRANSACTION_EVENT,a),a;for(await new Promise(c=>setTimeout(c,O));!(Date.now()-l>s);){try{await this.ctx.client.getPendingTransaction(this.userId,a.pendingTransactionId)}catch{let d=new F;throw y(g.SIGN_TRANSACTION_EVENT,a,d.message),d}if(a=await this.platformUtils.signTransaction(this.ctx,o,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===p.WalletScheme.DKLS),a.pendingTransactionId)await new Promise(c=>setTimeout(c,O));else break}if(a.pendingTransactionId){let c=new V(await this.getTransactionReviewUrl(a.pendingTransactionId),a.pendingTransactionId);throw y(g.SIGN_TRANSACTION_EVENT,a,c.message),c}return y(g.SIGN_TRANSACTION_EVENT,a),a}async sendTransaction({walletId:e,rlpEncodedTxBase64:t,chainId:r}){this.assertIsValidWalletId(e);let s=this.wallets[e],n=await this.platformUtils.sendTransaction(this.ctx,this.userId,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),s.scheme===p.WalletScheme.DKLS);if(n.pendingTransactionId)throw this.platformUtils.openPopup(await this.getTransactionReviewUrl(n.pendingTransactionId),{type:"SIGN_TRANSACTION_REVIEW"}),new J(await this.getTransactionReviewUrl(n.pendingTransactionId));return n}isProviderModalDisabled(){return!!this.disableProviderModal}async initiateOnRampTransaction(e){let{params:t,shouldOpenPopup:r,...s}=e,n=await this.ctx.client.createOnRampPurchase({userId:this.userId,params:{...t,address:s.externalWalletAddress??this.getDisplayAddress(s.walletId,{addressType:t.walletType})},...s}),o=await this.getOnRampTransactionUrl({purchaseId:n.id,providerKey:n.providerKey,...s});return r&&this.platformUtils.openPopup(o,{type:"ON_RAMP_TRANSACTION"}),{onRampPurchase:n,portalUrl:o}}async keepSessionAlive(){try{return await this.ctx.client.keepSessionAlive(this.userId),!0}catch{return!1}}exportSession(){let e={email:this.email,userId:this.userId,wallets:this.wallets,currentWalletIds:this.currentWalletIds,sessionCookie:this.sessionCookie,phone:this.phone,countryCode:this.countryCode,telegramUserId:this.telegramUserId,farcasterUsername:this.farcasterUsername,externalWallets:this.externalWallets};return Buffer.from(JSON.stringify(e)).toString("base64")}async importSession(e){let t=Buffer.from(e,"base64").toString("utf8"),r=JSON.parse(t);await this.setEmail(r.email),await this.setUserId(r.userId),await this.setWallets(r.wallets),await this.setExternalWallets(r.externalWallets||{});for(let s of Object.keys(this.wallets))this.wallets[s].userId||(this.wallets[s].userId=this.userId);if(Object.keys(r.currentWalletIds).length!==0)await this.setCurrentWalletIds(r.currentWalletIds);else{let s={};for(let n of Object.keys(r.wallets))s[r.wallets[n].type]=[...s[r.wallets[n].type]??[],n];await this.setCurrentWalletIds(s)}this.persistSessionCookie(r.sessionCookie),await this.setPhoneNumber(r.phone,r.countryCode)}exitAccountCreation(){this.isAwaitingAccountCreation=!1}exitLogin(){this.isAwaitingLogin=!1}exitFarcaster(){this.isAwaitingFarcaster=!1}exitOAuth(){this.isAwaitingOAuth=!1}exitLoops(){this.exitAccountCreation(),this.exitLogin(),this.exitFarcaster(),this.exitOAuth()}async getVerificationToken(){let{data:e}=await this.touchSession();return e.sessionLookupId}async logout({clearPregenWallets:e=!1}={}){await this.ctx.client.logout(),await this.clearStorage(),e?this.wallets={}:(Object.entries(this.wallets).forEach(([t,r])=>{r.pregenIdentifier||delete this.wallets[t]}),await this.setWallets(this.wallets)),this.currentWalletIds={},this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.loginEncryptionKeyPair=void 0,this.email=void 0,this.telegramUserId=void 0,this.phone=void 0,this.countryCode=void 0,this.userId=void 0,this.sessionCookie=void 0,y(g.LOGOUT_EVENT,null)}async getSupportedCreateAuthMethods(){let t=(await this.touchSession()).data.partnerId,r=await this.ctx.client.getPartner(t),s=new Set;for(let n of r.data.partner.supportedAuthMethods)s.add(p.AuthMethod[n]);return s}toString(){let e=Object.keys(this.wallets).reduce((r,s)=>({...r,[s]:{...this.wallets[s],signer:this.wallets[s].signer?"[REDACTED]":void 0}}),{}),t={supportedWalletTypes:this.supportedWalletTypes,cosmosPrefix:this.cosmosPrefix,email:this.email,phone:this.phone,countryCode:this.countryCode,telegramUserId:this.telegramUserId,farcasterUsername:this.farcasterUsername,userId:this.userId,pregenIds:this.pregenIds,currentWalletIds:this.currentWalletIds,wallets:e,loginEncryptionKeyPair:this.loginEncryptionKeyPair?"[REDACTED]":void 0,ctx:{apiKey:this.ctx.apiKey,disableWorkers:this.ctx.disableWorkers,disableWebSockets:this.ctx.disableWebSockets,env:this.ctx.env,offloadMPCComputationURL:this.ctx.offloadMPCComputationURL,useLocalFiles:this.ctx.useLocalFiles,useDKLS:this.ctx.useDKLS,cosmosPrefix:this.ctx.cosmosPrefix}};return`Para ${JSON.stringify(t,null,2)}`}};var h=require("@getpara/user-management-client"),jt=q.version,Jt=q;0&&(module.exports={AuthMethod,EmailTheme,EnabledFlow,Environment,KeyContainer,NON_ED25519,Network,OAuthMethod,OnRampAsset,OnRampMethod,OnRampProvider,OnRampPurchaseStatus,OnRampPurchaseType,PREGEN_IDENTIFIER_TYPES,ParaEvent,PopupType,PregenIdentifierType,RecoveryStatus,STORAGE_PREFIX,TransactionReviewDenied,TransactionReviewError,TransactionReviewTimeout,WalletScheme,WalletType,decimalToHex,decryptPrivateKey,decryptPrivateKeyAndDecryptShare,decryptPrivateKeyWithPassword,decryptWithKeyPair,decryptWithPrivateKey,distributeNewShare,encodePrivateKeyToPemHex,encryptPrivateKey,encryptPrivateKeyWithPassword,encryptWithDerivedPublicKey,entityToWallet,getAsymmetricKeyPair,getBaseMPCNetworkUrl,getBaseOAuthUrl,getBaseUrl,getCosmosAddress,getDerivedPrivateKeyAndDecrypt,getOnRampAssets,getOnRampNetworks,getPortalBaseURL,getPortalDomain,getPublicKeyFromSignature,getPublicKeyHex,getSHA256HashHex,hashPasswordWithSalt,hexStringToBase64,hexToDecimal,hexToSignature,hexToUint8Array,initClient,isWalletSupported,mpcComputationClient,normalizePhoneNumber,paraVersion,publicKeyFromHex,stringToPhoneNumber,toAssetInfoArray,transmissionUtilsRetrieve,truncateAddress,waitUntilTrue});
Binary file
Binary file
File without changes
File without changes
package/dist/esm/index.js CHANGED
@@ -1,23 +1,2 @@
1
- import { ParaCore } from './ParaCore.js';
2
- export { AuthMethod, EmailTheme, Network, WalletType, WalletScheme, OnRampAsset, OnRampPurchaseType, OnRampProvider, OnRampPurchaseStatus, OAuthMethod, NON_ED25519, PREGEN_IDENTIFIER_TYPES, } from '@getpara/user-management-client';
3
- export { OnRampMethod, PopupType, PregenIdentifierType, RecoveryStatus, } from './types/index.js';
4
- export * from './types/events.js';
5
- export * from './types/config.js';
6
- export { getPortalDomain, stringToPhoneNumber, entityToWallet } from './utils/index.js';
7
- export { PREFIX as STORAGE_PREFIX } from './constants.js';
8
- export { distributeNewShare } from './shares/shareDistribution.js';
9
- export { KeyContainer } from './shares/KeyContainer.js';
10
- export { getBaseUrl, initClient } from './external/userManagementClient.js';
11
- import * as mpcComputationClient_1 from './external/mpcComputationClient.js';
12
- export { mpcComputationClient_1 as mpcComputationClient };
13
- export { decryptWithKeyPair, decryptWithPrivateKey, getAsymmetricKeyPair, getPublicKeyHex, encryptWithDerivedPublicKey, encodePrivateKeyToPemHex, getDerivedPrivateKeyAndDecrypt, getPublicKeyFromSignature, getSHA256HashHex, encryptPrivateKey, decryptPrivateKey, decryptPrivateKeyAndDecryptShare, hashPasswordWithSalt, encryptPrivateKeyWithPassword, decryptPrivateKeyWithPassword, publicKeyFromHex, } from './cryptography/utils.js';
14
- export * from './external/userManagementClient.js';
15
- export * from './errors.js';
16
- export * from './utils/formatting.js';
17
- export * from './utils/polling.js';
18
- export { isWalletSupported } from './utils/wallet.js';
19
- export { getOnRampAssets, getOnRampNetworks, toAssetInfoArray } from './utils/onRamps.js';
20
- export { getPortalBaseURL } from './utils/url.js';
21
- export { retrieve as transmissionUtilsRetrieve } from './transmission/transmissionUtils.js';
22
- export const paraVersion = ParaCore.version;
23
- export default ParaCore;
1
+ var Qe=Object.defineProperty;var Ze=(i,e)=>{for(var t in e)Qe(i,t,{get:e[t],enumerable:!0})};import{Buffer as fe}from"buffer";import{AuthMethod as Se,PublicKeyStatus as Xe,PublicKeyType as qe,WalletType as w,WalletScheme as P,OAuthMethod as kt,extractWalletRef as Dt,PasswordStatus as Gt,extractAuthInfo as Bt}from"@getpara/user-management-client";import Mt from"node-forge";import gt from"base64url";import S from"node-forge";function g(i,e,t){typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent(i,{detail:{data:e,...t&&{error:new Error(t)}}}))}import{toBech32 as et}from"@cosmjs/encoding";import{sha256 as tt}from"@noble/hashes/sha256";import{ripemd160 as rt}from"@noble/hashes/ripemd160";import st from"elliptic";import it from"libphonenumber-js";var nt=new st.ec("secp256k1");function qt(i){return i.substring(0,2)==="0x"&&(i=i.substring(2)),Buffer.from(i,"hex").toString("base64")}function zt(i){return{r:`0x${i.slice(2,66)}`,s:`0x${i.slice(66,130)}`,v:BigInt(i.slice(130,132))}}function Qt(i){return i.startsWith("0x")&&(i=i.slice(2)),new Uint8Array(Buffer.from(i,"hex"))}function Zt(i){return i.startsWith("0x")&&(i=i.slice(2)),`${parseInt(i,16)}`}function er(i){return`0x${parseInt(i).toString(16)}`}function at(i){switch(i.length){case 33:return i;case 65:return Uint8Array.from(nt.keyFromPublic(i).getPublic(!0,"array"));default:throw new Error("Invalid pubkey length")}}function ot(i){if(i.length!==33)throw new Error(`Invalid Secp256k1 pubkey length (compressed): ${i.length}`);return rt(tt(i))}function Ie(i,e){let t=new Uint8Array(Buffer.from(i.startsWith("0x")?i.slice(2):i,"hex")),r=at(t);return et(e,ot(r))}function ne(i,e,{prefix:t=e==="COSMOS"?"cosmos":void 0}={}){let r=(e==="COSMOS"?t.length:e==="SOLANA"?0:2)+4;return`${i.slice(0,r)}...${i.slice(-4)}`}function D(i){return it(i)?.formatInternational().replace(/[^\d+]/g,"")}function Pe(i,e){return D(`${i[0]!=="+"?"+":""}${i}${e}`)}function ae(i){let e=[];return Object.keys(i).forEach(t=>{let r=i[t];Object.keys(r).forEach(s=>{let n=r[s];Object.keys(n).forEach(o=>{let a=n[o];e.push([t,s,o,a])})})}),e}function lt(i,{walletType:e,allowed:t}={}){return[...new Set(ae(i).filter(([r,s])=>(!e||r===e)&&(!t||t.includes(s))).map(([r,s])=>s))]}function ct(i,{walletType:e,network:t,allowed:r}={}){return[...new Set(ae(i).filter(([s,n,o])=>(!e||s===e)&&(!t||n===t)&&(!Array.isArray(r)||r.includes(o))).map(([,,s])=>s))]}async function sr(i,e,t){let r=Date.now();for(;Date.now()-r<e;){if(await i())return!0;await new Promise(s=>setTimeout(s,t))}return!1}var pt=(o=>(o.DEV="DEV",o.SANDBOX="SANDBOX",o.BETA="BETA",o.PROD="PROD",o.DEVELOPMENT="BETA",o.PRODUCTION="PROD",o))(pt||{}),dt=(r=>(r.BUY="BUY",r.RECEIVE="RECEIVE",r.WITHDRAW="WITHDRAW",r))(dt||{});var Ae=(t=>(t.EMAIL="EMAIL",t.PHONE="PHONE",t))(Ae||{});var Te=(s=>(s.ACH="ACH",s.DEBIT="Debit",s.CREDIT="Credit",s.APPLE_PAY="Apple Pay",s))(Te||{});var oe=(o=>(o.SIGN_TRANSACTION_REVIEW="SIGN_TRANSACTION_REVIEW",o.SIGN_MESSAGE_REVIEW="SIGN_MESSAGE_REVIEW",o.LOGIN_PASSKEY="LOGIN_PASSKEY",o.CREATE_PASSKEY="CREATE_PASSKEY",o.OAUTH="OAUTH",o.ON_RAMP_TRANSACTION="ON_RAMP_TRANSACTION",o))(oe||{});var We=(n=>(n.INITIATED="INITIATED",n.READY="READY",n.EXPIRED="EXPIRED",n.FINISHED="FINISHED",n.CANCELLED="CANCELLED",n))(We||{});var T="para",h=(p=>(p.LOGIN_EVENT=`${T}Login`,p.ACCOUNT_CREATION_EVENT=`${T}AccountCreation`,p.ACCOUNT_SETUP_EVENT=`${T}AccountSetup`,p.LOGOUT_EVENT=`${T}Logout`,p.SIGN_MESSAGE_EVENT=`${T}SignMessage`,p.SIGN_TRANSACTION_EVENT=`${T}SignTransaction`,p.EXTERNAL_WALLET_CHANGE_EVENT=`${T}ExternalWalletChange`,p.WALLETS_CHANGE_EVENT=`${T}WalletsChange`,p.WALLET_CREATED=`${T}WalletCreated`,p.PREGEN_WALLET_CLAIMED=`${T}PregenWalletClaimed`,p))(h||{});function Ce(i,e){if(e)return"localhost";switch(i){case"DEV":return"localhost";case"SANDBOX":return"app.sandbox.usecapsule.com";case"BETA":return"app.beta.usecapsule.com";case"PROD":return"app.usecapsule.com";default:throw new Error(`env: ${i} not supported`)}}function R({env:i,isE2E:e},t,r){if(e)return r?"https://app.sandbox.usecapsule.com":"http://localhost:3003";let s=Ce(i);return i==="DEV"?t?"http://127.0.0.1:3003":`http://${s}:3003`:`https://${s}`}function ut(i){switch(i){case"DEV":return"localhost";case"SANDBOX":return"connect.sandbox.getpara.com";case"BETA":return"connect.beta.getpara.com";case"PROD":return"connect.getpara.com";default:throw new Error(`env: ${i} not supported`)}}function Re({env:i},e){let t=ut(i);return i==="DEV"?e?"http://127.0.0.1:3008":`http://${t}:3008`:`https://${t}`}function j({base:i,path:e,params:t={}}){let r=new URL(e,i);return Object.entries(t).forEach(([s,n])=>{n&&n!=="undefined"&&n!=="null"&&r.searchParams.set(s,n.toString())}),r.toString()}import{WalletScheme as b,WalletType as W}from"@getpara/user-management-client";var C={[b.DKLS]:{[W.EVM]:!0,[W.COSMOS]:!0},[b.CGGMP]:{[W.EVM]:!0,[W.COSMOS]:!0},[b.ED25519]:{[W.SOLANA]:!0}};function xe(i,e,t){if(!i||!e)return!1;switch(t){case"EMAIL":return i.toLowerCase()===e.toLowerCase();case"PHONE":return D(i)===D(e);case"CUSTOM_ID":return i===e;default:return i.replace(/^@/g,"").toLowerCase()===e.replace(/^@/g,"").toLowerCase()}}function le(i,e){return i.some(t=>!!C[e.scheme][t])}function ce(i){return Object.keys(C).filter(e=>e===b.CGGMP?!1:(Array.isArray(i)?i:Object.keys(i)).some(t=>C[e][t]))}function ht(i){return[...new Set(i.reduce((e,t)=>[...e,...Object.keys(C[t]).filter(r=>C[t][r])],[]))]}function pe(i){return ht(ce((Array.isArray(i)?i:[i]).map(e=>W[e])))}function L(i){return{...i,scheme:i.scheme,type:i.type,pregenIdentifierType:i.pregenIdentifierType}}function v(i){return["USER","PREGEN"].includes(i.type)&&(i.isPregen=i.type==="PREGEN",i.type=i.scheme===b.ED25519?W.SOLANA:W.EVM),i.scheme&&!i.type&&(i.type=i.scheme===b.ED25519?W.SOLANA:W.EVM),i}var mt=S.pki.rsa,de="RSA-OAEP",Oe="794241bc819a125a7b78ea313decc0bc",J=new Uint8Array([23,66,157,146,179,158,117,120,184,73,123,81]);function be(i){let e=S.md.sha256.create();return e.update(i),e.digest().toHex()}function _(i){let e=S.pki.publicKeyToRSAPublicKeyPem(i.publicKey);return Buffer.from(e,"utf-8").toString("hex")}function yt(i){let e=Le(i);return S.pki.publicKeyFromPem(e)}function Le(i){return Buffer.from(i,"hex").toString("utf-8")}function ue(i){let e=S.pki.privateKeyToPem(i.privateKey);return Buffer.from(e,"utf-8").toString("hex")}function ve(i){let e=Buffer.from(i,"hex").toString("utf-8");return S.pki.privateKeyFromPem(e)}async function ft(i,e){let t=ue(i),r=await window.crypto.subtle.importKey("raw",Buffer.from(e,"base64"),{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),s=new TextEncoder().encode(t),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:J},r,s);return Buffer.from(n).toString("base64")}async function _e(i,e){let t=await crypto.subtle.importKey("raw",Buffer.from(e,"base64"),{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:J},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return ve(s)}async function G(i,e){let t=S.random.createInstance();e&&(t.seedFileSync=s=>e,t.seedFile=(s,n)=>{n(null,e)});let r={bits:2048,e:65537,prng:t};if(!i.disableWorkers){r.workLoad=100,r.workers=e?1:-1;let s=await fetch(`${R(i)}/static/js/prime.worker.min.js`),n=new Blob([await s.text()],{type:"application/javascript"});r.workerScript=URL.createObjectURL(n)}return new Promise((s,n)=>mt.generateKeyPair(r,(o,a)=>{o&&n(o),s(a)}))}async function St(i,e){let t=gt.encode(e),r=await G(i,t);return _(r)}function Et(i){let e=S.random.getBytesSync(16),t=S.cipher.createCipher("AES-CBC",e);t.start({iv:Oe}),t.update(S.util.createBuffer(i)),t.finish();let r=t.output.toHex();return{key:e,encryptedMessageHex:r}}function Ue(i,e){let t=S.cipher.createDecipher("AES-CBC",i);return t.start({iv:Oe}),t.update(S.util.createBuffer(S.util.hexToBytes(e))),t.finish(),t.output.toString()}function wt(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.privateKey.decrypt(r,de);return Ue(s,e)}function B(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.decrypt(r,de);return Ue(s,e)}async function It(i,{seedValue:e,encryptedMessageHex:t,encryptedKeyHex:r}){let s=await G(i,e);return B(s.privateKey,t,r)}async function Pt(i,e,t){return Promise.all(t.map(async r=>({walletId:r.walletId,walletScheme:r.walletScheme,partnerId:r.partnerId,signer:await It(i,{seedValue:e,encryptedMessageHex:r.encryptedShare,encryptedKeyHex:r.encryptedKey}),protocolId:r.protocolId})))}async function At(i,e,t){let r;try{r=await _e(t,i)}catch{}try{r=await Ne(t,i)}catch{}if(!r)throw new Error("Could not decrypt private key");return e.map(s=>({walletId:s.walletId,walletScheme:s.walletScheme,partnerId:s.partnerId,signer:B(r,s.encryptedShare,s.encryptedKey),protocolId:s.protocolId}))}function Y(i,e){let{key:t,encryptedMessageHex:r}=Et(e),s=Le(i),o=S.pki.publicKeyFromPem(s).encrypt(t,de),a=Buffer.from(o,"utf-8").toString("hex");return{encryptedMessageHex:r,encryptedKeyHex:a}}function Tt(i){let e=Wt(),t=e+i,r=be(t);return{salt:e,hash:r}}function Wt(i=16){return S.util.bytesToHex(S.random.getBytesSync(i))}async function Ct(i){let e=Buffer.from(i,"hex");return await window.crypto.subtle.importKey("raw",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function Rt(i,e){let t=await Ct(e),r=ue(i),s=new TextEncoder().encode(r),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:J},t,s);return Buffer.from(n).toString("base64")}async function Ne(i,e){let t=await crypto.subtle.importKey("raw",Buffer.from(e,"hex"),{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:J},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return ve(s)}import xt from"@getpara/user-management-client";function Ke(i){switch(i){case"DEV":return"http://localhost:8080/";case"SANDBOX":return"https://api.sandbox.usecapsule.com/";case"BETA":return"https://api.beta.usecapsule.com/";case"PROD":return"https://api.usecapsule.com/";default:throw new Error(`unsupported env: ${i}`)}}function ke(i){switch(i){case"DEV":return"http://localhost:8080/";case"SANDBOX":return"https://api.sandbox.getpara.com/";case"BETA":return"https://api.beta.getpara.com/";case"PROD":return"https://api.getpara.com/";default:throw new Error(`unsupported env: ${i}`)}}function Pr(i,e){let t=e?"ws":"http";switch(i){case"DEV":return`${t}://localhost:3000`;case"SANDBOX":return`${t}s://mpc-network.sandbox.getpara.com`;case"BETA":return`${t}s://mpc-network.beta.getpara.com`;case"PROD":return`${t}s://mpc-network.prod.getpara.com`;default:throw new Error(`unsupported env: ${i}`)}}function he({env:i,version:e,apiKey:t,partnerId:r,useFetchAdapter:s=!1,retrieveSessionCookie:n,persistSessionCookie:o}){return new xt({userManagementHost:ke(i),version:["DEV","SANDBOX"].includes(i)?"dev":e,apiKey:t,partnerId:r,opts:{useFetchAdapter:s},retrieveSessionCookie:n,persistSessionCookie:o})}var me={};Ze(me,{initClient:()=>ge});import Ot from"axios";function ge(i,e){let t=Ot.create({baseURL:i});return e&&(t.defaults.adapter=function(r){return fetch(r.baseURL+r.url,{method:r.method,headers:r.headers,body:r.data,credentials:r.withCredentials?"include":void 0}).then(s=>s.text().then(n=>({data:n,status:s.status,statusText:s.statusText,headers:s.headers,config:r,request:fetch}))).catch(function(s){throw s})}),t}import{EncryptorType as Ve,KeyShareType as $e}from"@getpara/user-management-client";import{EncryptorType as Me,KeyShareType as Fe}from"@getpara/user-management-client";import{Encrypt as De,Decrypt as bt}from"@celo/utils/lib/ecies.js";import*as Ge from"ethereumjs-util";import*as Be from"node-forge";var U=class i{constructor(e,t,r){this.walletId=e,this.keyshare=t,this.address=r,this.backupDecryptionKey=Buffer.from(Be.random.getBytesSync(32),"binary").toString("hex")}static buildFrom(e){try{let t=JSON.parse(e);return Object.assign(new i("","",""),t)}catch{let r=new i("","","");return r.backupDecryptionKey=e.split("|")[0],r}}getPublicEncryptionKey(){return Buffer.from(Ge.privateToPublic(Buffer.from(this.backupDecryptionKey,"hex")))}getPublicEncryptionKeyHex(){return this.getPublicEncryptionKey().toString("hex")}encryptForSelf(e){try{let t=this.getPublicEncryptionKey();return De(t,Buffer.from(e,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}static encryptWithPublicKey(e,t){try{return De(e,Buffer.from(t,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}decrypt(e){try{let t=Buffer.from(e,"base64"),r=bt(Buffer.from(this.backupDecryptionKey,"hex"),t);return Buffer.from(r.buffer).toString("ucs2")}catch{throw Error("Error decrypting backup")}}};async function X({ctx:i,userId:e,walletId:t,otherEncryptedShares:r=[],userSigner:s,ignoreRedistributingBackupEncryptedShare:n=!1,emailProps:o={},forceRefresh:a=!1}){if(n)return await i.client.uploadUserKeyShares(e,r.map(f=>({walletId:t,...f}))),"";let l,c,{recoveryPublicKeys:p}=await i.client.getRecoveryPublicKeys(e);if(a||!p?.length){c=new U(t,"","");let{recoveryPublicKeys:f}=await i.client.persistRecoveryPublicKeys(e,[c.getPublicEncryptionKeyHex()]),m=c.encryptForSelf(s);l=[{walletId:t,encryptedShare:m,type:Fe.USER,encryptor:Me.RECOVERY,recoveryPublicKeyId:f[0].id}]}else l=p.map(f=>{let{id:m,publicKey:u}=f,I=U.encryptWithPublicKey(Buffer.from(u,"hex"),s);return{walletId:t,encryptedShare:I,type:Fe.USER,encryptor:Me.RECOVERY,recoveryPublicKeyId:m}});return await i.client.uploadUserKeyShares(e,[...r.map(f=>({walletId:t,...f})),...n?[]:l]),await i.client.distributeParaShare({userId:e,walletId:t,useDKLS:i.useDKLS,...o}),c?JSON.stringify(c):""}async function N({ctx:i,userId:e,walletId:t,userShare:r,ignoreRedistributingBackupEncryptedShare:s=!1,emailProps:n={},partnerId:o,protocolId:a}){let c=(await i.client.getSessionPublicKeys(e)).data.keys.map(u=>{if(!u.publicKey)return;let{encryptedMessageHex:I,encryptedKeyHex:d}=Y(u.sigDerivedPublicKey,r);return{encryptedShare:I,encryptedKey:d,type:$e.USER,encryptor:Ve.BIOMETRICS,biometricPublicKey:u.sigDerivedPublicKey,partnerId:o,protocolId:a}}).filter(Boolean),f=(await i.client.getPasswords({userId:e})).map(u=>{if(u.status==="PENDING")return;let{encryptedMessageHex:I,encryptedKeyHex:d}=Y(u.sigDerivedPublicKey,r);return{encryptedShare:I,encryptedKey:d,type:$e.USER,encryptor:Ve.PASSWORD,passwordId:u.id,partnerId:o,protocolId:a}}).filter(Boolean),m=[...c,...f];return await X({ctx:i,userId:e,walletId:t,otherEncryptedShares:m,userSigner:r,ignoreRedistributingBackupEncryptedShare:s,emailProps:n})}import{Encrypt as Lt,Decrypt as vt}from"@celo/utils/lib/ecies.js";import{Buffer as K}from"buffer";import*as He from"ethereumjs-util";import{randomBytes as _t}from"crypto";async function je(i,e){let t,r;for(;;)try{t=_t(32).toString("hex"),r=He.privateToPublic(K.from(t,"hex"));break}catch{continue}let s=K.from(r),n=Lt(s,K.from(i,"ucs2")).toString("base64"),{data:{id:o}}=await e.tempTrasmissionInit(n);return encodeURIComponent(o+"|"+t)}async function Ut(i,e){let[t,r]=decodeURIComponent(i).split("|"),n=(await e.tempTrasmission(t)).data.message,o=K.from(n,"base64");return K.from(vt(K.from(r,"hex"),o).buffer).toString("ucs2")}var q=class extends Error{constructor(e){super("transaction review error"),this.name="TransactionReviewError",this.transactionReviewUrl=e}},M=class extends Error{constructor(){super("transaction review has been denied by the user"),this.name="TransactionReviewDenied"}},F=class extends Error{constructor(e,t){super("transaction review has timed out"),this.name="TransactionReviewTimeout",this.transactionReviewUrl=e,this.pendingTransactionId=t}};var Je='1.3.0',y="@CAPSULE/",z=`${y}e-mail`,Q=`${y}phone`,Z=`${y}countryCode`,Ye=`${y}farcasterUsername`,ee=`${y}telegramUserId`,te=`${y}userId`,V=`${y}ed25519Wallets`,O=`${y}wallets`,re=`${y}externalWallets`,se=`${y}currentWalletIds`,ie=`${y}currentExternalWalletAddresses`,k=`${y}sessionCookie`,$=`${y}loginEncryptionKeyPair`,x=2e3,ye=1e3;typeof global<"u"?global.Buffer=global.Buffer||fe:typeof window<"u"?(window.Buffer=window.Buffer||fe,window.global=window.global||window):(self.Buffer=self.Buffer||fe,self.global=self.global||self);var{pki:ze,jsbn:Ft}=Mt,H=class i{constructor(e,t,r){this.isAwaitingAccountCreation=!1;this.isAwaitingLogin=!1;this.isAwaitingFarcaster=!1;this.isAwaitingOAuth=!1;this.currentWalletIds={};this.#e=void 0;this.#t=void 0;this.localStorageGetItem=e=>this.platformUtils.localStorage.get(e);this.localStorageSetItem=(e,t)=>this.platformUtils.localStorage.set(e,t);this.sessionStorageGetItem=e=>this.platformUtils.sessionStorage.get(e);this.sessionStorageSetItem=(e,t)=>this.platformUtils.sessionStorage.set(e,t);this.sessionStorageRemoveItem=e=>this.platformUtils.sessionStorage.removeItem(e);this.retrieveSessionCookie=()=>this.sessionCookie;this.clearStorage=async(e="all")=>{let t=e==="all";(t||e==="local")&&this.platformUtils.localStorage.clear(y),(t||e==="session")&&this.platformUtils.sessionStorage.clear(y),(t||e==="secure")&&this.platformUtils.secureStorage&&this.platformUtils.secureStorage.clear(y)};this.createWalletPerMissingType=this.createWalletPerType;r||(r={}),this.emailPrimaryColor=r.emailPrimaryColor,this.emailTheme=r.emailTheme,this.homepageUrl=r.homepageUrl,this.supportUrl=r.supportUrl,this.xUrl=r.xUrl,this.githubUrl=r.githubUrl,this.linkedinUrl=r.linkedinUrl,this.portalBackgroundColor=r.portalBackgroundColor,this.portalPrimaryButtonColor=r.portalPrimaryButtonColor,this.portalTextColor=r.portalTextColor,this.portalPrimaryButtonTextColor=r.portalPrimaryButtonTextColor,this.portalTheme=r.portalTheme,this.platformUtils=this.getPlatformUtils(),this.disableProviderModal=this.platformUtils.disableProviderModal,r.useStorageOverrides&&(this.localStorageGetItem=r.localStorageGetItemOverride,this.localStorageSetItem=r.localStorageSetItemOverride,this.sessionStorageGetItem=r.sessionStorageGetItemOverride,this.sessionStorageSetItem=r.sessionStorageSetItemOverride,this.sessionStorageRemoveItem=r.sessionStorageRemoveItemOverride,this.clearStorage=r.clearStorageOverride),r.useSessionStorage&&(this.localStorageGetItem=this.sessionStorageGetItem,this.localStorageSetItem=this.sessionStorageSetItem),this.persistSessionCookie=d=>{this.sessionCookie=d,(r.useSessionStorage?this.sessionStorageSetItem:this.localStorageSetItem)(k,d)},this.ctx={env:e,apiKey:t,client:he({env:e,version:i.version,apiKey:t,partnerId:this.isPortal(e)?r.portalPartnerId:void 0,useFetchAdapter:!!r.disableWorkers,retrieveSessionCookie:this.retrieveSessionCookie,persistSessionCookie:this.persistSessionCookie}),disableWorkers:r.disableWorkers,offloadMPCComputationURL:r.offloadMPCComputationURL,useLocalFiles:r.useLocalFiles,useDKLS:r.useDKLSForCreation||!r.offloadMPCComputationURL,disableWebSockets:!!r.disableWebSockets,wasmOverride:r.wasmOverride,cosmosPrefix:this.cosmosPrefix},r.offloadMPCComputationURL&&(this.ctx.mpcComputationClient=ge(r.offloadMPCComputationURL,r.disableWorkers));try{this.#e=r.supportedWalletTypes?(()=>{if(Object.values(r.supportedWalletTypes).every(d=>!!d&&typeof d=="object"&&d.optional))throw new Error("at least one wallet type must be non-optional");if(!Object.keys(r.supportedWalletTypes).every(d=>Object.values(w).includes(d)))throw new Error("unsupported wallet type");return this.#t=r.supportedWalletTypes,Object.entries(r.supportedWalletTypes).reduce((d,[E,A])=>A?(E===w.COSMOS&&typeof A=="object"&&A.prefix&&(this.cosmosPrefix=A.prefix),[...d,{type:E,optional:A===!0?!1:A.optional??!1}]):d,[])})():void 0}catch{this.#e=void 0}if(!this.platformUtils.isSyncStorage||r.useStorageOverrides)return;this.email=this.localStorageGetItem(z)||void 0,this.countryCode=this.localStorageGetItem(Z)||void 0,this.phone=this.localStorageGetItem(Q)||void 0,this.userId=this.localStorageGetItem(te)||void 0,this.telegramUserId=this.localStorageGetItem(ee)||void 0;let s=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(O):this.localStorageGetItem(O),n=JSON.parse(s||"{}"),o=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(V):this.localStorageGetItem(V),a=JSON.parse(o||"{}"),l={...Object.keys(n).reduce((d,E)=>({...d,[E]:v(n[E])}),{}),...Object.keys(a).reduce((d,E)=>({...d,...d[E]?{}:{[E]:v(a[E])}}),{})};this.setWallets(l);let c=this.localStorageGetItem(se)??void 0,p=[void 0,null,"undefined"].includes(c)?{}:(()=>{let d=JSON.parse(c);return Array.isArray(d)?Object.keys(w).reduce((E,A)=>{let Ee=Object.values(this.wallets).find(we=>d.includes(we.id)&&C[we.scheme][A]);return{...E,...Ee&&!E[A]?{[A]:[Ee.id]}:{}}},{}):d})();this.setCurrentWalletIds(p),this.sessionCookie=this.localStorageGetItem(k)||this.sessionStorageGetItem(k)||void 0,Object.values(this.wallets).filter(d=>this.isWalletOwned(d)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0});let f=this.sessionStorageGetItem($);f&&f!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(f)));let m=this.localStorageGetItem(re),u=JSON.parse(m||"{}");this.setExternalWallets(u);let I=this.localStorageGetItem(ie)||void 0;this.currentExternalWalletAddresses=I?JSON.parse(I):void 0}static{this.version=Je}get isEmail(){return!!this.email&&!this.phone&&!this.countryCode&&!this.farcasterUsername&&!this.telegramUserId}get isPhone(){return!!this.phone&&!!this.countryCode&&!this.email&&!this.farcasterUsername&&!this.telegramUserId}get isFarcaster(){return!!this.farcasterUsername&&!this.email&&!this.phone&&!this.countryCode&&!this.telegramUserId}get isTelegram(){return!!this.telegramUserId&&!this.email&&!this.phone&&!this.countryCode&&!this.farcasterUsername}get currentWalletIdsArray(){return this.supportedWalletTypes.reduce((e,{type:t})=>[...e,...(this.currentWalletIds[t]??[]).map(r=>[r,t])],[])}get currentWalletIdsUnique(){return[...new Set(Object.values(this.currentWalletIds).flat())]}get pregenIds(){return{...Object.values(this.wallets).filter(e=>!this.userId||this.isPregenWalletClaimable(e)).reduce((e,t)=>(e[t.pregenIdentifierType]??[]).includes(t.pregenIdentifier)?e:{...e,[t.pregenIdentifierType]:[...new Set([...e[t.pregenIdentifierType]??[],t.pregenIdentifier])]},{})}}get isMultiWallet(){return this.currentWalletIdsArray.length>1}#e;#t;get supportedWalletTypes(){return this.#e??[]}get isWalletTypeEnabled(){return this.supportedWalletTypes.reduce((e,{type:t})=>({...e,[t]:!0}),{})}convertBigInt(e){let t=new Ft.BigInteger(null);return t.data=e.data,t.s=e.s,t.t=e.t,t}convertEncryptionKeyPair(e){return{privateKey:ze.setRsaPrivateKey(this.convertBigInt(e.privateKey.n),this.convertBigInt(e.privateKey.e),this.convertBigInt(e.privateKey.d),this.convertBigInt(e.privateKey.p),this.convertBigInt(e.privateKey.q),this.convertBigInt(e.privateKey.dP),this.convertBigInt(e.privateKey.dQ),this.convertBigInt(e.privateKey.qInv)),publicKey:ze.setRsaPublicKey(this.convertBigInt(e.publicKey.n),this.convertBigInt(e.publicKey.e))}}isPortal(e){return typeof window>"u"?!1:!!window.location?.host&&R(e?{env:e}:this.ctx).includes(window.location.host)}isParaConnect(){return typeof window>"u"?!1:!!window.location?.host&&Re(this.ctx).includes(window.location.host)}requireApiKey(){if(!this.ctx.apiKey)throw new Error(`in order to create a wallet or user with Para, you
2
+ must provide an API key to the Para instance`)}isWalletSupported(e){return!this.#e||le(this.supportedWalletTypes.map(({type:t})=>t)??[],e)}isWalletOwned(e){return this.isWalletSupported(e)&&!e.pregenIdentifier&&!e.pregenIdentifierType&&!!this.userId&&e.userId===this.userId}isPregenWalletUnclaimed(e){return this.isWalletSupported(e)&&(!e.userId||e.isPregen&&!!e.pregenIdentifier&&!!e.pregenIdentifierType)}isPregenWalletClaimable(e){return this.isWalletSupported(e)&&this.isPregenWalletUnclaimed(e)&&(!["EMAIL","PHONE","TELEGRAM"].includes(e.pregenIdentifierType)||xe(e.pregenIdentifierType==="EMAIL"?this.email:e.pregenIdentifierType==="TELEGRAM"?this.telegramUserId:this.getPhoneNumber(),e.pregenIdentifier,e.pregenIdentifierType))}isWalletUsable(e,{type:t,scheme:r,forbidPregen:s=!1}={},n=!1){let o;if(!this.wallets[e])o=`wallet with id ${e} does not exist`;else{let a=this.wallets[e],[l,c]=[this.isPregenWalletUnclaimed(a),this.isWalletOwned(a)];s&&l?o=`pre-generated wallet with id ${a.id} cannot be selected`:!c&&!l?o=`wallet with id ${a.id} is not owned by the current user`:this.isWalletSupported(a)?t&&(!pe(t).includes(a.type)||c&&!t.some(p=>(this.currentWalletIds[p]??[]).includes(e)))?o=`wallet with id ${a.id} and type ${a.type} cannot be selected`:r&&!r.includes(a.scheme)&&(o=`wallet with id ${a.id} and scheme ${a.scheme} cannot be selected`):o=`wallet with id ${a.id} and type ${a.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({type:p})=>p).join(", ")}`}if(o){if(n)throw new Error(o);return!1}return!0}getDisplayAddress(e,t={}){if(this.externalWallets[e]){let n=this.externalWallets[e];return t.truncate?ne(n.address,n.type,{prefix:this.cosmosPrefix}):n.address}let r=this.findWallet(e,t.addressType);if(!r)return;let s;switch(r.type){case w.COSMOS:s=Ie(r.publicKey,this.cosmosPrefix??"cosmos");break;default:s=r.address;break}return t.truncate?ne(s,r.type,{prefix:this.cosmosPrefix}):s}getIdenticonHash(e,t){if(this.externalWallets[e]){let s=this.externalWallets[e];return`${s.id}-${s.address}-${s.type}`}let r=this.findWallet(e,t);return r?`${r.id}-${r.address}-${r.type}`:void 0}getWallets(){return this.wallets}getAddress(e){return e?this.wallets[e].address:Object.values(this.wallets)?.[0]?.address}async constructPortalUrl(e,t={}){let r=e==="onRamp"?R(this.ctx):await this.getPortalURL(t.partnerId),s;switch(e){case"createPassword":{s=`/web/users/${this.userId}/passwords/${t.pathId}`;break}case"createAuth":{s=`/web/users/${this.userId}/biometrics/${t.pathId}`;break}case"loginPassword":{s="/web/passwords/login";break}case"loginAuth":{s="/web/biometrics/login";break}case"txReview":{s=`/web/users/${this.userId}/transaction-review/${t.pathId}`;break}case"onRamp":{s=`/web/users/${this.userId}/on-ramp-transaction/${t.pathId}`;break}default:throw new Error(`invalid URL type ${e}`)}let[n,o,a]=[["createAuth","createPassword"].includes(e),["loginAuth","loginPassword"].includes(e),e==="onRamp"],l=t.partnerId?(await this.ctx.client.getPartner(t.partnerId)).data?.partner:void 0,c={apiKey:this.ctx.apiKey,partnerId:t.partnerId,portalFont:t.theme?.font||l?.font||this.portalTheme?.font,portalBorderRadius:t.theme?.borderRadius||this.portalTheme?.borderRadius,portalThemeMode:t.theme?.mode||l?.themeMode||this.portalTheme?.mode,portalAccentColor:t.theme?.accentColor||l?.accentColor||this.portalTheme?.accentColor,portalForegroundColor:t.theme?.foregroundColor||l?.foregroundColor||this.portalTheme?.foregroundColor,portalBackgroundColor:t.theme?.backgroundColor||l?.backgroundColor||this.portalBackgroundColor||this.portalTheme?.backgroundColor,portalPrimaryButtonColor:this.portalPrimaryButtonColor,portalTextColor:this.portalTextColor,portalPrimaryButtonTextColor:this.portalPrimaryButtonTextColor,isForNewDevice:t.isForNewDevice?t.isForNewDevice.toString():void 0,supportedWalletTypes:this.#t?JSON.stringify(this.#t):void 0,...n||o?{...t.authType==="email"?{email:this.email}:{},...t.authType==="phone"?{phone:this.phone,countryCode:this.countryCode}:{},...t.authType==="farcaster"?{farcasterUsername:this.farcasterUsername}:{},...t.authType==="telegram"?{telegramUserId:this.telegramUserId}:{}}:{},...o||a?{sessionId:t.sessionId}:{},...o?{encryptionKey:t.loginEncryptionPublicKey,newDeviceSessionLookupId:t.newDeviceSessionId,newDeviceEncryptionKey:t.newDeviceEncryptionKey,pregenIds:JSON.stringify(this.pregenIds),displayName:t.displayName,pfpUrl:t.pfpUrl}:{},...t.params||{}};return j({base:r,path:s,params:c})}async touchSession(e=!1){let t=await this.ctx.client.touchSession(e);return this.setSupportedWalletTypes(t.data.supportedWalletTypes,t.data.cosmosPrefix),t}setSupportedWalletTypes(e,t){e&&!this.#e&&(this.#e=e,Object.keys(this.currentWalletIds).forEach(r=>{this.#e?.some(({type:s})=>s===r)||delete this.currentWalletIds[r]})),t&&!this.cosmosPrefix&&(this.cosmosPrefix=t)}getVerificationEmailProps(){return{brandColor:this.emailPrimaryColor,theme:this.emailTheme,supportUrl:this.supportUrl,homepageUrl:this.homepageUrl,xUrl:this.xUrl,githubUrl:this.githubUrl,linkedinUrl:this.linkedinUrl}}getBackupKitEmailProps(){return{brandColor:this.emailPrimaryColor,theme:this.emailTheme,homepageUrl:this.homepageUrl,xUrl:this.xUrl,linkedinUrl:this.linkedinUrl,githubUrl:this.githubUrl,supportUrl:this.supportUrl}}async init(){this.email=await this.localStorageGetItem(z)||void 0,this.countryCode=await this.localStorageGetItem(Z)||void 0,this.phone=await this.localStorageGetItem(Q)||void 0,this.userId=await this.localStorageGetItem(te)||void 0,this.telegramUserId=await this.localStorageGetItem(ee)||void 0;let e=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(O):await this.localStorageGetItem(O),t=JSON.parse(e||"{}"),r=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(V):await this.localStorageGetItem(V),s=JSON.parse(r||"{}"),n={...Object.keys(t).reduce((m,u)=>({...m,[u]:v(t[u])}),{}),...Object.keys(s).reduce((m,u)=>({...m,...m[u]?{}:{[u]:v(s[u])}}),{})};await this.setWallets(n);let o=await this.localStorageGetItem(se)??void 0,a=[void 0,null,"undefined","null"].includes(o)?{}:(()=>{let m=JSON.parse(o);return Array.isArray(m)?Object.keys(w).reduce((u,I)=>{let d=Object.values(this.wallets).find(E=>m.includes(E.id)&&C[E.scheme][I]);return{...u,...d&&!u[I]?{[I]:[d.id]}:{}}},{}):m})();await this.setCurrentWalletIds(a),this.sessionCookie=await this.localStorageGetItem(k)||await this.sessionStorageGetItem(k)||void 0,Object.values(this.wallets).filter(m=>this.isWalletOwned(m)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0});let l=await this.sessionStorageGetItem($);l&&l!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(l)));let c=await this.localStorageGetItem(re),p=JSON.parse(c||"{}");await this.setExternalWallets(p);let f=await this.localStorageGetItem(ie)||void 0;this.currentExternalWalletAddresses=f?JSON.parse(f):void 0,await this.touchSession()}async setEmail(e){this.email=e,await this.localStorageSetItem(z,e)}async setTelegramUserId(e){this.telegramUserId=e,await this.localStorageSetItem(ee,e)}async setPhoneNumber(e,t){this.phone=e,this.countryCode=t,await this.localStorageSetItem(Q,e),await this.localStorageSetItem(Z,t)}async setFarcasterUsername(e){this.farcasterUsername=e,await this.localStorageSetItem(Ye,e)}async setExternalWallet({address:e,type:t,provider:r,addressBech32:s}){this.externalWallets={[e]:{id:e,address:s??e,type:t,name:r,isExternal:!0,signer:""}},this.currentExternalWalletAddresses=[e],this.setCurrentExternalWalletAddresses(this.currentExternalWalletAddresses),this.setExternalWallets(this.externalWallets),g(h.EXTERNAL_WALLET_CHANGE_EVENT,null)}async setUserId(e){this.userId=e,await this.localStorageSetItem(te,e)}async setWallets(e){if(this.wallets=e,this.platformUtils.secureStorage){await this.platformUtils.secureStorage.set(O,JSON.stringify(e));return}await this.localStorageSetItem(O,JSON.stringify(e))}async setExternalWallets(e){this.externalWallets=e,await this.localStorageSetItem(re,JSON.stringify(e))}async setCurrentExternalWalletAddresses(e){this.currentExternalWalletAddresses=e,await this.localStorageSetItem(ie,JSON.stringify(e))}async setLoginEncryptionKeyPair(e){e||(e=await G(this.ctx)),this.loginEncryptionKeyPair=e,await this.sessionStorageSetItem($,JSON.stringify(e))}async deleteLoginEncryptionKeyPair(){this.loginEncryptionKeyPair=void 0,await this.sessionStorageRemoveItem($)}getUserId(){return this.userId}getEmail(){return this.email}getPhone(){return{phone:this.phone,countryCode:this.countryCode}}getPhoneNumber(){if(!(!this.phone||!this.countryCode))return Pe(this.countryCode,this.phone)}getFarcasterUsername(){return this.farcasterUsername}async setCurrentWalletIds(e,{needsWallet:t=!1,sessionLookupId:r,newDeviceSessionLookupId:s}={}){this.currentWalletIds=e,await this.localStorageSetItem(se,JSON.stringify(this.currentWalletIds)),r&&await this.ctx.client.setCurrentWalletIds(this.getUserId(),this.currentWalletIds,t,r,s),g(h.WALLETS_CHANGE_EVENT,null)}findWalletId(e,t={}){if(e)this.assertIsValidWalletId(e,t);else{for(let r of[...this.currentWalletIdsUnique,...Object.keys(this.wallets)])if(this.isWalletUsable(r,t)){e=r;break}if(!e)throw new Error("no valid wallet id found")}return e}findWalletByAddress(e,t){if(this.externalWallets[e])return this.externalWallets[e];let r;if(Object.entries(this.currentWalletIds).forEach(([s,n])=>{let o=Object.keys(this.wallets).filter(a=>this.wallets[a].type===s&&this.isPregenWalletClaimable(this.wallets[a]));[...n,...o].forEach(a=>{e.toLowerCase()===this.getDisplayAddress(a,{addressType:s}).toLowerCase()&&(r=this.wallets[a])})}),!r)throw new Error(`wallet with address ${e} not found`);return this.assertIsValidWalletId(r.id,t),r}findWallet(e,t,r={}){if(!e&&Object.keys(this.externalWallets).length>0)return Object.values(this.externalWallets)[0];if(this.externalWallets[e])return this.externalWallets[e];try{let s=this.findWalletId(e,r);if(s&&this.wallets[s]){let{signer:n,...o}=this.wallets[s],a=t??this.currentWalletIdsArray.find(([l])=>l===s)?.[1]??o.type;return{...o,type:w[a]}}}catch{return}}get availableWallets(){return[...this.currentWalletIdsArray.map(([e,t])=>[e,t,!1]).map(([e,t])=>{let r=this.findWallet(e,t);return r?{id:r.id,type:t,address:this.getDisplayAddress(e,{addressType:t}),name:r.name}:null}).filter(e=>e!==null),...Object.values(this.externalWallets??{})]}getWalletsByType(e){return Object.values(this.wallets).filter(t=>this.isWalletUsable(t.id,{type:[e]}))}assertIsValidWalletId(e,t={}){this.isWalletUsable(e,t,!0)}async assertIsValidWalletType(e,t){if(this.#e||await this.touchSession(),!e||!Object.values(w).includes(e)||!(t??this.supportedWalletTypes.map(({type:r})=>r)).includes(e))throw new Error(`wallet type ${e} is not supported`);return e}async getMissingTypes(){return this.#e||await this.touchSession(),this.supportedWalletTypes.filter(({type:e,optional:t})=>!t&&Object.values(this.wallets).every(r=>!this.isWalletOwned(r)||!C[r.scheme][e])).map(({type:e})=>e)}async getTypesToCreate(e){return this.#e||await this.touchSession(),ce(e??await this.getMissingTypes()).map(t=>{switch(t){case P.ED25519:return w.SOLANA;default:return this.supportedWalletTypes.some(({type:r,optional:s})=>r===w.COSMOS&&!s)?w.COSMOS:w.EVM}})}async getPartnerURL(e){return(await this.ctx.client.getPartner(e)).data.partner.portalUrl}async getPortalURL(e){return e&&await this.getPartnerURL(e)||R(this.ctx)}async getWebAuthURLForCreate({webAuthId:e,...t}){return this.constructPortalUrl("createAuth",{...t,pathId:e})}async getPasswordURLForCreate({passwordId:e,...t}){return this.constructPortalUrl("createPassword",{...t,pathId:e})}getShortUrl(e){return j({base:R(this.ctx),path:`/short/${e}`})}async shortenLoginLink(e){let t=await je(e,this.ctx.client);return this.getShortUrl(t)}async getWebAuthURLForLogin(e){return this.constructPortalUrl("loginAuth",e)}async getPasswordURLForLogin(e){return this.constructPortalUrl("loginPassword",e)}async getWebAuthURLForLoginForPhone(e){return this.constructPortalUrl("loginAuth",{authType:"phone",...e})}async getPrivateKey(e){let t=Object.values(this.wallets),r=e?this.wallets[e]:t?.[0];if(!r)throw new Error("wallet not found");if(r.scheme!==P.DKLS)throw new Error("invalid wallet scheme");return await this.platformUtils.getPrivateKey(this.ctx,this.userId,r.id,r.signer,this.retrieveSessionCookie())}async fetchWallets(){return(await(this.isPortal()||this.isParaConnect()?this.ctx.client.getAllWallets(this.userId):this.ctx.client.getWallets(this.userId,!0))).data.wallets.filter(t=>!!t.address&&(this.isParaConnect()||!this.isParaConnect()&&this.isWalletSupported(L(t))))}async populateWalletAddresses(){(await this.ctx.client.getWallets(this.userId,!0)).data.wallets.forEach(r=>{this.wallets[r.id]&&(this.wallets[r.id]={...L(r),...this.wallets[r.id]})}),await this.setWallets(this.wallets)}async populatePregenWalletAddresses(){(await this.getPregenWallets()).forEach(t=>{this.wallets[t.id]&&(this.wallets[t.id]={...L(t),...this.wallets[t.id]})}),await this.setWallets(this.wallets)}async checkIfUserExists({email:e}){return(await this.ctx.client.checkUserExists({email:e})).data.exists}async checkIfUserExistsByPhone({phone:e,countryCode:t}){return(await this.ctx.client.checkUserExists({phone:e,countryCode:t})).data.exists}async createUser({email:e}){this.requireApiKey(),await this.setEmail(e);let{userId:t}=await this.ctx.client.createUser({email:this.email,...this.getVerificationEmailProps()});await this.setUserId(t)}async createUserByPhone({phone:e,countryCode:t}){this.requireApiKey(),await this.setPhoneNumber(e,t);let{userId:r}=await this.ctx.client.createUser({phone:this.phone,countryCode:this.countryCode});await this.setUserId(r)}async externalWalletLogin(e){this.requireApiKey();let{userId:t}=await this.ctx.client.externalWalletLogin({externalAddress:e.address,type:e.type,externalWalletProvider:e.provider});await this.setExternalWallet(e),await this.setUserId(t)}isUsingExternalWallet(){return!!Object.keys(this.externalWallets).length}async verifyEmail({verificationCode:e}){return await this.ctx.client.verifyEmail(this.userId,{verificationCode:e}),this.getSetUpBiometricsURL()}async verifyPhone({verificationCode:e}){return await this.ctx.client.verifyPhone(this.userId,{verificationCode:e}),this.getSetUpBiometricsURLForPhone()}async verifyTelegram(e){let t=await this.ctx.client.verifyTelegram(e);return t.isValid&&(await this.setUserId(t.userId),await this.setTelegramUserId(t.telegramUserId),await this.touchSession(!0),this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair()),t}async verify2FA({email:e,verificationCode:t}){let r=await this.ctx.client.verify2FA(e,t);return{initiatedAt:r.data.initiatedAt,status:r.data.status,userId:r.data.userId,wallets:r.data.wallets}}async verify2FAForPhone({phone:e,countryCode:t,verificationCode:r}){let s=await this.ctx.client.verify2FAForPhone(e,t,r);return{initiatedAt:s.data.initiatedAt,status:s.data.status,userId:s.data.userId,wallets:s.data.wallets}}async setup2FA(){return{uri:(await this.ctx.client.setup2FA(this.userId)).data.uri}}async enable2FA({verificationCode:e}){await this.ctx.client.enable2FA(this.userId,e)}async check2FAStatus(){return this.userId?{isSetup:(await this.ctx.client.check2FAStatus(this.userId)).data.isSetup}:{isSetup:!1}}async resendVerificationCode(){await this.ctx.client.resendVerificationCode({userId:this.userId,...this.getVerificationEmailProps()})}async resendVerificationCodeByPhone(){await this.ctx.client.resendVerificationCodeByPhone({userId:this.userId})}async getSetUpBiometricsURL({authType:e="email",isForNewDevice:t=!1}={}){let r=await this.ctx.client.addSessionPublicKey(this.userId,{status:Xe.PENDING,type:qe.WEB});return this.getWebAuthURLForCreate({authType:e,isForNewDevice:t,webAuthId:r.data.id,partnerId:r.data.partnerId})}async getSetUpBiometricsURLForPhone({isForNewDevice:e=!1}={}){let t=await this.ctx.client.addSessionPublicKey(this.userId,{status:Xe.PENDING,type:qe.WEB});return this.getWebAuthURLForCreate({authType:"phone",isForNewDevice:e,webAuthId:t.data.id,partnerId:t.data.partnerId})}async getSetupPasswordURL({authType:e="email",isForNewDevice:t=!1,theme:r}={}){let s=await this.ctx.client.addSessionPasswordPublicKey(this.userId,{status:Gt.PENDING});return this.getPasswordURLForCreate({authType:e,isForNewDevice:t,passwordId:s.data.id,partnerId:s.data.partnerId,theme:r})}async isSessionActive(){return this.isUsingExternalWallet()?!0:!!(await this.touchSession()).data.isAuthenticated}async isFullyLoggedIn(){return this.isUsingExternalWallet()?!0:await this.isSessionActive()&&this.currentWalletIdsArray.length>0&&this.currentWalletIdsArray.reduce((t,[r])=>t&&!!this.wallets[r],!0)}async supportedAuthMethods(e){let{supportedAuthMethods:t}=await this.ctx.client.getSupportedAuthMethods(e),r=new Set;for(let s of t)switch(s){case"PASSWORD":r.add(Se.PASSWORD);break;case"BIOMETRIC":r.add(Se.PASSKEY);break}return r}async getUserBiometricLocationHints(){if(!this.email&&!this.phone&&!this.farcasterUsername&&!this.telegramUserId)throw new Error("one of email, phone or farcaster username are required to get biometric location hints");return await this.ctx.client.getBiometricLocationHints({email:this.email,phone:this.phone,countryCode:this.countryCode,farcasterUsername:this.farcasterUsername,telegramUserId:this.telegramUserId})}async setAuth(e){let t=Bt(e);if(t){switch(t.authType){case"email":await this.setEmail(t.identifier);break;case"phone":await this.setPhoneNumber(t.auth.phone,t.auth.countryCode);break;case"farcaster":await this.setFarcasterUsername(t.identifier);break;case"telegram":await this.setTelegramUserId(t.identifier);break}return t}}async initiateUserLogin({useShortUrl:e=!1,...t}){let r=await this.setAuth(t);if(!r)return;let s=await this.touchSession(!0);this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair();let n=await this.getWebAuthURLForLogin({authType:r.authType,sessionId:s.data.sessionId,partnerId:s.data.partnerId,loginEncryptionPublicKey:_(this.loginEncryptionKeyPair)});return e?this.shortenLoginLink(n):n}async initiateUserLoginV2(e){let t=await this.setAuth(e);if(t)return await this.touchSession(!0),this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair(),await this.supportedAuthMethods(t.auth)}async initiateUserLoginForPhone({useShortUrl:e=!1,...t}){await this.setAuth(t);let r=await this.touchSession(!0);this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair();let s=await this.getWebAuthURLForLoginForPhone({sessionId:r.data.sessionId,loginEncryptionPublicKey:_(this.loginEncryptionKeyPair),partnerId:r.data.partnerId});return e?this.shortenLoginLink(s):s}async waitForAccountCreation(){for(await this.touchSession(),this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingAccountCreation=!0;this.isAwaitingAccountCreation;)try{if(await new Promise(e=>setTimeout(e,x)),await this.isSessionActive())return this.isAwaitingAccountCreation=!1,g(h.ACCOUNT_CREATION_EVENT,!0),!0}catch(e){console.error(e)}return!1}async waitForPasskeyAndCreateWallet(){await this.waitForAccountCreation();let e=await this.getPregenWallets(),t,r={};e.length>0&&(t=await this.claimPregenWallets(),r=this.supportedWalletTypes.reduce((o,{type:a})=>({...o,[a]:[e.find(l=>!!C[l.scheme][a])?.id]}),{}));let s=await this.createWalletPerType();t=t??s.recoverySecret,r={...r,...s.walletIds};let n={walletIds:r,recoverySecret:t};return g(h.ACCOUNT_SETUP_EVENT,n),n}async getFarcasterConnectURL(){await this.logout(),await this.touchSession(!0);let{data:{connect_uri:e}}=await this.ctx.client.initializeFarcasterLogin();return e}async waitForFarcasterStatus(){for(this.isAwaitingFarcaster=!0;this.isAwaitingFarcaster;)try{await new Promise(t=>setTimeout(t,x));let e=await this.ctx.client.getFarcasterAuthStatus();if(e.data.state==="completed"){let{userId:t,userExists:r,username:s,pfpUrl:n}=e.data;return await this.setUserId(t),await this.setFarcasterUsername(s),{userExists:r,username:s,pfpUrl:n}}}catch(e){console.error(e),this.isAwaitingFarcaster=!1}}async getOAuthURL({method:e,deeplinkUrl:t}){await this.logout();let r=await this.touchSession(!0);return j({base:e===kt.TELEGRAM?R(this.ctx,!0):Ke(this.ctx.env),path:`/auth/${e.toLowerCase()}`,params:{apiKey:this.ctx.apiKey,sessionLookupId:r.data.sessionLookupId,deeplinkUrl:t}})}async waitForOAuth({popupWindow:e}={}){for(this.isAwaitingOAuth=!0;this.isAwaitingOAuth;)try{if(e?.closed)return{isError:!0,userExists:!1};if(await new Promise(t=>setTimeout(t,x)),this.isAwaitingOAuth){let t=await this.touchSession();if(t.data.userId){let{userId:r,email:s}=t.data;await this.setUserId(r),await this.setEmail(s);let n=await this.checkIfUserExists({email:s});return this.isAwaitingOAuth=!1,{userExists:n,email:s}}}}catch(t){console.error(t)}return{userExists:!1}}async waitForLoginAndSetup({popupWindow:e,skipSessionRefresh:t=!1}={}){for(this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingLogin=!0;this.isAwaitingLogin;)try{if(await new Promise(l=>setTimeout(l,x)),!await this.isSessionActive()){if(e?.closed){let l={isComplete:!1,isError:!0};return g(h.LOGIN_EVENT,l,"failed to setup user"),l}continue}let s=await this.userSetupAfterLogin(),n=s.data.needsWallet??!1;if(!n&&this.currentWalletIdsArray.length===0)if(e?.closed){let l={isComplete:!1,isError:!0};return g(h.LOGIN_EVENT,l,"failed to setup user"),l}else continue;let o=await this.fetchWallets(),a=await this.getTransmissionKeyShares();if(a.data.temporaryShares.length===o.length){await this.setupAfterLogin({temporaryShares:a.data.temporaryShares,skipSessionRefresh:t}),await this.claimPregenWallets();let l={isComplete:!0,needsWallet:n||Object.values(this.wallets).length===0,partnerId:s.data.partnerId};return g(h.LOGIN_EVENT,l),l}}catch(s){console.error(s)}let r={isComplete:!1};return g(h.LOGIN_EVENT,r,"exitted login without setting up user"),r}async refreshSession({shouldOpenPopup:e=!1}={}){let t=await this.touchSession(!0);this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair();let r=await this.getWebAuthURLForLogin({sessionId:t.data.sessionId,loginEncryptionPublicKey:_(this.loginEncryptionKeyPair)});return e&&this.platformUtils.openPopup(r),r}async userSetupAfterLogin(){let e=await this.touchSession();return await this.setUserId(e.data.userId),e.data.currentWalletIds&&e.data.currentWalletIds!==this.currentWalletIds&&await this.setCurrentWalletIds(e.data.currentWalletIds,{sessionLookupId:this.isPortal()?e.data.sessionLookupId:void 0}),e}async getTransmissionKeyShares({isForNewDevice:e=!1}={}){let t=await this.touchSession(),r=e?`${t.data.sessionLookupId}-new-device`:t.data.sessionLookupId;return this.ctx.client.getTransmissionKeyshares(this.userId,r)}async setupAfterLogin({temporaryShares:e,skipSessionRefresh:t=!1}={}){e||(e=(await this.getTransmissionKeyShares()).data.temporaryShares),e.forEach(r=>{let s=B(this.loginEncryptionKeyPair.privateKey,r.encryptedShare,r.encryptedKey);this.wallets[r.walletId]={id:r.walletId,signer:s}}),await this.deleteLoginEncryptionKeyPair(),await this.populateWalletAddresses(),await this.touchSession(!t)}async distributeNewWalletShare({walletId:e,userShare:t,skipBiometricShareCreation:r=!1,forceRefresh:s=!1}){let n=t;return n||(n=this.wallets[e].signer),r?await X({ctx:this.ctx,userId:this.userId,walletId:e,userSigner:n,emailProps:this.getBackupKitEmailProps(),forceRefresh:s}):await N({ctx:this.ctx,userId:this.userId,walletId:e,userShare:n,emailProps:this.getBackupKitEmailProps()})}async waitForWalletAddress(e){let t=0;for(;;)try{if(t===10)break;++t;let s=(await this.ctx.client.getWallets(this.userId)).data.wallets.find(n=>n.id===e);if(s&&s.address)return;await new Promise(n=>setTimeout(n,ye))}catch(r){console.error(r)}throw new Error("timed out waiting for wallet address")}async waitForPregenWalletAddress(e){let t=0;for(;;)try{if(t===10)break;++t;let s=(await this.getPregenWallets()).find(n=>n.id===e);if(s&&s.address)return;await new Promise(n=>setTimeout(n,ye))}catch(r){console.error(r)}throw new Error("timed out waiting for wallet address")}async createWalletPerType({skipDistribute:e=!1,types:t}={}){let r=[],s={},n;for(let o of await this.getTypesToCreate(t)){let[a,l]=await this.createWallet({type:o,skipDistribute:e});r.push(a),pe(o).filter(c=>!!this.isWalletTypeEnabled[c]).forEach(c=>{s[c]=[a.id]}),l&&(n=l)}return{wallets:r,walletIds:s,recoverySecret:n}}async refreshShare({walletId:e,share:t,oldPartnerId:r,newPartnerId:s,keyShareProtocolId:n,redistributeBackupEncryptedShares:o}){let{signer:a,protocolId:l}=await this.platformUtils.refresh(this.ctx,this.retrieveSessionCookie(),this.userId,e,t,r,s,n),c=await N({ctx:this.ctx,userId:this.userId,walletId:e,userShare:a,ignoreRedistributingBackupEncryptedShare:!o,emailProps:this.getBackupKitEmailProps(),partnerId:s,protocolId:l});return{signer:a,recoverySecret:c,protocolId:l}}async createWallet({type:e,skipDistribute:t=!1}={}){this.requireApiKey();let r=await this.assertIsValidWalletType(e??this.supportedWalletTypes.find(({optional:p})=>!p)?.type),s,n,o;switch(r){case w.SOLANA:{o=await this.platformUtils.ed25519Keygen(this.ctx,this.userId,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}default:{o=await this.platformUtils.keygen(this.ctx,this.userId,r,null,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}}let a=o.walletId;s=o.signer,this.wallets[a]={id:a,signer:s,scheme:r===w.SOLANA?P.ED25519:P.DKLS,type:r},n=this.wallets[a],await this.waitForWalletAddress(n.id),await this.populateWalletAddresses();let l=null;t||(l=await N({ctx:this.ctx,userId:this.userId,walletId:n.id,userShare:s,emailProps:this.getBackupKitEmailProps()})),await this.setCurrentWalletIds({...this.currentWalletIds,[r]:[...this.currentWalletIds[r]??[],a]});let c={...n};return delete c.signer,g(h.WALLET_CREATED,{wallet:c,recoverySecret:l}),[n,l]}async createPregenWallet(e){let{type:t=this.supportedWalletTypes.find(({optional:c})=>!c)?.type,pregenIdentifier:r,pregenIdentifierType:s="EMAIL"}=e;this.requireApiKey();let n=await this.assertIsValidWalletType(t??this.supportedWalletTypes.find(({optional:c})=>!c)?.type),o;switch(n){case w.SOLANA:o=await this.platformUtils.ed25519PreKeygen(this.ctx,r,s,this.retrieveSessionCookie());break;default:o=await this.platformUtils.preKeygen(this.ctx,void 0,r,s,n,null,this.retrieveSessionCookie());break}let{signer:a,walletId:l}=o;return this.wallets[l]={id:l,signer:a,scheme:n===w.SOLANA?P.ED25519:P.DKLS,type:n,isPregen:!0,pregenIdentifier:r,pregenIdentifierType:s},await this.waitForPregenWalletAddress(l),await this.populatePregenWalletAddresses(),this.wallets[l]}async createPregenWalletPerType({types:e,pregenIdentifier:t,pregenIdentifierType:r="EMAIL"}){let s=[];for(let n of await this.getTypesToCreate(e)){let o=await this.createPregenWallet({type:n,pregenIdentifier:t,pregenIdentifierType:r});s.push(o)}return s}async claimPregenWallets({pregenIdentifier:e,pregenIdentifierType:t=e?"EMAIL":void 0}={}){this.requireApiKey();let r=e&&t?await this.getPregenWallets({pregenIdentifier:e,pregenIdentifierType:t}):await this.getPregenWallets();if(r.length===0)return;let s,{walletIds:n}=await this.ctx.client.claimPregenWallets({userId:this.userId,walletIds:r.map(o=>o.id)});for(let o of n){let a=this.wallets[o],l;if(a.scheme===P.ED25519){let p=await N({ctx:this.ctx,userId:this.userId,walletId:a.id,userShare:this.wallets[a.id].signer,emailProps:this.getBackupKitEmailProps(),partnerId:a.partnerId});p.length>0&&(s=p)}else l=await this.refreshShare({walletId:a.id,share:this.wallets[a.id].signer,oldPartnerId:a.partnerId,newPartnerId:a.partnerId,redistributeBackupEncryptedShares:!0}),l.recoverySecret&&(s=l.recoverySecret);this.wallets[a.id]={...this.wallets[a.id],signer:l?.signer??a.signer,userId:this.userId,pregenIdentifier:void 0,pregenIdentifierType:void 0};let c={...this.wallets[a.id]};delete c.signer,g(h.PREGEN_WALLET_CLAIMED,{wallet:c,recoverySecret:s})}return await this.setWallets(this.wallets),s}async updatePregenWalletIdentifier({walletId:e,newPregenIdentifier:t,newPregenIdentifierType:r}){this.requireApiKey(),await this.ctx.client.updatePregenWallet(e,{pregenIdentifier:t,pregenIdentifierType:r}),this.wallets[e]&&(this.wallets[e]={...this.wallets[e],pregenIdentifier:t,pregenIdentifierType:r},await this.setWallets(this.wallets))}async hasPregenWallet({pregenIdentifier:e,pregenIdentifierType:t}){return this.requireApiKey(),!!(await this.getPregenWallets({pregenIdentifier:e,pregenIdentifierType:t})).find(n=>n.pregenIdentifier===e&&n.pregenIdentifierType===t)}async getPregenWallets({pregenIdentifier:e,pregenIdentifierType:t=e?"EMAIL":void 0}={}){return this.requireApiKey(),(await this.ctx.client.getPregenWallets(e&&t?{[t]:[e]}:this.pregenIds,this.isPortal(),this.userId)).wallets.filter(s=>this.isWalletSupported(L(s)))}encodeWalletBase64(e){let t=JSON.stringify(e);return Buffer.from(t).toString("base64")}getUserShare(){return Object.values(this.wallets).length===0?null:Object.values(this.wallets).map(e=>this.encodeWalletBase64(e)).join("-")}async setUserShare(e){if(!e)return;let t=e.split("-");for(let r of t){let s=Buffer.from(r,"base64").toString(),n=v(JSON.parse(s));this.wallets[n.id]=n,await this.setWallets(this.wallets)}}async getTransactionReviewUrl(e,t){let r=await this.touchSession();return this.constructPortalUrl("txReview",{partnerId:r.data.partnerId,pathId:e,params:{email:this.email,timeoutMs:t?.toString()}})}async getOnRampTransactionUrl({purchaseId:e,providerKey:t,...r}){let s=await this.touchSession(),[n,o]=Dt(r);return this.constructPortalUrl("onRamp",{partnerId:s.data.partnerId,pathId:e,sessionId:s.data.sessionId,params:{[n]:o,providerKey:t,currentWalletIds:JSON.stringify(this.currentWalletIds)}})}async signMessage({walletId:e,messageBase64:t,timeoutMs:r=3e4,cosmosSignDocBase64:s}){this.assertIsValidWalletId(e);let n=this.wallets[e],o=this.userId;n.partnerId&&!n.userId&&(o=n.partnerId);let a=await this.signMessageInner({wallet:n,signerId:o,messageBase64:t,cosmosSignDocBase64:s}),l=Date.now();if(a.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(a.pendingTransactionId,r),{type:s?"SIGN_TRANSACTION_REVIEW":"SIGN_MESSAGE_REVIEW"});else return g(h.SIGN_MESSAGE_EVENT,a),a;for(await new Promise(c=>setTimeout(c,x));!(Date.now()-l>r);){try{await this.ctx.client.getPendingTransaction(this.userId,a.pendingTransactionId)}catch{let p=new M;throw g(h.SIGN_MESSAGE_EVENT,a,p.message),p}if(a=await this.signMessageInner({wallet:n,signerId:o,messageBase64:t,cosmosSignDocBase64:s}),a.pendingTransactionId)await new Promise(c=>setTimeout(c,x));else break}if(a.pendingTransactionId){let c=new F(await this.getTransactionReviewUrl(a.pendingTransactionId),a.pendingTransactionId);throw g(h.SIGN_MESSAGE_EVENT,a,c.message),c}return g(h.SIGN_MESSAGE_EVENT,a),a}async signMessageInner({wallet:e,signerId:t,messageBase64:r,cosmosSignDocBase64:s}){let n;switch(e.scheme){case P.ED25519:n=await this.platformUtils.ed25519Sign(this.ctx,t,e.id,e.signer,r,this.retrieveSessionCookie());break;default:n=await this.platformUtils.signMessage(this.ctx,t,e.id,e.signer,r,this.retrieveSessionCookie(),e.scheme===P.DKLS,s);break}return n}async signTransaction({walletId:e,rlpEncodedTxBase64:t,chainId:r,timeoutMs:s=3e4}){this.assertIsValidWalletId(e);let n=this.wallets[e],o=this.userId;n.partnerId&&!n.userId&&(o=n.partnerId);let a=await this.platformUtils.signTransaction(this.ctx,o,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===P.DKLS),l=Date.now();if(a.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(a.pendingTransactionId,s),{type:"SIGN_TRANSACTION_REVIEW"});else return g(h.SIGN_TRANSACTION_EVENT,a),a;for(await new Promise(c=>setTimeout(c,x));!(Date.now()-l>s);){try{await this.ctx.client.getPendingTransaction(this.userId,a.pendingTransactionId)}catch{let p=new M;throw g(h.SIGN_TRANSACTION_EVENT,a,p.message),p}if(a=await this.platformUtils.signTransaction(this.ctx,o,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===P.DKLS),a.pendingTransactionId)await new Promise(c=>setTimeout(c,x));else break}if(a.pendingTransactionId){let c=new F(await this.getTransactionReviewUrl(a.pendingTransactionId),a.pendingTransactionId);throw g(h.SIGN_TRANSACTION_EVENT,a,c.message),c}return g(h.SIGN_TRANSACTION_EVENT,a),a}async sendTransaction({walletId:e,rlpEncodedTxBase64:t,chainId:r}){this.assertIsValidWalletId(e);let s=this.wallets[e],n=await this.platformUtils.sendTransaction(this.ctx,this.userId,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),s.scheme===P.DKLS);if(n.pendingTransactionId)throw this.platformUtils.openPopup(await this.getTransactionReviewUrl(n.pendingTransactionId),{type:"SIGN_TRANSACTION_REVIEW"}),new q(await this.getTransactionReviewUrl(n.pendingTransactionId));return n}isProviderModalDisabled(){return!!this.disableProviderModal}async initiateOnRampTransaction(e){let{params:t,shouldOpenPopup:r,...s}=e,n=await this.ctx.client.createOnRampPurchase({userId:this.userId,params:{...t,address:s.externalWalletAddress??this.getDisplayAddress(s.walletId,{addressType:t.walletType})},...s}),o=await this.getOnRampTransactionUrl({purchaseId:n.id,providerKey:n.providerKey,...s});return r&&this.platformUtils.openPopup(o,{type:"ON_RAMP_TRANSACTION"}),{onRampPurchase:n,portalUrl:o}}async keepSessionAlive(){try{return await this.ctx.client.keepSessionAlive(this.userId),!0}catch{return!1}}exportSession(){let e={email:this.email,userId:this.userId,wallets:this.wallets,currentWalletIds:this.currentWalletIds,sessionCookie:this.sessionCookie,phone:this.phone,countryCode:this.countryCode,telegramUserId:this.telegramUserId,farcasterUsername:this.farcasterUsername,externalWallets:this.externalWallets};return Buffer.from(JSON.stringify(e)).toString("base64")}async importSession(e){let t=Buffer.from(e,"base64").toString("utf8"),r=JSON.parse(t);await this.setEmail(r.email),await this.setUserId(r.userId),await this.setWallets(r.wallets),await this.setExternalWallets(r.externalWallets||{});for(let s of Object.keys(this.wallets))this.wallets[s].userId||(this.wallets[s].userId=this.userId);if(Object.keys(r.currentWalletIds).length!==0)await this.setCurrentWalletIds(r.currentWalletIds);else{let s={};for(let n of Object.keys(r.wallets))s[r.wallets[n].type]=[...s[r.wallets[n].type]??[],n];await this.setCurrentWalletIds(s)}this.persistSessionCookie(r.sessionCookie),await this.setPhoneNumber(r.phone,r.countryCode)}exitAccountCreation(){this.isAwaitingAccountCreation=!1}exitLogin(){this.isAwaitingLogin=!1}exitFarcaster(){this.isAwaitingFarcaster=!1}exitOAuth(){this.isAwaitingOAuth=!1}exitLoops(){this.exitAccountCreation(),this.exitLogin(),this.exitFarcaster(),this.exitOAuth()}async getVerificationToken(){let{data:e}=await this.touchSession();return e.sessionLookupId}async logout({clearPregenWallets:e=!1}={}){await this.ctx.client.logout(),await this.clearStorage(),e?this.wallets={}:(Object.entries(this.wallets).forEach(([t,r])=>{r.pregenIdentifier||delete this.wallets[t]}),await this.setWallets(this.wallets)),this.currentWalletIds={},this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.loginEncryptionKeyPair=void 0,this.email=void 0,this.telegramUserId=void 0,this.phone=void 0,this.countryCode=void 0,this.userId=void 0,this.sessionCookie=void 0,g(h.LOGOUT_EVENT,null)}async getSupportedCreateAuthMethods(){let t=(await this.touchSession()).data.partnerId,r=await this.ctx.client.getPartner(t),s=new Set;for(let n of r.data.partner.supportedAuthMethods)s.add(Se[n]);return s}toString(){let e=Object.keys(this.wallets).reduce((r,s)=>({...r,[s]:{...this.wallets[s],signer:this.wallets[s].signer?"[REDACTED]":void 0}}),{}),t={supportedWalletTypes:this.supportedWalletTypes,cosmosPrefix:this.cosmosPrefix,email:this.email,phone:this.phone,countryCode:this.countryCode,telegramUserId:this.telegramUserId,farcasterUsername:this.farcasterUsername,userId:this.userId,pregenIds:this.pregenIds,currentWalletIds:this.currentWalletIds,wallets:e,loginEncryptionKeyPair:this.loginEncryptionKeyPair?"[REDACTED]":void 0,ctx:{apiKey:this.ctx.apiKey,disableWorkers:this.ctx.disableWorkers,disableWebSockets:this.ctx.disableWebSockets,env:this.ctx.env,offloadMPCComputationURL:this.ctx.offloadMPCComputationURL,useLocalFiles:this.ctx.useLocalFiles,useDKLS:this.ctx.useDKLS,cosmosPrefix:this.ctx.cosmosPrefix}};return`Para ${JSON.stringify(t,null,2)}`}};import{AuthMethod as Fs,EmailTheme as Vs,Network as $s,WalletType as Hs,WalletScheme as js,OnRampAsset as Js,OnRampPurchaseType as Ys,OnRampProvider as Xs,OnRampPurchaseStatus as qs,OAuthMethod as zs,NON_ED25519 as Qs,PREGEN_IDENTIFIER_TYPES as Zs}from"@getpara/user-management-client";var Ds=H.version,Gs=H;export{Fs as AuthMethod,Vs as EmailTheme,dt as EnabledFlow,pt as Environment,U as KeyContainer,Qs as NON_ED25519,$s as Network,zs as OAuthMethod,Js as OnRampAsset,Te as OnRampMethod,Xs as OnRampProvider,qs as OnRampPurchaseStatus,Ys as OnRampPurchaseType,Zs as PREGEN_IDENTIFIER_TYPES,h as ParaEvent,oe as PopupType,Ae as PregenIdentifierType,We as RecoveryStatus,y as STORAGE_PREFIX,M as TransactionReviewDenied,q as TransactionReviewError,F as TransactionReviewTimeout,js as WalletScheme,Hs as WalletType,er as decimalToHex,_e as decryptPrivateKey,At as decryptPrivateKeyAndDecryptShare,Ne as decryptPrivateKeyWithPassword,wt as decryptWithKeyPair,B as decryptWithPrivateKey,Gs as default,N as distributeNewShare,ue as encodePrivateKeyToPemHex,ft as encryptPrivateKey,Rt as encryptPrivateKeyWithPassword,Y as encryptWithDerivedPublicKey,L as entityToWallet,G as getAsymmetricKeyPair,Pr as getBaseMPCNetworkUrl,Ke as getBaseOAuthUrl,ke as getBaseUrl,Ie as getCosmosAddress,Pt as getDerivedPrivateKeyAndDecrypt,ct as getOnRampAssets,lt as getOnRampNetworks,R as getPortalBaseURL,Ce as getPortalDomain,St as getPublicKeyFromSignature,_ as getPublicKeyHex,be as getSHA256HashHex,Tt as hashPasswordWithSalt,qt as hexStringToBase64,Zt as hexToDecimal,zt as hexToSignature,Qt as hexToUint8Array,he as initClient,le as isWalletSupported,me as mpcComputationClient,Pe as normalizePhoneNumber,Ds as paraVersion,yt as publicKeyFromHex,D as stringToPhoneNumber,ae as toAssetInfoArray,Ut as transmissionUtilsRetrieve,ne as truncateAddress,sr as waitUntilTrue};
Binary file
Binary file
@@ -565,10 +565,12 @@ export declare abstract class ParaCore {
565
565
  *
566
566
  * @param {Object} opts the options object
567
567
  * @param {OAuthMethod} opts.method the third-party service to use for OAuth.
568
+ * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
568
569
  * @returns {string} the URL for the user to log in with OAuth.
569
570
  */
570
- getOAuthURL({ method }: {
571
+ getOAuthURL({ method, deeplinkUrl }: {
571
572
  method: OAuthMethod;
573
+ deeplinkUrl?: string;
572
574
  }): Promise<string>;
573
575
  /**
574
576
  * Awaits the response from a user's attempt to log in with OAuth.
@@ -901,6 +903,11 @@ export declare abstract class ParaCore {
901
903
  protected exitFarcaster(): void;
902
904
  protected exitOAuth(): void;
903
905
  protected exitLoops(): void;
906
+ /**
907
+ * Retrieves a token to verify the current session.
908
+ * @returns {Promise<string>} the ID
909
+ **/
910
+ getVerificationToken(): Promise<string>;
904
911
  /**
905
912
  * Logs the user out.
906
913
  * @param {Object} opts the options object.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getpara/core-sdk",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "main": "dist/cjs/index.js",
5
5
  "module": "dist/esm/index.js",
6
6
  "types": "dist/types/index.d.ts",
@@ -9,17 +9,17 @@
9
9
  "dependencies": {
10
10
  "@celo/utils": "^8.0.0",
11
11
  "@cosmjs/encoding": "^0.32.4",
12
- "@getpara/user-management-client": "1.1.0",
12
+ "@getpara/user-management-client": "1.3.0",
13
13
  "@noble/hashes": "^1.5.0",
14
14
  "base64url": "^3.0.1",
15
- "buffer": "6.0.3",
16
15
  "ethereumjs-util": "7.1.5",
17
16
  "libphonenumber-js": "1.11.2",
18
17
  "node-forge": "^1.3.1",
19
18
  "qs": "^6.12.0"
20
19
  },
21
20
  "scripts": {
22
- "build": "yarn build:cjs && yarn build:esm && yarn build:types; yarn post-build",
21
+ "build": "rm -rf dist && node ./scripts/build.mjs && yarn build:types && yarn post-build",
22
+ "old-build": "yarn build:cjs && yarn build:esm && yarn build:types; yarn post-build",
23
23
  "post-build": "./scripts/set-version.sh",
24
24
  "build:cjs": "rm -rf dist/cjs && tsc --module commonjs --outDir dist/cjs && printf '{\"type\":\"commonjs\"}' > dist/cjs/package.json",
25
25
  "build:esm": "rm -rf dist/esm && tsc --module es6 --outDir dist/esm && printf '{\"type\":\"module\",\"sideEffects\":false}' > dist/esm/package.json",
@@ -35,10 +35,10 @@
35
35
  ],
36
36
  "exports": {
37
37
  ".": {
38
+ "types": "./dist/types/index.d.ts",
38
39
  "import": "./dist/esm/index.js",
39
- "require": "./dist/cjs/index.js",
40
- "types": "./dist/types/index.d.ts"
40
+ "require": "./dist/cjs/index.js"
41
41
  }
42
42
  },
43
- "gitHead": "a9e81f5c4560664441b3a18b3f8fe05c5db927ec"
43
+ "gitHead": "2d421556a0a1497abd08e18dca94f08ec3ad640b"
44
44
  }