@getpara/core-sdk 1.3.1 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/index.js.br +0 -0
- package/dist/cjs/index.js.gz +0 -0
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.br +0 -0
- package/dist/esm/index.js.gz +0 -0
- package/dist/types/ParaCore.d.ts +18 -2
- package/dist/types/utils/listeners.d.ts +2 -0
- package/package.json +3 -3
- /package/dist/cjs/{.!4351!index.js.br → .!56933!index.js.br} +0 -0
- /package/dist/cjs/{.!4353!index.js.gz → .!56935!index.js.gz} +0 -0
- /package/dist/esm/{.!4345!index.js.br → .!56930!index.js.br} +0 -0
- /package/dist/esm/{.!4347!index.js.gz → .!56932!index.js.gz} +0 -0
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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.1',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});
|
|
1
|
+
var wt=Object.create;var se=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var Ue=(i,e)=>{for(var t in e)se(i,t,{get:e[t],enumerable:!0})},Ne=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pt(e))!Tt.call(i,s)&&s!==t&&se(i,s,{get:()=>e[s],enumerable:!(r=It(e,s))||r.enumerable});return i};var P=(i,e,t)=>(t=i!=null?wt(At(i)):{},Ne(e||!i||!i.__esModule?se(t,"default",{value:i,enumerable:!0}):t,i)),Wt=i=>Ne(se({},"__esModule",{value:!0}),i);var Jt={};Ue(Jt,{AuthMethod:()=>u.AuthMethod,EmailTheme:()=>u.EmailTheme,EnabledFlow:()=>$e,Environment:()=>Ve,KeyContainer:()=>b,NON_ED25519:()=>u.NON_ED25519,Network:()=>u.Network,OAuthMethod:()=>u.OAuthMethod,OnRampAsset:()=>u.OnRampAsset,OnRampMethod:()=>Ee,OnRampProvider:()=>u.OnRampProvider,OnRampPurchaseStatus:()=>u.OnRampPurchaseStatus,OnRampPurchaseType:()=>u.OnRampPurchaseType,PREGEN_IDENTIFIER_TYPES:()=>u.PREGEN_IDENTIFIER_TYPES,ParaEvent:()=>h,PopupType:()=>ae,PregenIdentifierType:()=>Se,RecoveryStatus:()=>we,STORAGE_PREFIX:()=>f,TransactionReviewDenied:()=>$,TransactionReviewError:()=>te,TransactionReviewTimeout:()=>H,WalletScheme:()=>u.WalletScheme,WalletType:()=>u.WalletType,decimalToHex:()=>bt,decryptPrivateKey:()=>Ce,decryptPrivateKeyAndDecryptShare:()=>st,decryptPrivateKeyWithPassword:()=>Re,decryptWithKeyPair:()=>tt,decryptWithPrivateKey:()=>F,default:()=>jt,distributeNewShare:()=>v,encodePrivateKeyToPemHex:()=>pe,encryptPrivateKey:()=>Qe,encryptPrivateKeyWithPassword:()=>nt,encryptWithDerivedPublicKey:()=>Z,entityToWallet:()=>x,getAsymmetricKeyPair:()=>B,getBaseMPCNetworkUrl:()=>Mt,getBaseOAuthUrl:()=>Oe,getBaseUrl:()=>xe,getCosmosAddress:()=>ye,getDerivedPrivateKeyAndDecrypt:()=>rt,getOnRampAssets:()=>Me,getOnRampNetworks:()=>Fe,getPortalBaseURL:()=>T,getPortalDomain:()=>Ie,getPublicKeyFromSignature:()=>Ze,getPublicKeyHex:()=>L,getSHA256HashHex:()=>We,hashPasswordWithSalt:()=>it,hexStringToBase64:()=>Rt,hexToDecimal:()=>Lt,hexToSignature:()=>Ot,hexToUint8Array:()=>xt,initClient:()=>de,isWalletSupported:()=>le,mpcComputationClient:()=>ue,normalizePhoneNumber:()=>fe,paraVersion:()=>Ht,publicKeyFromHex:()=>Xe,stringToPhoneNumber:()=>D,toAssetInfoArray:()=>ne,transmissionUtilsRetrieve:()=>ht,truncateAddress:()=>ie,waitUntilTrue:()=>Ut});module.exports=Wt(Jt);var me=require("buffer"),p=require("@getpara/user-management-client"),Et=P(require("node-forge"));var Je=P(require("base64url")),E=P(require("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)}}}))}var ke=require("@cosmjs/encoding"),Ke=require("@noble/hashes/sha256"),De=require("@noble/hashes/ripemd160"),Ge=P(require("elliptic")),Be=P(require("libphonenumber-js")),Ct=new Ge.default.ec("secp256k1");function Rt(i){return i.substring(0,2)==="0x"&&(i=i.substring(2)),Buffer.from(i,"hex").toString("base64")}function Ot(i){return{r:`0x${i.slice(2,66)}`,s:`0x${i.slice(66,130)}`,v:BigInt(i.slice(130,132))}}function xt(i){return i.startsWith("0x")&&(i=i.slice(2)),new Uint8Array(Buffer.from(i,"hex"))}function Lt(i){return i.startsWith("0x")&&(i=i.slice(2)),`${parseInt(i,16)}`}function bt(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,De.ripemd160)((0,Ke.sha256)(i))}function ye(i,e){let t=new Uint8Array(Buffer.from(i.startsWith("0x")?i.slice(2):i,"hex")),r=vt(t);return(0,ke.toBech32)(e,_t(r))}function ie(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(0,Be.default)(i)?.formatInternational().replace(/[^\d+]/g,"")}function fe(i,e){return D(`${i[0]!=="+"?"+":""}${i}${e}`)}function ne(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(a=>{let o=n[a];e.push([t,s,a,o])})})}),e}function Fe(i,{walletType:e,allowed:t}={}){return[...new Set(ne(i).filter(([r,s])=>(!e||r===e)&&(!t||t.includes(s))).map(([r,s])=>s))]}function Me(i,{walletType:e,network:t,allowed:r}={}){return[...new Set(ne(i).filter(([s,n,a])=>(!e||s===e)&&(!t||n===t)&&(!Array.isArray(r)||r.includes(a))).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 Ve=(a=>(a.DEV="DEV",a.SANDBOX="SANDBOX",a.BETA="BETA",a.PROD="PROD",a.DEVELOPMENT="BETA",a.PRODUCTION="PROD",a))(Ve||{}),$e=(r=>(r.BUY="BUY",r.RECEIVE="RECEIVE",r.WITHDRAW="WITHDRAW",r))($e||{});var Se=(t=>(t.EMAIL="EMAIL",t.PHONE="PHONE",t))(Se||{});var Ee=(s=>(s.ACH="ACH",s.DEBIT="Debit",s.CREDIT="Credit",s.APPLE_PAY="Apple Pay",s))(Ee||{});var ae=(a=>(a.SIGN_TRANSACTION_REVIEW="SIGN_TRANSACTION_REVIEW",a.SIGN_MESSAGE_REVIEW="SIGN_MESSAGE_REVIEW",a.LOGIN_PASSKEY="LOGIN_PASSKEY",a.CREATE_PASSKEY="CREATE_PASSKEY",a.OAUTH="OAUTH",a.ON_RAMP_TRANSACTION="ON_RAMP_TRANSACTION",a))(ae||{});var we=(n=>(n.INITIATED="INITIATED",n.READY="READY",n.EXPIRED="EXPIRED",n.FINISHED="FINISHED",n.CANCELLED="CANCELLED",n))(we||{});var A="para",h=(d=>(d.LOGIN_EVENT=`${A}Login`,d.ACCOUNT_CREATION_EVENT=`${A}AccountCreation`,d.ACCOUNT_SETUP_EVENT=`${A}AccountSetup`,d.LOGOUT_EVENT=`${A}Logout`,d.SIGN_MESSAGE_EVENT=`${A}SignMessage`,d.SIGN_TRANSACTION_EVENT=`${A}SignTransaction`,d.EXTERNAL_WALLET_CHANGE_EVENT=`${A}ExternalWalletChange`,d.WALLETS_CHANGE_EVENT=`${A}WalletsChange`,d.WALLET_CREATED=`${A}WalletCreated`,d.PREGEN_WALLET_CLAIMED=`${A}PregenWalletClaimed`,d))(h||{});function Ie(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 T({env:i,isE2E:e},t,r){if(e)return r?"https://app.sandbox.usecapsule.com":"http://localhost:3003";let s=Ie(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 He({env:i},e){let t=Nt(i);return i==="DEV"?e?"http://127.0.0.1:3008":`http://${t}:3008`:`https://${t}`}function oe({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 S=require("@getpara/user-management-client");var I={[S.WalletScheme.DKLS]:{[S.WalletType.EVM]:!0,[S.WalletType.COSMOS]:!0},[S.WalletScheme.CGGMP]:{[S.WalletType.EVM]:!0,[S.WalletType.COSMOS]:!0},[S.WalletScheme.ED25519]:{[S.WalletType.SOLANA]:!0}};function je(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=>!!I[e.scheme][t])}function Pe(i){return Object.keys(I).filter(e=>e===S.WalletScheme.CGGMP?!1:(Array.isArray(i)?i:Object.keys(i)).some(t=>I[e][t]))}function kt(i){return[...new Set(i.reduce((e,t)=>[...e,...Object.keys(I[t]).filter(r=>I[t][r])],[]))]}function Ae(i){return kt(Pe((Array.isArray(i)?i:[i]).map(e=>S.WalletType[e])))}function x(i){return{...i,scheme:i.scheme,type:i.type,pregenIdentifierType:i.pregenIdentifierType}}function G(i){return["USER","PREGEN"].includes(i.type)&&(i.isPregen=i.type==="PREGEN",i.type=i.scheme===S.WalletScheme.ED25519?S.WalletType.SOLANA:S.WalletType.EVM),i.scheme&&!i.type&&(i.type=i.scheme===S.WalletScheme.ED25519?S.WalletType.SOLANA:S.WalletType.EVM),i}var Kt=E.default.pki.rsa,Te="RSA-OAEP",Ye="794241bc819a125a7b78ea313decc0bc",ce=new Uint8Array([23,66,157,146,179,158,117,120,184,73,123,81]);function We(i){let e=E.default.md.sha256.create();return e.update(i),e.digest().toHex()}function L(i){let e=E.default.pki.publicKeyToRSAPublicKeyPem(i.publicKey);return Buffer.from(e,"utf-8").toString("hex")}function Xe(i){let e=qe(i);return E.default.pki.publicKeyFromPem(e)}function qe(i){return Buffer.from(i,"hex").toString("utf-8")}function pe(i){let e=E.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 E.default.pki.privateKeyFromPem(e)}async function Qe(i,e){let t=pe(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:ce},r,s);return Buffer.from(n).toString("base64")}async function Ce(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:ce},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return ze(s)}async function B(i,e){let t=E.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(`${T(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,(a,o)=>{a&&n(a),s(o)}))}async function Ze(i,e){let t=Je.default.encode(e),r=await B(i,t);return L(r)}function Dt(i){let e=E.default.random.getBytesSync(16),t=E.default.cipher.createCipher("AES-CBC",e);t.start({iv:Ye}),t.update(E.default.util.createBuffer(i)),t.finish();let r=t.output.toHex();return{key:e,encryptedMessageHex:r}}function et(i,e){let t=E.default.cipher.createDecipher("AES-CBC",i);return t.start({iv:Ye}),t.update(E.default.util.createBuffer(E.default.util.hexToBytes(e))),t.finish(),t.output.toString()}function tt(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.privateKey.decrypt(r,Te);return et(s,e)}function F(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.decrypt(r,Te);return et(s,e)}async function Gt(i,{seedValue:e,encryptedMessageHex:t,encryptedKeyHex:r}){let s=await B(i,e);return F(s.privateKey,t,r)}async function rt(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 st(i,e,t){let r;try{r=await Ce(t,i)}catch{}try{r=await Re(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:F(r,s.encryptedShare,s.encryptedKey),protocolId:s.protocolId}))}function Z(i,e){let{key:t,encryptedMessageHex:r}=Dt(e),s=qe(i),a=E.default.pki.publicKeyFromPem(s).encrypt(t,Te),o=Buffer.from(a,"utf-8").toString("hex");return{encryptedMessageHex:r,encryptedKeyHex:o}}function it(i){let e=Bt(),t=e+i,r=We(t);return{salt:e,hash:r}}function Bt(i=16){return E.default.util.bytesToHex(E.default.random.getBytesSync(i))}async function Ft(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 nt(i,e){let t=await Ft(e),r=pe(i),s=new TextEncoder().encode(r),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:ce},t,s);return Buffer.from(n).toString("base64")}async function Re(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:ce},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return ze(s)}var at=P(require("@getpara/user-management-client"));function Oe(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 xe(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 Mt(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 de({env:i,version:e,apiKey:t,partnerId:r,useFetchAdapter:s=!1,retrieveSessionCookie:n,persistSessionCookie:a}){return new at.default({userManagementHost:xe(i),version:["DEV","SANDBOX"].includes(i)?"dev":e,apiKey:t,partnerId:r,opts:{useFetchAdapter:s},retrieveSessionCookie:n,persistSessionCookie:a})}var ue={};Ue(ue,{initClient:()=>Le});var ot=P(require("axios"));function Le(i,e){let t=ot.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 V=require("@getpara/user-management-client");var M=require("@getpara/user-management-client");var ee=require("@celo/utils/lib/ecies.js"),lt=P(require("ethereumjs-util")),ct=P(require("node-forge")),b=class i{constructor(e,t,r){this.walletId=e,this.keyshare=t,this.address=r,this.backupDecryptionKey=Buffer.from(ct.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(lt.privateToPublic(Buffer.from(this.backupDecryptionKey,"hex")))}getPublicEncryptionKeyHex(){return this.getPublicEncryptionKey().toString("hex")}encryptForSelf(e){try{let t=this.getPublicEncryptionKey();return(0,ee.Encrypt)(t,Buffer.from(e,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}static encryptWithPublicKey(e,t){try{return(0,ee.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,ee.Decrypt)(Buffer.from(this.backupDecryptionKey,"hex"),t);return Buffer.from(r.buffer).toString("ucs2")}catch{throw Error("Error decrypting backup")}}};async function he({ctx:i,userId:e,walletId:t,otherEncryptedShares:r=[],userSigner:s,ignoreRedistributingBackupEncryptedShare:n=!1,emailProps:a={},forceRefresh:o=!1}){if(n)return await i.client.uploadUserKeyShares(e,r.map(w=>({walletId:t,...w}))),"";let l,c,{recoveryPublicKeys:d}=await i.client.getRecoveryPublicKeys(e);if(o||!d?.length){c=new b(t,"","");let{recoveryPublicKeys:w}=await i.client.persistRecoveryPublicKeys(e,[c.getPublicEncryptionKeyHex()]),m=c.encryptForSelf(s);l=[{walletId:t,encryptedShare:m,type:M.KeyShareType.USER,encryptor:M.EncryptorType.RECOVERY,recoveryPublicKeyId:w[0].id}]}else l=d.map(w=>{let{id:m,publicKey:y}=w,W=b.encryptWithPublicKey(Buffer.from(y,"hex"),s);return{walletId:t,encryptedShare:W,type:M.KeyShareType.USER,encryptor:M.EncryptorType.RECOVERY,recoveryPublicKeyId:m}});return await i.client.uploadUserKeyShares(e,[...r.map(w=>({walletId:t,...w})),...n?[]:l]),await i.client.distributeParaShare({userId:e,walletId:t,useDKLS:i.useDKLS,...a}),c?JSON.stringify(c):""}async function v({ctx:i,userId:e,walletId:t,userShare:r,ignoreRedistributingBackupEncryptedShare:s=!1,emailProps:n={},partnerId:a,protocolId:o}){let c=(await i.client.getSessionPublicKeys(e)).data.keys.map(y=>{if(!y.publicKey)return;let{encryptedMessageHex:W,encryptedKeyHex:K}=Z(y.sigDerivedPublicKey,r);return{encryptedShare:W,encryptedKey:K,type:V.KeyShareType.USER,encryptor:V.EncryptorType.BIOMETRICS,biometricPublicKey:y.sigDerivedPublicKey,partnerId:a,protocolId:o}}).filter(Boolean),w=(await i.client.getPasswords({userId:e})).map(y=>{if(y.status==="PENDING")return;let{encryptedMessageHex:W,encryptedKeyHex:K}=Z(y.sigDerivedPublicKey,r);return{encryptedShare:W,encryptedKey:K,type:V.KeyShareType.USER,encryptor:V.EncryptorType.PASSWORD,passwordId:y.id,partnerId:a,protocolId:o}}).filter(Boolean),m=[...c,...w];return await he({ctx:i,userId:e,walletId:t,otherEncryptedShares:m,userSigner:r,ignoreRedistributingBackupEncryptedShare:s,emailProps:n})}var ge=require("@celo/utils/lib/ecies.js"),_=require("buffer"),pt=P(require("ethereumjs-util")),dt=require("crypto");async function ut(i,e){let t,r;for(;;)try{t=(0,dt.randomBytes)(32).toString("hex"),r=pt.privateToPublic(_.Buffer.from(t,"hex"));break}catch{continue}let s=_.Buffer.from(r),n=(0,ge.Encrypt)(s,_.Buffer.from(i,"ucs2")).toString("base64"),{data:{id:a}}=await e.tempTrasmissionInit(n);return encodeURIComponent(a+"|"+t)}async function ht(i,e){let[t,r]=decodeURIComponent(i).split("|"),n=(await e.tempTrasmission(t)).data.message,a=_.Buffer.from(n,"base64");return _.Buffer.from((0,ge.Decrypt)(_.Buffer.from(r,"hex"),a).buffer).toString("ucs2")}var te=class extends Error{constructor(e){super("transaction review error"),this.name="TransactionReviewError",this.transactionReviewUrl=e}},$=class extends Error{constructor(){super("transaction review has been denied by the user"),this.name="TransactionReviewDenied"}},H=class extends Error{constructor(e,t){super("transaction review has timed out"),this.name="TransactionReviewTimeout",this.transactionReviewUrl=e,this.pendingTransactionId=t}};var gt='1.4.1',f="@CAPSULE/",j=`${f}e-mail`,J=`${f}phone`,Y=`${f}countryCode`,mt=`${f}farcasterUsername`,X=`${f}telegramUserId`,q=`${f}userId`,U=`${f}ed25519Wallets`,C=`${f}wallets`,z=`${f}externalWallets`,N=`${f}currentWalletIds`,Q=`${f}currentExternalWalletAddresses`,O=`${f}sessionCookie`,k=`${f}loginEncryptionKeyPair`,R=2e3,be=1e3;function ft(i){i.url.includes(window.location.origin)&&(i.key===Q&&this.updateCurrentExternalWalletAddressesFromStorage(),i.key===z&&this.updateExternalWalletsFromStorage(),i.key===k&&this.updateLoginEncryptionKeyPairFromStorage(),i.key===O&&this.updateSessionCookieFromStorage(),i.key===N&&this.updateWalletIdsFromStorage(),(i.key===C||i.key===U)&&this.updateWalletsFromStorage(),i.key===j&&this.updateEmailFromStorage(),i.key===Y&&this.updateCountryCodeFromStorage(),i.key===J&&this.updatePhoneFromStorage(),i.key===q&&this.updateUserIdFromStorage(),i.key===X&&this.updateTelegramUserIdFromStorage())}function ve(){typeof window<"u"&&window.addEventListener&&window.location&&(window.removeEventListener("storage",ft.bind(this)),window.addEventListener("storage",ft.bind(this)))}typeof global<"u"?global.Buffer=global.Buffer||me.Buffer:typeof window<"u"?(window.Buffer=window.Buffer||me.Buffer,window.global=window.global||window):(self.Buffer=self.Buffer||me.Buffer,self.global=self.global||self);var{pki:St,jsbn:$t}=Et.default,re=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.initializeFromStorage=()=>{this.updateEmailFromStorage(),this.updateCountryCodeFromStorage(),this.updatePhoneFromStorage(),this.updateUserIdFromStorage(),this.updateTelegramUserIdFromStorage(),this.updateWalletsFromStorage(),this.updateWalletIdsFromStorage(),this.updateSessionCookieFromStorage(),this.updateLoginEncryptionKeyPairFromStorage(),this.updateExternalWalletsFromStorage(),this.updateCurrentExternalWalletAddressesFromStorage()};this.updateTelegramUserIdFromStorage=()=>{this.telegramUserId=this.localStorageGetItem(X)||void 0};this.updateUserIdFromStorage=()=>{this.userId=this.localStorageGetItem(q)||void 0};this.updatePhoneFromStorage=()=>{this.phone=this.localStorageGetItem(J)||void 0};this.updateCountryCodeFromStorage=()=>{this.countryCode=this.localStorageGetItem(Y)||void 0};this.updateEmailFromStorage=()=>{this.email=this.localStorageGetItem(j)||void 0};this.updateWalletsFromStorage=async()=>{let e=this.localStorageGetItem(N)??void 0,t=[void 0,null,"undefined"].includes(e)?{}:(()=>{let l=JSON.parse(e);return Array.isArray(l)?Object.keys(p.WalletType).reduce((c,d)=>{let w=Object.values(this.wallets).find(m=>l.includes(m.id)&&I[m.scheme][d]);return{...c,...w&&!c[d]?{[d]:[w.id]}:{}}},{}):l})();this.setCurrentWalletIds(t);let r=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(C):this.localStorageGetItem(C),s=JSON.parse(r||"{}"),n=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(U):this.localStorageGetItem(U),a=JSON.parse(n||"{}"),o={...Object.keys(s).reduce((l,c)=>({...l,[c]:G(s[c])}),{}),...Object.keys(a).reduce((l,c)=>({...l,...l[c]?{}:{[c]:G(a[c])}}),{})};this.setWallets(o)};this.updateWalletIdsFromStorage=()=>{let e=this.localStorageGetItem(N)??void 0,t=[void 0,null,"undefined"].includes(e)?{}:(()=>{let r=JSON.parse(e);return Array.isArray(r)?Object.keys(p.WalletType).reduce((s,n)=>{let a=Object.values(this.wallets).find(o=>r.includes(o.id)&&I[o.scheme][n]);return{...s,...a&&!s[n]?{[n]:[a.id]}:{}}},{}):r})();this.setCurrentWalletIds(t),Object.values(this.wallets).filter(r=>this.isWalletOwned(r)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0})};this.updateSessionCookieFromStorage=()=>{this.sessionCookie=this.localStorageGetItem(O)||this.sessionStorageGetItem(O)||void 0};this.updateLoginEncryptionKeyPairFromStorage=()=>{let e=this.sessionStorageGetItem(k);e&&e!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(e)))};this.updateExternalWalletsFromStorage=()=>{let e=this.localStorageGetItem(z),t=JSON.parse(e||"{}");this.setExternalWallets(t)};this.updateCurrentExternalWalletAddressesFromStorage=()=>{let e=this.localStorageGetItem(Q)||void 0;this.currentExternalWalletAddresses=e?JSON.parse(e):void 0};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=s=>{this.sessionCookie=s,(r.useSessionStorage?this.sessionStorageSetItem:this.localStorageSetItem)(O,s)},this.ctx={env:e,apiKey:t,client:de({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=Le(r.offloadMPCComputationURL,r.disableWorkers));try{this.#e=r.supportedWalletTypes?(()=>{if(Object.values(r.supportedWalletTypes).every(s=>!!s&&typeof s=="object"&&s.optional))throw new Error("at least one wallet type must be non-optional");if(!Object.keys(r.supportedWalletTypes).every(s=>Object.values(p.WalletType).includes(s)))throw new Error("unsupported wallet type");return this.#t=r.supportedWalletTypes,Object.entries(r.supportedWalletTypes).reduce((s,[n,a])=>a?(n===p.WalletType.COSMOS&&typeof a=="object"&&a.prefix&&(this.cosmosPrefix=a.prefix),[...s,{type:n,optional:a===!0?!1:a.optional??!1}]):s,[])})():void 0}catch{this.#e=void 0}!this.platformUtils.isSyncStorage||r.useStorageOverrides||(this.initializeFromStorage(),ve.bind(this)())}static{this.version=gt}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 $t.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&&T(e?{env:e}:this.ctx).includes(window.location.host)}isParaConnect(){return typeof window>"u"?!1:!!window.location?.host&&He(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)||je(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 a;if(!this.wallets[e])a=`wallet with id ${e} does not exist`;else{let o=this.wallets[e],[l,c]=[this.isPregenWalletUnclaimed(o),this.isWalletOwned(o)];s&&l?a=`pre-generated wallet with id ${o.id} cannot be selected`:!c&&!l?a=`wallet with id ${o.id} is not owned by the current user`:this.isWalletSupported(o)?t&&(!Ae(t).includes(o.type)||c&&!t.some(d=>(this.currentWalletIds[d]??[]).includes(e)))?a=`wallet with id ${o.id} and type ${o.type} cannot be selected`:r&&!r.includes(o.scheme)&&(a=`wallet with id ${o.id} and scheme ${o.scheme} cannot be selected`):a=`wallet with id ${o.id} and type ${o.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({type:d})=>d).join(", ")}`}if(a){if(n)throw new Error(a);return!1}return!0}getDisplayAddress(e,t={}){if(this.externalWallets[e]){let n=this.externalWallets[e];return t.truncate?ie(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=ye(r.publicKey,this.cosmosPrefix??"cosmos");break;default:s=r.address;break}return t.truncate?ie(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"?T(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,a,o]=[["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||a?{...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}:{}}:{},...a||o?{sessionId:t.sessionId}:{},...a?{encryptionKey:t.loginEncryptionPublicKey,newDeviceSessionLookupId:t.newDeviceSessionId,newDeviceEncryptionKey:t.newDeviceEncryptionKey,pregenIds:JSON.stringify(this.pregenIds),displayName:t.displayName,pfpUrl:t.pfpUrl}:{},...t.params||{}};return oe({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(j)||void 0,this.countryCode=await this.localStorageGetItem(Y)||void 0,this.phone=await this.localStorageGetItem(J)||void 0,this.userId=await this.localStorageGetItem(q)||void 0,this.telegramUserId=await this.localStorageGetItem(X)||void 0;let e=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(C):await this.localStorageGetItem(C),t=JSON.parse(e||"{}"),r=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(U):await this.localStorageGetItem(U),s=JSON.parse(r||"{}"),n={...Object.keys(t).reduce((m,y)=>({...m,[y]:G(t[y])}),{}),...Object.keys(s).reduce((m,y)=>({...m,...m[y]?{}:{[y]:G(s[y])}}),{})};await this.setWallets(n);let a=await this.localStorageGetItem(N)??void 0,o=[void 0,null,"undefined","null"].includes(a)?{}:(()=>{let m=JSON.parse(a);return Array.isArray(m)?Object.keys(p.WalletType).reduce((y,W)=>{let K=Object.values(this.wallets).find(_e=>m.includes(_e.id)&&I[_e.scheme][W]);return{...y,...K&&!y[W]?{[W]:[K.id]}:{}}},{}):m})();await this.setCurrentWalletIds(o),this.sessionCookie=await this.localStorageGetItem(O)||await this.sessionStorageGetItem(O)||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(k);l&&l!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(l)));let c=await this.localStorageGetItem(z),d=JSON.parse(c||"{}");await this.setExternalWallets(d);let w=await this.localStorageGetItem(Q)||void 0;this.currentExternalWalletAddresses=w?JSON.parse(w):void 0,ve.bind(this)(),await this.touchSession()}async setEmail(e){this.email=e,await this.localStorageSetItem(j,e)}async setTelegramUserId(e){this.telegramUserId=e,await this.localStorageSetItem(X,e)}async setPhoneNumber(e,t){this.phone=e,this.countryCode=t,await this.localStorageSetItem(J,e),await this.localStorageSetItem(Y,t)}async setFarcasterUsername(e){this.farcasterUsername=e,await this.localStorageSetItem(mt,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(q,e)}async setWallets(e){if(this.wallets=e,this.platformUtils.secureStorage){await this.platformUtils.secureStorage.set(C,JSON.stringify(e));return}await this.localStorageSetItem(C,JSON.stringify(e))}async setExternalWallets(e){this.externalWallets=e,await this.localStorageSetItem(z,JSON.stringify(e))}async setCurrentExternalWalletAddresses(e){this.currentExternalWalletAddresses=e,await this.localStorageSetItem(Q,JSON.stringify(e))}async setLoginEncryptionKeyPair(e){e||(e=await B(this.ctx)),this.loginEncryptionKeyPair=e,await this.sessionStorageSetItem(k,JSON.stringify(e))}async deleteLoginEncryptionKeyPair(){this.loginEncryptionKeyPair=void 0,await this.sessionStorageRemoveItem(k)}getUserId(){return this.userId}getEmail(){return this.email}getPhone(){return{phone:this.phone,countryCode:this.countryCode}}getPhoneNumber(){if(!(!this.phone||!this.countryCode))return fe(this.countryCode,this.phone)}getFarcasterUsername(){return this.farcasterUsername}async setCurrentWalletIds(e,{needsWallet:t=!1,sessionLookupId:r,newDeviceSessionLookupId:s}={}){this.currentWalletIds=e,await this.localStorageSetItem(N,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 a=Object.keys(this.wallets).filter(o=>this.wallets[o].type===s&&this.isPregenWalletClaimable(this.wallets[o]));[...n,...a].forEach(o=>{e.toLowerCase()===this.getDisplayAddress(o,{addressType:s}).toLowerCase()&&(r=this.wallets[o])})}),!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,...a}=this.wallets[s],o=t??this.currentWalletIdsArray.find(([l])=>l===s)?.[1]??a.type;return{...a,type:p.WalletType[o]}}}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)||!I[r.scheme][e])).map(({type:e})=>e)}async getTypesToCreate(e){return this.#e||await this.touchSession(),Pe(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)||T(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 oe({base:T(this.ctx),path:`/short/${e}`})}async shortenLoginLink(e){let t=await ut(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(x(t))))}async populateWalletAddresses(){(await this.ctx.client.getWallets(this.userId,!0)).data.wallets.forEach(r=>{this.wallets[r.id]&&(this.wallets[r.id]={...x(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]={...x(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({popupWindow:e}={}){for(await this.touchSession(),this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingAccountCreation=!0;this.isAwaitingAccountCreation;)try{if(await new Promise(t=>setTimeout(t,R)),await this.isSessionActive())return this.isAwaitingAccountCreation=!1,g(h.ACCOUNT_CREATION_EVENT,!0),!0;if(e?.closed)return this.isAwaitingAccountCreation=!1,!1}catch(t){console.error(t)}return!1}async waitForPasskeyAndCreateWallet({popupWindow:e}={}){await this.waitForAccountCreation({popupWindow:e});let t=await this.getPregenWallets(),r,s={};t.length>0&&(r=await this.claimPregenWallets(),s=this.supportedWalletTypes.reduce((o,{type:l})=>({...o,[l]:[t.find(c=>!!I[c.scheme][l])?.id]}),{}));let n=await this.createWalletPerType();r=r??n.recoverySecret,s={...s,...n.walletIds};let a={walletIds:s,recoverySecret:r};return g(h.ACCOUNT_SETUP_EVENT,a),a}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,R));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 oe({base:e===p.OAuthMethod.TELEGRAM?T(this.ctx,!0):Oe(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,R)),this.isAwaitingOAuth){let t=await this.touchSession();if(t.data.userId){let{userId:r,email:s}=t.data;this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair(),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,R)),!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 a=await this.fetchWallets(),o=await this.getTransmissionKeyShares();if(o.data.temporaryShares.length===a.length){await this.setupAfterLogin({temporaryShares:o.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: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=F(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 he({ctx:this.ctx,userId:this.userId,walletId:e,userSigner:n,emailProps:this.getBackupKitEmailProps(),forceRefresh:s}):await v({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,be))}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,be))}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 a of await this.getTypesToCreate(t)){let[o,l]=await this.createWallet({type:a,skipDistribute:e});r.push(o),Ae(a).filter(c=>!!this.isWalletTypeEnabled[c]).forEach(c=>{s[c]=[o.id]}),l&&(n=l)}return{wallets:r,walletIds:s,recoverySecret:n}}async refreshShare({walletId:e,share:t,oldPartnerId:r,newPartnerId:s,keyShareProtocolId:n,redistributeBackupEncryptedShares:a}){let{signer:o,protocolId:l}=await this.platformUtils.refresh(this.ctx,this.retrieveSessionCookie(),this.userId,e,t,r,s,n),c=await v({ctx:this.ctx,userId:this.userId,walletId:e,userShare:o,ignoreRedistributingBackupEncryptedShare:!a,emailProps:this.getBackupKitEmailProps(),partnerId:s,protocolId:l});return{signer:o,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,a;switch(r){case p.WalletType.SOLANA:{a=await this.platformUtils.ed25519Keygen(this.ctx,this.userId,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}default:{a=await this.platformUtils.keygen(this.ctx,this.userId,r,null,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}}let o=a.walletId;s=a.signer,this.wallets[o]={id:o,signer:s,scheme:r===p.WalletType.SOLANA?p.WalletScheme.ED25519:p.WalletScheme.DKLS,type:r},n=this.wallets[o],await this.waitForWalletAddress(n.id),await this.populateWalletAddresses();let l=null;t||(l=await v({ctx:this.ctx,userId:this.userId,walletId:n.id,userShare:s,emailProps:this.getBackupKitEmailProps()})),await this.setCurrentWalletIds({...this.currentWalletIds,[r]:[...this.currentWalletIds[r]??[],o]});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),a;switch(n){case p.WalletType.SOLANA:a=await this.platformUtils.ed25519PreKeygen(this.ctx,r,s,this.retrieveSessionCookie());break;default:a=await this.platformUtils.preKeygen(this.ctx,void 0,r,s,n,null,this.retrieveSessionCookie());break}let{signer:o,walletId:l}=a;return this.wallets[l]={id:l,signer:o,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 a=await this.createPregenWallet({type:n,pregenIdentifier:t,pregenIdentifierType:r});s.push(a)}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(a=>a.id)});for(let a of n){let o=this.wallets[a],l;if(o.scheme===p.WalletScheme.ED25519){let d=await v({ctx:this.ctx,userId:this.userId,walletId:o.id,userShare:this.wallets[o.id].signer,emailProps:this.getBackupKitEmailProps(),partnerId:o.partnerId});d.length>0&&(s=d)}else l=await this.refreshShare({walletId:o.id,share:this.wallets[o.id].signer,oldPartnerId:o.partnerId,newPartnerId:o.partnerId,redistributeBackupEncryptedShares:!0}),l.recoverySecret&&(s=l.recoverySecret);this.wallets[o.id]={...this.wallets[o.id],signer:l?.signer??o.signer,userId:this.userId,pregenIdentifier:void 0,pregenIdentifierType:void 0};let c={...this.wallets[o.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(x(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=G(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,a]=(0,p.extractWalletRef)(r);return this.constructPortalUrl("onRamp",{partnerId:s.data.partnerId,pathId:e,sessionId:s.data.sessionId,params:{[n]:a,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],a=this.userId;n.partnerId&&!n.userId&&(a=n.partnerId);let o=await this.signMessageInner({wallet:n,signerId:a,messageBase64:t,cosmosSignDocBase64:s}),l=Date.now();if(o.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(o.pendingTransactionId,r),{type:s?"SIGN_TRANSACTION_REVIEW":"SIGN_MESSAGE_REVIEW"});else return g(h.SIGN_MESSAGE_EVENT,o),o;for(await new Promise(c=>setTimeout(c,R));!(Date.now()-l>r);){try{await this.ctx.client.getPendingTransaction(this.userId,o.pendingTransactionId)}catch{let d=new $;throw g(h.SIGN_MESSAGE_EVENT,o,d.message),d}if(o=await this.signMessageInner({wallet:n,signerId:a,messageBase64:t,cosmosSignDocBase64:s}),o.pendingTransactionId)await new Promise(c=>setTimeout(c,R));else break}if(o.pendingTransactionId){let c=new H(await this.getTransactionReviewUrl(o.pendingTransactionId),o.pendingTransactionId);throw g(h.SIGN_MESSAGE_EVENT,o,c.message),c}return g(h.SIGN_MESSAGE_EVENT,o),o}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],a=this.userId;n.partnerId&&!n.userId&&(a=n.partnerId);let o=await this.platformUtils.signTransaction(this.ctx,a,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===p.WalletScheme.DKLS),l=Date.now();if(o.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(o.pendingTransactionId,s),{type:"SIGN_TRANSACTION_REVIEW"});else return g(h.SIGN_TRANSACTION_EVENT,o),o;for(await new Promise(c=>setTimeout(c,R));!(Date.now()-l>s);){try{await this.ctx.client.getPendingTransaction(this.userId,o.pendingTransactionId)}catch{let d=new $;throw g(h.SIGN_TRANSACTION_EVENT,o,d.message),d}if(o=await this.platformUtils.signTransaction(this.ctx,a,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===p.WalletScheme.DKLS),o.pendingTransactionId)await new Promise(c=>setTimeout(c,R));else break}if(o.pendingTransactionId){let c=new H(await this.getTransactionReviewUrl(o.pendingTransactionId),o.pendingTransactionId);throw g(h.SIGN_TRANSACTION_EVENT,o,c.message),c}return g(h.SIGN_TRANSACTION_EVENT,o),o}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 te(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}),a=await this.getOnRampTransactionUrl({purchaseId:n.id,providerKey:n.providerKey,...s});return r&&this.platformUtils.openPopup(a,{type:"ON_RAMP_TRANSACTION"}),{onRampPurchase:n,portalUrl:a}}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.setTelegramUserId(r.telegramUserId),await this.setFarcasterUsername(r.farcasterUsername),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(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 u=require("@getpara/user-management-client"),Ht=re.version,jt=re;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});
|
package/dist/cjs/index.js.br
CHANGED
|
Binary file
|
package/dist/cjs/index.js.gz
CHANGED
|
Binary file
|
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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.1',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};
|
|
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 ye}from"buffer";import{AuthMethod as fe,PublicKeyStatus as Xe,PublicKeyType as qe,WalletType as f,WalletScheme as E,OAuthMethod as kt,extractWalletRef as Kt,PasswordStatus as Dt,extractAuthInfo as Gt}from"@getpara/user-management-client";import Bt from"node-forge";import gt from"base64url";import y from"node-forge";function u(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 Xt(i){return i.substring(0,2)==="0x"&&(i=i.substring(2)),Buffer.from(i,"hex").toString("base64")}function qt(i){return{r:`0x${i.slice(2,66)}`,s:`0x${i.slice(66,130)}`,v:BigInt(i.slice(130,132))}}function zt(i){return i.startsWith("0x")&&(i=i.slice(2)),new Uint8Array(Buffer.from(i,"hex"))}function Qt(i){return i.startsWith("0x")&&(i=i.slice(2)),`${parseInt(i,16)}`}function Zt(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 Ee(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 se(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 j(i){return it(i)?.formatInternational().replace(/[^\d+]/g,"")}function we(i,e){return j(`${i[0]!=="+"?"+":""}${i}${e}`)}function ie(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(a=>{let o=n[a];e.push([t,s,a,o])})})}),e}function lt(i,{walletType:e,allowed:t}={}){return[...new Set(ie(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(ie(i).filter(([s,n,a])=>(!e||s===e)&&(!t||n===t)&&(!Array.isArray(r)||r.includes(a))).map(([,,s])=>s))]}async function rr(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=(a=>(a.DEV="DEV",a.SANDBOX="SANDBOX",a.BETA="BETA",a.PROD="PROD",a.DEVELOPMENT="BETA",a.PRODUCTION="PROD",a))(pt||{}),dt=(r=>(r.BUY="BUY",r.RECEIVE="RECEIVE",r.WITHDRAW="WITHDRAW",r))(dt||{});var Ie=(t=>(t.EMAIL="EMAIL",t.PHONE="PHONE",t))(Ie||{});var Pe=(s=>(s.ACH="ACH",s.DEBIT="Debit",s.CREDIT="Credit",s.APPLE_PAY="Apple Pay",s))(Pe||{});var ne=(a=>(a.SIGN_TRANSACTION_REVIEW="SIGN_TRANSACTION_REVIEW",a.SIGN_MESSAGE_REVIEW="SIGN_MESSAGE_REVIEW",a.LOGIN_PASSKEY="LOGIN_PASSKEY",a.CREATE_PASSKEY="CREATE_PASSKEY",a.OAUTH="OAUTH",a.ON_RAMP_TRANSACTION="ON_RAMP_TRANSACTION",a))(ne||{});var Ae=(n=>(n.INITIATED="INITIATED",n.READY="READY",n.EXPIRED="EXPIRED",n.FINISHED="FINISHED",n.CANCELLED="CANCELLED",n))(Ae||{});var I="para",d=(p=>(p.LOGIN_EVENT=`${I}Login`,p.ACCOUNT_CREATION_EVENT=`${I}AccountCreation`,p.ACCOUNT_SETUP_EVENT=`${I}AccountSetup`,p.LOGOUT_EVENT=`${I}Logout`,p.SIGN_MESSAGE_EVENT=`${I}SignMessage`,p.SIGN_TRANSACTION_EVENT=`${I}SignTransaction`,p.EXTERNAL_WALLET_CHANGE_EVENT=`${I}ExternalWalletChange`,p.WALLETS_CHANGE_EVENT=`${I}WalletsChange`,p.WALLET_CREATED=`${I}WalletCreated`,p.PREGEN_WALLET_CLAIMED=`${I}PregenWalletClaimed`,p))(d||{});function Te(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 T({env:i,isE2E:e},t,r){if(e)return r?"https://app.sandbox.usecapsule.com":"http://localhost:3003";let s=Te(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 We({env:i},e){let t=ut(i);return i==="DEV"?e?"http://127.0.0.1:3008":`http://${t}:3008`:`https://${t}`}function Q({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 v,WalletType as P}from"@getpara/user-management-client";var w={[v.DKLS]:{[P.EVM]:!0,[P.COSMOS]:!0},[v.CGGMP]:{[P.EVM]:!0,[P.COSMOS]:!0},[v.ED25519]:{[P.SOLANA]:!0}};function Ce(i,e,t){if(!i||!e)return!1;switch(t){case"EMAIL":return i.toLowerCase()===e.toLowerCase();case"PHONE":return j(i)===j(e);case"CUSTOM_ID":return i===e;default:return i.replace(/^@/g,"").toLowerCase()===e.replace(/^@/g,"").toLowerCase()}}function ae(i,e){return i.some(t=>!!w[e.scheme][t])}function oe(i){return Object.keys(w).filter(e=>e===v.CGGMP?!1:(Array.isArray(i)?i:Object.keys(i)).some(t=>w[e][t]))}function ht(i){return[...new Set(i.reduce((e,t)=>[...e,...Object.keys(w[t]).filter(r=>w[t][r])],[]))]}function le(i){return ht(oe((Array.isArray(i)?i:[i]).map(e=>P[e])))}function _(i){return{...i,scheme:i.scheme,type:i.type,pregenIdentifierType:i.pregenIdentifierType}}function U(i){return["USER","PREGEN"].includes(i.type)&&(i.isPregen=i.type==="PREGEN",i.type=i.scheme===v.ED25519?P.SOLANA:P.EVM),i.scheme&&!i.type&&(i.type=i.scheme===v.ED25519?P.SOLANA:P.EVM),i}var mt=y.pki.rsa,ce="RSA-OAEP",Re="794241bc819a125a7b78ea313decc0bc",Z=new Uint8Array([23,66,157,146,179,158,117,120,184,73,123,81]);function Oe(i){let e=y.md.sha256.create();return e.update(i),e.digest().toHex()}function N(i){let e=y.pki.publicKeyToRSAPublicKeyPem(i.publicKey);return Buffer.from(e,"utf-8").toString("hex")}function yt(i){let e=xe(i);return y.pki.publicKeyFromPem(e)}function xe(i){return Buffer.from(i,"hex").toString("utf-8")}function pe(i){let e=y.pki.privateKeyToPem(i.privateKey);return Buffer.from(e,"utf-8").toString("hex")}function Le(i){let e=Buffer.from(i,"hex").toString("utf-8");return y.pki.privateKeyFromPem(e)}async function ft(i,e){let t=pe(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:Z},r,s);return Buffer.from(n).toString("base64")}async function be(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:Z},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return Le(s)}async function J(i,e){let t=y.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(`${T(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,(a,o)=>{a&&n(a),s(o)}))}async function St(i,e){let t=gt.encode(e),r=await J(i,t);return N(r)}function Et(i){let e=y.random.getBytesSync(16),t=y.cipher.createCipher("AES-CBC",e);t.start({iv:Re}),t.update(y.util.createBuffer(i)),t.finish();let r=t.output.toHex();return{key:e,encryptedMessageHex:r}}function ve(i,e){let t=y.cipher.createDecipher("AES-CBC",i);return t.start({iv:Re}),t.update(y.util.createBuffer(y.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,ce);return ve(s,e)}function Y(i,e,t){let r=Buffer.from(t,"hex").toString("utf-8"),s=i.decrypt(r,ce);return ve(s,e)}async function It(i,{seedValue:e,encryptedMessageHex:t,encryptedKeyHex:r}){let s=await J(i,e);return Y(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 be(t,i)}catch{}try{r=await _e(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:Y(r,s.encryptedShare,s.encryptedKey),protocolId:s.protocolId}))}function ee(i,e){let{key:t,encryptedMessageHex:r}=Et(e),s=xe(i),a=y.pki.publicKeyFromPem(s).encrypt(t,ce),o=Buffer.from(a,"utf-8").toString("hex");return{encryptedMessageHex:r,encryptedKeyHex:o}}function Tt(i){let e=Wt(),t=e+i,r=Oe(t);return{salt:e,hash:r}}function Wt(i=16){return y.util.bytesToHex(y.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=pe(i),s=new TextEncoder().encode(r),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:Z},t,s);return Buffer.from(n).toString("base64")}async function _e(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:Z},t,Buffer.from(i,"base64")),s=new TextDecoder().decode(r);return Le(s)}import Ot from"@getpara/user-management-client";function Ue(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 Ne(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 Ir(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 de({env:i,version:e,apiKey:t,partnerId:r,useFetchAdapter:s=!1,retrieveSessionCookie:n,persistSessionCookie:a}){return new Ot({userManagementHost:Ne(i),version:["DEV","SANDBOX"].includes(i)?"dev":e,apiKey:t,partnerId:r,opts:{useFetchAdapter:s},retrieveSessionCookie:n,persistSessionCookie:a})}var he={};Ze(he,{initClient:()=>ue});import xt from"axios";function ue(i,e){let t=xt.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 Fe,KeyShareType as Me}from"@getpara/user-management-client";import{EncryptorType as Ge,KeyShareType as Be}from"@getpara/user-management-client";import{Encrypt as ke,Decrypt as Lt}from"@celo/utils/lib/ecies.js";import*as Ke from"ethereumjs-util";import*as De from"node-forge";var k=class i{constructor(e,t,r){this.walletId=e,this.keyshare=t,this.address=r,this.backupDecryptionKey=Buffer.from(De.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(Ke.privateToPublic(Buffer.from(this.backupDecryptionKey,"hex")))}getPublicEncryptionKeyHex(){return this.getPublicEncryptionKey().toString("hex")}encryptForSelf(e){try{let t=this.getPublicEncryptionKey();return ke(t,Buffer.from(e,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}static encryptWithPublicKey(e,t){try{return ke(e,Buffer.from(t,"ucs2")).toString("base64")}catch{throw Error("Error encrypting backup")}}decrypt(e){try{let t=Buffer.from(e,"base64"),r=Lt(Buffer.from(this.backupDecryptionKey,"hex"),t);return Buffer.from(r.buffer).toString("ucs2")}catch{throw Error("Error decrypting backup")}}};async function te({ctx:i,userId:e,walletId:t,otherEncryptedShares:r=[],userSigner:s,ignoreRedistributingBackupEncryptedShare:n=!1,emailProps:a={},forceRefresh:o=!1}){if(n)return await i.client.uploadUserKeyShares(e,r.map(S=>({walletId:t,...S}))),"";let l,c,{recoveryPublicKeys:p}=await i.client.getRecoveryPublicKeys(e);if(o||!p?.length){c=new k(t,"","");let{recoveryPublicKeys:S}=await i.client.persistRecoveryPublicKeys(e,[c.getPublicEncryptionKeyHex()]),h=c.encryptForSelf(s);l=[{walletId:t,encryptedShare:h,type:Be.USER,encryptor:Ge.RECOVERY,recoveryPublicKeyId:S[0].id}]}else l=p.map(S=>{let{id:h,publicKey:g}=S,A=k.encryptWithPublicKey(Buffer.from(g,"hex"),s);return{walletId:t,encryptedShare:A,type:Be.USER,encryptor:Ge.RECOVERY,recoveryPublicKeyId:h}});return await i.client.uploadUserKeyShares(e,[...r.map(S=>({walletId:t,...S})),...n?[]:l]),await i.client.distributeParaShare({userId:e,walletId:t,useDKLS:i.useDKLS,...a}),c?JSON.stringify(c):""}async function K({ctx:i,userId:e,walletId:t,userShare:r,ignoreRedistributingBackupEncryptedShare:s=!1,emailProps:n={},partnerId:a,protocolId:o}){let c=(await i.client.getSessionPublicKeys(e)).data.keys.map(g=>{if(!g.publicKey)return;let{encryptedMessageHex:A,encryptedKeyHex:b}=ee(g.sigDerivedPublicKey,r);return{encryptedShare:A,encryptedKey:b,type:Me.USER,encryptor:Fe.BIOMETRICS,biometricPublicKey:g.sigDerivedPublicKey,partnerId:a,protocolId:o}}).filter(Boolean),S=(await i.client.getPasswords({userId:e})).map(g=>{if(g.status==="PENDING")return;let{encryptedMessageHex:A,encryptedKeyHex:b}=ee(g.sigDerivedPublicKey,r);return{encryptedShare:A,encryptedKey:b,type:Me.USER,encryptor:Fe.PASSWORD,passwordId:g.id,partnerId:a,protocolId:o}}).filter(Boolean),h=[...c,...S];return await te({ctx:i,userId:e,walletId:t,otherEncryptedShares:h,userSigner:r,ignoreRedistributingBackupEncryptedShare:s,emailProps:n})}import{Encrypt as bt,Decrypt as vt}from"@celo/utils/lib/ecies.js";import{Buffer as D}from"buffer";import*as Ve from"ethereumjs-util";import{randomBytes as _t}from"crypto";async function $e(i,e){let t,r;for(;;)try{t=_t(32).toString("hex"),r=Ve.privateToPublic(D.from(t,"hex"));break}catch{continue}let s=D.from(r),n=bt(s,D.from(i,"ucs2")).toString("base64"),{data:{id:a}}=await e.tempTrasmissionInit(n);return encodeURIComponent(a+"|"+t)}async function Ut(i,e){let[t,r]=decodeURIComponent(i).split("|"),n=(await e.tempTrasmission(t)).data.message,a=D.from(n,"base64");return D.from(vt(D.from(r,"hex"),a).buffer).toString("ucs2")}var re=class extends Error{constructor(e){super("transaction review error"),this.name="TransactionReviewError",this.transactionReviewUrl=e}},X=class extends Error{constructor(){super("transaction review has been denied by the user"),this.name="TransactionReviewDenied"}},q=class extends Error{constructor(e,t){super("transaction review has timed out"),this.name="TransactionReviewTimeout",this.transactionReviewUrl=e,this.pendingTransactionId=t}};var He='1.4.1',m="@CAPSULE/",G=`${m}e-mail`,B=`${m}phone`,F=`${m}countryCode`,je=`${m}farcasterUsername`,M=`${m}telegramUserId`,V=`${m}userId`,O=`${m}ed25519Wallets`,W=`${m}wallets`,$=`${m}externalWallets`,x=`${m}currentWalletIds`,H=`${m}currentExternalWalletAddresses`,R=`${m}sessionCookie`,L=`${m}loginEncryptionKeyPair`,C=2e3,ge=1e3;function Ye(i){i.url.includes(window.location.origin)&&(i.key===H&&this.updateCurrentExternalWalletAddressesFromStorage(),i.key===$&&this.updateExternalWalletsFromStorage(),i.key===L&&this.updateLoginEncryptionKeyPairFromStorage(),i.key===R&&this.updateSessionCookieFromStorage(),i.key===x&&this.updateWalletIdsFromStorage(),(i.key===W||i.key===O)&&this.updateWalletsFromStorage(),i.key===G&&this.updateEmailFromStorage(),i.key===F&&this.updateCountryCodeFromStorage(),i.key===B&&this.updatePhoneFromStorage(),i.key===V&&this.updateUserIdFromStorage(),i.key===M&&this.updateTelegramUserIdFromStorage())}function me(){typeof window<"u"&&window.addEventListener&&window.location&&(window.removeEventListener("storage",Ye.bind(this)),window.addEventListener("storage",Ye.bind(this)))}typeof global<"u"?global.Buffer=global.Buffer||ye:typeof window<"u"?(window.Buffer=window.Buffer||ye,window.global=window.global||window):(self.Buffer=self.Buffer||ye,self.global=self.global||self);var{pki:ze,jsbn:Ft}=Bt,z=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(m),(t||e==="session")&&this.platformUtils.sessionStorage.clear(m),(t||e==="secure")&&this.platformUtils.secureStorage&&this.platformUtils.secureStorage.clear(m)};this.initializeFromStorage=()=>{this.updateEmailFromStorage(),this.updateCountryCodeFromStorage(),this.updatePhoneFromStorage(),this.updateUserIdFromStorage(),this.updateTelegramUserIdFromStorage(),this.updateWalletsFromStorage(),this.updateWalletIdsFromStorage(),this.updateSessionCookieFromStorage(),this.updateLoginEncryptionKeyPairFromStorage(),this.updateExternalWalletsFromStorage(),this.updateCurrentExternalWalletAddressesFromStorage()};this.updateTelegramUserIdFromStorage=()=>{this.telegramUserId=this.localStorageGetItem(M)||void 0};this.updateUserIdFromStorage=()=>{this.userId=this.localStorageGetItem(V)||void 0};this.updatePhoneFromStorage=()=>{this.phone=this.localStorageGetItem(B)||void 0};this.updateCountryCodeFromStorage=()=>{this.countryCode=this.localStorageGetItem(F)||void 0};this.updateEmailFromStorage=()=>{this.email=this.localStorageGetItem(G)||void 0};this.updateWalletsFromStorage=async()=>{let e=this.localStorageGetItem(x)??void 0,t=[void 0,null,"undefined"].includes(e)?{}:(()=>{let l=JSON.parse(e);return Array.isArray(l)?Object.keys(f).reduce((c,p)=>{let S=Object.values(this.wallets).find(h=>l.includes(h.id)&&w[h.scheme][p]);return{...c,...S&&!c[p]?{[p]:[S.id]}:{}}},{}):l})();this.setCurrentWalletIds(t);let r=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(W):this.localStorageGetItem(W),s=JSON.parse(r||"{}"),n=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(O):this.localStorageGetItem(O),a=JSON.parse(n||"{}"),o={...Object.keys(s).reduce((l,c)=>({...l,[c]:U(s[c])}),{}),...Object.keys(a).reduce((l,c)=>({...l,...l[c]?{}:{[c]:U(a[c])}}),{})};this.setWallets(o)};this.updateWalletIdsFromStorage=()=>{let e=this.localStorageGetItem(x)??void 0,t=[void 0,null,"undefined"].includes(e)?{}:(()=>{let r=JSON.parse(e);return Array.isArray(r)?Object.keys(f).reduce((s,n)=>{let a=Object.values(this.wallets).find(o=>r.includes(o.id)&&w[o.scheme][n]);return{...s,...a&&!s[n]?{[n]:[a.id]}:{}}},{}):r})();this.setCurrentWalletIds(t),Object.values(this.wallets).filter(r=>this.isWalletOwned(r)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0})};this.updateSessionCookieFromStorage=()=>{this.sessionCookie=this.localStorageGetItem(R)||this.sessionStorageGetItem(R)||void 0};this.updateLoginEncryptionKeyPairFromStorage=()=>{let e=this.sessionStorageGetItem(L);e&&e!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(e)))};this.updateExternalWalletsFromStorage=()=>{let e=this.localStorageGetItem($),t=JSON.parse(e||"{}");this.setExternalWallets(t)};this.updateCurrentExternalWalletAddressesFromStorage=()=>{let e=this.localStorageGetItem(H)||void 0;this.currentExternalWalletAddresses=e?JSON.parse(e):void 0};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=s=>{this.sessionCookie=s,(r.useSessionStorage?this.sessionStorageSetItem:this.localStorageSetItem)(R,s)},this.ctx={env:e,apiKey:t,client:de({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=ue(r.offloadMPCComputationURL,r.disableWorkers));try{this.#e=r.supportedWalletTypes?(()=>{if(Object.values(r.supportedWalletTypes).every(s=>!!s&&typeof s=="object"&&s.optional))throw new Error("at least one wallet type must be non-optional");if(!Object.keys(r.supportedWalletTypes).every(s=>Object.values(f).includes(s)))throw new Error("unsupported wallet type");return this.#t=r.supportedWalletTypes,Object.entries(r.supportedWalletTypes).reduce((s,[n,a])=>a?(n===f.COSMOS&&typeof a=="object"&&a.prefix&&(this.cosmosPrefix=a.prefix),[...s,{type:n,optional:a===!0?!1:a.optional??!1}]):s,[])})():void 0}catch{this.#e=void 0}!this.platformUtils.isSyncStorage||r.useStorageOverrides||(this.initializeFromStorage(),me.bind(this)())}static{this.version=He}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&&T(e?{env:e}:this.ctx).includes(window.location.host)}isParaConnect(){return typeof window>"u"?!1:!!window.location?.host&&We(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||ae(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)||Ce(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 a;if(!this.wallets[e])a=`wallet with id ${e} does not exist`;else{let o=this.wallets[e],[l,c]=[this.isPregenWalletUnclaimed(o),this.isWalletOwned(o)];s&&l?a=`pre-generated wallet with id ${o.id} cannot be selected`:!c&&!l?a=`wallet with id ${o.id} is not owned by the current user`:this.isWalletSupported(o)?t&&(!le(t).includes(o.type)||c&&!t.some(p=>(this.currentWalletIds[p]??[]).includes(e)))?a=`wallet with id ${o.id} and type ${o.type} cannot be selected`:r&&!r.includes(o.scheme)&&(a=`wallet with id ${o.id} and scheme ${o.scheme} cannot be selected`):a=`wallet with id ${o.id} and type ${o.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({type:p})=>p).join(", ")}`}if(a){if(n)throw new Error(a);return!1}return!0}getDisplayAddress(e,t={}){if(this.externalWallets[e]){let n=this.externalWallets[e];return t.truncate?se(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 f.COSMOS:s=Ee(r.publicKey,this.cosmosPrefix??"cosmos");break;default:s=r.address;break}return t.truncate?se(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"?T(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,a,o]=[["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||a?{...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}:{}}:{},...a||o?{sessionId:t.sessionId}:{},...a?{encryptionKey:t.loginEncryptionPublicKey,newDeviceSessionLookupId:t.newDeviceSessionId,newDeviceEncryptionKey:t.newDeviceEncryptionKey,pregenIds:JSON.stringify(this.pregenIds),displayName:t.displayName,pfpUrl:t.pfpUrl}:{},...t.params||{}};return Q({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(G)||void 0,this.countryCode=await this.localStorageGetItem(F)||void 0,this.phone=await this.localStorageGetItem(B)||void 0,this.userId=await this.localStorageGetItem(V)||void 0,this.telegramUserId=await this.localStorageGetItem(M)||void 0;let e=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(W):await this.localStorageGetItem(W),t=JSON.parse(e||"{}"),r=this.platformUtils.secureStorage?await this.platformUtils.secureStorage.get(O):await this.localStorageGetItem(O),s=JSON.parse(r||"{}"),n={...Object.keys(t).reduce((h,g)=>({...h,[g]:U(t[g])}),{}),...Object.keys(s).reduce((h,g)=>({...h,...h[g]?{}:{[g]:U(s[g])}}),{})};await this.setWallets(n);let a=await this.localStorageGetItem(x)??void 0,o=[void 0,null,"undefined","null"].includes(a)?{}:(()=>{let h=JSON.parse(a);return Array.isArray(h)?Object.keys(f).reduce((g,A)=>{let b=Object.values(this.wallets).find(Se=>h.includes(Se.id)&&w[Se.scheme][A]);return{...g,...b&&!g[A]?{[A]:[b.id]}:{}}},{}):h})();await this.setCurrentWalletIds(o),this.sessionCookie=await this.localStorageGetItem(R)||await this.sessionStorageGetItem(R)||void 0,Object.values(this.wallets).filter(h=>this.isWalletOwned(h)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0});let l=await this.sessionStorageGetItem(L);l&&l!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(l)));let c=await this.localStorageGetItem($),p=JSON.parse(c||"{}");await this.setExternalWallets(p);let S=await this.localStorageGetItem(H)||void 0;this.currentExternalWalletAddresses=S?JSON.parse(S):void 0,me.bind(this)(),await this.touchSession()}async setEmail(e){this.email=e,await this.localStorageSetItem(G,e)}async setTelegramUserId(e){this.telegramUserId=e,await this.localStorageSetItem(M,e)}async setPhoneNumber(e,t){this.phone=e,this.countryCode=t,await this.localStorageSetItem(B,e),await this.localStorageSetItem(F,t)}async setFarcasterUsername(e){this.farcasterUsername=e,await this.localStorageSetItem(je,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),u(d.EXTERNAL_WALLET_CHANGE_EVENT,null)}async setUserId(e){this.userId=e,await this.localStorageSetItem(V,e)}async setWallets(e){if(this.wallets=e,this.platformUtils.secureStorage){await this.platformUtils.secureStorage.set(W,JSON.stringify(e));return}await this.localStorageSetItem(W,JSON.stringify(e))}async setExternalWallets(e){this.externalWallets=e,await this.localStorageSetItem($,JSON.stringify(e))}async setCurrentExternalWalletAddresses(e){this.currentExternalWalletAddresses=e,await this.localStorageSetItem(H,JSON.stringify(e))}async setLoginEncryptionKeyPair(e){e||(e=await J(this.ctx)),this.loginEncryptionKeyPair=e,await this.sessionStorageSetItem(L,JSON.stringify(e))}async deleteLoginEncryptionKeyPair(){this.loginEncryptionKeyPair=void 0,await this.sessionStorageRemoveItem(L)}getUserId(){return this.userId}getEmail(){return this.email}getPhone(){return{phone:this.phone,countryCode:this.countryCode}}getPhoneNumber(){if(!(!this.phone||!this.countryCode))return we(this.countryCode,this.phone)}getFarcasterUsername(){return this.farcasterUsername}async setCurrentWalletIds(e,{needsWallet:t=!1,sessionLookupId:r,newDeviceSessionLookupId:s}={}){this.currentWalletIds=e,await this.localStorageSetItem(x,JSON.stringify(this.currentWalletIds)),r&&await this.ctx.client.setCurrentWalletIds(this.getUserId(),this.currentWalletIds,t,r,s),u(d.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 a=Object.keys(this.wallets).filter(o=>this.wallets[o].type===s&&this.isPregenWalletClaimable(this.wallets[o]));[...n,...a].forEach(o=>{e.toLowerCase()===this.getDisplayAddress(o,{addressType:s}).toLowerCase()&&(r=this.wallets[o])})}),!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,...a}=this.wallets[s],o=t??this.currentWalletIdsArray.find(([l])=>l===s)?.[1]??a.type;return{...a,type:f[o]}}}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(f).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)||!w[r.scheme][e])).map(({type:e})=>e)}async getTypesToCreate(e){return this.#e||await this.touchSession(),oe(e??await this.getMissingTypes()).map(t=>{switch(t){case E.ED25519:return f.SOLANA;default:return this.supportedWalletTypes.some(({type:r,optional:s})=>r===f.COSMOS&&!s)?f.COSMOS:f.EVM}})}async getPartnerURL(e){return(await this.ctx.client.getPartner(e)).data.partner.portalUrl}async getPortalURL(e){return e&&await this.getPartnerURL(e)||T(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 Q({base:T(this.ctx),path:`/short/${e}`})}async shortenLoginLink(e){let t=await $e(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!==E.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(_(t))))}async populateWalletAddresses(){(await this.ctx.client.getWallets(this.userId,!0)).data.wallets.forEach(r=>{this.wallets[r.id]&&(this.wallets[r.id]={..._(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]={..._(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:Dt.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(fe.PASSWORD);break;case"BIOMETRIC":r.add(fe.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=Gt(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:N(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:N(this.loginEncryptionKeyPair),partnerId:r.data.partnerId});return e?this.shortenLoginLink(s):s}async waitForAccountCreation({popupWindow:e}={}){for(await this.touchSession(),this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingAccountCreation=!0;this.isAwaitingAccountCreation;)try{if(await new Promise(t=>setTimeout(t,C)),await this.isSessionActive())return this.isAwaitingAccountCreation=!1,u(d.ACCOUNT_CREATION_EVENT,!0),!0;if(e?.closed)return this.isAwaitingAccountCreation=!1,!1}catch(t){console.error(t)}return!1}async waitForPasskeyAndCreateWallet({popupWindow:e}={}){await this.waitForAccountCreation({popupWindow:e});let t=await this.getPregenWallets(),r,s={};t.length>0&&(r=await this.claimPregenWallets(),s=this.supportedWalletTypes.reduce((o,{type:l})=>({...o,[l]:[t.find(c=>!!w[c.scheme][l])?.id]}),{}));let n=await this.createWalletPerType();r=r??n.recoverySecret,s={...s,...n.walletIds};let a={walletIds:s,recoverySecret:r};return u(d.ACCOUNT_SETUP_EVENT,a),a}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,C));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 Q({base:e===kt.TELEGRAM?T(this.ctx,!0):Ue(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,C)),this.isAwaitingOAuth){let t=await this.touchSession();if(t.data.userId){let{userId:r,email:s}=t.data;this.loginEncryptionKeyPair||await this.setLoginEncryptionKeyPair(),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,C)),!await this.isSessionActive()){if(e?.closed){let l={isComplete:!1,isError:!0};return u(d.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 u(d.LOGIN_EVENT,l,"failed to setup user"),l}else continue;let a=await this.fetchWallets(),o=await this.getTransmissionKeyShares();if(o.data.temporaryShares.length===a.length){await this.setupAfterLogin({temporaryShares:o.data.temporaryShares,skipSessionRefresh:t}),await this.claimPregenWallets();let l={isComplete:!0,needsWallet:n||Object.values(this.wallets).length===0,partnerId:s.data.partnerId};return u(d.LOGIN_EVENT,l),l}}catch(s){console.error(s)}let r={isComplete:!1};return u(d.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:N(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=Y(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 te({ctx:this.ctx,userId:this.userId,walletId:e,userSigner:n,emailProps:this.getBackupKitEmailProps(),forceRefresh:s}):await K({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,ge))}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,ge))}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 a of await this.getTypesToCreate(t)){let[o,l]=await this.createWallet({type:a,skipDistribute:e});r.push(o),le(a).filter(c=>!!this.isWalletTypeEnabled[c]).forEach(c=>{s[c]=[o.id]}),l&&(n=l)}return{wallets:r,walletIds:s,recoverySecret:n}}async refreshShare({walletId:e,share:t,oldPartnerId:r,newPartnerId:s,keyShareProtocolId:n,redistributeBackupEncryptedShares:a}){let{signer:o,protocolId:l}=await this.platformUtils.refresh(this.ctx,this.retrieveSessionCookie(),this.userId,e,t,r,s,n),c=await K({ctx:this.ctx,userId:this.userId,walletId:e,userShare:o,ignoreRedistributingBackupEncryptedShare:!a,emailProps:this.getBackupKitEmailProps(),partnerId:s,protocolId:l});return{signer:o,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,a;switch(r){case f.SOLANA:{a=await this.platformUtils.ed25519Keygen(this.ctx,this.userId,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}default:{a=await this.platformUtils.keygen(this.ctx,this.userId,r,null,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}}let o=a.walletId;s=a.signer,this.wallets[o]={id:o,signer:s,scheme:r===f.SOLANA?E.ED25519:E.DKLS,type:r},n=this.wallets[o],await this.waitForWalletAddress(n.id),await this.populateWalletAddresses();let l=null;t||(l=await K({ctx:this.ctx,userId:this.userId,walletId:n.id,userShare:s,emailProps:this.getBackupKitEmailProps()})),await this.setCurrentWalletIds({...this.currentWalletIds,[r]:[...this.currentWalletIds[r]??[],o]});let c={...n};return delete c.signer,u(d.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),a;switch(n){case f.SOLANA:a=await this.platformUtils.ed25519PreKeygen(this.ctx,r,s,this.retrieveSessionCookie());break;default:a=await this.platformUtils.preKeygen(this.ctx,void 0,r,s,n,null,this.retrieveSessionCookie());break}let{signer:o,walletId:l}=a;return this.wallets[l]={id:l,signer:o,scheme:n===f.SOLANA?E.ED25519:E.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 a=await this.createPregenWallet({type:n,pregenIdentifier:t,pregenIdentifierType:r});s.push(a)}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(a=>a.id)});for(let a of n){let o=this.wallets[a],l;if(o.scheme===E.ED25519){let p=await K({ctx:this.ctx,userId:this.userId,walletId:o.id,userShare:this.wallets[o.id].signer,emailProps:this.getBackupKitEmailProps(),partnerId:o.partnerId});p.length>0&&(s=p)}else l=await this.refreshShare({walletId:o.id,share:this.wallets[o.id].signer,oldPartnerId:o.partnerId,newPartnerId:o.partnerId,redistributeBackupEncryptedShares:!0}),l.recoverySecret&&(s=l.recoverySecret);this.wallets[o.id]={...this.wallets[o.id],signer:l?.signer??o.signer,userId:this.userId,pregenIdentifier:void 0,pregenIdentifierType:void 0};let c={...this.wallets[o.id]};delete c.signer,u(d.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(_(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=U(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,a]=Kt(r);return this.constructPortalUrl("onRamp",{partnerId:s.data.partnerId,pathId:e,sessionId:s.data.sessionId,params:{[n]:a,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],a=this.userId;n.partnerId&&!n.userId&&(a=n.partnerId);let o=await this.signMessageInner({wallet:n,signerId:a,messageBase64:t,cosmosSignDocBase64:s}),l=Date.now();if(o.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(o.pendingTransactionId,r),{type:s?"SIGN_TRANSACTION_REVIEW":"SIGN_MESSAGE_REVIEW"});else return u(d.SIGN_MESSAGE_EVENT,o),o;for(await new Promise(c=>setTimeout(c,C));!(Date.now()-l>r);){try{await this.ctx.client.getPendingTransaction(this.userId,o.pendingTransactionId)}catch{let p=new X;throw u(d.SIGN_MESSAGE_EVENT,o,p.message),p}if(o=await this.signMessageInner({wallet:n,signerId:a,messageBase64:t,cosmosSignDocBase64:s}),o.pendingTransactionId)await new Promise(c=>setTimeout(c,C));else break}if(o.pendingTransactionId){let c=new q(await this.getTransactionReviewUrl(o.pendingTransactionId),o.pendingTransactionId);throw u(d.SIGN_MESSAGE_EVENT,o,c.message),c}return u(d.SIGN_MESSAGE_EVENT,o),o}async signMessageInner({wallet:e,signerId:t,messageBase64:r,cosmosSignDocBase64:s}){let n;switch(e.scheme){case E.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===E.DKLS,s);break}return n}async signTransaction({walletId:e,rlpEncodedTxBase64:t,chainId:r,timeoutMs:s=3e4}){this.assertIsValidWalletId(e);let n=this.wallets[e],a=this.userId;n.partnerId&&!n.userId&&(a=n.partnerId);let o=await this.platformUtils.signTransaction(this.ctx,a,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===E.DKLS),l=Date.now();if(o.pendingTransactionId)this.platformUtils.openPopup(await this.getTransactionReviewUrl(o.pendingTransactionId,s),{type:"SIGN_TRANSACTION_REVIEW"});else return u(d.SIGN_TRANSACTION_EVENT,o),o;for(await new Promise(c=>setTimeout(c,C));!(Date.now()-l>s);){try{await this.ctx.client.getPendingTransaction(this.userId,o.pendingTransactionId)}catch{let p=new X;throw u(d.SIGN_TRANSACTION_EVENT,o,p.message),p}if(o=await this.platformUtils.signTransaction(this.ctx,a,e,this.wallets[e].signer,t,r,this.retrieveSessionCookie(),n.scheme===E.DKLS),o.pendingTransactionId)await new Promise(c=>setTimeout(c,C));else break}if(o.pendingTransactionId){let c=new q(await this.getTransactionReviewUrl(o.pendingTransactionId),o.pendingTransactionId);throw u(d.SIGN_TRANSACTION_EVENT,o,c.message),c}return u(d.SIGN_TRANSACTION_EVENT,o),o}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===E.DKLS);if(n.pendingTransactionId)throw this.platformUtils.openPopup(await this.getTransactionReviewUrl(n.pendingTransactionId),{type:"SIGN_TRANSACTION_REVIEW"}),new re(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}),a=await this.getOnRampTransactionUrl({purchaseId:n.id,providerKey:n.providerKey,...s});return r&&this.platformUtils.openPopup(a,{type:"ON_RAMP_TRANSACTION"}),{onRampPurchase:n,portalUrl:a}}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.setTelegramUserId(r.telegramUserId),await this.setFarcasterUsername(r.farcasterUsername),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,u(d.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(fe[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 Vs,EmailTheme as $s,Network as Hs,WalletType as js,WalletScheme as Js,OnRampAsset as Ys,OnRampPurchaseType as Xs,OnRampProvider as qs,OnRampPurchaseStatus as zs,OAuthMethod as Qs,NON_ED25519 as Zs,PREGEN_IDENTIFIER_TYPES as ei}from"@getpara/user-management-client";var Gs=z.version,Bs=z;export{Vs as AuthMethod,$s as EmailTheme,dt as EnabledFlow,pt as Environment,k as KeyContainer,Zs as NON_ED25519,Hs as Network,Qs as OAuthMethod,Ys as OnRampAsset,Pe as OnRampMethod,qs as OnRampProvider,zs as OnRampPurchaseStatus,Xs as OnRampPurchaseType,ei as PREGEN_IDENTIFIER_TYPES,d as ParaEvent,ne as PopupType,Ie as PregenIdentifierType,Ae as RecoveryStatus,m as STORAGE_PREFIX,X as TransactionReviewDenied,re as TransactionReviewError,q as TransactionReviewTimeout,Js as WalletScheme,js as WalletType,Zt as decimalToHex,be as decryptPrivateKey,At as decryptPrivateKeyAndDecryptShare,_e as decryptPrivateKeyWithPassword,wt as decryptWithKeyPair,Y as decryptWithPrivateKey,Bs as default,K as distributeNewShare,pe as encodePrivateKeyToPemHex,ft as encryptPrivateKey,Rt as encryptPrivateKeyWithPassword,ee as encryptWithDerivedPublicKey,_ as entityToWallet,J as getAsymmetricKeyPair,Ir as getBaseMPCNetworkUrl,Ue as getBaseOAuthUrl,Ne as getBaseUrl,Ee as getCosmosAddress,Pt as getDerivedPrivateKeyAndDecrypt,ct as getOnRampAssets,lt as getOnRampNetworks,T as getPortalBaseURL,Te as getPortalDomain,St as getPublicKeyFromSignature,N as getPublicKeyHex,Oe as getSHA256HashHex,Tt as hashPasswordWithSalt,Xt as hexStringToBase64,Qt as hexToDecimal,qt as hexToSignature,zt as hexToUint8Array,de as initClient,ae as isWalletSupported,he as mpcComputationClient,we as normalizePhoneNumber,Gs as paraVersion,yt as publicKeyFromHex,j as stringToPhoneNumber,ie as toAssetInfoArray,Ut as transmissionUtilsRetrieve,se as truncateAddress,rr as waitUntilTrue};
|
package/dist/esm/index.js.br
CHANGED
|
Binary file
|
package/dist/esm/index.js.gz
CHANGED
|
Binary file
|
package/dist/types/ParaCore.d.ts
CHANGED
|
@@ -171,6 +171,18 @@ export declare abstract class ParaCore {
|
|
|
171
171
|
* @returns - A new ParaCore instance.
|
|
172
172
|
*/
|
|
173
173
|
constructor(env: Environment, apiKey?: string, opts?: ConstructorOpts);
|
|
174
|
+
private initializeFromStorage;
|
|
175
|
+
private updateTelegramUserIdFromStorage;
|
|
176
|
+
private updateUserIdFromStorage;
|
|
177
|
+
private updatePhoneFromStorage;
|
|
178
|
+
private updateCountryCodeFromStorage;
|
|
179
|
+
private updateEmailFromStorage;
|
|
180
|
+
private updateWalletsFromStorage;
|
|
181
|
+
private updateWalletIdsFromStorage;
|
|
182
|
+
private updateSessionCookieFromStorage;
|
|
183
|
+
private updateLoginEncryptionKeyPairFromStorage;
|
|
184
|
+
private updateExternalWalletsFromStorage;
|
|
185
|
+
private updateCurrentExternalWalletAddressesFromStorage;
|
|
174
186
|
touchSession(regenerate?: boolean): Promise<Awaited<ReturnType<Client['touchSession']>>>;
|
|
175
187
|
private setSupportedWalletTypes;
|
|
176
188
|
private getVerificationEmailProps;
|
|
@@ -542,8 +554,12 @@ export declare abstract class ParaCore {
|
|
|
542
554
|
/**
|
|
543
555
|
* Waits for the session to be active.
|
|
544
556
|
**/
|
|
545
|
-
waitForAccountCreation(
|
|
546
|
-
|
|
557
|
+
waitForAccountCreation({ popupWindow }?: {
|
|
558
|
+
popupWindow?: Window;
|
|
559
|
+
}): Promise<boolean>;
|
|
560
|
+
waitForPasskeyAndCreateWallet({ popupWindow, }?: {
|
|
561
|
+
popupWindow?: Window;
|
|
562
|
+
}): Promise<AccountSetupResponse>;
|
|
547
563
|
/**
|
|
548
564
|
* Initiates a Farcaster login attempt and return the URI for the user to connect.
|
|
549
565
|
* You can create a QR code with this URI that works with Farcaster's mobile app.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getpara/core-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"main": "dist/cjs/index.js",
|
|
5
5
|
"module": "dist/esm/index.js",
|
|
6
6
|
"types": "dist/types/index.d.ts",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"dependencies": {
|
|
10
10
|
"@celo/utils": "^8.0.0",
|
|
11
11
|
"@cosmjs/encoding": "^0.32.4",
|
|
12
|
-
"@getpara/user-management-client": "1.
|
|
12
|
+
"@getpara/user-management-client": "1.4.1",
|
|
13
13
|
"@noble/hashes": "^1.5.0",
|
|
14
14
|
"base64url": "^3.0.1",
|
|
15
15
|
"ethereumjs-util": "7.1.5",
|
|
@@ -40,5 +40,5 @@
|
|
|
40
40
|
"require": "./dist/cjs/index.js"
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
|
-
"gitHead": "
|
|
43
|
+
"gitHead": "9a5c5bbfac988416397562e5f56d12c063db6862"
|
|
44
44
|
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|