@openfort/openfort-js 0.10.36 → 0.10.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/cjs/sdk/src/api/auth.js +1 -1
  2. package/dist/cjs/sdk/src/api/embeddedWallet.js +1 -1
  3. package/dist/cjs/sdk/src/core/configuration/account.js +1 -1
  4. package/dist/cjs/sdk/src/core/errors/sentry.js +1 -1
  5. package/dist/cjs/sdk/src/core/openfort.js +1 -1
  6. package/dist/cjs/sdk/src/core/openfortInternal.js +1 -1
  7. package/dist/cjs/sdk/src/storage/lazyStorage.js +1 -1
  8. package/dist/cjs/sdk/src/storage/scopedStorage.js +1 -0
  9. package/dist/cjs/sdk/src/utils/chains/index.js +1 -1
  10. package/dist/cjs/sdk/src/version.js +1 -1
  11. package/dist/cjs/sdk/src/wallets/embedded.js +1 -1
  12. package/dist/cjs/sdk/src/wallets/evm/getAssets.js +1 -1
  13. package/dist/cjs/sdk/src/wallets/evm/registerSession.js +1 -1
  14. package/dist/cjs/sdk/src/wallets/evm/revokeSession.js +1 -1
  15. package/dist/cjs/sdk/src/wallets/evm/sendCallSync.js +1 -1
  16. package/dist/index.d.ts +30 -4
  17. package/dist/sdk/src/api/auth.js +1 -1
  18. package/dist/sdk/src/api/embeddedWallet.js +1 -1
  19. package/dist/sdk/src/core/configuration/account.js +1 -1
  20. package/dist/sdk/src/core/errors/sentry.js +1 -1
  21. package/dist/sdk/src/core/openfort.js +1 -1
  22. package/dist/sdk/src/core/openfortInternal.js +1 -1
  23. package/dist/sdk/src/storage/lazyStorage.js +1 -1
  24. package/dist/sdk/src/storage/scopedStorage.js +1 -0
  25. package/dist/sdk/src/utils/chains/index.js +1 -1
  26. package/dist/sdk/src/version.js +1 -1
  27. package/dist/sdk/src/wallets/embedded.js +1 -1
  28. package/dist/sdk/src/wallets/evm/getAssets.js +1 -1
  29. package/dist/sdk/src/wallets/evm/registerSession.js +1 -1
  30. package/dist/sdk/src/wallets/evm/revokeSession.js +1 -1
  31. package/dist/sdk/src/wallets/evm/sendCallSync.js +1 -1
  32. package/package.json +1 -1
@@ -1 +1 @@
1
- "use strict";var t=require("../core/configuration/authentication.js"),e=require("../core/errors/openfortError.js"),i=require("../types/types.js");exports.AuthApi=class{storage;authManager;validateAndRefreshToken;ensureInitialized;eventEmitter;constructor(t,e,i,a,r){this.storage=t,this.authManager=e,this.validateAndRefreshToken=i,this.ensureInitialized=a,this.eventEmitter=r}async logInWithEmailPassword({email:a,password:r,ecosystemGame:n}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.loginEmailPassword(a,r,n);return"action"in e||(new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async signUpGuest(){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"guest"});try{const e=await this.authManager.registerGuest();return new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async signUpWithEmailPassword({email:a,password:r,options:n,ecosystemGame:s}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.signupEmailPassword(a,r,n?.data.name,s);return"action"in e||(new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async linkEmailPassword({email:t,password:e,authToken:i,ecosystemGame:a}){return await this.validateAndRefreshToken(),await this.authManager.linkEmail(t,e,i,a)}async unlinkEmailPassword({email:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkEmail(t,e)}async requestEmailVerification({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestEmailVerification(t,e)}async resetPassword({email:t,password:e,state:i}){await this.ensureInitialized(),await this.authManager.resetPassword(t,e,i)}async requestResetPassword({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestResetPassword(t,e)}async verifyEmail({email:t,state:e}){await this.ensureInitialized(),await this.authManager.verifyEmail(t,e)}async initOAuth({provider:a,options:r,ecosystemGame:n}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"oauth",provider:a}),await this.authManager.initOAuth(a,r,n)}async initLinkOAuth({provider:a,options:r,ecosystemGame:n}){await this.validateAndRefreshToken();const s=await t.Authentication.fromStorage(this.storage);if(!s)throw new e.OpenfortError("No authentication found",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"oauth",provider:a}),await this.authManager.linkOAuth(s,a,r,n)}async unlinkOAuth({provider:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkOAuth(t,e)}async poolOAuth(e){await this.ensureInitialized();try{const a=await this.authManager.poolOAuth(e);return new t.Authentication("jwt",a.token,a.player.id,a.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,a),a}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async loginWithIdToken({provider:a,token:r,ecosystemGame:n}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"idToken",provider:a});try{const e=await this.authManager.loginWithIdToken(a,r,n);return new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async initSIWE({address:t,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initSIWE(t,e)}async authenticateWithSIWE({signature:a,message:r,walletClientType:n,connectorType:s}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"siwe",provider:"wallet"});try{const e=await this.authManager.authenticateSIWE(a,r,n,s);return new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async linkWallet({signature:t,message:e,walletClientType:i,connectorType:a,authToken:r}){return await this.validateAndRefreshToken(),await this.authManager.linkWallet(t,e,i,a,r)}async unlinkWallet({address:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkWallet(t,e)}async storeCredentials(i){if(await this.ensureInitialized(),!i.player)throw new e.OpenfortError("Player ID is required to store credentials",e.OpenfortErrorType.INVALID_CONFIGURATION);new t.Authentication("jwt",i.accessToken,i.player,i.refreshToken).save(this.storage)}async logout(){const e=await t.Authentication.fromStorage(this.storage);if(e){try{"third_party"!==e.type&&await this.authManager.logout(e.token,e?.refreshToken)}catch(t){}t.Authentication.clear(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_LOGOUT)}}};
1
+ "use strict";var t=require("../core/configuration/authentication.js"),e=require("../core/errors/openfortError.js"),i=require("../types/types.js");exports.AuthApi=class{storage;authManager;validateAndRefreshToken;ensureInitialized;eventEmitter;constructor(t,e,i,a,r){this.storage=t,this.authManager=e,this.validateAndRefreshToken=i,this.ensureInitialized=a,this.eventEmitter=r}async logInWithEmailPassword({email:a,password:r,ecosystemGame:n}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.loginEmailPassword(a,r,n);return"action"in e||(new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async signUpGuest(){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"guest"});try{const e=await this.authManager.registerGuest();return new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async signUpWithEmailPassword({email:a,password:r,options:n,ecosystemGame:s}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.signupEmailPassword(a,r,n?.data.name,s);return"action"in e||(new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async linkEmailPassword({email:t,password:e,authToken:i,ecosystemGame:a}){return await this.validateAndRefreshToken(),await this.authManager.linkEmail(t,e,i,a)}async unlinkEmailPassword({email:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkEmail(t,e)}async requestEmailVerification({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestEmailVerification(t,e)}async resetPassword({email:t,password:e,state:i}){await this.ensureInitialized(),await this.authManager.resetPassword(t,e,i)}async requestResetPassword({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestResetPassword(t,e)}async verifyEmail({email:t,state:e}){await this.ensureInitialized(),await this.authManager.verifyEmail(t,e)}async initOAuth({provider:a,options:r,ecosystemGame:n}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"oauth",provider:a}),await this.authManager.initOAuth(a,r,n)}async initLinkOAuth({provider:a,options:r,ecosystemGame:n}){await this.validateAndRefreshToken();const s=await t.Authentication.fromStorage(this.storage);if(!s)throw new e.OpenfortError("No authentication found",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"oauth",provider:a}),await this.authManager.linkOAuth(s,a,r,n)}async unlinkOAuth({provider:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkOAuth(t,e)}async poolOAuth(e){await this.ensureInitialized();try{const a=await this.authManager.poolOAuth(e);return new t.Authentication("jwt",a.token,a.player.id,a.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,a),a}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async loginWithIdToken({provider:a,token:r,ecosystemGame:n}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"idToken",provider:a});try{const e=await this.authManager.loginWithIdToken(a,r,n);return new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async initSIWE({address:t,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initSIWE(t,e)}async authenticateWithSIWE({signature:a,message:r,walletClientType:n,connectorType:s}){await this.ensureInitialized();if(await t.Authentication.fromStorage(this.storage))throw new e.OpenfortError("Already logged in",e.OpenfortErrorType.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_INIT,{method:"siwe",provider:"wallet"});try{const e=await this.authManager.authenticateSIWE(a,r,n,s);return new t.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.OpenfortEvents.ON_AUTH_FAILURE,t),t}}async linkWallet({signature:t,message:e,walletClientType:i,connectorType:a,authToken:r}){return await this.validateAndRefreshToken(),await this.authManager.linkWallet(t,e,i,a,r)}async unlinkWallet({address:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkWallet(t,e)}async storeCredentials(i){if(await this.ensureInitialized(),!i.player)throw new e.OpenfortError("Player ID is required to store credentials",e.OpenfortErrorType.INVALID_CONFIGURATION);new t.Authentication("jwt",i.accessToken,i.player,i.refreshToken).save(this.storage)}async logout(){const e=await t.Authentication.fromStorage(this.storage);if(e){try{"third_party"!==e.type&&await this.authManager.logout(e.token,e.refreshToken??"")}catch(t){}t.Authentication.clear(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_LOGOUT)}}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../core/configuration/passkey.js"),t=require("../core/config/config.js"),a=require("../core/configuration/account.js"),s=require("../core/configuration/authentication.js"),n=require("../core/errors/openfortError.js"),i=require("../types/types.js"),o=require("../utils/debug.js"),d=require("../wallets/embedded.js"),c=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var g=require("../wallets/evm/provider/eip6963.js"),h=require("../wallets/evm/walletHelpers.js"),y=require("../wallets/iframeManager.js"),p=require("../wallets/messaging/ReactNativeMessenger.js");require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var u=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.js");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,a,s){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=a,this.passkeyHandler=s,this.eventEmitter.on(i.OpenfortEvents.ON_LOGOUT,()=>{o.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.SDKConfiguration.getInstance();if(!r)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(o.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(o.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return o.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return o.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;o.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return o.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,o.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw o.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){o.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.SDKConfiguration.getInstance();if(!e)throw o.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);let r;if(o.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)o.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(o.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),o.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{o.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;r=new u({remoteWindow:t.contentWindow,allowedOrigins:[a]}),o.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return o.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new y.IframeManager(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(o.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new d.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n.OpenfortError("Document is not available. Please provide a message poster for non-browser environments.",n.OpenfortErrorType.INVALID_CONFIGURATION);const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await s.Authentication.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r.player})}async getEntropy(e){switch(e.recoveryMethod){case i.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case i.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case i.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n.OpenfortError("Invalid recovery method",n.OpenfortErrorType.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},[t,n,o]=await Promise.all([s.Authentication.fromStorage(this.storage),this.ensureSigner(),this.getEntropy(r)]),d={chainId:e.chainId,entropy:o,accountType:e.accountType??i.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??i.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},c=await n.configure(d);return{id:c.id,chainId:c.chainId,user:t.player,address:c.address,ownerAddress:c.ownerAddress,chainType:c.chainType,accountType:c.accountType,implementationType:c.implementationType,factoryAddress:c.factoryAddress,salt:c.salt,createdAt:c.createdAt,implementationAddress:c.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(c.recoveryMethod),recoveryMethodDetails:c.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},o=await s.Authentication.fromStorage(this.storage);if(!o)throw new n.OpenfortError("missing authentication",n.OpenfortErrorType.AUTHENTICATION_ERROR);if(t.recoveryMethod===i.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.player});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,c]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:c}),h={id:g.id,chainId:g.chainId,user:o.player,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(i.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,h),h}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC};if(r.recoveryMethod===i.RecoveryMethod.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n.OpenfortError("Passkey ID must be provided for passkey recovery",n.OpenfortErrorType.INVALID_CONFIGURATION);r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,o,d]=await Promise.all([this.ensureSigner(),this.getEntropy(r),s.Authentication.fromStorage(this.storage)]),c=await t.recover({account:e.account,entropy:o}),g={id:c.id,chainId:c.chainId,implementationAddress:c.implementationAddress,factoryAddress:c.factoryAddress,salt:c.salt,user:d.player,address:c.address,ownerAddress:c.ownerAddress,chainType:c.chainType,accountType:c.accountType,implementationType:c.implementationType,createdAt:c.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(c.recoveryMethod),recoveryMethodDetails:c.recoveryMethodDetails};return this.eventEmitter.emit(i.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,g),g}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:n=!1}=r||{},i=await a.Account.fromStorage(this.storage);return await t.sign(e,n,s,i?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await a.Account.fromStorage(this.storage);if(!i)throw new n.OpenfortError("No account found",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),c=d.hash(e,o,t);return await h.signMessage({hash:c,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await s.Authentication.fromStorage(this.storage);if(!d)throw new n.OpenfortError("missing authentication",n.OpenfortErrorType.AUTHENTICATION_ERROR);let c,g,h,y;if(e.recoveryMethod===i.RecoveryMethod.PASSKEY){const e=await a.Account.fromStorage(this.storage);if(!e)throw new n.OpenfortError("missing account",n.OpenfortErrorType.INVALID_CONFIGURATION);const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n.OpenfortError("missing passkey id for account",n.OpenfortErrorType.INVALID_CONFIGURATION);h={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:d.player})}}else if(t.recoveryMethod===i.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:d.player});h={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===i.RecoveryMethod.PASSWORD?c=e.password:t.recoveryMethod===i.RecoveryMethod.PASSWORD&&(c=t.password),e.recoveryMethod===i.RecoveryMethod.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===i.RecoveryMethod.AUTOMATIC&&(g=t.encryptionSession),!c&&!g)throw new n.OpenfortError("Password or encryption session is not provided",n.OpenfortErrorType.INVALID_CONFIGURATION);await o.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:c,encryptionSession:g,passkeyInfo:h});const p=await a.Account.fromStorage(this.storage);p&&new a.Account({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){const e=await a.Account.fromStorage(this.storage);if(!e)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const r=await s.Authentication.fromStorage(this.storage);if(!r)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:r.player,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const r={accountType:i.AccountTypeEnum.SMART_ACCOUNT,...e},o=t.SDKConfiguration.getInstance();if(!o)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const d=await s.Authentication.fromStorage(this.storage);if(!d)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return n.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:{authorization:`Bearer ${o.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{default:n.OpenfortErrorType.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await s.Authentication.fromStorage(this.storage))return i.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?i.EmbeddedState.READY:i.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return o.debugLog("Failed to get embedded state:",e),i.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await s.Authentication.fromStorage(this.storage),n=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new c.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:n||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&g.announceProvider({info:{...g.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await s.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return o.debugLog("Ping failed:",e),!1}}getURL(){const e=t.SDKConfiguration.getInstance();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n.OpenfortError("Invalid message poster",n.OpenfortErrorType.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void o.debugLog("Invalid message received:",e);o.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return o.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();o.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&o.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),o.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),o.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../core/configuration/passkey.js"),t=require("../core/config/config.js"),a=require("../core/configuration/account.js"),s=require("../core/configuration/authentication.js"),n=require("../core/errors/openfortError.js"),i=require("../types/types.js"),o=require("../utils/debug.js"),d=require("../wallets/embedded.js"),c=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var g=require("../wallets/evm/provider/eip6963.js"),h=require("../wallets/evm/walletHelpers.js"),y=require("../wallets/iframeManager.js"),p=require("../wallets/messaging/ReactNativeMessenger.js");require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var u=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.js");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,a,s){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=a,this.passkeyHandler=s,this.eventEmitter.on(i.OpenfortEvents.ON_LOGOUT,()=>{o.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.SDKConfiguration.getInstance();if(!r)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(o.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(o.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return o.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return o.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;o.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return o.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,o.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw o.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){o.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.SDKConfiguration.getInstance();if(!e)throw o.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);let r;if(o.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)o.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(o.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),o.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{o.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;r=new u({remoteWindow:t.contentWindow,allowedOrigins:[a]}),o.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return o.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new y.IframeManager(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(o.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new d.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n.OpenfortError("Document is not available. Please provide a message poster for non-browser environments.",n.OpenfortErrorType.INVALID_CONFIGURATION);const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await s.Authentication.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r.player})}async getEntropy(e){switch(e.recoveryMethod){case i.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case i.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case i.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n.OpenfortError("Invalid recovery method",n.OpenfortErrorType.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),n={chainId:e.chainId,entropy:s,accountType:e.accountType??i.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??i.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},o=await t.configure(n);return{id:o.id,chainId:o.chainId,user:o.user,address:o.address,ownerAddress:o.ownerAddress,chainType:o.chainType,accountType:o.accountType,implementationType:o.implementationType,factoryAddress:o.factoryAddress,salt:o.salt,createdAt:o.createdAt,implementationAddress:o.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(o.recoveryMethod),recoveryMethodDetails:o.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},o=await s.Authentication.fromStorage(this.storage);if(!o)throw new n.OpenfortError("missing authentication",n.OpenfortErrorType.AUTHENTICATION_ERROR);if(t.recoveryMethod===i.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.player??""});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,c]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:c}),h={id:g.id,chainId:g.chainId,user:o.player,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(i.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,h),h}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC};if(r.recoveryMethod===i.RecoveryMethod.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n.OpenfortError("Passkey ID must be provided for passkey recovery",n.OpenfortErrorType.INVALID_CONFIGURATION);r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),o=await t.recover({account:e.account,entropy:s}),d={id:o.id,chainId:o.chainId,implementationAddress:o.implementationAddress,factoryAddress:o.factoryAddress,salt:o.salt,user:o.user,address:o.address,ownerAddress:o.ownerAddress,chainType:o.chainType,accountType:o.accountType,implementationType:o.implementationType,createdAt:o.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(o.recoveryMethod),recoveryMethodDetails:o.recoveryMethodDetails};return this.eventEmitter.emit(i.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,d),d}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:n=!1}=r||{},i=await a.Account.fromStorage(this.storage);return await t.sign(e,n,s,i?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await a.Account.fromStorage(this.storage);if(!i)throw new n.OpenfortError("No account found",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),c=d.hash(e,o,t);return await h.signMessage({hash:c,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await s.Authentication.fromStorage(this.storage);if(!d)throw new n.OpenfortError("missing authentication",n.OpenfortErrorType.AUTHENTICATION_ERROR);let c,g,h,y;if(e.recoveryMethod===i.RecoveryMethod.PASSKEY){const e=await a.Account.fromStorage(this.storage);if(!e)throw new n.OpenfortError("missing account",n.OpenfortErrorType.INVALID_CONFIGURATION);const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n.OpenfortError("missing passkey id for account",n.OpenfortErrorType.INVALID_CONFIGURATION);h={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:d.player})}}else if(t.recoveryMethod===i.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:d.player});h={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===i.RecoveryMethod.PASSWORD?c=e.password:t.recoveryMethod===i.RecoveryMethod.PASSWORD&&(c=t.password),e.recoveryMethod===i.RecoveryMethod.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===i.RecoveryMethod.AUTOMATIC&&(g=t.encryptionSession),!c&&!g)throw new n.OpenfortError("Password or encryption session is not provided",n.OpenfortErrorType.INVALID_CONFIGURATION);await o.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:c,encryptionSession:g,passkeyInfo:h});const p=await a.Account.fromStorage(this.storage);p&&new a.Account({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){const e=await a.Account.fromStorage(this.storage);if(!e)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const r=await s.Authentication.fromStorage(this.storage);if(!r)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:r.player,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const r={accountType:i.AccountTypeEnum.SMART_ACCOUNT,...e},o=t.SDKConfiguration.getInstance();if(!o)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const d=await s.Authentication.fromStorage(this.storage);if(!d)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return n.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:{authorization:`Bearer ${o.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{default:n.OpenfortErrorType.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await s.Authentication.fromStorage(this.storage))return i.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?i.EmbeddedState.READY:i.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return o.debugLog("Failed to get embedded state:",e),i.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await s.Authentication.fromStorage(this.storage),n=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new c.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:n||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&g.announceProvider({info:{...g.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await s.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return o.debugLog("Ping failed:",e),!1}}getURL(){const e=t.SDKConfiguration.getInstance();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n.OpenfortError("Invalid message poster",n.OpenfortErrorType.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void o.debugLog("Invalid message received:",e);o.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return o.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();o.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&o.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),o.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),o.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../storage/istorage.js");require("../errors/openfortError.js");var t=require("../../types/types.js");require("human-id"),require("eventemitter3"),require("../../wallets/evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("../../wallets/evm/types.js"),require("../../wallets/evm/provider/eip6963.js"),require("../errors/sentry.js"),require("../../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../../wallets/types.js"),require("jose");class r{constructor(e){this.user=e.user,this.id=e.id,this.chainType=e.chainType,this.address=e.address,this.accountType=e.accountType,this.chainId=e.chainId,this.createdAt=e.createdAt,this.implementationAddress=e.implementationAddress,this.implementationType=e.implementationType,this.factoryAddress=e.factoryAddress,this.recoveryMethod=e.recoveryMethod,this.recoveryMethodDetails=e.recoveryMethodDetails,this.salt=e.salt,this.ownerAddress=e.ownerAddress,this.type=e.type}user;id;chainType;address;accountType;chainId;ownerAddress;factoryAddress;implementationAddress;salt;createdAt;implementationType;recoveryMethod;recoveryMethodDetails;type;save(t){t.save(e.StorageKeys.ACCOUNT,JSON.stringify({user:this.user,id:this.id,chainType:this.chainType,address:this.address,accountType:this.accountType,chainId:this.chainId,ownerAddress:this.ownerAddress,createdAt:this.createdAt,implementationType:this.implementationType,factoryAddress:this.factoryAddress,implementationAddress:this.implementationAddress,salt:this.salt,recoveryMethod:this.recoveryMethod,recoveryMethodDetails:this.recoveryMethodDetails}))}static parseRecoveryMethod=e=>{switch(e){case"user":case t.RecoveryMethod.PASSWORD:return t.RecoveryMethod.PASSWORD;case"project":case t.RecoveryMethod.AUTOMATIC:return t.RecoveryMethod.AUTOMATIC;case"passkey":case t.RecoveryMethod.PASSKEY:return t.RecoveryMethod.PASSKEY;default:return}};static async fromStorage(t){const s=await t.get(e.StorageKeys.ACCOUNT);if(!s)return null;try{const e=JSON.parse(s);return new r(e)}catch{return null}}}exports.Account=r;
1
+ "use strict";var e=require("../../storage/istorage.js"),t=require("../../types/types.js");class s{constructor(e){this.user=e.user,this.id=e.id,this.chainType=e.chainType,this.address=e.address,this.accountType=e.accountType,this.chainId=e.chainId,this.createdAt=e.createdAt,this.implementationAddress=e.implementationAddress,this.implementationType=e.implementationType,this.factoryAddress=e.factoryAddress,this.recoveryMethod=e.recoveryMethod,this.recoveryMethodDetails=e.recoveryMethodDetails,this.salt=e.salt,this.ownerAddress=e.ownerAddress,this.type=e.type}user;id;chainType;address;accountType;chainId;ownerAddress;factoryAddress;implementationAddress;salt;createdAt;implementationType;recoveryMethod;recoveryMethodDetails;type;save(t){t.save(e.StorageKeys.ACCOUNT,JSON.stringify({user:this.user,id:this.id,chainType:this.chainType,address:this.address,accountType:this.accountType,chainId:this.chainId,ownerAddress:this.ownerAddress,createdAt:this.createdAt,implementationType:this.implementationType,factoryAddress:this.factoryAddress,implementationAddress:this.implementationAddress,salt:this.salt,recoveryMethod:this.recoveryMethod,recoveryMethodDetails:this.recoveryMethodDetails}))}static parseRecoveryMethod=e=>{switch(e){case"user":case t.RecoveryMethod.PASSWORD:return t.RecoveryMethod.PASSWORD;case"project":case t.RecoveryMethod.AUTOMATIC:return t.RecoveryMethod.AUTOMATIC;case"passkey":case t.RecoveryMethod.PASSKEY:return t.RecoveryMethod.PASSKEY;default:return}};static async fromStorage(t){const r=await t.get(e.StorageKeys.ACCOUNT);if(!r)return null;try{const e=JSON.parse(r);return new s(e)}catch{return null}}}exports.Account=s;
@@ -1 +1 @@
1
- "use strict";var t=require("axios"),e=require("../../version.js");const s="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class r{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(e){const n=e.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==s.split("https://")[1].split("/")[1]||n.host!==s.split("@")[1].split("/")[0]||n.publicKey!==s.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");e.captureAxiosError=(s,n,a,o)=>{if(n instanceof t.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=s,e.captureException(n,{...a,captureContext:{...a?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...r.baseTags,method:s}}})}else e.captureException(n,a,o)},r.sentryInstance=e}static get sentry(){return r.proxy}static async init({sentry:t,configuration:n}){if(t)return void(r.sentry=t);const a=await import("@sentry/browser");r.sentry=new a.BrowserClient({dsn:s,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),r.baseTags={projectId:n?.baseConfiguration.publishableKey,sdk:e.PACKAGE,sdkVersion:e.VERSION},r.processQueuedCalls()}static proxy=new Proxy({},{get:(t,e)=>r.sentryInstance&&"function"==typeof r.sentryInstance[e]?(...t)=>r.sentryInstance[e](...t):(...t)=>{r.queuedCalls.push({fn:e,args:t})}});static processQueuedCalls(){r.sentryInstance&&(r.queuedCalls.forEach(({fn:t,args:e})=>{"function"==typeof r.sentryInstance[t]&&r.sentryInstance[t](...e)}),r.queuedCalls=[])}}const{sentry:n}=r;exports.InternalSentry=r,exports.sentry=n;
1
+ "use strict";var t=require("axios"),e=require("../../version.js");const s="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class r{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(e){const n=e.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==s.split("https://")[1].split("/")[1]||n.host!==s.split("@")[1].split("/")[0]||n.publicKey!==s.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");e.captureAxiosError=(s,n,a,o)=>{if(n instanceof t.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=s,e.captureException(n,{...a,captureContext:{...a?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...r.baseTags,method:s}}})}else e.captureException(n,a,o)},r.sentryInstance=e}static get sentry(){return r.proxy}static async init({sentry:t,configuration:n}){if(t)return void(r.sentry=t);const a=await import("@sentry/browser");r.sentry=new a.BrowserClient({dsn:s,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),r.baseTags={projectId:n?.baseConfiguration.publishableKey??"",sdk:e.PACKAGE,sdkVersion:e.VERSION},r.processQueuedCalls()}static proxy=new Proxy({},{get:(t,e)=>r.sentryInstance&&"function"==typeof r.sentryInstance[e]?(...t)=>r.sentryInstance[e](...t):(...t)=>{r.queuedCalls.push({fn:e,args:t})}});static processQueuedCalls(){r.sentryInstance&&(r.queuedCalls.forEach(({fn:t,args:e})=>{"function"==typeof r.sentryInstance[t]&&r.sentryInstance[t](...e)}),r.queuedCalls=[])}}const{sentry:n}=r;exports.InternalSentry=r,exports.sentry=n;
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),t=require("../api/auth.js"),i=require("../api/embeddedWallet.js"),n=require("../api/proxy.js"),r=require("../api/user.js"),a=require("../auth/authManager.js"),s=require("../storage/istorage.js"),o=require("../storage/lazyStorage.js"),h=require("../utils/typedEventEmitter.js"),l=require("./config/config.js"),c=require("./configuration/passkey.js"),u=require("./errors/openfortError.js"),d=require("./errors/sentry.js"),g=require("./openfortInternal.js");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new a.AuthManager(this.storage),this.openfortInternal=new g.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new r.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new u.OpenfortError("Embedded wallet not initialized",u.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.OpenfortError("Openfort SDK synchronous initialization failed",u.OpenfortErrorType.INVALID_CONFIGURATION)}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=new c.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new u.OpenfortError("AuthManager not initialized",u.OpenfortErrorType.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=s.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){try{if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",u.OpenfortErrorType.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(e){throw new u.OpenfortError("Openfort SDK async initialization failed",u.OpenfortErrorType.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),t=require("../api/auth.js"),i=require("../api/embeddedWallet.js"),n=require("../api/proxy.js"),r=require("../api/user.js"),a=require("../auth/authManager.js"),s=require("../storage/istorage.js"),o=require("../storage/lazyStorage.js"),h=require("../utils/typedEventEmitter.js"),l=require("./config/config.js"),c=require("./configuration/passkey.js"),u=require("./errors/openfortError.js"),d=require("./errors/sentry.js"),g=require("./openfortInternal.js");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new a.AuthManager(this.storage),this.openfortInternal=new g.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new r.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new u.OpenfortError("Embedded wallet not initialized",u.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.OpenfortError("Openfort SDK synchronous initialization failed",u.OpenfortErrorType.INVALID_CONFIGURATION)}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=new c.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new u.OpenfortError("AuthManager not initialized",u.OpenfortErrorType.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=s.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){try{if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",u.OpenfortErrorType.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(e){throw new u.OpenfortError("Openfort SDK async initialization failed",u.OpenfortErrorType.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
@@ -1 +1 @@
1
- "use strict";var e=require("./configuration/authentication.js"),r=require("./errors/openfortError.js"),t=require("../types/types.js");require("human-id");var n=require("./config/config.js");require("../storage/istorage.js");var i=require("../utils/debug.js");require("eventemitter3"),require("../wallets/evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("../wallets/evm/types.js"),require("../wallets/evm/provider/eip6963.js"),require("./errors/sentry.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../wallets/types.js"),require("jose");var o=require("../utils/promiseUtils.js");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(e,r,t){this.storage=e,this.authManager=r,this.eventEmitter=t}async getThirdPartyAuthToken(){const i=n.SDKConfiguration.getInstance();if(!i?.thirdPartyAuth)throw new r.OpenfortError("No third party configuration found",r.OpenfortErrorType.INTERNAL_ERROR);const{getAccessToken:o,provider:a}=i.thirdPartyAuth;if(!o||!a)throw new r.OpenfortError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",r.OpenfortErrorType.INVALID_CONFIGURATION);const s=await o();if(!s)throw new r.OpenfortError("Could not get access token",r.OpenfortErrorType.AUTHENTICATION_ERROR);let u=(await e.Authentication.fromStorage(this.storage))?.player;if(!u){const e=await this.authManager.authenticateThirdParty(a,s,t.TokenType.ID_TOKEN);u=e?.id}return new e.Authentication("third_party",s,u,null,a,t.TokenType.ID_TOKEN).save(this.storage),s}async getAccessToken(){if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await e.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(a){return o.singlePromise(async()=>{if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const o=await e.Authentication.fromStorage(this.storage);if(!o)throw new r.OpenfortError("Must be logged in to validate and refresh token",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);let s;i.debugLog("validating credentials...");try{s=await this.authManager.validateCredentials(o,a)}catch(r){throw e.Authentication.clear(this.storage),this.eventEmitter.emit(t.OpenfortEvents.ON_LOGOUT),r}if(!s.player)throw new r.OpenfortError("No user found in credentials",r.OpenfortErrorType.INTERNAL_ERROR);s.accessToken!==o.token&&(i.debugLog("tokens refreshed"),new e.Authentication("jwt",s.accessToken,s.player,s.refreshToken).save(this.storage))},"openfort.validateAndRefreshToken")}};
1
+ "use strict";var t=require("../utils/debug.js"),e=require("../utils/promiseUtils.js"),r=require("../types/types.js"),n=require("./config/config.js"),o=require("./configuration/authentication.js"),i=require("./errors/openfortError.js");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(t,e,r){this.storage=t,this.authManager=e,this.eventEmitter=r}async getThirdPartyAuthToken(){const t=n.SDKConfiguration.getInstance();if(!t?.thirdPartyAuth)throw new i.OpenfortError("No third party configuration found",i.OpenfortErrorType.INTERNAL_ERROR);const{getAccessToken:e,provider:a}=t.thirdPartyAuth;if(!e||!a)throw new i.OpenfortError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",i.OpenfortErrorType.INVALID_CONFIGURATION);const s=await e();if(!s)throw new i.OpenfortError("Could not get access token",i.OpenfortErrorType.AUTHENTICATION_ERROR);let h=(await o.Authentication.fromStorage(this.storage))?.player;if(!h){const t=await this.authManager.authenticateThirdParty(a,s,r.TokenType.ID_TOKEN);h=t?.id}return new o.Authentication("third_party",s,h,null,a,r.TokenType.ID_TOKEN).save(this.storage),s}async getAccessToken(){if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await o.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(a){return e.singlePromise(async()=>{if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const e=await o.Authentication.fromStorage(this.storage);if(!e)throw new i.OpenfortError("Must be logged in to validate and refresh token",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);let s;t.debugLog("validating credentials...");try{s=await this.authManager.validateCredentials(e,a)}catch(t){throw o.Authentication.clear(this.storage),this.eventEmitter.emit(r.OpenfortEvents.ON_LOGOUT),t}if(!s.player)throw new i.OpenfortError("No user found in credentials",i.OpenfortErrorType.INTERNAL_ERROR);s.accessToken!==e.token&&(t.debugLog("tokens refreshed"),new o.Authentication("jwt",s.accessToken,s.player,s.refreshToken).save(this.storage))},"openfort.validateAndRefreshToken")}};
@@ -1 +1 @@
1
- "use strict";var e=require("../core/errors/openfortError.js"),r=require("./storage.js");exports.LazyStorage=class{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e.OpenfortError("Storage not available. Please provide custom storage or use in browser environment.",e.OpenfortErrorType.INVALID_CONFIGURATION);this.realStorage=new r.StorageImplementation(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,r){this.getRealStorage().save(e,r)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}};
1
+ "use strict";var e=require("../core/errors/openfortError.js"),r=require("./scopedStorage.js"),t=require("./storage.js");exports.LazyStorage=class{realStorage=null;customStorage;publishableKey;constructor(e,r){this.publishableKey=e,this.customStorage=r}getRealStorage(){if(!this.realStorage){let o;if(this.customStorage)o=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e.OpenfortError("Storage not available. Please provide custom storage or use in browser environment.",e.OpenfortErrorType.INVALID_CONFIGURATION);o=new t.StorageImplementation(localStorage)}this.realStorage=new r.ScopedStorage(o,this.publishableKey)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,r){this.getRealStorage().save(e,r)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}};
@@ -0,0 +1 @@
1
+ "use strict";var e=require("./istorage.js");exports.ScopedStorage=class{storage;scope;constructor(e,s){this.storage=e,this.scope=this.createScope(s)}createScope(e){return e.substring(8).substring(0,8)}scopeKey(e){return`${this.scope}.${e}`}async get(e){return this.storage.get(this.scopeKey(e))}save(e,s){this.storage.save(this.scopeKey(e),s)}remove(e){this.storage.remove(this.scopeKey(e))}flush(){for(const s of Object.values(e.StorageKeys))this.storage.remove(this.scopeKey(s))}};
@@ -1 +1 @@
1
- "use strict";exports.defaultChainRpcs={1:"https://cloudflare-eth.com",10:"https://optimism-rpc.publicnode.com",56:"https://bsc.publicnode.com",97:"https://bsc-testnet.publicnode.com",137:"https://polygon-rpc.com",204:"https://opbnb-mainnet-rpc.bnbchain.org",300:"https://sepolia.era.zksync.dev",324:"https://mainnet.era.zksync.io",1946:"https://rpc.minato.soneium.org",2741:"https://api.mainnet.abs.xyz",3939:"https://test.doschain.com",4337:"https://build.onbeam.com/rpc",5611:"https://opbnb-testnet-rpc.bnbchain.org",7979:"https://main.doschain.com",8453:"https://mainnet.base.org",11124:"https://api.testnet.abs.xyz",13337:"https://build.onbeam.com/rpc/testnet",13473:"https://rpc.testnet.immutable.com",42161:"https://arb1.arbitrum.io/rpc",42170:"https://nova.arbitrum.io/rpc",43113:"https://api.avax-test.network/ext/bc/C/rpc",43114:"https://api.avax.network/ext/bc/C/rpc",50104:"https://rpc.sophon.xyz",80002:"https://polygon-amoy-bor-rpc.publicnode.com",84532:"https://sepolia.base.org",421614:"https://sepolia-rollup.arbitrum.io/rpc",7225878:"https://rpc.saakuru.network",7777777:"https://rpc.zora.energy",11155111:"https://ethereum-sepolia-rpc.publicnode.com",11155420:"https://optimism-sepolia-rpc.publicnode.com",28122024:"https://rpcv2-testnet.ancient8.gg",531050104:"https://rpc.testnet.sophon.xyz",666666666:"https://rpc.degen.tips",888888888:"https://rpc.ancient8.gg",999999999:"https://sepolia.rpc.zora.energy",85011:"https://subnets.avax.network/criminalsa/testnet/rpc",84358:"https://subnets.avax.network/titan/mainnet/rpc",10143:"https://testnet-rpc.monad.xyz",510525:"https://rpc.clankermon.com",3008:"https://kl1-testnet.kiooverse.xyz/rpc",167e3:"https://rpc.taiko.xyz"};
1
+ "use strict";exports.defaultChainRpcs={1:"https://cloudflare-eth.com",10:"https://optimism-rpc.publicnode.com",56:"https://bsc.publicnode.com",97:"https://bsc-testnet.publicnode.com",137:"https://polygon-rpc.com",1946:"https://rpc.minato.soneium.org",3008:"https://kl1-testnet.kiooverse.xyz/rpc",4337:"https://build.onbeam.com/rpc",5611:"https://opbnb-testnet-rpc.bnbchain.org",8453:"https://mainnet.base.org",10143:"https://testnet-rpc.monad.xyz",13337:"https://build.onbeam.com/rpc/testnet",42161:"https://arb1.arbitrum.io/rpc",42170:"https://nova.arbitrum.io/rpc",43113:"https://api.avax-test.network/ext/bc/C/rpc",43114:"https://api.avax.network/ext/bc/C/rpc",80002:"https://polygon-amoy-bor-rpc.publicnode.com",84358:"https://subnets.avax.network/titan/mainnet/rpc",84532:"https://sepolia.base.org",421614:"https://sepolia-rollup.arbitrum.io/rpc",510525:"https://rpc.clankermon.com",510530:"https://open-loot.rpc.syndicate.io",510531:"https://open-loot.rpc.testnet.syndicate.io",7225878:"https://rpc.saakuru.network",7777777:"https://rpc.zora.energy",11155111:"https://ethereum-sepolia-rpc.publicnode.com",11155420:"https://optimism-sepolia-rpc.publicnode.com",28122024:"https://rpcv2-testnet.ancient8.gg",666666666:"https://rpc.degen.tips",888888888:"https://rpc.ancient8.gg",999999999:"https://sepolia.rpc.zora.energy"};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.36";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.38";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/configuration/passkey.js"),r=require("../core/errors/openfortError.js"),a=require("../types/types.js"),o=require("../core/config/config.js"),n=require("../core/configuration/account.js"),s=require("../storage/istorage.js");require("eventemitter3"),require("./evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("./evm/types.js"),require("./evm/provider/eip6963.js"),require("../core/errors/sentry.js"),require("./messaging/browserMessenger/backwardCompatibility.js"),require("./types.js"),require("jose");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,r,a,o){this.iframeManager=e,this.storage=t,this.backendApiClients=r,this.passkeyHandler=a,this.eventEmitter=o}async createPasskey(e){const r=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:r.id,key:r.key}}async configure(t){const s=await e.Authentication.fromStorage(this.storage);if(!s)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i=o.SDKConfiguration.getInstance();if(!i)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);const c=await n.Account.fromStorage(this.storage);let d;if(c){const e={account:c.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===c.recoveryMethod&&{passkey:{id:c.recoveryMethodDetails?.passkeyId,env:c.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(c.recoveryMethodDetails?.passkeyId)}}}}},r=await this.iframeManager.recover(e);d=r.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:s.player,accountType:t.accountType,chainType:t.chainType},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(s.player):void 0,r={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(r);d=a.account}else{const r=e.data.data,a=r.find(e=>e.chainId===t.chainId),o=a||r[0],n={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId)}}}}},s=await this.iframeManager.recover(n);if(d=s.account,!a){const e=await this.iframeManager.switchChain(t.chainId);d=e.account}}}return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:d},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(e,t,r,o){const n=await this.iframeManager.sign(e,t,r,o);return this.eventEmitter.emit(a.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:n}),n}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await n.Account.fromStorage(this.storage);if(t?.accountType===a.AccountTypeEnum.EOA)new n.Account({...t,chainId:e}).save(this.storage);else{const r=await this.iframeManager.switchChain(e);new n.Account({...t,id:r.account,chainId:e}).save(this.storage)}}async create(t){const s=await this.iframeManager.create(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(t){const s=await this.iframeManager.recover(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:r,passkeyInfo:a}){await this.iframeManager.setRecoveryMethod(e,t,r,a?.passkeyKey,a?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(s.StorageKeys.ACCOUNT)}};
1
+ "use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/configuration/passkey.js"),a=require("../core/errors/openfortError.js"),r=require("../core/config/config.js"),o=require("../core/configuration/account.js"),n=require("../storage/istorage.js"),s=require("../types/types.js");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const a=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:a.id,key:a.key}}async configure(t){const n=await e.Authentication.fromStorage(this.storage);if(!n)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i=r.SDKConfiguration.getInstance();if(!i)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);const c=await o.Account.fromStorage(this.storage);let d;if(c){const e={account:c.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===c.recoveryMethod&&{passkey:{id:c.recoveryMethodDetails?.passkeyId,env:c.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(c.recoveryMethodDetails?.passkeyId??"")}}}}},a=await this.iframeManager.recover(e);d=a.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:n.player,accountType:t.accountType,chainType:t.chainType},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(n.player):void 0,a={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},r=await this.iframeManager.create(a);d=r.account}else{const a=e.data.data,r=a.find(e=>e.chainId===t.chainId),o=r||a[0],n={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId??"")}}}}},s=await this.iframeManager.recover(n);if(d=s.account,!r){const e=await this.iframeManager.switchChain(t.chainId);d=e.account}}}return a.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:d},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}}),t=new o.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:o.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(s.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:a.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(s.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await o.Account.fromStorage(this.storage);if(t?.accountType===s.AccountTypeEnum.EOA)new o.Account({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new o.Account({...t,id:a.account,chainId:e}).save(this.storage)}}async create(t){const n=await this.iframeManager.create(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=r.SDKConfiguration.getInstance();if(!c)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return a.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:n.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new o.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:o.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(s.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:a.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(t){const n=await this.iframeManager.recover(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=r.SDKConfiguration.getInstance();if(!c)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return a.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:n.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new o.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:o.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(s.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:a.OpenfortErrorType.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(n.StorageKeys.ACCOUNT)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("./JsonRpcError.js");exports.getAssets=async({params:t,account:a,authentication:s,backendClient:o})=>{const n=await(async(r,t,a,s)=>{const o=s?.chainFilter?.map(e=>Number.parseInt(e,16));return e.withOpenfortError(async()=>(await r.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:t.address,chainFilter:o,assetFilter:s?.assetFilter,assetTypeFilter:s?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:{authorization:`Bearer ${r.config.backend.accessToken}`,"x-player-token":a.token,"x-auth-provider":a.thirdPartyProvider,"x-token-type":a.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(o,a,s,t).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message)});return n.result};
1
+ "use strict";var e=require("../../core/errors/openfortError.js"),r=require("./JsonRpcError.js");exports.getAssets=async({params:t,account:a,authentication:s,backendClient:o})=>{const n=await(async(r,t,a,s)=>e.withOpenfortError(async()=>(await r.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:t.address,chainFilter:s?.chainFilter,assetFilter:s?.assetFilter,assetTypeFilter:s?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:{authorization:`Bearer ${r.config.backend.accessToken}`,"x-player-token":a.token,"x-auth-provider":a.thirdPartyProvider,"x-token-type":a.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}))(o,a,s,t).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message)});return n.result};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),t=require("../../types/types.js"),r=require("./JsonRpcError.js");function i(e){return{data:(()=>{if("token-allowance"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return e.data})(),type:e.type.custom}}function o(e){if("native-token-transfer"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...e,policies:e?.policies?.map(i),required:e.required??!1,type:"string"==typeof e.type?e.type:e.type.custom}}function n(e){return{expiry:e.validUntil?Number(e.validUntil):0,grantedPermissions:e.whitelist?e.whitelist.map(t=>({type:"contract-call",data:{address:t,calls:[]},policies:[{data:{limit:e.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:e.id}}exports.registerSession=async({params:i,signer:s,account:a,authentication:p,backendClient:c,policyId:l})=>{const d=await(async(t,i,n,s,a)=>{const p=t[0],c=Math.floor(Date.now()/1e3),l=Math.floor(new Date(Date.now()+1e3*p.expiry).getTime()/1e3),d=p.permissions.map(o),u=d.filter(e=>"contract-call"===e.type||"erc20-token-transfer"===e.type||"erc721-token-transfer"===e.type||"erc1155-token-transfer"===e.type).map(e=>e.data.address);let y,m=d.find(e=>"call-limit"===e.type)?.data;if(m=d[0]?.policies?.find(e=>"call-limit"===e.type)?.data?.limit,"signer"in p&&p.signer){if("keys"===p.signer.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==p.signer.type&&"account"!==p.signer.type||(y=p.signer.data.id)}else"account"in p&&p.account&&(y=p.account);if(!y)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Failed to request permissions - missing session address");const R=((e,t,r,i,o,n=!1,s,a,p,c)=>{const l={address:e,chainId:t,validAfter:r,validUntil:i,optimistic:n,whitelist:s,player:a,account:c};return o&&(l.policy=o),p&&(l.limit=p),l})(y,n.chainId,c,l,a,!1,u,s.player,m,n.id);return e.withOpenfortError(async()=>(await i.sessionsApi.createSession({createSessionRequest:R},{headers:{authorization:`Bearer ${i.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(i,c,a,p,l).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let i;i=[300,531050104,324,50104,2741,11124].includes(a.chainId)||a.implementationType&&[t.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return n(await e.withOpenfortError(async()=>(await c.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:i}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)}))}if(!1===d.isActive)throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,"Failed to grant permissions");return n(d)};
1
+ "use strict";var e=require("../../core/errors/openfortError.js"),t=require("../../types/types.js"),r=require("./JsonRpcError.js");function i(e){return{data:(()=>{if("token-allowance"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return e.data})(),type:e.type.custom}}function o(e){if("native-token-transfer"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...e,policies:e?.policies?.map(i),required:e.required??!1,type:"string"==typeof e.type?e.type:e.type.custom}}function n(e){return{expiry:e.validUntil?Number(e.validUntil):0,grantedPermissions:e.whitelist?e.whitelist.map(t=>({type:"contract-call",data:{address:t,calls:[]},policies:[{data:{limit:e.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:e.id}}exports.registerSession=async({params:i,signer:s,account:a,authentication:p,backendClient:c,policyId:l})=>{const d=await(async(t,i,n,s,a)=>{const p=t[0],c=Math.floor(Date.now()/1e3),l=Math.floor(new Date(Date.now()+1e3*p.expiry).getTime()/1e3),d=p.permissions.map(o),u=d.filter(e=>"contract-call"===e.type||"erc20-token-transfer"===e.type||"erc721-token-transfer"===e.type||"erc1155-token-transfer"===e.type).map(e=>e.data.address);let y,m=d.find(e=>"call-limit"===e.type)?.data;if(m=d[0]?.policies?.find(e=>"call-limit"===e.type)?.data?.limit,"signer"in p&&p.signer){if("keys"===p.signer.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==p.signer.type&&"account"!==p.signer.type||(y=p.signer.data.id)}else"account"in p&&p.account&&(y=p.account);if(!y)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Failed to request permissions - missing session address");const R=((e,t,r,i,o,n=!1,s,a,p,c)=>{const l={address:e,chainId:t,validAfter:r,validUntil:i,optimistic:n,whitelist:s,player:a,account:c};return o&&(l.policy=o),p&&(l.limit=p),l})(y,n.chainId,c,l,a,!1,u,s.player,m,n.id);return e.withOpenfortError(async()=>(await i.sessionsApi.createSession({createSessionRequest:R},{headers:{authorization:`Bearer ${i.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(i,c,a,p,l).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let i;i=[300,324].includes(a.chainId)||a.implementationType&&[t.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return n(await e.withOpenfortError(async()=>(await c.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:i}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)}))}if(!1===d.isActive)throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,"Failed to grant permissions");return n(d)};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("../../types/types.js"),n=require("./JsonRpcError.js");exports.revokeSession=async({params:t,signer:s,account:a,authentication:o,backendClient:i,policyId:c})=>{const p=t[0];if(!p.permissionContext)return await s.disconnect(),{};const d=await(async(r,n,t,s,a)=>{const o=((e,r,n,t,s)=>{const a={address:e,chainId:r,player:n,account:s};return t&&(a.policy=t),a})(r.permissionContext,t.chainId,s.player,a,t.id);return e.withOpenfortError(async()=>(await n.sessionsApi.revokeSession({revokeSessionRequest:o},{headers:{authorization:`Bearer ${n.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(p,i,a,o,c).catch(e=>{throw new n.JsonRpcError(n.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let e;e=[300,531050104,324,50104,2741,11124].includes(a.chainId)||a.implementationType&&[r.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return(await i.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:e}}).catch(e=>{throw new n.JsonRpcError(n.RpcErrorCode.TRANSACTION_REJECTED,e.message)})).data}return d};
1
+ "use strict";var e=require("../../core/errors/openfortError.js"),r=require("../../types/types.js"),n=require("./JsonRpcError.js");exports.revokeSession=async({params:t,signer:s,account:a,authentication:o,backendClient:i,policyId:c})=>{const p=t[0];if(!p.permissionContext)return await s.disconnect(),{};const d=await(async(r,n,t,s,a)=>{const o=((e,r,n,t,s)=>{const a={address:e,chainId:r,player:n,account:s};return t&&(a.policy=t),a})(r.permissionContext,t.chainId,s.player,a,t.id);return e.withOpenfortError(async()=>(await n.sessionsApi.revokeSession({revokeSessionRequest:o},{headers:{authorization:`Bearer ${n.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(p,i,a,o,c).catch(e=>{throw new n.JsonRpcError(n.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let e;e=[300,324].includes(a.chainId)||a.implementationType&&[r.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return(await i.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:e}}).catch(e=>{throw new n.JsonRpcError(n.RpcErrorCode.TRANSACTION_REJECTED,e.message)})).data}return d};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("../../types/types.js"),t=require("../../utils/authorization.js"),o=require("./JsonRpcError.js");const a=e=>{const r=e?.logs?.[0];return{blockHash:r?.blockHash,blockNumber:e?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:e?.gasUsed,effectiveGasPrice:e?.gasFee,from:void 0,gasUsed:e?.gasUsed,logs:e?.logs||[],logsBloom:void 0,status:1===e?.status?"success":0===e?.status?"reverted":void 0,to:e?.to,transactionHash:e?.transactionHash,transactionIndex:r?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function n(e,r){try{const t=await e.getCode(r);return"0x"!==t&&t.length>2}catch{return!1}}exports.sendCallsSync=async({params:s,signer:i,account:c,authentication:d,backendClient:p,rpcProvider:u,policyId:l})=>{const E=s[0]?.capabilities?.paymasterService?.policy??l;let T;if(c.accountType===r.AccountTypeEnum.DELEGATED_ACCOUNT){const[e,r]=await Promise.all([n(u,c.address),u.getTransactionCount(c.address)]);if(!e){const e=await t.prepareAndSignAuthorization({signer:i,accountAddress:c.address,contractAddress:c.implementationAddress,chainId:c.chainId,nonce:r});T=t.serializeSignedAuthorization(e)}}const A=await(async(r,t,a,n,s,i)=>{const c=r.map(e=>{if(!e.to)throw new o.JsonRpcError(o.RpcErrorCode.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(e.to),data:e.data?String(e.data):void 0,value:e.value?String(e.value):void 0}});return e.withOpenfortError(async()=>(await t.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:a.id,policy:s,signedAuthorization:i,chainId:a.chainId,interactions:c}},{headers:{authorization:`Bearer ${t.config.backend.accessToken}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(s,p,c,d,E,T).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(A.response?.error.reason)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,A.response?.error.reason);if(A?.nextAction?.payload?.signableHash){let t;t=[300,531050104,324,50104,2741,11124].includes(c.chainId)||c.implementationType&&[r.AccountType.CALIBUR].includes(c.implementationType)?await i.sign(A.nextAction.payload.signableHash,!1,!1):await i.sign(A.nextAction.payload.signableHash);const n=await e.withOpenfortError(async()=>await p.transactionIntentsApi.signature({id:A.id,signatureRequest:{signature:t}}),{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(0===n.data.response?.status)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,n.data.response?.error.reason);if(!n.data.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(n.data.response)}}if(!A.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(A.response)}};
1
+ "use strict";var e=require("../../core/errors/openfortError.js"),r=require("../../types/types.js"),t=require("../../utils/authorization.js"),o=require("./JsonRpcError.js");const a=e=>{const r=e?.logs?.[0];return{blockHash:r?.blockHash,blockNumber:e?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:e?.gasUsed,effectiveGasPrice:e?.gasFee,from:void 0,gasUsed:e?.gasUsed,logs:e?.logs||[],logsBloom:void 0,status:1===e?.status?"success":0===e?.status?"reverted":void 0,to:e?.to,transactionHash:e?.transactionHash,transactionIndex:r?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function n(e,r){try{const t=await e.getCode(r);return"0x"!==t&&t.length>2}catch{return!1}}exports.sendCallsSync=async({params:s,signer:i,account:c,authentication:d,backendClient:p,rpcProvider:u,policyId:l})=>{const E=s[0]?.capabilities?.paymasterService?.policy??l;let T;if(c.accountType===r.AccountTypeEnum.DELEGATED_ACCOUNT){const[e,r]=await Promise.all([n(u,c.address),u.getTransactionCount(c.address)]);if(!e){const e=await t.prepareAndSignAuthorization({signer:i,accountAddress:c.address,contractAddress:c.implementationAddress,chainId:c.chainId,nonce:r});T=t.serializeSignedAuthorization(e)}}const A=await(async(r,t,a,n,s,i)=>{const c=r.map(e=>{if(!e.to)throw new o.JsonRpcError(o.RpcErrorCode.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(e.to),data:e.data?String(e.data):void 0,value:e.value?String(e.value):void 0}});return e.withOpenfortError(async()=>(await t.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:a.id,policy:s,signedAuthorization:i,chainId:a.chainId,interactions:c}},{headers:{authorization:`Bearer ${t.config.backend.accessToken}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(s,p,c,d,E,T).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(A.response?.error.reason)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,A.response?.error.reason);if(A?.nextAction?.payload?.signableHash){let t;t=[300,324].includes(c.chainId)||c.implementationType&&[r.AccountType.CALIBUR].includes(c.implementationType)?await i.sign(A.nextAction.payload.signableHash,!1,!1):await i.sign(A.nextAction.payload.signableHash);const n=await e.withOpenfortError(async()=>await p.transactionIntentsApi.signature({id:A.id,signatureRequest:{signature:t}}),{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(0===n.data.response?.status)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,n.data.response?.error.reason);if(!n.data.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(n.data.response)}}if(!A.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(A.response)}};
package/dist/index.d.ts CHANGED
@@ -405,6 +405,10 @@ interface AxiosRequestConfig<D = any> {
405
405
  withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
406
406
  parseReviver?: (this: any, key: string, value: any) => any;
407
407
  fetchOptions?: Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'> | Record<string, any>;
408
+ httpVersion?: 1 | 2;
409
+ http2Options?: Record<string, any> & {
410
+ sessionTimeout?: number;
411
+ };
408
412
  }
409
413
 
410
414
  interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
@@ -6937,9 +6941,9 @@ declare enum StorageKeys {
6937
6941
  PKCE_VERIFIER = "openfort.pkce_verifier"
6938
6942
  }
6939
6943
  interface IStorage {
6940
- get(key: StorageKeys): Promise<string | null>;
6941
- save(key: StorageKeys, value: string): void;
6942
- remove(key: StorageKeys): void;
6944
+ get(key: StorageKeys | string): Promise<string | null>;
6945
+ save(key: StorageKeys | string, value: string): void;
6946
+ remove(key: StorageKeys | string): void;
6943
6947
  flush(): void;
6944
6948
  }
6945
6949
 
@@ -7214,6 +7218,7 @@ interface TransactionIntentResponsePlayer {
7214
7218
  declare const TRANSACTION_ABSTRACTION_TYPE: {
7215
7219
  readonly accountAbstractionV6: "accountAbstractionV6";
7216
7220
  readonly accountAbstractionV8: "accountAbstractionV8";
7221
+ readonly accountAbstractionV9: "accountAbstractionV9";
7217
7222
  readonly zksync: "zkSync";
7218
7223
  readonly standard: "standard";
7219
7224
  };
@@ -7224,7 +7229,7 @@ interface TransactionIntentResponse {
7224
7229
  createdAt: number;
7225
7230
  updatedAt: number;
7226
7231
  abstractionType: TransactionAbstractionType;
7227
- details?: AccountAbstractionV6Details | AccountAbstractionV8Details | ZKSyncDetails | StandardDetails;
7232
+ details?: AccountAbstractionV6Details | AccountAbstractionV8Details | AccountAbstractionV9Details | ZKSyncDetails | StandardDetails;
7228
7233
  chainId: number;
7229
7234
  response?: ResponseResponse;
7230
7235
  interactions?: Interaction[];
@@ -7310,6 +7315,27 @@ interface UserOperationV6 {
7310
7315
  signature: string;
7311
7316
  verificationGasLimit: string;
7312
7317
  }
7318
+ interface AccountAbstractionV9Details {
7319
+ userOperation: UserOperationV9;
7320
+ userOperationHash: string;
7321
+ }
7322
+ interface UserOperationV9 {
7323
+ callData: string;
7324
+ callGasLimit: string;
7325
+ factory?: string;
7326
+ factoryData?: string;
7327
+ maxFeePerGas: string;
7328
+ maxPriorityFeePerGas: string;
7329
+ nonce: string;
7330
+ paymaster?: string;
7331
+ paymasterVerificationGasLimit?: string;
7332
+ paymasterPostOpGasLimit?: string;
7333
+ paymasterData?: string;
7334
+ preVerificationGas: string;
7335
+ sender: string;
7336
+ signature: string;
7337
+ verificationGasLimit: string;
7338
+ }
7313
7339
  interface AccountAbstractionV8Details {
7314
7340
  userOperation: UserOperationV8;
7315
7341
  userOperationHash: string;
@@ -1 +1 @@
1
- import{Authentication as t}from"../core/configuration/authentication.js";import{OpenfortError as e,OpenfortErrorType as a}from"../core/errors/openfortError.js";import{OpenfortEvents as i}from"../types/types.js";class r{storage;authManager;validateAndRefreshToken;ensureInitialized;eventEmitter;constructor(t,e,a,i,r){this.storage=t,this.authManager=e,this.validateAndRefreshToken=a,this.ensureInitialized=i,this.eventEmitter=r}async logInWithEmailPassword({email:r,password:s,ecosystemGame:n}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.loginEmailPassword(r,s,n);return"action"in e||(new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async signUpGuest(){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"guest"});try{const e=await this.authManager.registerGuest();return new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async signUpWithEmailPassword({email:r,password:s,options:n,ecosystemGame:o}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.signupEmailPassword(r,s,n?.data.name,o);return"action"in e||(new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async linkEmailPassword({email:t,password:e,authToken:a,ecosystemGame:i}){return await this.validateAndRefreshToken(),await this.authManager.linkEmail(t,e,a,i)}async unlinkEmailPassword({email:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkEmail(t,e)}async requestEmailVerification({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestEmailVerification(t,e)}async resetPassword({email:t,password:e,state:a}){await this.ensureInitialized(),await this.authManager.resetPassword(t,e,a)}async requestResetPassword({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestResetPassword(t,e)}async verifyEmail({email:t,state:e}){await this.ensureInitialized(),await this.authManager.verifyEmail(t,e)}async initOAuth({provider:r,options:s,ecosystemGame:n}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"oauth",provider:r}),await this.authManager.initOAuth(r,s,n)}async initLinkOAuth({provider:r,options:s,ecosystemGame:n}){await this.validateAndRefreshToken();const o=await t.fromStorage(this.storage);if(!o)throw new e("No authentication found",a.NOT_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"oauth",provider:r}),await this.authManager.linkOAuth(o,r,s,n)}async unlinkOAuth({provider:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkOAuth(t,e)}async poolOAuth(e){await this.ensureInitialized();try{const a=await this.authManager.poolOAuth(e);return new t("jwt",a.token,a.player.id,a.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,a),a}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async loginWithIdToken({provider:r,token:s,ecosystemGame:n}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"idToken",provider:r});try{const e=await this.authManager.loginWithIdToken(r,s,n);return new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async initSIWE({address:t,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initSIWE(t,e)}async authenticateWithSIWE({signature:r,message:s,walletClientType:n,connectorType:o}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"siwe",provider:"wallet"});try{const e=await this.authManager.authenticateSIWE(r,s,n,o);return new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async linkWallet({signature:t,message:e,walletClientType:a,connectorType:i,authToken:r}){return await this.validateAndRefreshToken(),await this.authManager.linkWallet(t,e,a,i,r)}async unlinkWallet({address:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkWallet(t,e)}async storeCredentials(i){if(await this.ensureInitialized(),!i.player)throw new e("Player ID is required to store credentials",a.INVALID_CONFIGURATION);new t("jwt",i.accessToken,i.player,i.refreshToken).save(this.storage)}async logout(){const e=await t.fromStorage(this.storage);if(e){try{"third_party"!==e.type&&await this.authManager.logout(e.token,e?.refreshToken)}catch(t){}t.clear(this.storage),this.eventEmitter.emit(i.ON_LOGOUT)}}}export{r as AuthApi};
1
+ import{Authentication as t}from"../core/configuration/authentication.js";import{OpenfortError as e,OpenfortErrorType as a}from"../core/errors/openfortError.js";import{OpenfortEvents as i}from"../types/types.js";class r{storage;authManager;validateAndRefreshToken;ensureInitialized;eventEmitter;constructor(t,e,a,i,r){this.storage=t,this.authManager=e,this.validateAndRefreshToken=a,this.ensureInitialized=i,this.eventEmitter=r}async logInWithEmailPassword({email:r,password:s,ecosystemGame:n}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.loginEmailPassword(r,s,n);return"action"in e||(new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async signUpGuest(){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"guest"});try{const e=await this.authManager.registerGuest();return new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async signUpWithEmailPassword({email:r,password:s,options:n,ecosystemGame:o}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"email",provider:"email"});try{const e=await this.authManager.signupEmailPassword(r,s,n?.data.name,o);return"action"in e||(new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e)),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async linkEmailPassword({email:t,password:e,authToken:a,ecosystemGame:i}){return await this.validateAndRefreshToken(),await this.authManager.linkEmail(t,e,a,i)}async unlinkEmailPassword({email:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkEmail(t,e)}async requestEmailVerification({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestEmailVerification(t,e)}async resetPassword({email:t,password:e,state:a}){await this.ensureInitialized(),await this.authManager.resetPassword(t,e,a)}async requestResetPassword({email:t,redirectUrl:e}){await this.ensureInitialized(),await this.authManager.requestResetPassword(t,e)}async verifyEmail({email:t,state:e}){await this.ensureInitialized(),await this.authManager.verifyEmail(t,e)}async initOAuth({provider:r,options:s,ecosystemGame:n}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"oauth",provider:r}),await this.authManager.initOAuth(r,s,n)}async initLinkOAuth({provider:r,options:s,ecosystemGame:n}){await this.validateAndRefreshToken();const o=await t.fromStorage(this.storage);if(!o)throw new e("No authentication found",a.NOT_LOGGED_IN_ERROR);return this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"oauth",provider:r}),await this.authManager.linkOAuth(o,r,s,n)}async unlinkOAuth({provider:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkOAuth(t,e)}async poolOAuth(e){await this.ensureInitialized();try{const a=await this.authManager.poolOAuth(e);return new t("jwt",a.token,a.player.id,a.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,a),a}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async loginWithIdToken({provider:r,token:s,ecosystemGame:n}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"idToken",provider:r});try{const e=await this.authManager.loginWithIdToken(r,s,n);return new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async initSIWE({address:t,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initSIWE(t,e)}async authenticateWithSIWE({signature:r,message:s,walletClientType:n,connectorType:o}){await this.ensureInitialized();if(await t.fromStorage(this.storage))throw new e("Already logged in",a.ALREADY_LOGGED_IN_ERROR);this.eventEmitter.emit(i.ON_AUTH_INIT,{method:"siwe",provider:"wallet"});try{const e=await this.authManager.authenticateSIWE(r,s,n,o);return new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),this.eventEmitter.emit(i.ON_AUTH_SUCCESS,e),e}catch(t){throw this.eventEmitter.emit(i.ON_AUTH_FAILURE,t),t}}async linkWallet({signature:t,message:e,walletClientType:a,connectorType:i,authToken:r}){return await this.validateAndRefreshToken(),await this.authManager.linkWallet(t,e,a,i,r)}async unlinkWallet({address:t,authToken:e}){return await this.validateAndRefreshToken(),await this.authManager.unlinkWallet(t,e)}async storeCredentials(i){if(await this.ensureInitialized(),!i.player)throw new e("Player ID is required to store credentials",a.INVALID_CONFIGURATION);new t("jwt",i.accessToken,i.player,i.refreshToken).save(this.storage)}async logout(){const e=await t.fromStorage(this.storage);if(e){try{"third_party"!==e.type&&await this.authManager.logout(e.token,e.refreshToken??"")}catch(t){}t.clear(this.storage),this.eventEmitter.emit(i.ON_LOGOUT)}}}export{r as AuthApi};
@@ -1 +1 @@
1
- import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{PasskeyHandler as t}from"../core/configuration/passkey.js";import{SDKConfiguration as r}from"../core/config/config.js";import{Account as s}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as i,OpenfortErrorType as n,withOpenfortError as o}from"../core/errors/openfortError.js";import{OpenfortEvents as d,RecoveryMethod as c,ChainTypeEnum as h,AccountTypeEnum as m,EmbeddedState as g}from"../types/types.js";import{debugLog as y}from"../utils/debug.js";import{EmbeddedSigner as l}from"../wallets/embedded.js";import{EvmProvider as p}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as f,openfortProviderInfo as A}from"../wallets/evm/provider/eip6963.js";import{signMessage as u}from"../wallets/evm/walletHelpers.js";import{IframeManager as w}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import v from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class M{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,s,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(d.ON_LOGOUT,()=>{y("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=r.getInstance();if(!t)throw new i("Configuration not found",n.INVALID_CONFIGURATION);return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(y("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(y("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return y("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return y("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;y("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return y("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,y("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw y("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){y("[HANDSHAKE DEBUG] createIframeManager starting");const e=r.getInstance();if(!e)throw y("[HANDSHAKE DEBUG] Configuration not found"),new i("Configuration not found",n.INVALID_CONFIGURATION);let t;if(y("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)y("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(y("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),y("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{y("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new v({remoteWindow:r.contentWindow,allowedOrigins:[s]}),y("[HANDSHAKE DEBUG] Created WindowMessenger")}return y("[HANDSHAKE DEBUG] Creating IframeManager instance"),new w(e,this.storage,t)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(y("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new l(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new i("Document is not available. Please provide a message poster for non-browser environments.",n.INVALID_CONFIGURATION);const t=document.getElementById("openfort-iframe");t&&t.remove();const r=document.createElement("iframe");return r.style.display="none",r.id="openfort-iframe",r.src=e,document.body.appendChild(r),r}async getPasskeyKey(e){const t=await a.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:t.player})}async getEntropy(e){switch(e.recoveryMethod){case c.PASSWORD:return{recoveryPassword:e.password};case c.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new i("Invalid recovery method",n.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.AUTOMATIC},[r,i,n]=await Promise.all([a.fromStorage(this.storage),this.ensureSigner(),this.getEntropy(t)]),o={chainId:e.chainId,entropy:n,accountType:e.accountType??m.SMART_ACCOUNT,chainType:e.chainType??h.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},d=await i.configure(o);return{id:d.id,chainId:d.chainId,user:r.player,address:d.address,ownerAddress:d.ownerAddress,chainType:d.chainType,accountType:d.accountType,implementationType:d.implementationType,factoryAddress:d.factoryAddress,salt:d.salt,createdAt:d.createdAt,implementationAddress:d.implementationAddress,recoveryMethod:s.parseRecoveryMethod(d.recoveryMethod),recoveryMethodDetails:d.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.AUTOMATIC},o=await a.fromStorage(this.storage);if(!o)throw new i("missing authentication",n.AUTHENTICATION_ERROR);if(r.recoveryMethod===c.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.player});r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[h,m]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),g=await h.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:m}),y={id:g.id,chainId:g.chainId,user:o.player,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:s.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(d.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.AUTOMATIC};if(t.recoveryMethod===c.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new i("Passkey ID must be provided for passkey recovery",n.INVALID_CONFIGURATION);t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[r,o,h]=await Promise.all([this.ensureSigner(),this.getEntropy(t),a.fromStorage(this.storage)]),m=await r.recover({account:e.account,entropy:o}),g={id:m.id,chainId:m.chainId,implementationAddress:m.implementationAddress,factoryAddress:m.factoryAddress,salt:m.salt,user:h.player,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,createdAt:m.createdAt,recoveryMethod:s.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(d.ON_EMBEDDED_WALLET_RECOVERED,g),g}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=t||{},n=await s.fromStorage(this.storage);return await r.sign(e,i,a,n?.chainType)}async signTypedData(e,t,r){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await s.fromStorage(this.storage);if(!o)throw new i("No account found",n.MISSING_SIGNER_ERROR);const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,r);return await u({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await a.fromStorage(this.storage);if(!d)throw new i("missing authentication",n.AUTHENTICATION_ERROR);let h,m,g,y;if(e.recoveryMethod===c.PASSKEY){const e=await s.fromStorage(this.storage);if(!e)throw new i("missing account",n.INVALID_CONFIGURATION);const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new i("missing passkey id for account",n.INVALID_CONFIGURATION);g={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.player})}}else if(r.recoveryMethod===c.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:d.player});g={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===c.PASSWORD?h=e.password:r.recoveryMethod===c.PASSWORD&&(h=r.password),e.recoveryMethod===c.AUTOMATIC?m=e.encryptionSession:r.recoveryMethod===c.AUTOMATIC&&(m=r.encryptionSession),!h&&!m)throw new i("Password or encryption session is not provided",n.INVALID_CONFIGURATION);await o.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:g});const l=await s.fromStorage(this.storage);l&&new s({...l,recoveryMethod:r.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){const e=await s.fromStorage(this.storage);if(!e)throw new i("No signer configured",n.MISSING_SIGNER_ERROR);const t=await a.fromStorage(this.storage);if(!t)throw new i("No access token found",n.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:t.player,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const t={accountType:m.SMART_ACCOUNT,...e},d=r.getInstance();if(!d)throw new i("Configuration not found",n.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const c=await a.fromStorage(this.storage);if(!c)throw new i("No access token found",n.NOT_LOGGED_IN_ERROR);return o(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(t,{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{default:n.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return g.UNAUTHENTICATED;return await s.fromStorage(this.storage)?g.READY:g.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return y("Failed to get embedded state:",e),g.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},r=await a.fromStorage(this.storage),i=await s.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new p({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&f({info:{...A,...t.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(t=>{setTimeout(t,e)});const t=await this.getIframeManager();if(!t.isLoaded())return!1;const r=await a.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return y("Ping failed:",e),!1}}getURL(){const e=r.getInstance();if(!e)throw new i("Configuration not found",n.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new i("Invalid message poster",n.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void y("Invalid message received:",e);y("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const t="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(t&&this.messenger&&this.messagePoster)return y("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();y(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&y("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),y("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),y("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{M as EmbeddedWalletApi};
1
+ import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{PasskeyHandler as t}from"../core/configuration/passkey.js";import{SDKConfiguration as r}from"../core/config/config.js";import{Account as s}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as i,OpenfortErrorType as n,withOpenfortError as o}from"../core/errors/openfortError.js";import{OpenfortEvents as d,RecoveryMethod as c,ChainTypeEnum as h,AccountTypeEnum as m,EmbeddedState as y}from"../types/types.js";import{debugLog as g}from"../utils/debug.js";import{EmbeddedSigner as l}from"../wallets/embedded.js";import{EvmProvider as p}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as f,openfortProviderInfo as A}from"../wallets/evm/provider/eip6963.js";import{signMessage as u}from"../wallets/evm/walletHelpers.js";import{IframeManager as w}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import v from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class M{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,s,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(d.ON_LOGOUT,()=>{g("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=r.getInstance();if(!t)throw new i("Configuration not found",n.INVALID_CONFIGURATION);return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(g("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(g("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return g("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return g("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;g("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return g("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,g("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw g("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){g("[HANDSHAKE DEBUG] createIframeManager starting");const e=r.getInstance();if(!e)throw g("[HANDSHAKE DEBUG] Configuration not found"),new i("Configuration not found",n.INVALID_CONFIGURATION);let t;if(g("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)g("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(g("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),g("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{g("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new v({remoteWindow:r.contentWindow,allowedOrigins:[s]}),g("[HANDSHAKE DEBUG] Created WindowMessenger")}return g("[HANDSHAKE DEBUG] Creating IframeManager instance"),new w(e,this.storage,t)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(g("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new l(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new i("Document is not available. Please provide a message poster for non-browser environments.",n.INVALID_CONFIGURATION);const t=document.getElementById("openfort-iframe");t&&t.remove();const r=document.createElement("iframe");return r.style.display="none",r.id="openfort-iframe",r.src=e,document.body.appendChild(r),r}async getPasskeyKey(e){const t=await a.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:t.player})}async getEntropy(e){switch(e.recoveryMethod){case c.PASSWORD:return{recoveryPassword:e.password};case c.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new i("Invalid recovery method",n.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.AUTOMATIC},[r,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??m.SMART_ACCOUNT,chainType:e.chainType??h.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await r.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.AUTOMATIC},o=await a.fromStorage(this.storage);if(!o)throw new i("missing authentication",n.AUTHENTICATION_ERROR);if(r.recoveryMethod===c.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.player??""});r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[h,m]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),y=await h.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:m}),g={id:y.id,chainId:y.chainId,user:o.player,address:y.address,ownerAddress:y.ownerAddress,chainType:y.chainType,accountType:y.accountType,implementationType:y.implementationType,factoryAddress:y.factoryAddress,salt:y.salt,createdAt:y.createdAt,implementationAddress:y.implementationAddress,recoveryMethod:s.parseRecoveryMethod(y.recoveryMethod),recoveryMethodDetails:y.recoveryMethodDetails};return this.eventEmitter.emit(d.ON_EMBEDDED_WALLET_CREATED,g),g}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.AUTOMATIC};if(t.recoveryMethod===c.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new i("Passkey ID must be provided for passkey recovery",n.INVALID_CONFIGURATION);t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[r,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),o=await r.recover({account:e.account,entropy:a}),h={id:o.id,chainId:o.chainId,implementationAddress:o.implementationAddress,factoryAddress:o.factoryAddress,salt:o.salt,user:o.user,address:o.address,ownerAddress:o.ownerAddress,chainType:o.chainType,accountType:o.accountType,implementationType:o.implementationType,createdAt:o.createdAt,recoveryMethod:s.parseRecoveryMethod(o.recoveryMethod),recoveryMethodDetails:o.recoveryMethodDetails};return this.eventEmitter.emit(d.ON_EMBEDDED_WALLET_RECOVERED,h),h}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=t||{},n=await s.fromStorage(this.storage);return await r.sign(e,i,a,n?.chainType)}async signTypedData(e,t,r){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await s.fromStorage(this.storage);if(!o)throw new i("No account found",n.MISSING_SIGNER_ERROR);const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,r);return await u({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await a.fromStorage(this.storage);if(!d)throw new i("missing authentication",n.AUTHENTICATION_ERROR);let h,m,y,g;if(e.recoveryMethod===c.PASSKEY){const e=await s.fromStorage(this.storage);if(!e)throw new i("missing account",n.INVALID_CONFIGURATION);const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new i("missing passkey id for account",n.INVALID_CONFIGURATION);y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.player})}}else if(r.recoveryMethod===c.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:d.player});y={passkeyId:e.id,passkeyKey:e.key},g={passkeyId:e.id}}if(e.recoveryMethod===c.PASSWORD?h=e.password:r.recoveryMethod===c.PASSWORD&&(h=r.password),e.recoveryMethod===c.AUTOMATIC?m=e.encryptionSession:r.recoveryMethod===c.AUTOMATIC&&(m=r.encryptionSession),!h&&!m)throw new i("Password or encryption session is not provided",n.INVALID_CONFIGURATION);await o.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const l=await s.fromStorage(this.storage);l&&new s({...l,recoveryMethod:r.recoveryMethod,recoveryMethodDetails:g}).save(this.storage)}async get(){const e=await s.fromStorage(this.storage);if(!e)throw new i("No signer configured",n.MISSING_SIGNER_ERROR);const t=await a.fromStorage(this.storage);if(!t)throw new i("No access token found",n.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:t.player,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const t={accountType:m.SMART_ACCOUNT,...e},d=r.getInstance();if(!d)throw new i("Configuration not found",n.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const c=await a.fromStorage(this.storage);if(!c)throw new i("No access token found",n.NOT_LOGGED_IN_ERROR);return o(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(t,{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{default:n.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return y.UNAUTHENTICATED;return await s.fromStorage(this.storage)?y.READY:y.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return g("Failed to get embedded state:",e),y.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},r=await a.fromStorage(this.storage),i=await s.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new p({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&f({info:{...A,...t.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(t=>{setTimeout(t,e)});const t=await this.getIframeManager();if(!t.isLoaded())return!1;const r=await a.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return g("Ping failed:",e),!1}}getURL(){const e=r.getInstance();if(!e)throw new i("Configuration not found",n.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new i("Invalid message poster",n.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void g("Invalid message received:",e);g("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const t="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(t&&this.messenger&&this.messagePoster)return g("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();g(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&g("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),g("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),g("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{M as EmbeddedWalletApi};
@@ -1 +1 @@
1
- import{StorageKeys as e}from"../../storage/istorage.js";import"../errors/openfortError.js";import{RecoveryMethod as t}from"../../types/types.js";import"human-id";import"eventemitter3";import"../../wallets/evm/JsonRpcError.js";import"@ethersproject/keccak256";import"../../wallets/evm/types.js";import"../../wallets/evm/provider/eip6963.js";import"../errors/sentry.js";import"../../wallets/messaging/browserMessenger/backwardCompatibility.js";import"../../wallets/types.js";import"jose";class s{constructor(e){this.user=e.user,this.id=e.id,this.chainType=e.chainType,this.address=e.address,this.accountType=e.accountType,this.chainId=e.chainId,this.createdAt=e.createdAt,this.implementationAddress=e.implementationAddress,this.implementationType=e.implementationType,this.factoryAddress=e.factoryAddress,this.recoveryMethod=e.recoveryMethod,this.recoveryMethodDetails=e.recoveryMethodDetails,this.salt=e.salt,this.ownerAddress=e.ownerAddress,this.type=e.type}user;id;chainType;address;accountType;chainId;ownerAddress;factoryAddress;implementationAddress;salt;createdAt;implementationType;recoveryMethod;recoveryMethodDetails;type;save(t){t.save(e.ACCOUNT,JSON.stringify({user:this.user,id:this.id,chainType:this.chainType,address:this.address,accountType:this.accountType,chainId:this.chainId,ownerAddress:this.ownerAddress,createdAt:this.createdAt,implementationType:this.implementationType,factoryAddress:this.factoryAddress,implementationAddress:this.implementationAddress,salt:this.salt,recoveryMethod:this.recoveryMethod,recoveryMethodDetails:this.recoveryMethodDetails}))}static parseRecoveryMethod=e=>{switch(e){case"user":case t.PASSWORD:return t.PASSWORD;case"project":case t.AUTOMATIC:return t.AUTOMATIC;case"passkey":case t.PASSKEY:return t.PASSKEY;default:return}};static async fromStorage(t){const r=await t.get(e.ACCOUNT);if(!r)return null;try{const e=JSON.parse(r);return new s(e)}catch{return null}}}export{s as Account};
1
+ import{StorageKeys as e}from"../../storage/istorage.js";import{RecoveryMethod as t}from"../../types/types.js";class s{constructor(e){this.user=e.user,this.id=e.id,this.chainType=e.chainType,this.address=e.address,this.accountType=e.accountType,this.chainId=e.chainId,this.createdAt=e.createdAt,this.implementationAddress=e.implementationAddress,this.implementationType=e.implementationType,this.factoryAddress=e.factoryAddress,this.recoveryMethod=e.recoveryMethod,this.recoveryMethodDetails=e.recoveryMethodDetails,this.salt=e.salt,this.ownerAddress=e.ownerAddress,this.type=e.type}user;id;chainType;address;accountType;chainId;ownerAddress;factoryAddress;implementationAddress;salt;createdAt;implementationType;recoveryMethod;recoveryMethodDetails;type;save(t){t.save(e.ACCOUNT,JSON.stringify({user:this.user,id:this.id,chainType:this.chainType,address:this.address,accountType:this.accountType,chainId:this.chainId,ownerAddress:this.ownerAddress,createdAt:this.createdAt,implementationType:this.implementationType,factoryAddress:this.factoryAddress,implementationAddress:this.implementationAddress,salt:this.salt,recoveryMethod:this.recoveryMethod,recoveryMethodDetails:this.recoveryMethodDetails}))}static parseRecoveryMethod=e=>{switch(e){case"user":case t.PASSWORD:return t.PASSWORD;case"project":case t.AUTOMATIC:return t.AUTOMATIC;case"passkey":case t.PASSKEY:return t.PASSKEY;default:return}};static async fromStorage(t){const r=await t.get(e.ACCOUNT);if(!r)return null;try{const e=JSON.parse(r);return new s(e)}catch{return null}}}export{s as Account};
@@ -1 +1 @@
1
- import{AxiosError as t}from"axios";import{VERSION as s,PACKAGE as e}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(s){const e=s.getDsn();if(!e)throw new Error("Sentry DSN is not set");if(e.projectId!==r.split("https://")[1].split("/")[1]||e.host!==r.split("@")[1].split("/")[0]||e.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");s.captureAxiosError=(e,r,a,o)=>{if(r instanceof t){if(400===r.response?.status||401===r.response?.status)return;r.name=e,s.captureException(r,{...a,captureContext:{...a?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:e}}})}else s.captureException(r,a,o)},n.sentryInstance=s}static get sentry(){return n.proxy}static async init({sentry:t,configuration:a}){if(t)return void(n.sentry=t);const o=await import("@sentry/browser");n.sentry=new o.BrowserClient({dsn:r,integrations:[],stackParser:o.defaultStackParser,transport:o.makeFetchTransport}),n.baseTags={projectId:a?.baseConfiguration.publishableKey,sdk:e,sdkVersion:s},n.processQueuedCalls()}static proxy=new Proxy({},{get:(t,s)=>n.sentryInstance&&"function"==typeof n.sentryInstance[s]?(...t)=>n.sentryInstance[s](...t):(...t)=>{n.queuedCalls.push({fn:s,args:t})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:t,args:s})=>{"function"==typeof n.sentryInstance[t]&&n.sentryInstance[t](...s)}),n.queuedCalls=[])}}const{sentry:a}=n;export{n as InternalSentry,a as sentry};
1
+ import{AxiosError as t}from"axios";import{VERSION as s,PACKAGE as e}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(s){const e=s.getDsn();if(!e)throw new Error("Sentry DSN is not set");if(e.projectId!==r.split("https://")[1].split("/")[1]||e.host!==r.split("@")[1].split("/")[0]||e.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");s.captureAxiosError=(e,r,a,o)=>{if(r instanceof t){if(400===r.response?.status||401===r.response?.status)return;r.name=e,s.captureException(r,{...a,captureContext:{...a?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:e}}})}else s.captureException(r,a,o)},n.sentryInstance=s}static get sentry(){return n.proxy}static async init({sentry:t,configuration:a}){if(t)return void(n.sentry=t);const o=await import("@sentry/browser");n.sentry=new o.BrowserClient({dsn:r,integrations:[],stackParser:o.defaultStackParser,transport:o.makeFetchTransport}),n.baseTags={projectId:a?.baseConfiguration.publishableKey??"",sdk:e,sdkVersion:s},n.processQueuedCalls()}static proxy=new Proxy({},{get:(t,s)=>n.sentryInstance&&"function"==typeof n.sentryInstance[s]?(...t)=>n.sentryInstance[s](...t):(...t)=>{n.queuedCalls.push({fn:s,args:t})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:t,args:s})=>{"function"==typeof n.sentryInstance[t]&&n.sentryInstance[t](...s)}),n.queuedCalls=[])}}const{sentry:a}=n;export{n as InternalSentry,a as sentry};
@@ -1 +1 @@
1
- import{BackendApiClients as t}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as e}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{ProxyApi as n}from"../api/proxy.js";import{UserApi as a}from"../api/user.js";import{AuthManager as s}from"../auth/authManager.js";import{StorageKeys as r}from"../storage/istorage.js";import{LazyStorage as o}from"../storage/lazyStorage.js";import h from"../utils/typedEventEmitter.js";import{SDKConfiguration as l}from"./config/config.js";import{PasskeyHandler as c}from"./configuration/passkey.js";import{OpenfortError as d,OpenfortErrorType as u}from"./errors/openfortError.js";import{InternalSentry as g}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";class m{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",u.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",u.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",u.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",u.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s(this.storage),this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new e(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new d("Embedded wallet not initialized",u.MISSING_SIGNER_ERROR);const t=this.embeddedWalletInstance;return e=>t.signMessage(e,{hashMessage:!0,arrayifyMessage:!0})})}catch(t){throw new d("Openfort SDK synchronous initialization failed",u.INVALID_CONFIGURATION)}}constructor(t){if(this.configuration=new l(t),this.storage=new o(this.configuration.storage),this.eventEmitter=new h,m.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(t=>{this.eventEmitter.on(t,(...e)=>{m.globalEventEmitter?.emit(t,...e)})})}else m.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=new c({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),g.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return m.globalEventEmitter||(m.globalEventEmitter=new h),m.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(t){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(t)}get backendApiClients(){return new t({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new d("AuthManager not initialized",u.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(t){try{const e=r.TEST,i="openfort_storage_test";t.save(e,i);const n=await t.get(e);return t.remove(e),n===i}catch(t){return!1}}async initializeAsync(){try{if(!await m.isStorageAccessible(this.storage))throw new d("Storage is not accessible",u.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(t){throw new d("Openfort SDK async initialization failed",u.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{m as Openfort};
1
+ import{BackendApiClients as t}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as e}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{ProxyApi as n}from"../api/proxy.js";import{UserApi as a}from"../api/user.js";import{AuthManager as s}from"../auth/authManager.js";import{StorageKeys as r}from"../storage/istorage.js";import{LazyStorage as o}from"../storage/lazyStorage.js";import h from"../utils/typedEventEmitter.js";import{SDKConfiguration as l}from"./config/config.js";import{PasskeyHandler as c}from"./configuration/passkey.js";import{OpenfortError as d,OpenfortErrorType as u}from"./errors/openfortError.js";import{InternalSentry as g}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";class m{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",u.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",u.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",u.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new d("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",u.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s(this.storage),this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new e(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new d("Embedded wallet not initialized",u.MISSING_SIGNER_ERROR);const t=this.embeddedWalletInstance;return e=>t.signMessage(e,{hashMessage:!0,arrayifyMessage:!0})})}catch(t){throw new d("Openfort SDK synchronous initialization failed",u.INVALID_CONFIGURATION)}}constructor(t){if(this.configuration=new l(t),this.storage=new o(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,m.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(t=>{this.eventEmitter.on(t,(...e)=>{m.globalEventEmitter?.emit(t,...e)})})}else m.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=new c({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),g.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return m.globalEventEmitter||(m.globalEventEmitter=new h),m.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(t){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(t)}get backendApiClients(){return new t({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new d("AuthManager not initialized",u.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(t){try{const e=r.TEST,i="openfort_storage_test";t.save(e,i);const n=await t.get(e);return t.remove(e),n===i}catch(t){return!1}}async initializeAsync(){try{if(!await m.isStorageAccessible(this.storage))throw new d("Storage is not accessible",u.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(t){throw new d("Openfort SDK async initialization failed",u.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{m as Openfort};
@@ -1 +1 @@
1
- import{Authentication as t}from"./configuration/authentication.js";import{OpenfortError as e,OpenfortErrorType as r}from"./errors/openfortError.js";import{TokenType as o,OpenfortEvents as i}from"../types/types.js";import"human-id";import{SDKConfiguration as s}from"./config/config.js";import"../storage/istorage.js";import{debugLog as a}from"../utils/debug.js";import"eventemitter3";import"../wallets/evm/JsonRpcError.js";import"@ethersproject/keccak256";import"../wallets/evm/types.js";import"../wallets/evm/provider/eip6963.js";import"./errors/sentry.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import"../wallets/types.js";import"jose";import{singlePromise as n}from"../utils/promiseUtils.js";class h{storage;authManager;eventEmitter;constructor(t,e,r){this.storage=t,this.authManager=e,this.eventEmitter=r}async getThirdPartyAuthToken(){const i=s.getInstance();if(!i?.thirdPartyAuth)throw new e("No third party configuration found",r.INTERNAL_ERROR);const{getAccessToken:a,provider:n}=i.thirdPartyAuth;if(!a||!n)throw new e("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",r.INVALID_CONFIGURATION);const h=await a();if(!h)throw new e("Could not get access token",r.AUTHENTICATION_ERROR);let c=(await t.fromStorage(this.storage))?.player;if(!c){const t=await this.authManager.authenticateThirdParty(n,h,o.ID_TOKEN);c=t?.id}return new t("third_party",h,c,null,n,o.ID_TOKEN).save(this.storage),h}async getAccessToken(){if(s.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await t.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(o){return n(async()=>{if(s.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const n=await t.fromStorage(this.storage);if(!n)throw new e("Must be logged in to validate and refresh token",r.NOT_LOGGED_IN_ERROR);let h;a("validating credentials...");try{h=await this.authManager.validateCredentials(n,o)}catch(e){throw t.clear(this.storage),this.eventEmitter.emit(i.ON_LOGOUT),e}if(!h.player)throw new e("No user found in credentials",r.INTERNAL_ERROR);h.accessToken!==n.token&&(a("tokens refreshed"),new t("jwt",h.accessToken,h.player,h.refreshToken).save(this.storage))},"openfort.validateAndRefreshToken")}}export{h as OpenfortInternal};
1
+ import{debugLog as t}from"../utils/debug.js";import{singlePromise as e}from"../utils/promiseUtils.js";import{TokenType as r,OpenfortEvents as a}from"../types/types.js";import{SDKConfiguration as o}from"./config/config.js";import{Authentication as i}from"./configuration/authentication.js";import{OpenfortError as n,OpenfortErrorType as s}from"./errors/openfortError.js";class h{storage;authManager;eventEmitter;constructor(t,e,r){this.storage=t,this.authManager=e,this.eventEmitter=r}async getThirdPartyAuthToken(){const t=o.getInstance();if(!t?.thirdPartyAuth)throw new n("No third party configuration found",s.INTERNAL_ERROR);const{getAccessToken:e,provider:a}=t.thirdPartyAuth;if(!e||!a)throw new n("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",s.INVALID_CONFIGURATION);const h=await e();if(!h)throw new n("Could not get access token",s.AUTHENTICATION_ERROR);let c=(await i.fromStorage(this.storage))?.player;if(!c){const t=await this.authManager.authenticateThirdParty(a,h,r.ID_TOKEN);c=t?.id}return new i("third_party",h,c,null,a,r.ID_TOKEN).save(this.storage),h}async getAccessToken(){if(o.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await i.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(r){return e(async()=>{if(o.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const e=await i.fromStorage(this.storage);if(!e)throw new n("Must be logged in to validate and refresh token",s.NOT_LOGGED_IN_ERROR);let h;t("validating credentials...");try{h=await this.authManager.validateCredentials(e,r)}catch(t){throw i.clear(this.storage),this.eventEmitter.emit(a.ON_LOGOUT),t}if(!h.player)throw new n("No user found in credentials",s.INTERNAL_ERROR);h.accessToken!==e.token&&(t("tokens refreshed"),new i("jwt",h.accessToken,h.player,h.refreshToken).save(this.storage))},"openfort.validateAndRefreshToken")}}export{h as OpenfortInternal};
@@ -1 +1 @@
1
- import{OpenfortError as e,OpenfortErrorType as t}from"../core/errors/openfortError.js";import{StorageImplementation as r}from"./storage.js";class o{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e("Storage not available. Please provide custom storage or use in browser environment.",t.INVALID_CONFIGURATION);this.realStorage=new r(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,t){this.getRealStorage().save(e,t)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}}export{o as LazyStorage};
1
+ import{OpenfortError as e,OpenfortErrorType as t}from"../core/errors/openfortError.js";import{ScopedStorage as o}from"./scopedStorage.js";import{StorageImplementation as r}from"./storage.js";class a{realStorage=null;customStorage;publishableKey;constructor(e,t){this.publishableKey=e,this.customStorage=t}getRealStorage(){if(!this.realStorage){let a;if(this.customStorage)a=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e("Storage not available. Please provide custom storage or use in browser environment.",t.INVALID_CONFIGURATION);a=new r(localStorage)}this.realStorage=new o(a,this.publishableKey)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,t){this.getRealStorage().save(e,t)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}}export{a as LazyStorage};
@@ -0,0 +1 @@
1
+ import{StorageKeys as e}from"./istorage.js";class s{storage;scope;constructor(e,s){this.storage=e,this.scope=this.createScope(s)}createScope(e){return e.substring(8).substring(0,8)}scopeKey(e){return`${this.scope}.${e}`}async get(e){return this.storage.get(this.scopeKey(e))}save(e,s){this.storage.save(this.scopeKey(e),s)}remove(e){this.storage.remove(this.scopeKey(e))}flush(){for(const s of Object.values(e))this.storage.remove(this.scopeKey(s))}}export{s as ScopedStorage};
@@ -1 +1 @@
1
- const t={1:"https://cloudflare-eth.com",10:"https://optimism-rpc.publicnode.com",56:"https://bsc.publicnode.com",97:"https://bsc-testnet.publicnode.com",137:"https://polygon-rpc.com",204:"https://opbnb-mainnet-rpc.bnbchain.org",300:"https://sepolia.era.zksync.dev",324:"https://mainnet.era.zksync.io",1946:"https://rpc.minato.soneium.org",2741:"https://api.mainnet.abs.xyz",3939:"https://test.doschain.com",4337:"https://build.onbeam.com/rpc",5611:"https://opbnb-testnet-rpc.bnbchain.org",7979:"https://main.doschain.com",8453:"https://mainnet.base.org",11124:"https://api.testnet.abs.xyz",13337:"https://build.onbeam.com/rpc/testnet",13473:"https://rpc.testnet.immutable.com",42161:"https://arb1.arbitrum.io/rpc",42170:"https://nova.arbitrum.io/rpc",43113:"https://api.avax-test.network/ext/bc/C/rpc",43114:"https://api.avax.network/ext/bc/C/rpc",50104:"https://rpc.sophon.xyz",80002:"https://polygon-amoy-bor-rpc.publicnode.com",84532:"https://sepolia.base.org",421614:"https://sepolia-rollup.arbitrum.io/rpc",7225878:"https://rpc.saakuru.network",7777777:"https://rpc.zora.energy",11155111:"https://ethereum-sepolia-rpc.publicnode.com",11155420:"https://optimism-sepolia-rpc.publicnode.com",28122024:"https://rpcv2-testnet.ancient8.gg",531050104:"https://rpc.testnet.sophon.xyz",666666666:"https://rpc.degen.tips",888888888:"https://rpc.ancient8.gg",999999999:"https://sepolia.rpc.zora.energy",85011:"https://subnets.avax.network/criminalsa/testnet/rpc",84358:"https://subnets.avax.network/titan/mainnet/rpc",10143:"https://testnet-rpc.monad.xyz",510525:"https://rpc.clankermon.com",3008:"https://kl1-testnet.kiooverse.xyz/rpc",167e3:"https://rpc.taiko.xyz"};export{t as defaultChainRpcs};
1
+ const t={1:"https://cloudflare-eth.com",10:"https://optimism-rpc.publicnode.com",56:"https://bsc.publicnode.com",97:"https://bsc-testnet.publicnode.com",137:"https://polygon-rpc.com",1946:"https://rpc.minato.soneium.org",3008:"https://kl1-testnet.kiooverse.xyz/rpc",4337:"https://build.onbeam.com/rpc",5611:"https://opbnb-testnet-rpc.bnbchain.org",8453:"https://mainnet.base.org",10143:"https://testnet-rpc.monad.xyz",13337:"https://build.onbeam.com/rpc/testnet",42161:"https://arb1.arbitrum.io/rpc",42170:"https://nova.arbitrum.io/rpc",43113:"https://api.avax-test.network/ext/bc/C/rpc",43114:"https://api.avax.network/ext/bc/C/rpc",80002:"https://polygon-amoy-bor-rpc.publicnode.com",84358:"https://subnets.avax.network/titan/mainnet/rpc",84532:"https://sepolia.base.org",421614:"https://sepolia-rollup.arbitrum.io/rpc",510525:"https://rpc.clankermon.com",510530:"https://open-loot.rpc.syndicate.io",510531:"https://open-loot.rpc.testnet.syndicate.io",7225878:"https://rpc.saakuru.network",7777777:"https://rpc.zora.energy",11155111:"https://ethereum-sepolia-rpc.publicnode.com",11155420:"https://optimism-sepolia-rpc.publicnode.com",28122024:"https://rpcv2-testnet.ancient8.gg",666666666:"https://rpc.degen.tips",888888888:"https://rpc.ancient8.gg",999999999:"https://sepolia.rpc.zora.energy"};export{t as defaultChainRpcs};
@@ -1 +1 @@
1
- const o="0.10.36",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="0.10.38",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -1 +1 @@
1
- import{Authentication as e}from"../core/configuration/authentication.js";import{PasskeyHandler as t}from"../core/configuration/passkey.js";import{OpenfortError as a,OpenfortErrorType as r,withOpenfortError as o}from"../core/errors/openfortError.js";import{OpenfortEvents as s,AccountTypeEnum as n}from"../types/types.js";import{SDKConfiguration as i}from"../core/config/config.js";import{Account as c}from"../core/configuration/account.js";import{StorageKeys as d}from"../storage/istorage.js";import"eventemitter3";import"./evm/JsonRpcError.js";import"@ethersproject/keccak256";import"./evm/types.js";import"./evm/provider/eip6963.js";import"../core/errors/sentry.js";import"./messaging/browserMessenger/backwardCompatibility.js";import"./types.js";import"jose";class y{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const a=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:a.id,key:a.key}}async configure(t){const n=await e.fromStorage(this.storage);if(!n)throw new a("No access token found",r.NOT_LOGGED_IN_ERROR);const d=i.getInstance();if(!d)throw new a("Configuration not found",r.INVALID_CONFIGURATION);const y=await c.fromStorage(this.storage);let p;if(y){const e={account:y.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===y.recoveryMethod&&{passkey:{id:y.recoveryMethodDetails?.passkeyId,env:y.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(y.recoveryMethodDetails?.passkeyId)}}}}},a=await this.iframeManager.recover(e);p=a.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:n.player,accountType:t.accountType,chainType:t.chainType},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(n.player):void 0,a={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},r=await this.iframeManager.create(a);p=r.account}else{const a=e.data.data,r=a.find(e=>e.chainId===t.chainId),o=r||a[0],s={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId)}}}}},n=await this.iframeManager.recover(s);if(p=n.account,!r){const e=await this.iframeManager.switchChain(t.chainId);p=e.account}}}return o(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:p},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}}),t=new c({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:c.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(s.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.AUTHENTICATION_ERROR})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(s.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await c.fromStorage(this.storage);if(t?.accountType===n.EOA)new c({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new c({...t,id:a.account,chainId:e}).save(this.storage)}}async create(t){const n=await this.iframeManager.create(t),d=await e.fromStorage(this.storage);if(!d)throw new a("No access token found",r.NOT_LOGGED_IN_ERROR);const y=i.getInstance();if(!y)throw new a("Configuration not found",r.INVALID_CONFIGURATION);return o(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:n.account},{headers:{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}}),t=new c({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:c.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(s.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.AUTHENTICATION_ERROR})}async recover(t){const n=await this.iframeManager.recover(t),d=await e.fromStorage(this.storage);if(!d)throw new a("No access token found",r.NOT_LOGGED_IN_ERROR);const y=i.getInstance();if(!y)throw new a("Configuration not found",r.INVALID_CONFIGURATION);return o(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:n.account},{headers:{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}}),t=new c({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:c.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(s.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(d.ACCOUNT)}}export{y as EmbeddedSigner};
1
+ import{Authentication as e}from"../core/configuration/authentication.js";import{PasskeyHandler as t}from"../core/configuration/passkey.js";import{OpenfortError as a,OpenfortErrorType as r,withOpenfortError as o}from"../core/errors/openfortError.js";import{SDKConfiguration as s}from"../core/config/config.js";import{Account as n}from"../core/configuration/account.js";import{StorageKeys as i}from"../storage/istorage.js";import{OpenfortEvents as c,AccountTypeEnum as d}from"../types/types.js";class y{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const a=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:a.id,key:a.key}}async configure(t){const i=await e.fromStorage(this.storage);if(!i)throw new a("No access token found",r.NOT_LOGGED_IN_ERROR);const d=s.getInstance();if(!d)throw new a("Configuration not found",r.INVALID_CONFIGURATION);const y=await n.fromStorage(this.storage);let p;if(y){const e={account:y.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===y.recoveryMethod&&{passkey:{id:y.recoveryMethodDetails?.passkeyId,env:y.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(y.recoveryMethodDetails?.passkeyId??"")}}}}},a=await this.iframeManager.recover(e);p=a.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:i.player,accountType:t.accountType,chainType:t.chainType},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(i.player):void 0,a={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},r=await this.iframeManager.create(a);p=r.account}else{const a=e.data.data,r=a.find(e=>e.chainId===t.chainId),o=r||a[0],s={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId??"")}}}}},n=await this.iframeManager.recover(s);if(p=n.account,!r){const e=await this.iframeManager.switchChain(t.chainId);p=e.account}}}return o(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:p},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.AUTHENTICATION_ERROR})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(c.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await n.fromStorage(this.storage);if(t?.accountType===d.EOA)new n({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new n({...t,id:a.account,chainId:e}).save(this.storage)}}async create(t){const i=await this.iframeManager.create(t),d=await e.fromStorage(this.storage);if(!d)throw new a("No access token found",r.NOT_LOGGED_IN_ERROR);const y=s.getInstance();if(!y)throw new a("Configuration not found",r.INVALID_CONFIGURATION);return o(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:i.account},{headers:{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}}),t=new n({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.AUTHENTICATION_ERROR})}async recover(t){const i=await this.iframeManager.recover(t),d=await e.fromStorage(this.storage);if(!d)throw new a("No access token found",r.NOT_LOGGED_IN_ERROR);const y=s.getInstance();if(!y)throw new a("Configuration not found",r.INVALID_CONFIGURATION);return o(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:i.account},{headers:{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}}),t=new n({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(i.ACCOUNT)}}export{y as EmbeddedSigner};
@@ -1 +1 @@
1
- import{withOpenfortError as e,OpenfortErrorType as t}from"../../core/errors/openfortError.js";import{JsonRpcError as r,RpcErrorCode as a}from"./JsonRpcError.js";const s=async({params:s,account:o,authentication:n,backendClient:c})=>{const i=await(async(r,a,s,o)=>{const n=o?.chainFilter?.map(e=>Number.parseInt(e,16));return e(async()=>(await r.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:a.address,chainFilter:n,assetFilter:o?.assetFilter,assetTypeFilter:o?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:{authorization:`Bearer ${r.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:t.AUTHENTICATION_ERROR})})(c,o,n,s).catch(e=>{throw new r(a.INTERNAL_ERROR,e.message)});return i.result};export{s as getAssets};
1
+ import{withOpenfortError as e,OpenfortErrorType as t}from"../../core/errors/openfortError.js";import{JsonRpcError as r,RpcErrorCode as a}from"./JsonRpcError.js";const s=async({params:s,account:o,authentication:n,backendClient:c})=>{const i=await(async(r,a,s,o)=>e(async()=>(await r.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:a.address,chainFilter:o?.chainFilter,assetFilter:o?.assetFilter,assetTypeFilter:o?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:{authorization:`Bearer ${r.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:t.AUTHENTICATION_ERROR}))(c,o,n,s).catch(e=>{throw new r(a.INTERNAL_ERROR,e.message)});return i.result};export{s as getAssets};
@@ -1 +1 @@
1
- import{withOpenfortError as t,OpenfortErrorType as e}from"../../core/errors/openfortError.js";import{AccountType as i}from"../../types/types.js";import{JsonRpcError as n,RpcErrorCode as a}from"./JsonRpcError.js";function s(t){return{data:(()=>{if("token-allowance"===t.type)throw new n(a.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===t.type)throw new n(a.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===t.type)throw new n(a.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return t.data})(),type:t.type.custom}}function o(t){if("native-token-transfer"===t.type)throw new n(a.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===t.type)throw new n(a.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===t.type)throw new n(a.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...t,policies:t?.policies?.map(s),required:t.required??!1,type:"string"==typeof t.type?t.type:t.type.custom}}function r(t){return{expiry:t.validUntil?Number(t.validUntil):0,grantedPermissions:t.whitelist?t.whitelist.map(e=>({type:"contract-call",data:{address:e,calls:[]},policies:[{data:{limit:t.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:t.id}}const p=async({params:s,signer:p,account:c,authentication:l,backendClient:d,policyId:m})=>{const y=await(async(i,s,r,p,c)=>{const l=i[0],d=Math.floor(Date.now()/1e3),m=Math.floor(new Date(Date.now()+1e3*l.expiry).getTime()/1e3),y=l.permissions.map(o),u=y.filter(t=>"contract-call"===t.type||"erc20-token-transfer"===t.type||"erc721-token-transfer"===t.type||"erc1155-token-transfer"===t.type).map(t=>t.data.address);let h,w=y.find(t=>"call-limit"===t.type)?.data;if(w=y[0]?.policies?.find(t=>"call-limit"===t.type)?.data?.limit,"signer"in l&&l.signer){if("keys"===l.signer.type)throw new n(a.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==l.signer.type&&"account"!==l.signer.type||(h=l.signer.data.id)}else"account"in l&&l.account&&(h=l.account);if(!h)throw new n(a.INVALID_PARAMS,"Failed to request permissions - missing session address");const A=((t,e,i,n,a,s=!1,o,r,p,c)=>{const l={address:t,chainId:e,validAfter:i,validUntil:n,optimistic:s,whitelist:o,player:r,account:c};return a&&(l.policy=a),p&&(l.limit=p),l})(h,r.chainId,d,m,c,!1,u,p.player,w,r.id);return t(async()=>(await s.sessionsApi.createSession({createSessionRequest:A},{headers:{authorization:`Bearer ${s.config.backend.accessToken}`,"x-player-token":p.token,"x-auth-provider":p.thirdPartyProvider,"x-token-type":p.thirdPartyTokenType}})).data,{default:e.AUTHENTICATION_ERROR})})(s,d,c,l,m).catch(t=>{throw new n(a.TRANSACTION_REJECTED,t.message)});if(y?.nextAction?.payload?.signableHash){let s;s=[300,531050104,324,50104,2741,11124].includes(c.chainId)||c.implementationType&&[i.CALIBUR].includes(c.implementationType)?await p.sign(y.nextAction.payload.signableHash,!1,!1):await p.sign(y.nextAction.payload.signableHash);return r(await t(async()=>(await d.sessionsApi.signatureSession({id:y.id,signatureRequest:{signature:s}})).data,{default:e.AUTHENTICATION_ERROR}).catch(t=>{throw new n(a.TRANSACTION_REJECTED,t.message)}))}if(!1===y.isActive)throw new n(a.TRANSACTION_REJECTED,"Failed to grant permissions");return r(y)};export{p as registerSession};
1
+ import{withOpenfortError as t,OpenfortErrorType as e}from"../../core/errors/openfortError.js";import{AccountType as i}from"../../types/types.js";import{JsonRpcError as n,RpcErrorCode as a}from"./JsonRpcError.js";function s(t){return{data:(()=>{if("token-allowance"===t.type)throw new n(a.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===t.type)throw new n(a.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===t.type)throw new n(a.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return t.data})(),type:t.type.custom}}function o(t){if("native-token-transfer"===t.type)throw new n(a.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===t.type)throw new n(a.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===t.type)throw new n(a.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...t,policies:t?.policies?.map(s),required:t.required??!1,type:"string"==typeof t.type?t.type:t.type.custom}}function r(t){return{expiry:t.validUntil?Number(t.validUntil):0,grantedPermissions:t.whitelist?t.whitelist.map(e=>({type:"contract-call",data:{address:e,calls:[]},policies:[{data:{limit:t.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:t.id}}const p=async({params:s,signer:p,account:c,authentication:l,backendClient:d,policyId:m})=>{const y=await(async(i,s,r,p,c)=>{const l=i[0],d=Math.floor(Date.now()/1e3),m=Math.floor(new Date(Date.now()+1e3*l.expiry).getTime()/1e3),y=l.permissions.map(o),u=y.filter(t=>"contract-call"===t.type||"erc20-token-transfer"===t.type||"erc721-token-transfer"===t.type||"erc1155-token-transfer"===t.type).map(t=>t.data.address);let h,w=y.find(t=>"call-limit"===t.type)?.data;if(w=y[0]?.policies?.find(t=>"call-limit"===t.type)?.data?.limit,"signer"in l&&l.signer){if("keys"===l.signer.type)throw new n(a.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==l.signer.type&&"account"!==l.signer.type||(h=l.signer.data.id)}else"account"in l&&l.account&&(h=l.account);if(!h)throw new n(a.INVALID_PARAMS,"Failed to request permissions - missing session address");const A=((t,e,i,n,a,s=!1,o,r,p,c)=>{const l={address:t,chainId:e,validAfter:i,validUntil:n,optimistic:s,whitelist:o,player:r,account:c};return a&&(l.policy=a),p&&(l.limit=p),l})(h,r.chainId,d,m,c,!1,u,p.player,w,r.id);return t(async()=>(await s.sessionsApi.createSession({createSessionRequest:A},{headers:{authorization:`Bearer ${s.config.backend.accessToken}`,"x-player-token":p.token,"x-auth-provider":p.thirdPartyProvider,"x-token-type":p.thirdPartyTokenType}})).data,{default:e.AUTHENTICATION_ERROR})})(s,d,c,l,m).catch(t=>{throw new n(a.TRANSACTION_REJECTED,t.message)});if(y?.nextAction?.payload?.signableHash){let s;s=[300,324].includes(c.chainId)||c.implementationType&&[i.CALIBUR].includes(c.implementationType)?await p.sign(y.nextAction.payload.signableHash,!1,!1):await p.sign(y.nextAction.payload.signableHash);return r(await t(async()=>(await d.sessionsApi.signatureSession({id:y.id,signatureRequest:{signature:s}})).data,{default:e.AUTHENTICATION_ERROR}).catch(t=>{throw new n(a.TRANSACTION_REJECTED,t.message)}))}if(!1===y.isActive)throw new n(a.TRANSACTION_REJECTED,"Failed to grant permissions");return r(y)};export{p as registerSession};
@@ -1 +1 @@
1
- import{withOpenfortError as e,OpenfortErrorType as t}from"../../core/errors/openfortError.js";import{AccountType as n}from"../../types/types.js";import{JsonRpcError as a,RpcErrorCode as s}from"./JsonRpcError.js";const i=async({params:i,signer:o,account:r,authentication:c,backendClient:p,policyId:d})=>{const y=i[0];if(!y.permissionContext)return await o.disconnect(),{};const l=await(async(n,a,s,i,o)=>{const r=((e,t,n,a,s)=>{const i={address:e,chainId:t,player:n,account:s};return a&&(i.policy=a),i})(n.permissionContext,s.chainId,i.player,o,s.id);return e(async()=>(await a.sessionsApi.revokeSession({revokeSessionRequest:r},{headers:{authorization:`Bearer ${a.config.backend.accessToken}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}})).data,{default:t.AUTHENTICATION_ERROR})})(y,p,r,c,d).catch(e=>{throw new a(s.TRANSACTION_REJECTED,e.message)});if(l?.nextAction?.payload?.signableHash){let e;e=[300,531050104,324,50104,2741,11124].includes(r.chainId)||r.implementationType&&[n.CALIBUR].includes(r.implementationType)?await o.sign(l.nextAction.payload.signableHash,!1,!1):await o.sign(l.nextAction.payload.signableHash);return(await p.sessionsApi.signatureSession({id:l.id,signatureRequest:{signature:e}}).catch(e=>{throw new a(s.TRANSACTION_REJECTED,e.message)})).data}return l};export{i as revokeSession};
1
+ import{withOpenfortError as e,OpenfortErrorType as t}from"../../core/errors/openfortError.js";import{AccountType as n}from"../../types/types.js";import{JsonRpcError as a,RpcErrorCode as s}from"./JsonRpcError.js";const i=async({params:i,signer:o,account:r,authentication:c,backendClient:p,policyId:d})=>{const y=i[0];if(!y.permissionContext)return await o.disconnect(),{};const l=await(async(n,a,s,i,o)=>{const r=((e,t,n,a,s)=>{const i={address:e,chainId:t,player:n,account:s};return a&&(i.policy=a),i})(n.permissionContext,s.chainId,i.player,o,s.id);return e(async()=>(await a.sessionsApi.revokeSession({revokeSessionRequest:r},{headers:{authorization:`Bearer ${a.config.backend.accessToken}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}})).data,{default:t.AUTHENTICATION_ERROR})})(y,p,r,c,d).catch(e=>{throw new a(s.TRANSACTION_REJECTED,e.message)});if(l?.nextAction?.payload?.signableHash){let e;e=[300,324].includes(r.chainId)||r.implementationType&&[n.CALIBUR].includes(r.implementationType)?await o.sign(l.nextAction.payload.signableHash,!1,!1):await o.sign(l.nextAction.payload.signableHash);return(await p.sessionsApi.signatureSession({id:l.id,signatureRequest:{signature:e}}).catch(e=>{throw new a(s.TRANSACTION_REJECTED,e.message)})).data}return l};export{i as revokeSession};
@@ -1 +1 @@
1
- import{withOpenfortError as e,OpenfortErrorType as t}from"../../core/errors/openfortError.js";import{AccountTypeEnum as a,AccountType as n}from"../../types/types.js";import{prepareAndSignAuthorization as s,serializeSignedAuthorization as o}from"../../utils/authorization.js";import{JsonRpcError as r,RpcErrorCode as i}from"./JsonRpcError.js";const c=e=>{const t=e?.logs?.[0];return{blockHash:t?.blockHash,blockNumber:e?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:e?.gasUsed,effectiveGasPrice:e?.gasFee,from:void 0,gasUsed:e?.gasUsed,logs:e?.logs||[],logsBloom:void 0,status:1===e?.status?"success":0===e?.status?"reverted":void 0,to:e?.to,transactionHash:e?.transactionHash,transactionIndex:t?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function d(e,t){try{const a=await e.getCode(t);return"0x"!==a&&a.length>2}catch{return!1}}const p=async({params:p,signer:l,account:u,authentication:T,backendClient:A,rpcProvider:h,policyId:g})=>{const E=p[0]?.capabilities?.paymasterService?.policy??g;let m;if(u.accountType===a.DELEGATED_ACCOUNT){const[e,t]=await Promise.all([d(h,u.address),h.getTransactionCount(u.address)]);if(!e){const e=await s({signer:l,accountAddress:u.address,contractAddress:u.implementationAddress,chainId:u.chainId,nonce:t});m=o(e)}}const I=await(async(a,n,s,o,c,d)=>{const p=a.map(e=>{if(!e.to)throw new r(i.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(e.to),data:e.data?String(e.data):void 0,value:e.value?String(e.value):void 0}});return e(async()=>(await n.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:s.id,policy:c,signedAuthorization:d,chainId:s.chainId,interactions:p}},{headers:{authorization:`Bearer ${n.config.backend.accessToken}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}})).data,{default:t.AUTHENTICATION_ERROR})})(p,A,u,T,E,m).catch(e=>{throw new r(i.TRANSACTION_REJECTED,e.message)});if(I.response?.error.reason)throw new r(i.TRANSACTION_REJECTED,I.response?.error.reason);if(I?.nextAction?.payload?.signableHash){let a;a=[300,531050104,324,50104,2741,11124].includes(u.chainId)||u.implementationType&&[n.CALIBUR].includes(u.implementationType)?await l.sign(I.nextAction.payload.signableHash,!1,!1):await l.sign(I.nextAction.payload.signableHash);const s=await e(async()=>await A.transactionIntentsApi.signature({id:I.id,signatureRequest:{signature:a}}),{default:t.AUTHENTICATION_ERROR}).catch(e=>{throw new r(i.TRANSACTION_REJECTED,e.message)});if(0===s.data.response?.status)throw new r(i.TRANSACTION_REJECTED,s.data.response?.error.reason);if(!s.data.response)throw new r(i.TRANSACTION_REJECTED,"No transaction response received");return{id:I.id,receipt:c(s.data.response)}}if(!I.response)throw new r(i.TRANSACTION_REJECTED,"No transaction response received");return{id:I.id,receipt:c(I.response)}};export{p as sendCallsSync};
1
+ import{withOpenfortError as e,OpenfortErrorType as t}from"../../core/errors/openfortError.js";import{AccountTypeEnum as a,AccountType as n}from"../../types/types.js";import{prepareAndSignAuthorization as s,serializeSignedAuthorization as o}from"../../utils/authorization.js";import{JsonRpcError as r,RpcErrorCode as i}from"./JsonRpcError.js";const c=e=>{const t=e?.logs?.[0];return{blockHash:t?.blockHash,blockNumber:e?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:e?.gasUsed,effectiveGasPrice:e?.gasFee,from:void 0,gasUsed:e?.gasUsed,logs:e?.logs||[],logsBloom:void 0,status:1===e?.status?"success":0===e?.status?"reverted":void 0,to:e?.to,transactionHash:e?.transactionHash,transactionIndex:t?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function d(e,t){try{const a=await e.getCode(t);return"0x"!==a&&a.length>2}catch{return!1}}const p=async({params:p,signer:l,account:u,authentication:T,backendClient:A,rpcProvider:h,policyId:g})=>{const E=p[0]?.capabilities?.paymasterService?.policy??g;let m;if(u.accountType===a.DELEGATED_ACCOUNT){const[e,t]=await Promise.all([d(h,u.address),h.getTransactionCount(u.address)]);if(!e){const e=await s({signer:l,accountAddress:u.address,contractAddress:u.implementationAddress,chainId:u.chainId,nonce:t});m=o(e)}}const I=await(async(a,n,s,o,c,d)=>{const p=a.map(e=>{if(!e.to)throw new r(i.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(e.to),data:e.data?String(e.data):void 0,value:e.value?String(e.value):void 0}});return e(async()=>(await n.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:s.id,policy:c,signedAuthorization:d,chainId:s.chainId,interactions:p}},{headers:{authorization:`Bearer ${n.config.backend.accessToken}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}})).data,{default:t.AUTHENTICATION_ERROR})})(p,A,u,T,E,m).catch(e=>{throw new r(i.TRANSACTION_REJECTED,e.message)});if(I.response?.error.reason)throw new r(i.TRANSACTION_REJECTED,I.response?.error.reason);if(I?.nextAction?.payload?.signableHash){let a;a=[300,324].includes(u.chainId)||u.implementationType&&[n.CALIBUR].includes(u.implementationType)?await l.sign(I.nextAction.payload.signableHash,!1,!1):await l.sign(I.nextAction.payload.signableHash);const s=await e(async()=>await A.transactionIntentsApi.signature({id:I.id,signatureRequest:{signature:a}}),{default:t.AUTHENTICATION_ERROR}).catch(e=>{throw new r(i.TRANSACTION_REJECTED,e.message)});if(0===s.data.response?.status)throw new r(i.TRANSACTION_REJECTED,s.data.response?.error.reason);if(!s.data.response)throw new r(i.TRANSACTION_REJECTED,"No transaction response received");return{id:I.id,receipt:c(s.data.response)}}if(!I.response)throw new r(i.TRANSACTION_REJECTED,"No transaction response received");return{id:I.id,receipt:c(I.response)}};export{p as sendCallsSync};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfort/openfort-js",
3
- "version": "0.10.36",
3
+ "version": "0.10.38",
4
4
  "author": "Openfort (https://www.openfort.io)",
5
5
  "bugs": "https://github.com/openfort-xyz/openfort-js/issues",
6
6
  "repository": "openfort-xyz/openfort-js.git",