@openfort/openfort-js 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/src/api/embeddedWallet.cjs +1 -1
- package/dist/cjs/sdk/src/types/types.cjs +1 -1
- package/dist/cjs/sdk/src/utils/observe.cjs +1 -0
- package/dist/cjs/sdk/src/version.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/evm/evmProvider.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/evm/types.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/evm/walletHelpers.cjs +1 -1
- package/dist/index.d.cts +26 -2
- package/dist/index.d.ts +26 -2
- package/dist/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/sdk/src/types/types.js +1 -1
- package/dist/sdk/src/utils/observe.js +1 -0
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/evm/evmProvider.js +1 -1
- package/dist/sdk/src/wallets/evm/types.js +1 -1
- package/dist/sdk/src/wallets/evm/walletHelpers.js +1 -1
- package/package.json +1 -1
|
@@ -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"),i=require("../core/configuration/authentication.cjs"),n=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../wallets/embedded.cjs"),h=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var u=require("../wallets/evm/provider/eip6963.cjs"),y=require("../wallets/evm/walletHelpers.cjs"),l=require("../wallets/iframeManager.cjs"),m=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var f=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(d.OpenfortEvents.ON_LOGOUT,()=>{c.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(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new m.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new f({remoteWindow:r.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new l.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(c.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 g.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 i.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 d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.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:d.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:s,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await i.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===d.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[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.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,i]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),n=await s.recover({account:e.account,entropy:i}),o={id:n.id,chainId:n.chainId,implementationAddress:n.implementationAddress,factoryAddress:n.factoryAddress,salt:n.salt,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,createdAt:n.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:i=!1}=r||{},n=await a.Account.fromStorage(this.storage);return await t.sign(e,i,s,n?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const i=await this.ensureSigner(),o=await a.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,s);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:i,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(),c=await i.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.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(!c.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");u={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:c.userId})}}else if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:s.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=s.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:s.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=s.encryptionSession),!g&&!h)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await a.Account.fromStorage(this.storage);l&&new a.Account({...l,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await i.Authentication.fromStorage(this.storage))throw new r.SessionError(n.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 i.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(n.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 i.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await i.Authentication.fromStorage(this.storage),s=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new h.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&u.announceProvider({info:{...u.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 i.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.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("undefined"==typeof document&&!this.messagePoster)return c.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 c.debugLog("Invalid message received:",e);c.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 c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.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"),n=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),h=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var y=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),m=require("../wallets/iframeManager.cjs"),f=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var p=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,n){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=n,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.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(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new f.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new p({remoteWindow:r.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new m.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(c.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 h.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 a.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 d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.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:d.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.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:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===d.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[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.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,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),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:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await n.Account.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await n.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"),g=c.hash(e,d,s);return await l.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await n.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(!c.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");u={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:c.userId})}}else if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:s.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=s.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:s.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=s.encryptionSession),!g&&!h)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await n.Account.fromStorage(this.storage);l&&new n.Account({...l,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await n.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await a.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:n.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 a.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:n.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await n.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.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 n=()=>s(),a=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(d.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.on(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const c=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(c),this.eventEmitter.off(d.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.off(d.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.off(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.Authentication.fromStorage(this.storage),s=await n.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(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,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&y.announceProvider({info:{...y.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 a.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.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("undefined"==typeof document&&!this.messagePoster)return c.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 c.debugLog("Invalid message received:",e);c.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 c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,t,o,E,
|
|
1
|
+
"use strict";var e,t,o,r,E,A,T,p,s,i,d,n;exports.EmbeddedState=void 0,(e=exports.EmbeddedState||(exports.EmbeddedState={}))[e.NONE=0]="NONE",e[e.UNAUTHENTICATED=1]="UNAUTHENTICATED",e[e.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",e[e.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",e[e.READY=4]="READY",exports.OpenfortEvents=void 0,(t=exports.OpenfortEvents||(exports.OpenfortEvents={})).ON_AUTH_INIT="onAuthInit",t.ON_AUTH_SUCCESS="onAuthSuccess",t.ON_OTP_REQUEST="onOtpRequest",t.ON_OTP_FAILURE="onOtpFailure",t.ON_AUTH_FAILURE="onAuthFailure",t.ON_LOGOUT="onLogout",t.ON_SWITCH_ACCOUNT="onSwitchAccount",t.ON_SIGNED_MESSAGE="onSignedMessage",t.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",t.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered",exports.RecoveryMethod=void 0,(o=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",o.AUTOMATIC="automatic",o.PASSKEY="passkey",exports.AccountType=void 0,(r=exports.AccountType||(exports.AccountType={})).UPGRADEABLE_V5="UpgradeableV5",r.UPGRADEABLE_V6="UpgradeableV6",r.SIMPLE="Simple",r.CALIBUR="Calibur",r.CALIBUR_V9="CaliburV9",exports.AuthType=void 0,(E=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",E.THIRD_PARTY="thirdParty",exports.TokenType=void 0,(A=exports.TokenType||(exports.TokenType={})).ID_TOKEN="idToken",A.CUSTOM_TOKEN="customToken",exports.ThirdPartyAuthProvider=void 0,(T=exports.ThirdPartyAuthProvider||(exports.ThirdPartyAuthProvider={})).ACCELBYTE="accelbyte",T.FIREBASE="firebase",T.BETTER_AUTH="better-auth",T.LOOTLOCKER="lootlocker",T.PLAYFAB="playfab",T.SUPABASE="supabase",T.CUSTOM="custom",T.OIDC="oidc",exports.BasicAuthProvider=void 0,(p=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",p.WALLET="wallet",exports.OAuthProvider=void 0,(s=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",s.TWITTER="twitter",s.APPLE="apple",s.FACEBOOK="facebook",s.DISCORD="discord",s.EPIC_GAMES="epic_games",s.LINE="line",exports.AuthActionRequiredActions=void 0,(exports.AuthActionRequiredActions||(exports.AuthActionRequiredActions={})).ACTION_VERIFY_EMAIL="verify_email",exports.AccountTypeEnum=void 0,(i=exports.AccountTypeEnum||(exports.AccountTypeEnum={})).EOA="Externally Owned Account",i.SMART_ACCOUNT="Smart Account",i.DELEGATED_ACCOUNT="Delegated Account",exports.ChainTypeEnum=void 0,(d=exports.ChainTypeEnum||(exports.ChainTypeEnum={})).EVM="EVM",d.SVM="SVM",function(e){e.ASC="asc",e.DESC="desc"}(n||(n={}));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const t=new Map,n=new Map;let e=0;exports.observe=function(s,o,c){const f=++e,i=()=>t.get(s)||[],r=()=>{const e=i();if(!e.some(t=>t.id===f))return;const o=n.get(s);if(1===e.length&&o){const t=o();t instanceof Promise&&t.catch(()=>{})}(()=>{const n=i();t.set(s,n.filter(t=>t.id!==f))})()},u=i();if(t.set(s,[...u,{id:f,fns:o}]),u&&u.length>0)return r;const g={};for(const t in o)g[t]=(...n)=>{const e=i();if(0!==e.length)for(const s of e)s.fns[t]?.(...n)};const l=c(g);return"function"==typeof l&&n.set(s,l),r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.2.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.2.1";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),a=require("../../utils/chains/index.cjs"),
|
|
1
|
+
"use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),a=require("../../utils/chains/index.cjs"),i=require("../../utils/crypto.cjs"),s=require("../../utils/typedEventEmitter.cjs"),o=require("./addEthereumChain.cjs"),n=require("./estimateGas.cjs"),c=require("./getAssets.cjs"),h=require("./getCallsStatus.cjs"),d=require("./JsonRpcError.cjs"),u=require("./personalSign.cjs"),p=require("./registerSession.cjs"),l=require("./revokeSession.cjs"),w=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;#a;updatePolicy(e){this.#t=e}#i;#s;#o=null;#n;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:a,policyId:i,ensureSigner:o,chains:n,validateAndRefreshSession:c}){this.#c=o,this.#e=e,this.#r=n,this.#t=i,this.#i=c,this.#n=t,this.#s=new s,a.on(r.OpenfortEvents.ON_LOGOUT,this.#h),a.on(r.OpenfortEvents.ON_SWITCH_ACCOUNT,this.#d)}#u=async()=>(this.#a||(this.#a=await this.#c()),this.#a);#h=async()=>{this.#a=void 0,this.#s.emit(E.ProviderEvent.DISCONNECT,{code:4900,message:"Disconnected"}),this.#s.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#s.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#o){const t=await e.Account.fromStorage(this.#e),r=t?.chainId||8453;await import("@ethersproject/providers").then(e=>{const t=this.#r?this.#r[r]:void 0;this.#o=new e.StaticJsonRpcProvider(t??a.defaultChainRpcs[r])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#p(s){switch(s.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.#s.emit(E.ProviderEvent.ACCOUNTS_CONNECT,{chainId:i.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),a=await this.#u(),i=await t.Authentication.fromStorage(this.#e);if(!r||!i)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=s.params||[];c.chainId||(c.chainId=n.toString());const h=A.parseTransactionRequest(c),{serialize:u}=await import("@ethersproject/transactions"),p=e=>({legacy:0,eip2930:1,eip1559:2}[e]),{gas:l,...w}=h,m={...w,gasLimit:l,to:h.to??void 0,type:p(h.type)},g=u(m),{keccak256:E}=await import("@ethersproject/keccak256"),R=E(g);await this.#i();const v=await a.sign(R,!1,!1),{splitSignature:f}=await import("@ethersproject/bytes");return u(m,f(v))}case"eth_sendTransaction":{const[a,i,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#u(),t.Authentication.fromStorage(this.#e)]);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#i(),a?.accountType===r.AccountTypeEnum.EOA){const[e]=s.params||[],t=await this.getRpcProvider(),r=await A.prepareEOATransaction(e,t,a.address),i=await this.#p({method:"eth_signTransaction",params:[r]});return this.#p({method:"eth_sendRawTransaction",params:[i]})}return(await w.sendCallsSync({params:s.params||[],signer:i,account:a,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#t})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[a,i,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#u(),t.Authentication.fromStorage(this.#e)]);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);return await this.#i(),await w.sendCallsSync({params:s.params||[],signer:i,account:a,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#t})}case"eth_estimateGas":{const r=await e.Account.fromStorage(this.#e),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.#i(),await n.estimateGas({params:s.params||[],account:r,authentication:a,backendClient:this.#n,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),r=await this.#u();if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();const a=await this.getRpcProvider();return await g.signTypedDataV4({method:s.method,params:s.params||[],signer:r,implementationType:t.implementationType||t.type,rpcProvider:a,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.#u();return await this.#i(),await u.personalSign({params:s.params||[],signer:r,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return i.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#u();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new d.JsonRpcError(d.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#i();try{const t=parseInt(s.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??a.defaultChainRpcs[t])}),this.#s.emit(E.ProviderEvent.CHAIN_CHANGED,i.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.#u();const e=await this.getRpcProvider();return await o.addEthereumChain({params:s.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const a=await e.Account.fromStorage(this.#e);if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await t.Authentication.fromStorage(this.#e);if(!a||!i)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await h.getCallStatus({params:s.params||{},authentication:i,backendClient:this.#n})}case"wallet_sendCalls":{const[a,i,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#u(),t.Authentication.fromStorage(this.#e)]);if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();return await m.sendCalls({params:s.params?s.params[0].calls:[],signer:i,account:a,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#t})}case"wallet_grantPermissions":{const a=await e.Account.fromStorage(this.#e);if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await this.#u(),o=await t.Authentication.fromStorage(this.#e);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await p.registerSession({params:s.params||[],signer:i,account:a,authentication:o,backendClient:this.#n,policyId:this.#t})}case"wallet_revokePermissions":{const r=await e.Account.fromStorage(this.#e),a=await this.#u(),i=await t.Authentication.fromStorage(this.#e);if(!r||!i)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await l.revokeSession({params:s.params||[],signer:a,account:r,authentication:i,backendClient:this.#n,policyId: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,`${s.method}: Method not supported`);const a=await this.getRpcProvider(),{chainId:o}=await a.detectNetwork();return{[i.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),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.#i(),await c.getAssets({params:s.params?.[0],account:r,authentication:a,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.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(e){try{return this.#p(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.#s.on(e,t)}removeListener(e,t){this.#s.off(e,t)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e;exports.ProviderEvent=void 0,(e=exports.ProviderEvent||(exports.ProviderEvent={})).ACCOUNTS_CHANGED="accountsChanged",e.ACCOUNTS_CONNECT="connect";
|
|
1
|
+
"use strict";var e;exports.ProviderEvent=void 0,(e=exports.ProviderEvent||(exports.ProviderEvent={})).ACCOUNTS_CHANGED="accountsChanged",e.CHAIN_CHANGED="chainChanged",e.ACCOUNTS_CONNECT="connect",e.DISCONNECT="disconnect";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../types/types.cjs");exports.parseTransactionRequest=function({from:e,...t}){return{to:t.to,data:t.data,accessList:t.accessList,chainId:(i=t.chainId,i.startsWith("0x")?parseInt(i,16):parseInt(i,10)),type:t.type&&{"0x0":"legacy","0x1":"eip2930","0x2":"eip1559"}[t.type]||"eip1559",maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,value:(a=t.value,s=BigInt,r=0n,void 0!==a?s(a):r),nonce:t.nonce?parseInt(t.nonce.toString(),16):void 0,gas:t.gas?BigInt(t.gas):void 0};var a,s,r,i},exports.prepareEOATransaction=async function(e,t,a){const s={...e};if(!s.nonce){const e=await t.getTransactionCount(a,"pending");s.nonce=`0x${e.toString(16)}`}if(!s.gas)try{const e=await t.estimateGas({from:a,to:s.to,data:s.data,value:s.value});s.gas=e.toHexString()}catch{s.gas="0x5208"}const r=s.maxFeePerGas&&s.maxPriorityFeePerGas,i=s.gasPrice;if(!r&&!i){const e=await t.getBlock("latest");if(null!==e.baseFeePerGas&&void 0!==e.baseFeePerGas){const a=e.baseFeePerGas,r=a.mul(12).div(10),i=await t.getGasPrice();let n=i.sub(a);n.lt(0)&&(n=i.mul(0));const o=r.add(n);s.maxFeePerGas=o.toHexString(),s.maxPriorityFeePerGas=n.toHexString(),s.type="0x2",delete s.gasPrice}else{const e=(await t.getGasPrice()).mul(12).div(10);s.gasPrice=e.toHexString(),s.type="0x0",delete s.maxFeePerGas,delete s.maxPriorityFeePerGas}}return s},exports.signMessage=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let p=a;if([e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6
|
|
1
|
+
"use strict";var e=require("../../types/types.cjs");exports.parseTransactionRequest=function({from:e,...t}){return{to:t.to,data:t.data,accessList:t.accessList,chainId:(i=t.chainId,i.startsWith("0x")?parseInt(i,16):parseInt(i,10)),type:t.type&&{"0x0":"legacy","0x1":"eip2930","0x2":"eip1559"}[t.type]||"eip1559",maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,value:(a=t.value,s=BigInt,r=0n,void 0!==a?s(a):r),nonce:t.nonce?parseInt(t.nonce.toString(),16):void 0,gas:t.gas?BigInt(t.gas):void 0};var a,s,r,i},exports.prepareEOATransaction=async function(e,t,a){const s={...e};if(!s.nonce){const e=await t.getTransactionCount(a,"pending");s.nonce=`0x${e.toString(16)}`}if(!s.gas)try{const e=await t.estimateGas({from:a,to:s.to,data:s.data,value:s.value});s.gas=e.toHexString()}catch{s.gas="0x5208"}const r=s.maxFeePerGas&&s.maxPriorityFeePerGas,i=s.gasPrice;if(!r&&!i){const e=await t.getBlock("latest");if(null!==e.baseFeePerGas&&void 0!==e.baseFeePerGas){const a=e.baseFeePerGas,r=a.mul(12).div(10),i=await t.getGasPrice();let n=i.sub(a);n.lt(0)&&(n=i.mul(0));const o=r.add(n);s.maxFeePerGas=o.toHexString(),s.maxPriorityFeePerGas=n.toHexString(),s.type="0x2",delete s.gasPrice}else{const e=(await t.getGasPrice()).mul(12).div(10);s.gasPrice=e.toHexString(),s.type="0x0",delete s.maxFeePerGas,delete s.maxPriorityFeePerGas}}return s},exports.signMessage=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let p=a;if([e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6].includes(d)){const e={name:"Openfort",version:"0.5",chainId:Number(o),verifyingContract:c},t={OpenfortMessage:[{name:"hashedMessage",type:"bytes32"}]},a={hashedMessage:p},{_TypedDataEncoder:s}=await import("@ethersproject/hash");p=s.hash(e,t,a)}const g=await s.sign(p,!1,!1);if(i&&n&&[e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6].includes(d)){const{id:e}=await import("@ethersproject/hash"),{defaultAbiCoder:t}=await import("@ethersproject/abi"),{hexConcat:a}=await import("@ethersproject/bytes"),s=a([e("createAccountWithNonce(address,bytes32,bool)").slice(0,10),t.encode(["address","bytes32","bool"],[r,n,!1])]);return a([t.encode(["address","bytes","bytes"],[i,s,g]),"0x6492649264926492649264926492649264926492649264926492649264926492"])}return g};
|
package/dist/index.d.cts
CHANGED
|
@@ -12130,10 +12130,29 @@ interface RequestArguments {
|
|
|
12130
12130
|
method: string;
|
|
12131
12131
|
params?: any[];
|
|
12132
12132
|
}
|
|
12133
|
+
declare enum ProviderEvent {
|
|
12134
|
+
ACCOUNTS_CHANGED = "accountsChanged",
|
|
12135
|
+
CHAIN_CHANGED = "chainChanged",
|
|
12136
|
+
ACCOUNTS_CONNECT = "connect",
|
|
12137
|
+
DISCONNECT = "disconnect"
|
|
12138
|
+
}
|
|
12139
|
+
interface ProviderConnectInfo {
|
|
12140
|
+
chainId: string;
|
|
12141
|
+
}
|
|
12142
|
+
interface ProviderDisconnectError {
|
|
12143
|
+
code: number;
|
|
12144
|
+
message: string;
|
|
12145
|
+
}
|
|
12146
|
+
interface ProviderEventMap extends Record<string, any> {
|
|
12147
|
+
[ProviderEvent.ACCOUNTS_CHANGED]: [string[]];
|
|
12148
|
+
[ProviderEvent.CHAIN_CHANGED]: [string];
|
|
12149
|
+
[ProviderEvent.ACCOUNTS_CONNECT]: [ProviderConnectInfo];
|
|
12150
|
+
[ProviderEvent.DISCONNECT]: [ProviderDisconnectError];
|
|
12151
|
+
}
|
|
12133
12152
|
type Provider = {
|
|
12134
12153
|
request: (request: RequestArguments) => Promise<any>;
|
|
12135
|
-
on: (event:
|
|
12136
|
-
removeListener: (event:
|
|
12154
|
+
on: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12155
|
+
removeListener: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12137
12156
|
isOpenfort: boolean;
|
|
12138
12157
|
};
|
|
12139
12158
|
|
|
@@ -12185,6 +12204,11 @@ declare class EmbeddedWalletApi {
|
|
|
12185
12204
|
get(): Promise<EmbeddedAccount>;
|
|
12186
12205
|
list(requestParams?: ListAccountsParams): Promise<EmbeddedAccount[]>;
|
|
12187
12206
|
getEmbeddedState(): Promise<EmbeddedState>;
|
|
12207
|
+
watchEmbeddedState(params: {
|
|
12208
|
+
onChange: (state: EmbeddedState, prevState?: EmbeddedState) => void;
|
|
12209
|
+
onError?: (error: Error) => void;
|
|
12210
|
+
pollingInterval?: number;
|
|
12211
|
+
}): () => void;
|
|
12188
12212
|
getEthereumProvider(options?: {
|
|
12189
12213
|
policy?: string;
|
|
12190
12214
|
chains?: Record<number, string>;
|
package/dist/index.d.ts
CHANGED
|
@@ -12130,10 +12130,29 @@ interface RequestArguments {
|
|
|
12130
12130
|
method: string;
|
|
12131
12131
|
params?: any[];
|
|
12132
12132
|
}
|
|
12133
|
+
declare enum ProviderEvent {
|
|
12134
|
+
ACCOUNTS_CHANGED = "accountsChanged",
|
|
12135
|
+
CHAIN_CHANGED = "chainChanged",
|
|
12136
|
+
ACCOUNTS_CONNECT = "connect",
|
|
12137
|
+
DISCONNECT = "disconnect"
|
|
12138
|
+
}
|
|
12139
|
+
interface ProviderConnectInfo {
|
|
12140
|
+
chainId: string;
|
|
12141
|
+
}
|
|
12142
|
+
interface ProviderDisconnectError {
|
|
12143
|
+
code: number;
|
|
12144
|
+
message: string;
|
|
12145
|
+
}
|
|
12146
|
+
interface ProviderEventMap extends Record<string, any> {
|
|
12147
|
+
[ProviderEvent.ACCOUNTS_CHANGED]: [string[]];
|
|
12148
|
+
[ProviderEvent.CHAIN_CHANGED]: [string];
|
|
12149
|
+
[ProviderEvent.ACCOUNTS_CONNECT]: [ProviderConnectInfo];
|
|
12150
|
+
[ProviderEvent.DISCONNECT]: [ProviderDisconnectError];
|
|
12151
|
+
}
|
|
12133
12152
|
type Provider = {
|
|
12134
12153
|
request: (request: RequestArguments) => Promise<any>;
|
|
12135
|
-
on: (event:
|
|
12136
|
-
removeListener: (event:
|
|
12154
|
+
on: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12155
|
+
removeListener: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12137
12156
|
isOpenfort: boolean;
|
|
12138
12157
|
};
|
|
12139
12158
|
|
|
@@ -12185,6 +12204,11 @@ declare class EmbeddedWalletApi {
|
|
|
12185
12204
|
get(): Promise<EmbeddedAccount>;
|
|
12186
12205
|
list(requestParams?: ListAccountsParams): Promise<EmbeddedAccount[]>;
|
|
12187
12206
|
getEmbeddedState(): Promise<EmbeddedState>;
|
|
12207
|
+
watchEmbeddedState(params: {
|
|
12208
|
+
onChange: (state: EmbeddedState, prevState?: EmbeddedState) => void;
|
|
12209
|
+
onError?: (error: Error) => void;
|
|
12210
|
+
pollingInterval?: number;
|
|
12211
|
+
}): () => void;
|
|
12188
12212
|
getEthereumProvider(options?: {
|
|
12189
12213
|
policy?: string;
|
|
12190
12214
|
chains?: Record<number, string>;
|
|
@@ -1 +1 @@
|
|
|
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{OpenfortEvents as m,RecoveryMethod as g,ChainTypeEnum as y,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{EmbeddedSigner as u}from"../wallets/embedded.js";import{EvmProvider as w}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}from"../wallets/evm/walletHelpers.js";import{IframeManager as E}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import D 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(m.ON_LOGOUT,()=>{f("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(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new D({remoteWindow:r.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new E(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(f("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 u(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.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??l.SMART_ACCOUNT,chainType:e.chainType??y.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)]),y=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:y.id,chainId:y.chainId,address:y.address,ownerAddress:y.ownerAddress,chainType:y.chainType,accountType:y.accountType,implementationType:y.implementationType,factoryAddress:y.factoryAddress,salt:y.salt,createdAt:y.createdAt,implementationAddress:y.implementationAddress,recoveryMethod:o.parseRecoveryMethod(y.recoveryMethod),recoveryMethodDetails:y.recoveryMethodDetails};return this.eventEmitter.emit(m.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(m.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 M({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 p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}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.policy&&this.provider.updatePolicy(r.policy):(this.provider=new w({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...v,...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 f("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("undefined"==typeof document&&!this.messagePoster)return f("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 f("Invalid message received:",e);f("[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 f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),f("[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 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{OpenfortEvents as m,RecoveryMethod as g,ChainTypeEnum as y,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{observe as u}from"../utils/observe.js";import{EmbeddedSigner as w}from"../wallets/embedded.js";import{EvmProvider as A}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as E,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}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 T from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class S{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(m.ON_LOGOUT,()=>{f("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(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new t("Configuration not found");let r;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new T({remoteWindow:t.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,r)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(f("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 w(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??l.SMART_ACCOUNT,chainType:e.chainType??y.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)]),y=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:y.id,chainId:y.chainId,address:y.address,ownerAddress:y.ownerAddress,chainType:y.chainType,accountType:y.accountType,implementationType:y.implementationType,factoryAddress:y.factoryAddress,salt:y.salt,createdAt:y.createdAt,implementationAddress:y.implementationAddress,recoveryMethod:o.parseRecoveryMethod(y.recoveryMethod),recoveryMethodDetails:y.recoveryMethodDetails};return this.eventEmitter.emit(m.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(m.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 M({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 p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}watchEmbeddedState(e){return u("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(m.ON_AUTH_SUCCESS,a),this.eventEmitter.on(m.ON_LOGOUT,i),this.eventEmitter.on(m.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(m.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(m.ON_AUTH_SUCCESS,a),this.eventEmitter.off(m.ON_LOGOUT,i),this.eventEmitter.off(m.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(m.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.policy&&this.provider.updatePolicy(t.policy):(this.provider=new A({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&E({info:{...v,...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 f("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("undefined"==typeof document&&!this.messagePoster)return f("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 f("Invalid message received:",e);f("[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 f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),f("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{S as EmbeddedWalletApi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E,A,e,
|
|
1
|
+
var E,A,e,T,t,n,o,O,_,C,N,c,a;!function(E){E[E.NONE=0]="NONE",E[E.UNAUTHENTICATED=1]="UNAUTHENTICATED",E[E.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",E[E.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",E[E.READY=4]="READY"}(E||(E={})),function(E){E.ON_AUTH_INIT="onAuthInit",E.ON_AUTH_SUCCESS="onAuthSuccess",E.ON_OTP_REQUEST="onOtpRequest",E.ON_OTP_FAILURE="onOtpFailure",E.ON_AUTH_FAILURE="onAuthFailure",E.ON_LOGOUT="onLogout",E.ON_SWITCH_ACCOUNT="onSwitchAccount",E.ON_SIGNED_MESSAGE="onSignedMessage",E.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",E.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered"}(A||(A={})),function(E){E.PASSWORD="password",E.AUTOMATIC="automatic",E.PASSKEY="passkey"}(e||(e={})),function(E){E.UPGRADEABLE_V5="UpgradeableV5",E.UPGRADEABLE_V6="UpgradeableV6",E.SIMPLE="Simple",E.CALIBUR="Calibur",E.CALIBUR_V9="CaliburV9"}(T||(T={})),function(E){E.OPENFORT="openfort",E.THIRD_PARTY="thirdParty"}(t||(t={})),function(E){E.ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken"}(n||(n={})),function(E){E.ACCELBYTE="accelbyte",E.FIREBASE="firebase",E.BETTER_AUTH="better-auth",E.LOOTLOCKER="lootlocker",E.PLAYFAB="playfab",E.SUPABASE="supabase",E.CUSTOM="custom",E.OIDC="oidc"}(o||(o={})),function(E){E.EMAIL="email",E.WALLET="wallet"}(O||(O={})),function(E){E.GOOGLE="google",E.TWITTER="twitter",E.APPLE="apple",E.FACEBOOK="facebook",E.DISCORD="discord",E.EPIC_GAMES="epic_games",E.LINE="line"}(_||(_={})),function(E){E.ACTION_VERIFY_EMAIL="verify_email"}(C||(C={})),function(E){E.EOA="Externally Owned Account",E.SMART_ACCOUNT="Smart Account",E.DELEGATED_ACCOUNT="Delegated Account"}(N||(N={})),function(E){E.EVM="EVM",E.SVM="SVM"}(c||(c={})),function(E){E.ASC="asc",E.DESC="desc"}(a||(a={}));export{T as AccountType,N as AccountTypeEnum,C as AuthActionRequiredActions,t as AuthType,O as BasicAuthProvider,c as ChainTypeEnum,E as EmbeddedState,_ as OAuthProvider,A as OpenfortEvents,e as RecoveryMethod,o as ThirdPartyAuthProvider,n as TokenType};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=new Map,n=new Map;let o=0;function e(e,s,c){const f=++o,i=()=>t.get(e)||[],r=()=>{const o=i();if(!o.some(t=>t.id===f))return;const s=n.get(e);if(1===o.length&&s){const t=s();t instanceof Promise&&t.catch(()=>{})}(()=>{const n=i();t.set(e,n.filter(t=>t.id!==f))})()},g=i();if(t.set(e,[...g,{id:f,fns:s}]),g&&g.length>0)return r;const l={};for(const t in s)l[t]=(...n)=>{const o=i();if(0!==o.length)for(const e of o)e.fns[t]?.(...n)};const u=c(l);return"function"==typeof u&&n.set(e,u),r}export{e as observe};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="1.2.
|
|
1
|
+
const o="1.2.1",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 a,AccountTypeEnum as i}from"../../types/types.js";import{defaultChainRpcs as s}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 c}from"./estimateGas.js";import{getAssets as h}from"./getAssets.js";import{getCallStatus as d}from"./getCallsStatus.js";import{JsonRpcError as p,ProviderErrorCode as m,RpcErrorCode as
|
|
1
|
+
import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as a,AccountTypeEnum as i}from"../../types/types.js";import{defaultChainRpcs as s}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 c}from"./estimateGas.js";import{getAssets as h}from"./getAssets.js";import{getCallStatus as d}from"./getCallsStatus.js";import{JsonRpcError as p,ProviderErrorCode as m,RpcErrorCode as w}from"./JsonRpcError.js";import{personalSign as l}from"./personalSign.js";import{registerSession as u}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;#a;#i;updatePolicy(t){this.#e=t}#s;#r;#o=null;#n;isOpenfort=!0;#c;constructor({storage:t,backendApiClients:e,openfortEventEmitter:i,policyId:s,ensureSigner:r,chains:n,validateAndRefreshSession:c}){this.#c=r,this.#t=t,this.#a=n,this.#e=s,this.#s=c,this.#n=e,this.#r=new o,i.on(a.ON_LOGOUT,this.#h),i.on(a.ON_SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#i||(this.#i=await this.#c()),this.#i);#h=async()=>{this.#i=void 0,this.#r.emit(R.DISCONNECT,{code:4900,message:"Disconnected"}),this.#r.emit(R.ACCOUNTS_CHANGED,[])};#d=async t=>{this.#r.emit(R.ACCOUNTS_CHANGED,[t])};async getRpcProvider(){if(!this.#o){const e=await t.fromStorage(this.#t),a=e?.chainId||8453;await import("@ethersproject/providers").then(t=>{const e=this.#a?this.#a[a]:void 0;this.#o=new t.StaticJsonRpcProvider(e??s[a])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#m(a){switch(a.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:a}=await t.detectNetwork();return this.#r.emit(R.ACCOUNTS_CONNECT,{chainId:r(a)}),[e.address]}throw new p(m.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const i=await t.fromStorage(this.#t),s=await this.#p(),r=await e.fromStorage(this.#t);if(!i||!r)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=a.params||[];c.chainId||(c.chainId=n.toString());const h=_(c),{serialize:d}=await import("@ethersproject/transactions"),w=t=>({legacy:0,eip2930:1,eip1559:2}[t]),{gas:l,...u}=h,g={...u,gasLimit:l,to:h.to??void 0,type:w(h.type)},f=d(g),{keccak256:S}=await import("@ethersproject/keccak256"),A=S(f);await this.#s();const R=await s.sign(A,!1,!1),{splitSignature:v}=await import("@ethersproject/bytes");return d(g,v(R))}case"eth_sendTransaction":{const[s,r,o]=await Promise.all([t.fromStorage(this.#t),this.#p(),e.fromStorage(this.#t)]);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#s(),s?.accountType===i.EOA){const[t]=a.params||[],e=await this.getRpcProvider(),i=await v(t,e,s.address),r=await this.#m({method:"eth_signTransaction",params:[i]});return this.#m({method:"eth_sendRawTransaction",params:[r]})}return(await f({params:a.params||[],signer:r,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#e})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[s,r,o]=await Promise.all([t.fromStorage(this.#t),this.#p(),e.fromStorage(this.#t)]);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);return await this.#s(),await f({params:a.params||[],signer:r,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#e})}case"eth_estimateGas":{const i=await t.fromStorage(this.#t),s=await e.fromStorage(this.#t);if(!i||!s)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await c({params:a.params||[],account:i,authentication:s,backendClient:this.#n,policyId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await t.fromStorage(this.#t),i=await this.#p();if(!e)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const s=await this.getRpcProvider();return await A({method:a.method,params:a.params||[],signer:i,implementationType:e.implementationType||e.type,rpcProvider:s,account:e})}case"personal_sign":{const e=await t.fromStorage(this.#t);if(!e)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const i=await this.#p();return await this.#s(),await l({params:a.params||[],signer:i,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.#p();if(!a.params||!Array.isArray(a.params)||0===a.params.length)throw new p(w.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const e=parseInt(a.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#o=new t.StaticJsonRpcProvider(a??s[e])}),this.#r.emit(R.CHAIN_CHANGED,r(e))}catch(t){const e=t;throw new p(w.INTERNAL_ERROR,`Failed to switch chain: ${e.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const t=await this.getRpcProvider();return await n({params:a.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const s=await t.fromStorage(this.#t);if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);const r=await e.fromStorage(this.#t);if(!s||!r)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await d({params:a.params||{},authentication:r,backendClient:this.#n})}case"wallet_sendCalls":{const[s,r,o]=await Promise.all([t.fromStorage(this.#t),this.#p(),e.fromStorage(this.#t)]);if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();return await S({params:a.params?a.params[0].calls:[],signer:r,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#e})}case"wallet_grantPermissions":{const s=await t.fromStorage(this.#t);if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);const r=await this.#p(),o=await e.fromStorage(this.#t);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u({params:a.params||[],signer:r,account:s,authentication:o,backendClient:this.#n,policyId:this.#e})}case"wallet_revokePermissions":{const i=await t.fromStorage(this.#t),s=await this.#p(),r=await e.fromStorage(this.#t);if(!i||!r)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:a.params||[],signer:s,account:i,authentication:r,backendClient:this.#n,policyId:this.#e})}case"wallet_getCapabilities":{const e=await t.fromStorage(this.#t);if(e?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);const s=await this.getRpcProvider(),{chainId:o}=await s.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 i=await t.fromStorage(this.#t),s=await e.fromStorage(this.#t);if(!i||!s)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await h({params:a.params?.[0],account:i,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(a.method,a.params||[]);default:throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`)}}async request(t){try{return this.#m(t)}catch(t){if(t instanceof p)throw t;if(t instanceof Error)throw new p(w.INTERNAL_ERROR,t.message);throw new p(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 +1 @@
|
|
|
1
|
-
var C;!function(C){C.ACCOUNTS_CHANGED="accountsChanged",C.ACCOUNTS_CONNECT="connect"}(C||(C={}));export{C as ProviderEvent};
|
|
1
|
+
var C;!function(C){C.ACCOUNTS_CHANGED="accountsChanged",C.CHAIN_CHANGED="chainChanged",C.ACCOUNTS_CONNECT="connect",C.DISCONNECT="disconnect"}(C||(C={}));export{C as ProviderEvent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AccountType as e}from"../../types/types.js";const t=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let g=a;if([e.UPGRADEABLE_V5,e.UPGRADEABLE_V6
|
|
1
|
+
import{AccountType as e}from"../../types/types.js";const t=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let g=a;if([e.UPGRADEABLE_V5,e.UPGRADEABLE_V6].includes(d)){const e={name:"Openfort",version:"0.5",chainId:Number(o),verifyingContract:c},t={OpenfortMessage:[{name:"hashedMessage",type:"bytes32"}]},a={hashedMessage:g},{_TypedDataEncoder:s}=await import("@ethersproject/hash");g=s.hash(e,t,a)}const P=await s.sign(g,!1,!1);if(i&&n&&[e.UPGRADEABLE_V5,e.UPGRADEABLE_V6].includes(d)){const{id:e}=await import("@ethersproject/hash"),{defaultAbiCoder:t}=await import("@ethersproject/abi"),{hexConcat:a}=await import("@ethersproject/bytes"),s=a([e("createAccountWithNonce(address,bytes32,bool)").slice(0,10),t.encode(["address","bytes32","bool"],[r,n,!1])]);return a([t.encode(["address","bytes","bytes"],[i,s,P]),"0x6492649264926492649264926492649264926492649264926492649264926492"])}return P};async function a(e,t,a){const s={...e};if(!s.nonce){const e=await t.getTransactionCount(a,"pending");s.nonce=`0x${e.toString(16)}`}if(!s.gas)try{const e=await t.estimateGas({from:a,to:s.to,data:s.data,value:s.value});s.gas=e.toHexString()}catch{s.gas="0x5208"}const r=s.maxFeePerGas&&s.maxPriorityFeePerGas,i=s.gasPrice;if(!r&&!i){const e=await t.getBlock("latest");if(null!==e.baseFeePerGas&&void 0!==e.baseFeePerGas){const a=e.baseFeePerGas,r=a.mul(12).div(10),i=await t.getGasPrice();let n=i.sub(a);n.lt(0)&&(n=i.mul(0));const o=r.add(n);s.maxFeePerGas=o.toHexString(),s.maxPriorityFeePerGas=n.toHexString(),s.type="0x2",delete s.gasPrice}else{const e=(await t.getGasPrice()).mul(12).div(10);s.gasPrice=e.toHexString(),s.type="0x0",delete s.maxFeePerGas,delete s.maxPriorityFeePerGas}}return s}function s({from:e,...t}){return{to:t.to,data:t.data,accessList:t.accessList,chainId:(i=t.chainId,i.startsWith("0x")?parseInt(i,16):parseInt(i,10)),type:t.type&&{"0x0":"legacy","0x1":"eip2930","0x2":"eip1559"}[t.type]||"eip1559",maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,value:(a=t.value,s=BigInt,r=0n,void 0!==a?s(a):r),nonce:t.nonce?parseInt(t.nonce.toString(),16):void 0,gas:t.gas?BigInt(t.gas):void 0};var a,s,r,i}export{s as parseTransactionRequest,a as prepareEOATransaction,t as signMessage};
|
package/package.json
CHANGED