@openfort/openfort-js 1.3.8 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),a=require("../core/configuration/account.cjs"),n=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../storage/istorage.cjs"),c=require("../types/types.cjs"),h=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),y=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var m=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),f=require("../wallets/iframeManager.cjs"),p=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var E=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");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,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,()=>{h.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(h.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(h.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;h.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return h.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,h.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw h.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){h.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw h.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(h.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)h.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(h.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),h.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{h.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new E({remoteWindow:r.contentWindow,allowedOrigins:[s]}),h.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return h.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new f.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(h.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();await e.initialize();return new y.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await n.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case c.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case c.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),n={chainId:e.chainId,entropy:s,accountType:e.accountType??c.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??c.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(n);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,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(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async import(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,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(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,n]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:n}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}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,t,s){await this.validateAndRefreshToken();const n=await this.ensureSigner(),o=await a.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,s);return await l.signMessage({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:n,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,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await n.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let h,g,y,u;if(e.recoveryMethod===c.RecoveryMethod.PASSKEY){const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.userId})}}else if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:d.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},u={passkeyId:e.id}}if(e.recoveryMethod===c.RecoveryMethod.PASSWORD?h=e.password:s.recoveryMethod===c.RecoveryMethod.PASSWORD&&(h=s.password),e.recoveryMethod===c.RecoveryMethod.AUTOMATIC?g=e.encryptionSession:s.recoveryMethod===c.RecoveryMethod.AUTOMATIC&&(g=s.encryptionSession),!h&&!g)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const m=await a.Account.fromStorage(this.storage);m&&new a.Account({...m,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:u}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await n.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,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){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await n.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({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})),{context:"list"})}async getEmbeddedState(){try{if(!await n.Authentication.fromStorage(this.storage))return c.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?c.EmbeddedState.READY:c.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return h.debugLog("Failed to get embedded state:",e),c.EmbeddedState.UNAUTHENTICATED}}watchEmbeddedState(e){return g.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),n=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.off(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await n.Authentication.fromStorage(this.storage),s=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new u.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&m.announceProvider({info:{...m.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 n.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return h.debugLog("Ping failed:",e),!1}}getURL(){const e=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");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(){if(this.storage.remove(d.StorageKeys.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return h.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 h.debugLog("Invalid message received:",e);h.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 h.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();h.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&h.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),h.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),h.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),a=require("../core/configuration/account.cjs"),n=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../storage/istorage.cjs"),c=require("../types/types.cjs"),h=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),y=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var m=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),f=require("../wallets/iframeManager.cjs"),p=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var E=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");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,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,()=>{h.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(h.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(h.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;h.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return h.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,h.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw h.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){h.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw h.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(h.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)h.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(h.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),h.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{h.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new E({remoteWindow:r.contentWindow,allowedOrigins:[s]}),h.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return h.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new f.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(h.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();await e.initialize();return new y.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.referrerPolicy="strict-origin-when-cross-origin",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await n.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case c.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case c.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),n={chainId:e.chainId,entropy:s,accountType:e.accountType??c.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??c.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(n);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,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(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async import(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,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(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,n]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:n}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}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,t,s){await this.validateAndRefreshToken();const n=await this.ensureSigner(),o=await a.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,s);return await l.signMessage({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:n,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,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await n.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let h,g,y,u;if(e.recoveryMethod===c.RecoveryMethod.PASSKEY){const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.userId})}}else if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:d.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},u={passkeyId:e.id}}if(e.recoveryMethod===c.RecoveryMethod.PASSWORD?h=e.password:s.recoveryMethod===c.RecoveryMethod.PASSWORD&&(h=s.password),e.recoveryMethod===c.RecoveryMethod.AUTOMATIC?g=e.encryptionSession:s.recoveryMethod===c.RecoveryMethod.AUTOMATIC&&(g=s.encryptionSession),!h&&!g)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const m=await a.Account.fromStorage(this.storage);m&&new a.Account({...m,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:u}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await n.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,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){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await n.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({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})),{context:"list"})}async getEmbeddedState(){try{if(!await n.Authentication.fromStorage(this.storage))return c.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?c.EmbeddedState.READY:c.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return h.debugLog("Failed to get embedded state:",e),c.EmbeddedState.UNAUTHENTICATED}}watchEmbeddedState(e){return g.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),n=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.off(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await n.Authentication.fromStorage(this.storage),s=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new u.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&m.announceProvider({info:{...m.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 n.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return h.debugLog("Ping failed:",e),!1}}getURL(){const e=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");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(){if(this.storage.remove(d.StorageKeys.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return h.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 h.debugLog("Invalid message received:",e);h.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 h.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();h.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&h.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),h.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),h.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../utils/crypto.cjs");class i{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:t,overrides:r,thirdPartyAuth:a,debug:n}){this.shieldConfiguration=t,this.baseConfiguration=s,this.backendUrl=r?.backendUrl||"https://api.openfort.io",this.iframeUrl=r?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=n,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=r?.shieldUrl||"https://shield.openfort.io",this.storage=r?.storage,this.thirdPartyAuth=a,this.nativeAppIdentifier=s.nativeAppIdentifier,r?.crypto?.digest&&e.setCryptoDigestOverride(r.crypto.digest),i.instance=this}static getInstance(){return i.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=i,exports.ShieldConfiguration=class{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
1
+ "use strict";var e=require("../../utils/crypto.cjs");class i{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;disableTelemetry;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:t,overrides:r,thirdPartyAuth:a,debug:l,disableTelemetry:n}){this.shieldConfiguration=t,this.baseConfiguration=s,this.backendUrl=r?.backendUrl||"https://api.openfort.io",this.iframeUrl=r?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=l,this.disableTelemetry=n,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=r?.shieldUrl||"https://shield.openfort.io",this.storage=r?.storage,this.thirdPartyAuth=a,this.nativeAppIdentifier=s.nativeAppIdentifier,r?.crypto?.digest&&e.setCryptoDigestOverride(r.crypto.digest),i.instance=this}static getInstance(){return i.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=i,exports.ShieldConfiguration=class{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
@@ -1 +1 @@
1
- "use strict";var e=require("axios"),t=require("../../version.cjs");const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class s{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const n=t.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==r.split("https://")[1].split("/")[1]||n.host!==r.split("@")[1].split("/")[0]||n.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(r,n,o,a)=>{if(n instanceof e.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=r,t.captureException(n,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...s.baseTags,method:r}}})}else t.captureException(n,o,a)},t.captureError=(e,r,n,o)=>{const a=r.statusCode;if(400===a||401===a)return;const c=r,i=c.error,u=c.error_description,p=n?.captureContext;t.captureException(r,{...n,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:r.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...s.baseTags,context:e,errorClass:r.constructor.name}}})},s.sentryInstance=t}static get sentry(){return s.proxy}static async init({sentry:e,configuration:n}){if(e)return void(s.sentry=e);const o=await import("@sentry/browser");s.sentry=new o.BrowserClient({dsn:r,release:`${t.PACKAGE}@${t.VERSION}`,integrations:[],stackParser:o.defaultStackParser,transport:o.makeFetchTransport}),s.baseTags={projectId:n?.baseConfiguration.publishableKey??"",sdk:t.PACKAGE,sdkVersion:t.VERSION},s.processQueuedCalls()}static proxy=new Proxy({},{get:(e,t)=>s.sentryInstance&&"function"==typeof s.sentryInstance[t]?(...e)=>s.sentryInstance[t](...e):(...e)=>{s.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){s.sentryInstance&&(s.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof s.sentryInstance[e]&&s.sentryInstance[e](...t)}),s.queuedCalls=[])}}const{sentry:n}=s;exports.InternalSentry=s,exports.sentry=n;
1
+ "use strict";var e=require("axios"),t=require("../../version.cjs");const s="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class r{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const n=t.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");t.captureAxiosError=(s,n,a,o)=>{if(n instanceof e.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=s,t.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 t.captureException(n,a,o)},t.captureError=(e,s,n,a)=>{const o=s.statusCode;if(400===o||401===o)return;const c=s,i=c.error,u=c.error_description,p=n?.captureContext;t.captureException(s,{...n,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...r.baseTags,context:e,errorClass:s.constructor.name}}})},r.sentryInstance=t}static get sentry(){return r.proxy}static async init({sentry:e,configuration:n}){if(e)r.sentry=e;else if(!n?.disableTelemetry)try{const e=await import("@sentry/browser");r.sentry=new e.BrowserClient({dsn:s,release:`${t.PACKAGE}@${t.VERSION}`,integrations:[],stackParser:e.defaultStackParser,transport:e.makeFetchTransport}),r.baseTags={projectId:n?.baseConfiguration.publishableKey??"",sdk:t.PACKAGE,sdkVersion:t.VERSION},r.processQueuedCalls()}catch{}}static proxy=new Proxy({},{get:(e,t)=>r.sentryInstance&&"function"==typeof r.sentryInstance[t]?(...e)=>r.sentryInstance[t](...e):(...e)=>{r.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){r.sentryInstance&&(r.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof r.sentryInstance[e]&&r.sentryInstance[e](...t)}),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.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/proxy.cjs"),a=require("../api/user.cjs"),s=require("../auth/authManager.cjs"),r=require("../storage/istorage.cjs"),o=require("../storage/lazyStorage.cjs"),h=require("../utils/typedEventEmitter.cjs"),l=require("./config/config.cjs"),c=require("./errors/authErrorCodes.cjs"),u=require("./errors/openfortError.cjs"),d=require("./errors/sentry.cjs"),g=require("./openfortInternal.cjs"),f=require("./passkey/handler.cjs");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.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s.AuthManager,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 a.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.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.ConfigurationError("Openfort SDK synchronous initialization failed")}}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=e.overrides?.passkeyHandler??new f.PasskeyHandler({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),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.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.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(){if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",c.OPENFORT_ERROR_CODES.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}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.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/proxy.cjs"),a=require("../api/user.cjs"),s=require("../auth/authManager.cjs"),r=require("../storage/istorage.cjs"),o=require("../storage/lazyStorage.cjs"),h=require("../utils/typedEventEmitter.cjs"),l=require("./config/config.cjs"),c=require("./errors/authErrorCodes.cjs"),u=require("./errors/openfortError.cjs"),d=require("./errors/sentry.cjs"),g=require("./openfortInternal.cjs"),p=require("./passkey/handler.cjs");class f{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.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s.AuthManager,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 a.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.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.ConfigurationError("Openfort SDK synchronous initialization failed")}}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,f.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{f.globalEventEmitter?.emit(e,...t)})})}else f.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new p.PasskeyHandler({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return f.globalEventEmitter||(f.globalEventEmitter=new h),f.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.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.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(){if(!await f.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible. The SDK needs a working key/value store to persist the session. On React Native, ensure the app is code-signed (an unsigned build cannot use the keychain) and that expo-secure-store — or your `overrides.storage` implementation — is installed and reachable.",c.OPENFORT_ERROR_CODES.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=f;
@@ -1 +1 @@
1
- "use strict";let t;exports.cryptoDigest=async function(r,e){if(t)return t(r,e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(r,e);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")},exports.hexToString=function(t){let r="";const e=t.startsWith("0x")?t.slice(2):t;for(let t=0;t<e.length;t+=2){const n=parseInt(e.substring(t,t+2),16);0!==n&&(r+=String.fromCharCode(n))}return r},exports.numberToHex=function(t){return`0x${t.toString(16)}`},exports.randomUUID=function(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const e=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${e}`:e}).join("")},exports.setCryptoDigestOverride=function(r){t=r};
1
+ "use strict";let t;exports.cryptoDigest=async function(r,e){if(t)return t(r,e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(r,e);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")},exports.numberToHex=function(t){return`0x${t.toString(16)}`},exports.randomUUID=function(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const e=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${e}`:e}).join("")},exports.setCryptoDigestOverride=function(r){t=r};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.8";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.4.0";
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),s=require("../../utils/chains/index.cjs"),a=require("../../utils/crypto.cjs"),i=require("../../utils/typedEventEmitter.cjs"),o=require("./addEthereumChain.cjs"),n=require("./estimateGas.cjs"),c=require("./getAssets.cjs"),h=require("./getCallsStatus.cjs"),d=require("./JsonRpcError.cjs"),p=require("./personalSign.cjs"),u=require("./registerSession.cjs"),w=require("./revokeSession.cjs"),l=require("./sendCallSync.cjs"),m=require("./sendCalls.cjs"),g=require("./signTypedDataV4.cjs"),E=require("./types.cjs"),A=require("./walletHelpers.cjs");exports.EvmProvider=class{#e;#t;#r;#s;updateFeeSponsorship(e){this.#t=e}#a;#i;#o=null;#n;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:s,feeSponsorshipId:a,ensureSigner:o,chains:n,validateAndRefreshSession:c}){this.#c=o,this.#e=e,this.#r=n,this.#t=a,this.#a=c,this.#n=t,this.#i=new i,s.on(r.OpenfortEvents.ON_LOGOUT,this.#h),s.on(r.OpenfortEvents.ON_SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#s||(this.#s=await this.#c()),this.#s);#h=async()=>{this.#s=void 0,this.#i.emit(E.ProviderEvent.DISCONNECT,{code:4900,message:"Disconnected"}),this.#i.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#i.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#o){const t=await e.Account.fromStorage(this.#e),r=t?.chainId||(this.#r?Number(Object.keys(this.#r)[0]):void 0)||8453;await import("@ethersproject/providers").then(e=>{const t=this.#r?this.#r[r]:void 0;this.#o=new e.StaticJsonRpcProvider(t??s.defaultChainRpcs[r])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#u(i){switch(i.method){case"eth_accounts":{const t=await e.Account.fromStorage(this.#e);return t?[t.address]:[]}case"eth_requestAccounts":{const t=await e.Account.fromStorage(this.#e);if(t){const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return this.#i.emit(E.ProviderEvent.ACCOUNTS_CONNECT,{chainId:a.numberToHex(r)}),[t.address]}throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=i.params||[];c.chainId||(c.chainId=n.toString());const h=A.parseTransactionRequest(c),{serialize:p}=await import("@ethersproject/transactions"),u=e=>({legacy:0,eip2930:1,eip1559:2}[e]),{gas:w,...l}=h,m={...l,gasLimit:w,to:h.to??void 0,type:u(h.type)},g=p(m),{keccak256:E}=await import("@ethersproject/keccak256"),f=E(g);await this.#a();const S=await s.sign(f,!1,!1),{splitSignature:R}=await import("@ethersproject/bytes");return p(m,R(S))}case"eth_sendTransaction":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#a(),s?.accountType===r.AccountTypeEnum.EOA){const[e]=i.params||[],t=await this.getRpcProvider(),r=await A.prepareEOATransaction(e,t,s.address),a=await this.#u({method:"eth_signTransaction",params:[r]});return this.#u({method:"eth_sendRawTransaction",params:[a]})}return(await l.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);return await this.#a(),await l.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"eth_estimateGas":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await n.estimateGas({params:i.params||[],account:r,authentication:s,backendClient:this.#n,feeSponsorshipId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),r=await this.#p();if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();const s=await this.getRpcProvider();return await g.signTypedDataV4({method:i.method,params:i.params||[],signer:r,implementationType:t.implementationType||t.type,rpcProvider:s,account:t})}case"personal_sign":{const t=await e.Account.fromStorage(this.#e);if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const r=await this.#p();return await this.#a(),await p.personalSign({params:i.params||[],signer:r,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return a.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#p();if(!i.params||!Array.isArray(i.params)||0===i.params.length)throw new d.JsonRpcError(d.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#a();try{const t=parseInt(i.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#o=new e.StaticJsonRpcProvider(r??s.defaultChainRpcs[t])}),this.#i.emit(E.ProviderEvent.CHAIN_CHANGED,a.numberToHex(t))}catch(e){const t=e;throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const e=await this.getRpcProvider();return await o.addEthereumChain({params:i.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await t.Authentication.fromStorage(this.#e);if(!s||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await h.getCallStatus({params:i.params||{},authentication:a,backendClient:this.#n})}case"wallet_sendCalls":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();return await m.sendCalls({params:i.params?i.params[0].calls:[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"wallet_grantPermissions":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await this.#p(),o=await t.Authentication.fromStorage(this.#e);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await u.registerSession({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_revokePermissions":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await w.revokeSession({params:i.params||[],signer:s,account:r,authentication:a,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_getCapabilities":{const t=await e.Account.fromStorage(this.#e);if(t?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const s=await this.getRpcProvider(),{chainId:o}=await s.detectNetwork();return{[a.numberToHex(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await c.getAssets({params:i.params?.[0],account:r,authentication:s,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(i.method,i.params||[]);default:throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`)}}async request(e){try{return this.#u(e)}catch(e){if(e instanceof d.JsonRpcError)throw e;if(e instanceof Error)throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,e.message);throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#i.on(e,t)}removeListener(e,t){this.#i.off(e,t)}};
1
+ "use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),s=require("../../utils/chains/index.cjs"),a=require("../../utils/crypto.cjs"),i=require("../../utils/typedEventEmitter.cjs"),o=require("./addEthereumChain.cjs"),n=require("./estimateGas.cjs"),c=require("./getAssets.cjs"),h=require("./getCallsStatus.cjs"),d=require("./JsonRpcError.cjs"),p=require("./normalizeRpcError.cjs"),u=require("./personalSign.cjs"),w=require("./registerSession.cjs"),l=require("./revokeSession.cjs"),m=require("./sendCallSync.cjs"),g=require("./sendCalls.cjs"),E=require("./signTypedDataV4.cjs"),A=require("./types.cjs"),f=require("./walletHelpers.cjs");exports.EvmProvider=class{#e;#t;#r;#s;updateFeeSponsorship(e){this.#t=e}#a;#i;#o=null;#n;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:s,feeSponsorshipId:a,ensureSigner:o,chains:n,validateAndRefreshSession:c}){this.#c=o,this.#e=e,this.#r=n,this.#t=a,this.#a=c,this.#n=t,this.#i=new i,s.on(r.OpenfortEvents.ON_LOGOUT,this.#h),s.on(r.OpenfortEvents.ON_SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#s||(this.#s=await this.#c()),this.#s);#h=async()=>{this.#s=void 0,this.#i.emit(A.ProviderEvent.DISCONNECT,{code:4900,message:"Disconnected"}),this.#i.emit(A.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#i.emit(A.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#o){const t=await e.Account.fromStorage(this.#e),r=t?.chainId||(this.#r?Number(Object.keys(this.#r)[0]):void 0)||8453;await import("@ethersproject/providers").then(e=>{const t=this.#r?this.#r[r]:void 0;this.#o=new e.StaticJsonRpcProvider(t??s.defaultChainRpcs[r])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#u(i){switch(i.method){case"eth_accounts":{const t=await e.Account.fromStorage(this.#e);return t?[t.address]:[]}case"eth_requestAccounts":{const t=await e.Account.fromStorage(this.#e);if(t){const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return this.#i.emit(A.ProviderEvent.ACCOUNTS_CONNECT,{chainId:a.numberToHex(r)}),[t.address]}throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=i.params||[];c.chainId||(c.chainId=n.toString());const h=f.parseTransactionRequest(c),{serialize:p}=await import("@ethersproject/transactions"),u=e=>({legacy:0,eip2930:1,eip1559:2}[e]),{gas:w,...l}=h,m={...l,gasLimit:w,to:h.to??void 0,type:u(h.type)},g=p(m),{keccak256:E}=await import("@ethersproject/keccak256"),A=E(g);await this.#a();const S=await s.sign(A,!1,!1),{splitSignature:R}=await import("@ethersproject/bytes");return p(m,R(S))}case"eth_sendTransaction":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#a(),s?.accountType===r.AccountTypeEnum.EOA){const[e]=i.params||[],t=await this.getRpcProvider(),r=await f.prepareEOATransaction(e,t,s.address),a=await this.#u({method:"eth_signTransaction",params:[r]});return this.#u({method:"eth_sendRawTransaction",params:[a]})}return(await m.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);return await this.#a(),await m.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"eth_estimateGas":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await n.estimateGas({params:i.params||[],account:r,authentication:s,backendClient:this.#n,feeSponsorshipId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),r=await this.#p();if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();const s=await this.getRpcProvider();return await E.signTypedDataV4({method:i.method,params:i.params||[],signer:r,implementationType:t.implementationType||t.type,rpcProvider:s,account:t})}case"personal_sign":{const t=await e.Account.fromStorage(this.#e);if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const r=await this.#p();return await this.#a(),await u.personalSign({params:i.params||[],signer:r,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return a.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#p();if(!i.params||!Array.isArray(i.params)||0===i.params.length)throw new d.JsonRpcError(d.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#a();try{const t=parseInt(i.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#o=new e.StaticJsonRpcProvider(r??s.defaultChainRpcs[t])}),this.#i.emit(A.ProviderEvent.CHAIN_CHANGED,a.numberToHex(t))}catch(e){const t=e;throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const e=await this.getRpcProvider();return await o.addEthereumChain({params:i.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await t.Authentication.fromStorage(this.#e);if(!s||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await h.getCallStatus({params:i.params||{},authentication:a,backendClient:this.#n})}case"wallet_sendCalls":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();return await g.sendCalls({params:i.params?i.params[0].calls:[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"wallet_grantPermissions":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await this.#p(),o=await t.Authentication.fromStorage(this.#e);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await w.registerSession({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_revokePermissions":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await l.revokeSession({params:i.params||[],signer:s,account:r,authentication:a,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_getCapabilities":{const t=await e.Account.fromStorage(this.#e);if(t?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const s=await this.getRpcProvider(),{chainId:o}=await s.detectNetwork();return{[a.numberToHex(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await c.getAssets({params:i.params?.[0],account:r,authentication:s,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(i.method,i.params||[]);default:throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`)}}async request(e){try{return await this.#u(e)}catch(e){if(e instanceof d.JsonRpcError)throw e;if(e instanceof Error)throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,p.normalizeRpcErrorMessage(e.message));throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#i.on(e,t)}removeListener(e,t){this.#i.off(e,t)}};
@@ -0,0 +1 @@
1
+ "use strict";exports.normalizeRpcErrorMessage=function(e){const n=e.toLowerCase();return n.includes("insufficient funds")?"Insufficient funds: the wallet doesn't have enough native token to cover gas (plus any value). Top up the wallet and try again.":n.includes("execution reverted")||n.includes("reverted")?"Transaction reverted: the contract rejected this call.":n.includes("nonce too low")||n.includes("replacement transaction underpriced")?"Nonce conflict: another transaction from this wallet is still pending. Wait for it to confirm, then retry.":n.includes("intrinsic gas too low")||n.includes("gas required exceeds")||n.includes("out of gas")?"Gas error: the transaction needs more gas than is available or allowed.":e};
@@ -1 +1 @@
1
- "use strict";var e=require("../../utils/crypto.cjs"),r=require("./JsonRpcError.cjs"),s=require("./walletHelpers.cjs");exports.personalSign=async({params:a,signer:o,account:t})=>{const n=a[0],i=a[1];if(!i||!n)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"personal_sign requires an address and a message");if(i.toLowerCase()!==t.address.toLowerCase())throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"personal_sign requires the signer to be the from address");const{hashMessage:d}=await import("@ethersproject/hash");return await s.signMessage({hash:d(e.hexToString(n)),implementationType:t.implementationType||t.type,chainId:Number(t.chainId),signer:o,address:i,salt:t.salt,factoryAddress:t.factoryAddress,ownerAddress:t.ownerAddress})};
1
+ "use strict";var e=require("./JsonRpcError.cjs"),r=require("./walletHelpers.cjs");exports.personalSign=async({params:s,signer:a,account:o})=>{const t=s[0],n=s[1];if(!n||!t)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"personal_sign requires an address and a message");if(n.toLowerCase()!==o.address.toLowerCase())throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"personal_sign requires the signer to be the from address");const{hashMessage:i}=await import("@ethersproject/hash"),{arrayify:d,isHexString:p}=await import("@ethersproject/bytes"),c=p(t)?d(t):t;return await r.signMessage({hash:i(c),implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:n,salt:o.salt,factoryAddress:o.factoryAddress,ownerAddress:o.ownerAddress})};
package/dist/index.d.cts CHANGED
@@ -11856,6 +11856,13 @@ type OpenfortSDKConfiguration = {
11856
11856
  overrides?: SDKOverrides;
11857
11857
  thirdPartyAuth?: ThirdPartyAuthConfiguration;
11858
11858
  debug?: boolean;
11859
+ /**
11860
+ * Disable anonymous error telemetry (Sentry). Telemetry is best-effort and
11861
+ * never throws, but you can turn it off entirely — for example in React
11862
+ * Native, where the telemetry SDK's dynamic import is unnecessary overhead.
11863
+ * Defaults to `false`.
11864
+ */
11865
+ disableTelemetry?: boolean;
11859
11866
  };
11860
11867
  declare class SDKConfiguration {
11861
11868
  readonly baseConfiguration: OpenfortConfiguration;
@@ -11867,8 +11874,9 @@ declare class SDKConfiguration {
11867
11874
  readonly storage?: IStorage;
11868
11875
  readonly nativeAppIdentifier?: string;
11869
11876
  readonly debug?: boolean;
11877
+ readonly disableTelemetry?: boolean;
11870
11878
  static instance: SDKConfiguration | null;
11871
- constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug }: OpenfortSDKConfiguration);
11879
+ constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug, disableTelemetry, }: OpenfortSDKConfiguration);
11872
11880
  static getInstance(): SDKConfiguration | null;
11873
11881
  }
11874
11882
 
package/dist/index.d.ts CHANGED
@@ -11856,6 +11856,13 @@ type OpenfortSDKConfiguration = {
11856
11856
  overrides?: SDKOverrides;
11857
11857
  thirdPartyAuth?: ThirdPartyAuthConfiguration;
11858
11858
  debug?: boolean;
11859
+ /**
11860
+ * Disable anonymous error telemetry (Sentry). Telemetry is best-effort and
11861
+ * never throws, but you can turn it off entirely — for example in React
11862
+ * Native, where the telemetry SDK's dynamic import is unnecessary overhead.
11863
+ * Defaults to `false`.
11864
+ */
11865
+ disableTelemetry?: boolean;
11859
11866
  };
11860
11867
  declare class SDKConfiguration {
11861
11868
  readonly baseConfiguration: OpenfortConfiguration;
@@ -11867,8 +11874,9 @@ declare class SDKConfiguration {
11867
11874
  readonly storage?: IStorage;
11868
11875
  readonly nativeAppIdentifier?: string;
11869
11876
  readonly debug?: boolean;
11877
+ readonly disableTelemetry?: boolean;
11870
11878
  static instance: SDKConfiguration | null;
11871
- constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug }: OpenfortSDKConfiguration);
11879
+ constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug, disableTelemetry, }: OpenfortSDKConfiguration);
11872
11880
  static getInstance(): SDKConfiguration | null;
11873
11881
  }
11874
11882
 
@@ -1 +1 @@
1
- import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as t,AuthenticationError as r,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{StorageKeys as m}from"../storage/istorage.js";import{OpenfortEvents as y,RecoveryMethod as g,ChainTypeEnum as l,AccountTypeEnum as p,EmbeddedState as f}from"../types/types.js";import{debugLog as u}from"../utils/debug.js";import{observe as w}from"../utils/observe.js";import{EmbeddedSigner as A}from"../wallets/embedded.js";import{EvmProvider as E}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as v,openfortProviderInfo as M}from"../wallets/evm/provider/eip6963.js";import{signMessage as T}from"../wallets/evm/walletHelpers.js";import{IframeManager as D}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import S from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class k{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(y.ON_LOGOUT,()=>{u("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=n.getInstance();if(!r)throw new t("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(u("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(u("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return u("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return u("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;u("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return u("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,u("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw u("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){u("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw u("[HANDSHAKE DEBUG] Configuration not found"),new t("Configuration not found");let r;if(u("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)u("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(u("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),u("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{u("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new S({remoteWindow:t.contentWindow,allowedOrigins:[s]}),u("[HANDSHAKE DEBUG] Created WindowMessenger")}return u("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,r)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(u("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();await e.initialize();return new A(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new t("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await d.fromStorage(this.storage);if(!t?.userId)throw new r("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case g.PASSWORD:return{recoveryPassword:e.password};case g.AUTOMATIC:return{encryptionSession:e.encryptionSession};case g.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new t("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},[r,s]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??p.SMART_ACCOUNT,chainType:e.chainType??l.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await r.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(r.recoveryMethod===g.PASSKEY){if(!a.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),m=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async import(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(r.recoveryMethod===g.PASSKEY){if(!a.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),m=await n.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC};if(r.recoveryMethod===g.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new t("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=t||{},i=await o.fromStorage(this.storage);return await r.sign(e,a,s,i?.chainType)}async signTypedData(e,t,r){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...t};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,r);return await T({hash:h,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,r){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,y,l;if(e.recoveryMethod===g.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new t("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new t("missing passkey id for account");if(!n.userId)throw new t("User ID is required for passkey key derivation");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:n.userId})}}else if(r.recoveryMethod===g.PASSKEY){if(!n.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?h=e.password:r.recoveryMethod===g.PASSWORD&&(h=r.password),e.recoveryMethod===g.AUTOMATIC?m=e.encryptionSession:r.recoveryMethod===g.AUTOMATIC&&(m=r.encryptionSession),!h&&!m)throw new t("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:r.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,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:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={...e},a=n.getInstance();if(!a)throw new t("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(r,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({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:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return f.UNAUTHENTICATED;return await o.fromStorage(this.storage)?f.READY:f.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return u("Failed to get embedded state:",e),f.UNAUTHENTICATED}}watchEmbeddedState(e){return w("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},t=>{let r;const s=async()=>{try{const e=await this.getEmbeddedState();r!==e&&(t.onChange?.(e,r),r=e)}catch(e){t.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(y.ON_AUTH_SUCCESS,a),this.eventEmitter.on(y.ON_LOGOUT,i),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(y.ON_AUTH_SUCCESS,a),this.eventEmitter.off(y.ON_LOGOUT,i),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},r=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&t.feeSponsorship&&this.provider.updateFeeSponsorship(t.feeSponsorship):(this.provider=new E({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:t.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&v({info:{...M,...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 d.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.userId),!0}catch(e){return!1}return t.isLoaded()}catch(e){return u("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new t("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new t("Invalid message poster");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(){if(this.storage.remove(m.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return u("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 u("Invalid message received:",e);u("[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 u("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();u(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&u("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),u("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),u("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{k as EmbeddedWalletApi};
1
+ import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as r,AuthenticationError as t,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{StorageKeys as m}from"../storage/istorage.js";import{OpenfortEvents as y,RecoveryMethod as g,ChainTypeEnum as l,AccountTypeEnum as p,EmbeddedState as f}from"../types/types.js";import{debugLog as u}from"../utils/debug.js";import{observe as w}from"../utils/observe.js";import{EmbeddedSigner as A}from"../wallets/embedded.js";import{EvmProvider as E}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as v,openfortProviderInfo as M}from"../wallets/evm/provider/eip6963.js";import{signMessage as T}from"../wallets/evm/walletHelpers.js";import{IframeManager as D}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import S from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class k{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(y.ON_LOGOUT,()=>{u("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=n.getInstance();if(!t)throw new r("Configuration not found");return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(u("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(u("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return u("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return u("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;u("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return u("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,u("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw u("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){u("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw u("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(u("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)u("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(u("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),u("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{u("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new S({remoteWindow:r.contentWindow,allowedOrigins:[s]}),u("[HANDSHAKE DEBUG] Created WindowMessenger")}return u("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(u("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();await e.initialize();return new A(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.referrerPolicy="strict-origin-when-cross-origin",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const r=await d.fromStorage(this.storage);if(!r?.userId)throw new t("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:r.userId})}async getEntropy(e){switch(e.recoveryMethod){case g.PASSWORD:return{recoveryPassword:e.password};case g.AUTOMATIC:return{encryptionSession:e.encryptionSession};case g.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??p.SMART_ACCOUNT,chainType:e.chainType??l.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===g.PASSKEY){if(!a.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),m=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async import(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===g.PASSKEY){if(!a.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),m=await n.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC};if(t.recoveryMethod===g.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await o.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...r};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,t);return await T({hash:h,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 a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,y,l;if(e.recoveryMethod===g.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new r("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r("missing passkey id for account");if(!n.userId)throw new r("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:n.userId})}}else if(t.recoveryMethod===g.PASSKEY){if(!n.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?h=e.password:t.recoveryMethod===g.PASSWORD&&(h=t.password),e.recoveryMethod===g.AUTOMATIC?m=e.encryptionSession:t.recoveryMethod===g.AUTOMATIC&&(m=t.encryptionSession),!h&&!m)throw new r("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,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:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},a=n.getInstance();if(!a)throw new r("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({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:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return f.UNAUTHENTICATED;return await o.fromStorage(this.storage)?f.READY:f.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return u("Failed to get embedded state:",e),f.UNAUTHENTICATED}}watchEmbeddedState(e){return w("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(y.ON_AUTH_SUCCESS,a),this.eventEmitter.on(y.ON_LOGOUT,i),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(y.ON_AUTH_SUCCESS,a),this.eventEmitter.off(y.ON_LOGOUT,i),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new E({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&v({info:{...M,...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 d.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return u("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new r("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r("Invalid message poster");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(){if(this.storage.remove(m.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return u("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 u("Invalid message received:",e);u("[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 u("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();u(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&u("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),u("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),u("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{k as EmbeddedWalletApi};
@@ -1 +1 @@
1
- import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class i{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class s{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:s,overrides:a,thirdPartyAuth:r,debug:h}){this.shieldConfiguration=s,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=h,s?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{i as OpenfortConfiguration,t as SDKConfiguration,s as ShieldConfiguration};
1
+ import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class i{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class s{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;disableTelemetry;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:s,overrides:a,thirdPartyAuth:r,debug:l,disableTelemetry:h}){this.shieldConfiguration=s,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=l,this.disableTelemetry=h,s?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{i as OpenfortConfiguration,t as SDKConfiguration,s as ShieldConfiguration};
@@ -1 +1 @@
1
- import{AxiosError as e}from"axios";import{PACKAGE as t,VERSION as s}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const s=t.getDsn();if(!s)throw new Error("Sentry DSN is not set");if(s.projectId!==r.split("https://")[1].split("/")[1]||s.host!==r.split("@")[1].split("/")[0]||s.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,r,o,a)=>{if(r instanceof e){if(400===r.response?.status||401===r.response?.status)return;r.name=s,t.captureException(r,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:s}}})}else t.captureException(r,o,a)},t.captureError=(e,s,r,o)=>{const a=s.statusCode;if(400===a||401===a)return;const c=s,i=c.error,u=c.error_description,p=r?.captureContext;t.captureException(s,{...r,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...n.baseTags,context:e,errorClass:s.constructor.name}}})},n.sentryInstance=t}static get sentry(){return n.proxy}static async init({sentry:e,configuration:o}){if(e)return void(n.sentry=e);const a=await import("@sentry/browser");n.sentry=new a.BrowserClient({dsn:r,release:`${t}@${s}`,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),n.baseTags={projectId:o?.baseConfiguration.publishableKey??"",sdk:t,sdkVersion:s},n.processQueuedCalls()}static proxy=new Proxy({},{get:(e,t)=>n.sentryInstance&&"function"==typeof n.sentryInstance[t]?(...e)=>n.sentryInstance[t](...e):(...e)=>{n.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof n.sentryInstance[e]&&n.sentryInstance[e](...t)}),n.queuedCalls=[])}}const{sentry:o}=n;export{n as InternalSentry,o as sentry};
1
+ import{AxiosError as e}from"axios";import{PACKAGE as t,VERSION as s}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const s=t.getDsn();if(!s)throw new Error("Sentry DSN is not set");if(s.projectId!==r.split("https://")[1].split("/")[1]||s.host!==r.split("@")[1].split("/")[0]||s.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,r,o,a)=>{if(r instanceof e){if(400===r.response?.status||401===r.response?.status)return;r.name=s,t.captureException(r,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:s}}})}else t.captureException(r,o,a)},t.captureError=(e,s,r,o)=>{const a=s.statusCode;if(400===a||401===a)return;const c=s,i=c.error,u=c.error_description,p=r?.captureContext;t.captureException(s,{...r,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...n.baseTags,context:e,errorClass:s.constructor.name}}})},n.sentryInstance=t}static get sentry(){return n.proxy}static async init({sentry:e,configuration:o}){if(e)n.sentry=e;else if(!o?.disableTelemetry)try{const e=await import("@sentry/browser");n.sentry=new e.BrowserClient({dsn:r,release:`${t}@${s}`,integrations:[],stackParser:e.defaultStackParser,transport:e.makeFetchTransport}),n.baseTags={projectId:o?.baseConfiguration.publishableKey??"",sdk:t,sdkVersion:s},n.processQueuedCalls()}catch{}}static proxy=new Proxy({},{get:(e,t)=>n.sentryInstance&&"function"==typeof n.sentryInstance[t]?(...e)=>n.sentryInstance[t](...e):(...e)=>{n.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof n.sentryInstance[e]&&n.sentryInstance[e](...t)}),n.queuedCalls=[])}}const{sentry:o}=n;export{n as InternalSentry,o as sentry};
@@ -1 +1 @@
1
- import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as t}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{OPENFORT_AUTH_ERROR_CODES as d,OPENFORT_ERROR_CODES as c}from"./errors/authErrorCodes.js";import{ConfigurationError as u,SignerError as g,RequestError as m,OpenfortError as f}from"./errors/openfortError.js";import{InternalSentry as p}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";import{PasskeyHandler as w}from"./passkey/handler.js";class y{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("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s,this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t(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 g(d.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l(e),this.storage=new o(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,y.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{y.globalEventEmitter?.emit(e,...t)})})}else y.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new w({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),p.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return y.globalEventEmitter||(y.globalEventEmitter=new h),y.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({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 m("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.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(){if(!await y.isStorageAccessible(this.storage))throw new f("Storage is not accessible",c.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{y as Openfort};
1
+ import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as t}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{ProxyApi as n}from"../api/proxy.js";import{UserApi as s}from"../api/user.js";import{AuthManager as a}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{OPENFORT_AUTH_ERROR_CODES as d,OPENFORT_ERROR_CODES as c}from"./errors/authErrorCodes.js";import{ConfigurationError as u,SignerError as g,RequestError as m,OpenfortError as p}from"./errors/openfortError.js";import{InternalSentry as f}from"./errors/sentry.js";import{OpenfortInternal as y}from"./openfortInternal.js";import{PasskeyHandler as w}from"./passkey/handler.js";class I{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("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new a,this.openfortInternal=new y(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t(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 s(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 g(d.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l(e),this.storage=new o(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,I.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{I.globalEventEmitter?.emit(e,...t)})})}else I.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new w({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),f.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return I.globalEventEmitter||(I.globalEventEmitter=new h),I.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({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 m("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.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(){if(!await I.isStorageAccessible(this.storage))throw new p("Storage is not accessible. The SDK needs a working key/value store to persist the session. On React Native, ensure the app is code-signed (an unsigned build cannot use the keychain) and that expo-secure-store — or your `overrides.storage` implementation — is installed and reachable.",c.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{I as Openfort};
@@ -1 +1 @@
1
- function t(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const n=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${n}`:n}).join("")}function r(t){return`0x${t.toString(16)}`}function n(t){let r="";const n=t.startsWith("0x")?t.slice(2):t;for(let t=0;t<n.length;t+=2){const e=parseInt(n.substring(t,t+2),16);0!==e&&(r+=String.fromCharCode(e))}return r}let e;function o(t){e=t}async function i(t,r){if(e)return e(t,r);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(t,r);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")}export{i as cryptoDigest,n as hexToString,r as numberToHex,t as randomUUID,o as setCryptoDigestOverride};
1
+ function t(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const n=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${n}`:n}).join("")}function r(t){return`0x${t.toString(16)}`}let n;function e(t){n=t}async function o(t,r){if(n)return n(t,r);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(t,r);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")}export{o as cryptoDigest,r as numberToHex,t as randomUUID,e as setCryptoDigestOverride};
@@ -1 +1 @@
1
- const o="1.3.8",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="1.4.0",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -1 +1 @@
1
- import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as s,AccountTypeEnum as a}from"../../types/types.js";import{defaultChainRpcs as i}from"../../utils/chains/index.js";import{numberToHex as r}from"../../utils/crypto.js";import o from"../../utils/typedEventEmitter.js";import{addEthereumChain as n}from"./addEthereumChain.js";import{estimateGas as h}from"./estimateGas.js";import{getAssets as c}from"./getAssets.js";import{getCallStatus as p}from"./getCallsStatus.js";import{JsonRpcError as d,ProviderErrorCode as m,RpcErrorCode as w}from"./JsonRpcError.js";import{personalSign as u}from"./personalSign.js";import{registerSession as l}from"./registerSession.js";import{revokeSession as g}from"./revokeSession.js";import{sendCallsSync as f}from"./sendCallSync.js";import{sendCalls as S}from"./sendCalls.js";import{signTypedDataV4 as A}from"./signTypedDataV4.js";import{ProviderEvent as R}from"./types.js";import{prepareEOATransaction as v,parseTransactionRequest as _}from"./walletHelpers.js";class E{#t;#e;#s;#a;updateFeeSponsorship(t){this.#e=t}#i;#r;#o=null;#n;isOpenfort=!0;#h;constructor({storage:t,backendApiClients:e,openfortEventEmitter:a,feeSponsorshipId:i,ensureSigner:r,chains:n,validateAndRefreshSession:h}){this.#h=r,this.#t=t,this.#s=n,this.#e=i,this.#i=h,this.#n=e,this.#r=new o,a.on(s.ON_LOGOUT,this.#c),a.on(s.ON_SWITCH_ACCOUNT,this.#p)}#d=async()=>(this.#a||(this.#a=await this.#h()),this.#a);#c=async()=>{this.#a=void 0,this.#r.emit(R.DISCONNECT,{code:4900,message:"Disconnected"}),this.#r.emit(R.ACCOUNTS_CHANGED,[])};#p=async t=>{this.#r.emit(R.ACCOUNTS_CHANGED,[t])};async getRpcProvider(){if(!this.#o){const e=await t.fromStorage(this.#t),s=e?.chainId||(this.#s?Number(Object.keys(this.#s)[0]):void 0)||8453;await import("@ethersproject/providers").then(t=>{const e=this.#s?this.#s[s]:void 0;this.#o=new t.StaticJsonRpcProvider(e??i[s])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#m(s){switch(s.method){case"eth_accounts":{const e=await t.fromStorage(this.#t);return e?[e.address]:[]}case"eth_requestAccounts":{const e=await t.fromStorage(this.#t);if(e){const t=await this.getRpcProvider(),{chainId:s}=await t.detectNetwork();return this.#r.emit(R.ACCOUNTS_CONNECT,{chainId:r(s)}),[e.address]}throw new d(m.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const a=await t.fromStorage(this.#t),i=await this.#d(),r=await e.fromStorage(this.#t);if(!a||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[h]=s.params||[];h.chainId||(h.chainId=n.toString());const c=_(h),{serialize:p}=await import("@ethersproject/transactions"),w=t=>({legacy:0,eip2930:1,eip1559:2}[t]),{gas:u,...l}=c,g={...l,gasLimit:u,to:c.to??void 0,type:w(c.type)},f=p(g),{keccak256:S}=await import("@ethersproject/keccak256"),A=S(f);await this.#i();const R=await i.sign(A,!1,!1),{splitSignature:v}=await import("@ethersproject/bytes");return p(g,v(R))}case"eth_sendTransaction":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#i(),i?.accountType===a.EOA){const[t]=s.params||[],e=await this.getRpcProvider(),a=await v(t,e,i.address),r=await this.#m({method:"eth_signTransaction",params:[a]});return this.#m({method:"eth_sendRawTransaction",params:[r]})}return(await f({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);return await this.#i(),await f({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})}case"eth_estimateGas":{const a=await t.fromStorage(this.#t),i=await e.fromStorage(this.#t);if(!a||!i)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await h({params:s.params||[],account:a,authentication:i,backendClient:this.#n,feeSponsorshipId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await t.fromStorage(this.#t),a=await this.#d();if(!e)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();const i=await this.getRpcProvider();return await A({method:s.method,params:s.params||[],signer:a,implementationType:e.implementationType||e.type,rpcProvider:i,account:e})}case"personal_sign":{const e=await t.fromStorage(this.#t);if(!e)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const a=await this.#d();return await this.#i(),await u({params:s.params||[],signer:a,account:e})}case"eth_chainId":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return r(e)}case"wallet_switchEthereumChain":{const t=await this.#d();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new d(w.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#i();try{const e=parseInt(s.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const s=this.#s?this.#s[e]:void 0;this.#o=new t.StaticJsonRpcProvider(s??i[e])}),this.#r.emit(R.CHAIN_CHANGED,r(e))}catch(t){const e=t;throw new d(w.INTERNAL_ERROR,`Failed to switch chain: ${e.message}`)}return null}case"wallet_addEthereumChain":{await this.#d();const t=await this.getRpcProvider();return await n({params:s.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const i=await t.fromStorage(this.#t);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const r=await e.fromStorage(this.#t);if(!i||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await p({params:s.params||{},authentication:r,backendClient:this.#n})}case"wallet_sendCalls":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();return await S({params:s.params?s.params[0].calls:[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})}case"wallet_grantPermissions":{const i=await t.fromStorage(this.#t);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const r=await this.#d(),o=await e.fromStorage(this.#t);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await l({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#e})}case"wallet_revokePermissions":{const a=await t.fromStorage(this.#t),i=await this.#d(),r=await e.fromStorage(this.#t);if(!a||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await g({params:s.params||[],signer:i,account:a,authentication:r,backendClient:this.#n,feeSponsorshipId:this.#e})}case"wallet_getCapabilities":{const e=await t.fromStorage(this.#t);if(e?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await this.getRpcProvider(),{chainId:o}=await i.detectNetwork();return{[r(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const a=await t.fromStorage(this.#t),i=await e.fromStorage(this.#t);if(!a||!i)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await c({params:s.params?.[0],account:a,authentication:i,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(s.method,s.params||[]);default:throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(t){try{return this.#m(t)}catch(t){if(t instanceof d)throw t;if(t instanceof Error)throw new d(w.INTERNAL_ERROR,t.message);throw new d(w.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{E as EvmProvider};
1
+ import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as s,AccountTypeEnum as a}from"../../types/types.js";import{defaultChainRpcs as i}from"../../utils/chains/index.js";import{numberToHex as r}from"../../utils/crypto.js";import o from"../../utils/typedEventEmitter.js";import{addEthereumChain as n}from"./addEthereumChain.js";import{estimateGas as h}from"./estimateGas.js";import{getAssets as c}from"./getAssets.js";import{getCallStatus as p}from"./getCallsStatus.js";import{JsonRpcError as d,ProviderErrorCode as m,RpcErrorCode as w}from"./JsonRpcError.js";import{normalizeRpcErrorMessage as u}from"./normalizeRpcError.js";import{personalSign as l}from"./personalSign.js";import{registerSession as g}from"./registerSession.js";import{revokeSession as f}from"./revokeSession.js";import{sendCallsSync as S}from"./sendCallSync.js";import{sendCalls as A}from"./sendCalls.js";import{signTypedDataV4 as R}from"./signTypedDataV4.js";import{ProviderEvent as v}from"./types.js";import{prepareEOATransaction as _,parseTransactionRequest as E}from"./walletHelpers.js";class C{#t;#e;#s;#a;updateFeeSponsorship(t){this.#e=t}#i;#r;#o=null;#n;isOpenfort=!0;#h;constructor({storage:t,backendApiClients:e,openfortEventEmitter:a,feeSponsorshipId:i,ensureSigner:r,chains:n,validateAndRefreshSession:h}){this.#h=r,this.#t=t,this.#s=n,this.#e=i,this.#i=h,this.#n=e,this.#r=new o,a.on(s.ON_LOGOUT,this.#c),a.on(s.ON_SWITCH_ACCOUNT,this.#p)}#d=async()=>(this.#a||(this.#a=await this.#h()),this.#a);#c=async()=>{this.#a=void 0,this.#r.emit(v.DISCONNECT,{code:4900,message:"Disconnected"}),this.#r.emit(v.ACCOUNTS_CHANGED,[])};#p=async t=>{this.#r.emit(v.ACCOUNTS_CHANGED,[t])};async getRpcProvider(){if(!this.#o){const e=await t.fromStorage(this.#t),s=e?.chainId||(this.#s?Number(Object.keys(this.#s)[0]):void 0)||8453;await import("@ethersproject/providers").then(t=>{const e=this.#s?this.#s[s]:void 0;this.#o=new t.StaticJsonRpcProvider(e??i[s])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#m(s){switch(s.method){case"eth_accounts":{const e=await t.fromStorage(this.#t);return e?[e.address]:[]}case"eth_requestAccounts":{const e=await t.fromStorage(this.#t);if(e){const t=await this.getRpcProvider(),{chainId:s}=await t.detectNetwork();return this.#r.emit(v.ACCOUNTS_CONNECT,{chainId:r(s)}),[e.address]}throw new d(m.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const a=await t.fromStorage(this.#t),i=await this.#d(),r=await e.fromStorage(this.#t);if(!a||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[h]=s.params||[];h.chainId||(h.chainId=n.toString());const c=E(h),{serialize:p}=await import("@ethersproject/transactions"),w=t=>({legacy:0,eip2930:1,eip1559:2}[t]),{gas:u,...l}=c,g={...l,gasLimit:u,to:c.to??void 0,type:w(c.type)},f=p(g),{keccak256:S}=await import("@ethersproject/keccak256"),A=S(f);await this.#i();const R=await i.sign(A,!1,!1),{splitSignature:v}=await import("@ethersproject/bytes");return p(g,v(R))}case"eth_sendTransaction":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#i(),i?.accountType===a.EOA){const[t]=s.params||[],e=await this.getRpcProvider(),a=await _(t,e,i.address),r=await this.#m({method:"eth_signTransaction",params:[a]});return this.#m({method:"eth_sendRawTransaction",params:[r]})}return(await S({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);return await this.#i(),await S({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})}case"eth_estimateGas":{const a=await t.fromStorage(this.#t),i=await e.fromStorage(this.#t);if(!a||!i)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await h({params:s.params||[],account:a,authentication:i,backendClient:this.#n,feeSponsorshipId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await t.fromStorage(this.#t),a=await this.#d();if(!e)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();const i=await this.getRpcProvider();return await R({method:s.method,params:s.params||[],signer:a,implementationType:e.implementationType||e.type,rpcProvider:i,account:e})}case"personal_sign":{const e=await t.fromStorage(this.#t);if(!e)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const a=await this.#d();return await this.#i(),await l({params:s.params||[],signer:a,account:e})}case"eth_chainId":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return r(e)}case"wallet_switchEthereumChain":{const t=await this.#d();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new d(w.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#i();try{const e=parseInt(s.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const s=this.#s?this.#s[e]:void 0;this.#o=new t.StaticJsonRpcProvider(s??i[e])}),this.#r.emit(v.CHAIN_CHANGED,r(e))}catch(t){const e=t;throw new d(w.INTERNAL_ERROR,`Failed to switch chain: ${e.message}`)}return null}case"wallet_addEthereumChain":{await this.#d();const t=await this.getRpcProvider();return await n({params:s.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const i=await t.fromStorage(this.#t);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const r=await e.fromStorage(this.#t);if(!i||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await p({params:s.params||{},authentication:r,backendClient:this.#n})}case"wallet_sendCalls":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();return await A({params:s.params?s.params[0].calls:[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})}case"wallet_grantPermissions":{const i=await t.fromStorage(this.#t);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const r=await this.#d(),o=await e.fromStorage(this.#t);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await g({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#e})}case"wallet_revokePermissions":{const a=await t.fromStorage(this.#t),i=await this.#d(),r=await e.fromStorage(this.#t);if(!a||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await f({params:s.params||[],signer:i,account:a,authentication:r,backendClient:this.#n,feeSponsorshipId:this.#e})}case"wallet_getCapabilities":{const e=await t.fromStorage(this.#t);if(e?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await this.getRpcProvider(),{chainId:o}=await i.detectNetwork();return{[r(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const a=await t.fromStorage(this.#t),i=await e.fromStorage(this.#t);if(!a||!i)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await c({params:s.params?.[0],account:a,authentication:i,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(s.method,s.params||[]);default:throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(t){try{return await this.#m(t)}catch(t){if(t instanceof d)throw t;if(t instanceof Error)throw new d(w.INTERNAL_ERROR,u(t.message));throw new d(w.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{C as EvmProvider};
@@ -0,0 +1 @@
1
+ function e(e){const n=e.toLowerCase();return n.includes("insufficient funds")?"Insufficient funds: the wallet doesn't have enough native token to cover gas (plus any value). Top up the wallet and try again.":n.includes("execution reverted")||n.includes("reverted")?"Transaction reverted: the contract rejected this call.":n.includes("nonce too low")||n.includes("replacement transaction underpriced")?"Nonce conflict: another transaction from this wallet is still pending. Wait for it to confirm, then retry.":n.includes("intrinsic gas too low")||n.includes("gas required exceeds")||n.includes("out of gas")?"Gas error: the transaction needs more gas than is available or allowed.":e}export{e as normalizeRpcErrorMessage};
@@ -1 +1 @@
1
- import{hexToString as e}from"../../utils/crypto.js";import{JsonRpcError as s,RpcErrorCode as r}from"./JsonRpcError.js";import{signMessage as a}from"./walletHelpers.js";const t=async({params:t,signer:o,account:n})=>{const i=t[0],d=t[1];if(!d||!i)throw new s(r.INVALID_PARAMS,"personal_sign requires an address and a message");if(d.toLowerCase()!==n.address.toLowerCase())throw new s(r.INVALID_PARAMS,"personal_sign requires the signer to be the from address");const{hashMessage:p}=await import("@ethersproject/hash");return await a({hash:p(e(i)),implementationType:n.implementationType||n.type,chainId:Number(n.chainId),signer:o,address:d,salt:n.salt,factoryAddress:n.factoryAddress,ownerAddress:n.ownerAddress})};export{t as personalSign};
1
+ import{JsonRpcError as e,RpcErrorCode as s}from"./JsonRpcError.js";import{signMessage as r}from"./walletHelpers.js";const a=async({params:a,signer:t,account:o})=>{const n=a[0],i=a[1];if(!i||!n)throw new e(s.INVALID_PARAMS,"personal_sign requires an address and a message");if(i.toLowerCase()!==o.address.toLowerCase())throw new e(s.INVALID_PARAMS,"personal_sign requires the signer to be the from address");const{hashMessage:d}=await import("@ethersproject/hash"),{arrayify:p,isHexString:h}=await import("@ethersproject/bytes"),m=h(n)?p(n):n;return await r({hash:d(m),implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:t,address:i,salt:o.salt,factoryAddress:o.factoryAddress,ownerAddress:o.ownerAddress})};export{a as personalSign};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfort/openfort-js",
3
- "version": "1.3.8",
3
+ "version": "1.4.0",
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",