@openfort/openfort-js 1.3.9 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/src/api/funding.cjs +1 -0
- package/dist/cjs/sdk/src/core/config/config.cjs +1 -1
- package/dist/cjs/sdk/src/core/errors/sentry.cjs +1 -1
- package/dist/cjs/sdk/src/core/openfort.cjs +1 -1
- package/dist/cjs/sdk/src/index.cjs +1 -1
- package/dist/cjs/sdk/src/utils/crypto.cjs +1 -1
- 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/normalizeRpcError.cjs +1 -0
- package/dist/cjs/sdk/src/wallets/evm/personalSign.cjs +1 -1
- package/dist/index.d.cts +227 -2
- package/dist/index.d.ts +227 -2
- package/dist/sdk/src/api/funding.js +1 -0
- package/dist/sdk/src/core/config/config.js +1 -1
- package/dist/sdk/src/core/errors/sentry.js +1 -1
- package/dist/sdk/src/core/openfort.js +1 -1
- package/dist/sdk/src/index.js +1 -1
- package/dist/sdk/src/utils/crypto.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/evm/evmProvider.js +1 -1
- package/dist/sdk/src/wallets/evm/normalizeRpcError.js +1 -0
- package/dist/sdk/src/wallets/evm/personalSign.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("../core/config/config.cjs"),t=require("../core/errors/openfortError.cjs");exports.FundingApi=class{async request(s,n){const r=e.SDKConfiguration.getInstance();if(!r)throw new t.ConfigurationError("Configuration not found");const i=await fetch(`${r.backendUrl}${s}`,{...n,headers:{Authorization:`Bearer ${r.baseConfiguration.publishableKey}`,"Content-Type":"application/json",...n?.headers??{}},signal:AbortSignal.timeout(3e4)});if(!i.ok){const e=await i.json().catch(()=>({})),s="string"==typeof e.error?e.error:e.error?.message;throw new t.RequestError(s??"Openfort funding request failed",i.status)}return i.json()}secrets=new Map;resolveSecret(e,t){const s=t??this.secrets.get(e);if(!s)throw new Error(`No clientSecret known for funding session ${e} — pass it explicitly (it was returned when the session was created)`);return s}remember(e){return e.clientSecret&&this.secrets.set(e.id,e.clientSecret),e}sessions={create:async e=>this.remember(await this.request("/v2/funding/sessions",{method:"POST",body:JSON.stringify(e)})),setPaymentMethod:async(e,t)=>this.request(`/v2/funding/sessions/${e}/payment_methods`,{method:"POST",body:JSON.stringify({clientSecret:this.resolveSecret(e,t.clientSecret),paymentMethod:t.paymentMethod})}),get:async(e,t)=>{const s=this.resolveSecret(e,t?.clientSecret);return this.request(`/v2/funding/sessions/${e}?clientSecret=${encodeURIComponent(s)}`)},wait:async(e,t)=>{const s=t?.pollMs??4e3,n=t?.timeoutMs??18e5,r=Date.now()+n;for(;;){const n=await this.sessions.get(e,t);if("succeeded"===n.status||"bounced"===n.status||"expired"===n.status)return n;if(Date.now()>=r)throw new Error(`Timed out waiting for funding session ${e} (last status: ${n.status})`);await new Promise(e=>setTimeout(e,s))}}};fund=async e=>{const t=await this.sessions.create({target:e.target,paymentMethod:e.paymentMethod,amountUnits:e.amountUnits,metadata:e.metadata,externalId:e.externalId,strict:e.strict});return this.sessions.wait(t.id,e.wait)};payLink=async e=>{const{url:t}=await this.request("/v2/funding/pay_link",{method:"POST",body:JSON.stringify({sessionId:e.sessionId,clientSecret:this.resolveSecret(e.sessionId,e.clientSecret),amount:e.amount,asset:e.asset})});return t};chains=async()=>{const{chains:e}=await this.request("/v2/funding/chains");return e}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../utils/crypto.cjs");class i{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:t,overrides:r,thirdPartyAuth:a,debug:n}){this.shieldConfiguration=t,this.baseConfiguration=s,this.backendUrl=r?.backendUrl||"https://api.openfort.io",this.iframeUrl=r?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=n,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=r?.shieldUrl||"https://shield.openfort.io",this.storage=r?.storage,this.thirdPartyAuth=a,this.nativeAppIdentifier=s.nativeAppIdentifier,r?.crypto?.digest&&e.setCryptoDigestOverride(r.crypto.digest),i.instance=this}static getInstance(){return i.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=i,exports.ShieldConfiguration=class{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
|
|
1
|
+
"use strict";var e=require("../../utils/crypto.cjs");class i{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;disableTelemetry;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:t,overrides:r,thirdPartyAuth:a,debug:l,disableTelemetry:n}){this.shieldConfiguration=t,this.baseConfiguration=s,this.backendUrl=r?.backendUrl||"https://api.openfort.io",this.iframeUrl=r?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=l,this.disableTelemetry=n,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=r?.shieldUrl||"https://shield.openfort.io",this.storage=r?.storage,this.thirdPartyAuth=a,this.nativeAppIdentifier=s.nativeAppIdentifier,r?.crypto?.digest&&e.setCryptoDigestOverride(r.crypto.digest),i.instance=this}static getInstance(){return i.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=i,exports.ShieldConfiguration=class{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("axios"),t=require("../../version.cjs");const
|
|
1
|
+
"use strict";var e=require("axios"),t=require("../../version.cjs");const s="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class r{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const n=t.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==s.split("https://")[1].split("/")[1]||n.host!==s.split("@")[1].split("/")[0]||n.publicKey!==s.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,n,a,o)=>{if(n instanceof e.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=s,t.captureException(n,{...a,captureContext:{...a?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...r.baseTags,method:s}}})}else t.captureException(n,a,o)},t.captureError=(e,s,n,a)=>{const o=s.statusCode;if(400===o||401===o)return;const c=s,i=c.error,u=c.error_description,p=n?.captureContext;t.captureException(s,{...n,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...r.baseTags,context:e,errorClass:s.constructor.name}}})},r.sentryInstance=t}static get sentry(){return r.proxy}static async init({sentry:e,configuration:n}){if(e)r.sentry=e;else if(!n?.disableTelemetry)try{const e=await import("@sentry/browser");r.sentry=new e.BrowserClient({dsn:s,release:`${t.PACKAGE}@${t.VERSION}`,integrations:[],stackParser:e.defaultStackParser,transport:e.makeFetchTransport}),r.baseTags={projectId:n?.baseConfiguration.publishableKey??"",sdk:t.PACKAGE,sdkVersion:t.VERSION},r.processQueuedCalls()}catch{}}static proxy=new Proxy({},{get:(e,t)=>r.sentryInstance&&"function"==typeof r.sentryInstance[t]?(...e)=>r.sentryInstance[t](...e):(...e)=>{r.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){r.sentryInstance&&(r.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof r.sentryInstance[e]&&r.sentryInstance[e](...t)}),r.queuedCalls=[])}}const{sentry:n}=r;exports.InternalSentry=r,exports.sentry=n;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/funding.cjs"),a=require("../api/proxy.cjs"),s=require("../api/user.cjs"),r=require("../auth/authManager.cjs"),o=require("../storage/istorage.cjs"),h=require("../storage/lazyStorage.cjs"),l=require("../utils/typedEventEmitter.cjs"),u=require("./config/config.cjs"),c=require("./errors/authErrorCodes.cjs"),d=require("./errors/openfortError.cjs"),g=require("./errors/sentry.cjs"),f=require("./openfortInternal.cjs"),p=require("./passkey/handler.cjs");class I{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;fundingInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}get funding(){if(!this.fundingInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing funding.");return this.fundingInstance}initializeSynchronously(){try{this.iAuthManager=new r.AuthManager,this.openfortInternal=new f.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new s.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.fundingInstance=new n.FundingApi,this.proxyInstance=new a.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new d.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new d.ConfigurationError("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new u.SDKConfiguration(e),this.storage=new h.LazyStorage(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new l,I.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{I.globalEventEmitter?.emit(e,...t)})})}else I.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new p.PasskeyHandler({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),g.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return I.globalEventEmitter||(I.globalEventEmitter=new l),I.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new d.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=o.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await I.isStorageAccessible(this.storage))throw new d.OpenfortError("Storage is not accessible. The SDK needs a working key/value store to persist the session. On React Native, ensure the app is code-signed (an unsigned build cannot use the keychain) and that expo-secure-store — or your `overrides.storage` implementation — is installed and reachable.",c.OPENFORT_ERROR_CODES.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=I;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var r=require("./core/openfort.cjs"),e=require("./api/auth.cjs"),o=require("./api/embeddedWallet.cjs"),t=require("./api/
|
|
1
|
+
"use strict";var r=require("./core/openfort.cjs"),e=require("./api/auth.cjs"),o=require("./api/embeddedWallet.cjs"),t=require("./api/funding.cjs"),s=require("./api/proxy.cjs"),n=require("./api/user.cjs"),i=require("./core/errors/authErrorCodes.cjs"),p=require("./core/errors/openfortError.cjs"),u=require("./core/passkey/errors.cjs"),a=require("./core/passkey/handler.cjs"),E=require("./core/passkey/utils.cjs"),c=require("./core/config/config.cjs"),d=require("./core/openfortInternal.cjs"),f=require("./utils/authorization.cjs"),y=require("./wallets/iframeManager.cjs"),x=require("./types/types.cjs"),P=require("./utils/crypto.cjs");const O=r.Openfort.getEventEmitter();exports.Openfort=r.Openfort,exports.AuthApi=e.AuthApi,exports.EmbeddedWalletApi=o.EmbeddedWalletApi,exports.FundingApi=t.FundingApi,exports.ProxyApi=s.ProxyApi,exports.UserApi=n.UserApi,exports.OPENFORT_AUTH_ERROR_CODES=i.OPENFORT_AUTH_ERROR_CODES,exports.OPENFORT_ERROR_CODES=i.OPENFORT_ERROR_CODES,exports.AuthenticationError=p.AuthenticationError,exports.AuthorizationError=p.AuthorizationError,exports.ConfigurationError=p.ConfigurationError,exports.OAuthError=p.OAuthError,exports.OTPError=p.OTPError,exports.OpenfortError=p.OpenfortError,exports.RecoveryError=p.RecoveryError,exports.RequestError=p.RequestError,exports.SessionError=p.SessionError,exports.SignerError=p.SignerError,exports.UserError=p.UserError,exports.PASSKEY_ERROR_CODES=u.PASSKEY_ERROR_CODES,exports.PasskeyAssertionFailedError=u.PasskeyAssertionFailedError,exports.PasskeyCreationFailedError=u.PasskeyCreationFailedError,exports.PasskeyPRFNotSupportedError=u.PasskeyPRFNotSupportedError,exports.PasskeySeedInvalidError=u.PasskeySeedInvalidError,exports.PasskeyUserCancelledError=u.PasskeyUserCancelledError,exports.PasskeyHandler=a.PasskeyHandler,exports.arrayBufferToBase64URL=E.arrayBufferToBase64URL,exports.base64ToArrayBuffer=E.base64ToArrayBuffer,exports.OpenfortConfiguration=c.OpenfortConfiguration,exports.SDKConfiguration=c.SDKConfiguration,exports.ShieldConfiguration=c.ShieldConfiguration,exports.OpenfortInternal=d.OpenfortInternal,exports.prepareAndSignAuthorization=f.prepareAndSignAuthorization,exports.serializeSignedAuthorization=f.serializeSignedAuthorization,exports.signAuthorization=f.signAuthorization,exports.IframeHandshakeTimeoutError=y.IframeHandshakeTimeoutError,exports.IframeSignEmptyResponseError=y.IframeSignEmptyResponseError,exports.IframeSignTimeoutError=y.IframeSignTimeoutError,exports.MissingProjectEntropyError=y.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=y.MissingRecoveryPasswordError,exports.NotConfiguredError=y.NotConfiguredError,exports.OTPRequiredError=y.OTPRequiredError,exports.SessionEndedBeforeSetupError=y.SessionEndedBeforeSetupError,exports.WrongPasskeyError=y.WrongPasskeyError,exports.WrongRecoveryPasswordError=y.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return x.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return x.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return x.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return x.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return x.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return x.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return x.OAuthProvider}}),Object.defineProperty(exports,"OpenfortEvents",{enumerable:!0,get:function(){return x.OpenfortEvents}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return x.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return x.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return x.TokenType}}),exports.cryptoDigest=P.cryptoDigest,exports.openfortEvents=O;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";let t;exports.cryptoDigest=async function(r,e){if(t)return t(r,e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(r,e);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")},exports.
|
|
1
|
+
"use strict";let t;exports.cryptoDigest=async function(r,e){if(t)return t(r,e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(r,e);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")},exports.numberToHex=function(t){return`0x${t.toString(16)}`},exports.randomUUID=function(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const e=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${e}`:e}).join("")},exports.setCryptoDigestOverride=function(r){t=r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.5.0";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),s=require("../../utils/chains/index.cjs"),a=require("../../utils/crypto.cjs"),i=require("../../utils/typedEventEmitter.cjs"),o=require("./addEthereumChain.cjs"),n=require("./estimateGas.cjs"),c=require("./getAssets.cjs"),h=require("./getCallsStatus.cjs"),d=require("./JsonRpcError.cjs"),p=require("./personalSign.cjs"),u=require("./registerSession.cjs"),w=require("./revokeSession.cjs"),l=require("./sendCallSync.cjs"),m=require("./sendCalls.cjs"),g=require("./signTypedDataV4.cjs"),E=require("./types.cjs"),A=require("./walletHelpers.cjs");exports.EvmProvider=class{#e;#t;#r;#s;updateFeeSponsorship(e){this.#t=e}#a;#i;#o=null;#n;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:s,feeSponsorshipId:a,ensureSigner:o,chains:n,validateAndRefreshSession:c}){this.#c=o,this.#e=e,this.#r=n,this.#t=a,this.#a=c,this.#n=t,this.#i=new i,s.on(r.OpenfortEvents.ON_LOGOUT,this.#h),s.on(r.OpenfortEvents.ON_SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#s||(this.#s=await this.#c()),this.#s);#h=async()=>{this.#s=void 0,this.#i.emit(E.ProviderEvent.DISCONNECT,{code:4900,message:"Disconnected"}),this.#i.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#i.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#o){const t=await e.Account.fromStorage(this.#e),r=t?.chainId||(this.#r?Number(Object.keys(this.#r)[0]):void 0)||8453;await import("@ethersproject/providers").then(e=>{const t=this.#r?this.#r[r]:void 0;this.#o=new e.StaticJsonRpcProvider(t??s.defaultChainRpcs[r])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#u(i){switch(i.method){case"eth_accounts":{const t=await e.Account.fromStorage(this.#e);return t?[t.address]:[]}case"eth_requestAccounts":{const t=await e.Account.fromStorage(this.#e);if(t){const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return this.#i.emit(E.ProviderEvent.ACCOUNTS_CONNECT,{chainId:a.numberToHex(r)}),[t.address]}throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=i.params||[];c.chainId||(c.chainId=n.toString());const h=A.parseTransactionRequest(c),{serialize:p}=await import("@ethersproject/transactions"),u=e=>({legacy:0,eip2930:1,eip1559:2}[e]),{gas:w,...l}=h,m={...l,gasLimit:w,to:h.to??void 0,type:u(h.type)},g=p(m),{keccak256:E}=await import("@ethersproject/keccak256"),f=E(g);await this.#a();const S=await s.sign(f,!1,!1),{splitSignature:R}=await import("@ethersproject/bytes");return p(m,R(S))}case"eth_sendTransaction":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#a(),s?.accountType===r.AccountTypeEnum.EOA){const[e]=i.params||[],t=await this.getRpcProvider(),r=await A.prepareEOATransaction(e,t,s.address),a=await this.#u({method:"eth_signTransaction",params:[r]});return this.#u({method:"eth_sendRawTransaction",params:[a]})}return(await l.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);return await this.#a(),await l.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"eth_estimateGas":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await n.estimateGas({params:i.params||[],account:r,authentication:s,backendClient:this.#n,feeSponsorshipId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),r=await this.#p();if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();const s=await this.getRpcProvider();return await g.signTypedDataV4({method:i.method,params:i.params||[],signer:r,implementationType:t.implementationType||t.type,rpcProvider:s,account:t})}case"personal_sign":{const t=await e.Account.fromStorage(this.#e);if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const r=await this.#p();return await this.#a(),await p.personalSign({params:i.params||[],signer:r,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return a.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#p();if(!i.params||!Array.isArray(i.params)||0===i.params.length)throw new d.JsonRpcError(d.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#a();try{const t=parseInt(i.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#o=new e.StaticJsonRpcProvider(r??s.defaultChainRpcs[t])}),this.#i.emit(E.ProviderEvent.CHAIN_CHANGED,a.numberToHex(t))}catch(e){const t=e;throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const e=await this.getRpcProvider();return await o.addEthereumChain({params:i.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await t.Authentication.fromStorage(this.#e);if(!s||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await h.getCallStatus({params:i.params||{},authentication:a,backendClient:this.#n})}case"wallet_sendCalls":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();return await m.sendCalls({params:i.params?i.params[0].calls:[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"wallet_grantPermissions":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await this.#p(),o=await t.Authentication.fromStorage(this.#e);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await u.registerSession({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_revokePermissions":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await w.revokeSession({params:i.params||[],signer:s,account:r,authentication:a,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_getCapabilities":{const t=await e.Account.fromStorage(this.#e);if(t?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const s=await this.getRpcProvider(),{chainId:o}=await s.detectNetwork();return{[a.numberToHex(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await c.getAssets({params:i.params?.[0],account:r,authentication:s,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(i.method,i.params||[]);default:throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`)}}async request(e){try{return this.#u(e)}catch(e){if(e instanceof d.JsonRpcError)throw e;if(e instanceof Error)throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,e.message);throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#i.on(e,t)}removeListener(e,t){this.#i.off(e,t)}};
|
|
1
|
+
"use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),s=require("../../utils/chains/index.cjs"),a=require("../../utils/crypto.cjs"),i=require("../../utils/typedEventEmitter.cjs"),o=require("./addEthereumChain.cjs"),n=require("./estimateGas.cjs"),c=require("./getAssets.cjs"),h=require("./getCallsStatus.cjs"),d=require("./JsonRpcError.cjs"),p=require("./normalizeRpcError.cjs"),u=require("./personalSign.cjs"),w=require("./registerSession.cjs"),l=require("./revokeSession.cjs"),m=require("./sendCallSync.cjs"),g=require("./sendCalls.cjs"),E=require("./signTypedDataV4.cjs"),A=require("./types.cjs"),f=require("./walletHelpers.cjs");exports.EvmProvider=class{#e;#t;#r;#s;updateFeeSponsorship(e){this.#t=e}#a;#i;#o=null;#n;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:s,feeSponsorshipId:a,ensureSigner:o,chains:n,validateAndRefreshSession:c}){this.#c=o,this.#e=e,this.#r=n,this.#t=a,this.#a=c,this.#n=t,this.#i=new i,s.on(r.OpenfortEvents.ON_LOGOUT,this.#h),s.on(r.OpenfortEvents.ON_SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#s||(this.#s=await this.#c()),this.#s);#h=async()=>{this.#s=void 0,this.#i.emit(A.ProviderEvent.DISCONNECT,{code:4900,message:"Disconnected"}),this.#i.emit(A.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#i.emit(A.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#o){const t=await e.Account.fromStorage(this.#e),r=t?.chainId||(this.#r?Number(Object.keys(this.#r)[0]):void 0)||8453;await import("@ethersproject/providers").then(e=>{const t=this.#r?this.#r[r]:void 0;this.#o=new e.StaticJsonRpcProvider(t??s.defaultChainRpcs[r])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#u(i){switch(i.method){case"eth_accounts":{const t=await e.Account.fromStorage(this.#e);return t?[t.address]:[]}case"eth_requestAccounts":{const t=await e.Account.fromStorage(this.#e);if(t){const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return this.#i.emit(A.ProviderEvent.ACCOUNTS_CONNECT,{chainId:a.numberToHex(r)}),[t.address]}throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=i.params||[];c.chainId||(c.chainId=n.toString());const h=f.parseTransactionRequest(c),{serialize:p}=await import("@ethersproject/transactions"),u=e=>({legacy:0,eip2930:1,eip1559:2}[e]),{gas:w,...l}=h,m={...l,gasLimit:w,to:h.to??void 0,type:u(h.type)},g=p(m),{keccak256:E}=await import("@ethersproject/keccak256"),A=E(g);await this.#a();const S=await s.sign(A,!1,!1),{splitSignature:R}=await import("@ethersproject/bytes");return p(m,R(S))}case"eth_sendTransaction":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#a(),s?.accountType===r.AccountTypeEnum.EOA){const[e]=i.params||[],t=await this.getRpcProvider(),r=await f.prepareEOATransaction(e,t,s.address),a=await this.#u({method:"eth_signTransaction",params:[r]});return this.#u({method:"eth_sendRawTransaction",params:[a]})}return(await m.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);return await this.#a(),await m.sendCallsSync({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"eth_estimateGas":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await n.estimateGas({params:i.params||[],account:r,authentication:s,backendClient:this.#n,feeSponsorshipId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),r=await this.#p();if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();const s=await this.getRpcProvider();return await E.signTypedDataV4({method:i.method,params:i.params||[],signer:r,implementationType:t.implementationType||t.type,rpcProvider:s,account:t})}case"personal_sign":{const t=await e.Account.fromStorage(this.#e);if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const r=await this.#p();return await this.#a(),await u.personalSign({params:i.params||[],signer:r,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return a.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#p();if(!i.params||!Array.isArray(i.params)||0===i.params.length)throw new d.JsonRpcError(d.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#a();try{const t=parseInt(i.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#o=new e.StaticJsonRpcProvider(r??s.defaultChainRpcs[t])}),this.#i.emit(A.ProviderEvent.CHAIN_CHANGED,a.numberToHex(t))}catch(e){const t=e;throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const e=await this.getRpcProvider();return await o.addEthereumChain({params:i.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await t.Authentication.fromStorage(this.#e);if(!s||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await h.getCallStatus({params:i.params||{},authentication:a,backendClient:this.#n})}case"wallet_sendCalls":{const[s,a,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#p(),t.Authentication.fromStorage(this.#e)]);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();return await g.sendCalls({params:i.params?i.params[0].calls:[],signer:a,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#t})}case"wallet_grantPermissions":{const s=await e.Account.fromStorage(this.#e);if(s?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const a=await this.#p(),o=await t.Authentication.fromStorage(this.#e);if(!s||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await w.registerSession({params:i.params||[],signer:a,account:s,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_revokePermissions":{const r=await e.Account.fromStorage(this.#e),s=await this.#p(),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await l.revokeSession({params:i.params||[],signer:s,account:r,authentication:a,backendClient:this.#n,feeSponsorshipId:this.#t})}case"wallet_getCapabilities":{const t=await e.Account.fromStorage(this.#e);if(t?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`);const s=await this.getRpcProvider(),{chainId:o}=await s.detectNetwork();return{[a.numberToHex(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const r=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!r||!s)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await c.getAssets({params:i.params?.[0],account:r,authentication:s,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(i.method,i.params||[]);default:throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`)}}async request(e){try{return await this.#u(e)}catch(e){if(e instanceof d.JsonRpcError)throw e;if(e instanceof Error)throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,p.normalizeRpcErrorMessage(e.message));throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#i.on(e,t)}removeListener(e,t){this.#i.off(e,t)}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.normalizeRpcErrorMessage=function(e){const n=e.toLowerCase();return n.includes("insufficient funds")?"Insufficient funds: the wallet doesn't have enough native token to cover gas (plus any value). Top up the wallet and try again.":n.includes("execution reverted")||n.includes("reverted")?"Transaction reverted: the contract rejected this call.":n.includes("nonce too low")||n.includes("replacement transaction underpriced")?"Nonce conflict: another transaction from this wallet is still pending. Wait for it to confirm, then retry.":n.includes("intrinsic gas too low")||n.includes("gas required exceeds")||n.includes("out of gas")?"Gas error: the transaction needs more gas than is available or allowed.":e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("
|
|
1
|
+
"use strict";var e=require("./JsonRpcError.cjs"),r=require("./walletHelpers.cjs");exports.personalSign=async({params:s,signer:a,account:o})=>{const t=s[0],n=s[1];if(!n||!t)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"personal_sign requires an address and a message");if(n.toLowerCase()!==o.address.toLowerCase())throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"personal_sign requires the signer to be the from address");const{hashMessage:i}=await import("@ethersproject/hash"),{arrayify:d,isHexString:p}=await import("@ethersproject/bytes"),c=p(t)?d(t):t;return await r.signMessage({hash:i(c),implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:n,salt:o.salt,factoryAddress:o.factoryAddress,ownerAddress:o.ownerAddress})};
|
package/dist/index.d.cts
CHANGED
|
@@ -11856,6 +11856,13 @@ type OpenfortSDKConfiguration = {
|
|
|
11856
11856
|
overrides?: SDKOverrides;
|
|
11857
11857
|
thirdPartyAuth?: ThirdPartyAuthConfiguration;
|
|
11858
11858
|
debug?: boolean;
|
|
11859
|
+
/**
|
|
11860
|
+
* Disable anonymous error telemetry (Sentry). Telemetry is best-effort and
|
|
11861
|
+
* never throws, but you can turn it off entirely — for example in React
|
|
11862
|
+
* Native, where the telemetry SDK's dynamic import is unnecessary overhead.
|
|
11863
|
+
* Defaults to `false`.
|
|
11864
|
+
*/
|
|
11865
|
+
disableTelemetry?: boolean;
|
|
11859
11866
|
};
|
|
11860
11867
|
declare class SDKConfiguration {
|
|
11861
11868
|
readonly baseConfiguration: OpenfortConfiguration;
|
|
@@ -11867,8 +11874,9 @@ declare class SDKConfiguration {
|
|
|
11867
11874
|
readonly storage?: IStorage;
|
|
11868
11875
|
readonly nativeAppIdentifier?: string;
|
|
11869
11876
|
readonly debug?: boolean;
|
|
11877
|
+
readonly disableTelemetry?: boolean;
|
|
11870
11878
|
static instance: SDKConfiguration | null;
|
|
11871
|
-
constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug }: OpenfortSDKConfiguration);
|
|
11879
|
+
constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug, disableTelemetry, }: OpenfortSDKConfiguration);
|
|
11872
11880
|
static getInstance(): SDKConfiguration | null;
|
|
11873
11881
|
}
|
|
11874
11882
|
|
|
@@ -12658,6 +12666,221 @@ declare class RequestError extends OpenfortError {
|
|
|
12658
12666
|
constructor(error_description: string, statusCode?: number | undefined);
|
|
12659
12667
|
}
|
|
12660
12668
|
|
|
12669
|
+
/**
|
|
12670
|
+
* Funding (cross-chain wallet deposit) resource.
|
|
12671
|
+
*
|
|
12672
|
+
* Wraps the API's `/v2/funding` session endpoints: create a session for a
|
|
12673
|
+
* destination, set a single payment method (a source route) to mint a Relay
|
|
12674
|
+
* deposit address, then poll until terminal. Sessions are guarded by a
|
|
12675
|
+
* per-session `clientSecret` and authenticated with the project publishable key.
|
|
12676
|
+
*
|
|
12677
|
+
* NOTE: This thin wrapper calls the backend directly. Once the API's funding
|
|
12678
|
+
* endpoints are part of the published OpenAPI spec, this can move onto the
|
|
12679
|
+
* generated `BackendApiClients.fundingApi` like the other resources.
|
|
12680
|
+
*/
|
|
12681
|
+
/** Where the funded crypto should land (CAIP-2 chain + token + wallet). */
|
|
12682
|
+
interface FundingTarget {
|
|
12683
|
+
chain: string;
|
|
12684
|
+
currency: string;
|
|
12685
|
+
address: string;
|
|
12686
|
+
}
|
|
12687
|
+
/** The source route the user commits to sending from. */
|
|
12688
|
+
interface FundingSource {
|
|
12689
|
+
chain: string;
|
|
12690
|
+
currency: string;
|
|
12691
|
+
amount: string;
|
|
12692
|
+
}
|
|
12693
|
+
interface CreateFundingSessionParams {
|
|
12694
|
+
target: FundingTarget;
|
|
12695
|
+
/** Lock the deposit to a fixed amount (destination base units). */
|
|
12696
|
+
amountUnits?: string;
|
|
12697
|
+
metadata?: Record<string, string>;
|
|
12698
|
+
/** Idempotency/correlation key — reusing it returns the existing session. */
|
|
12699
|
+
externalId?: string;
|
|
12700
|
+
/** true = single-use deposit address; false (default) = open/reusable. */
|
|
12701
|
+
strict?: boolean;
|
|
12702
|
+
/**
|
|
12703
|
+
* One-call funding: set the payment method at creation when the source route
|
|
12704
|
+
* is already known — the session comes back in `waiting_payment` with the
|
|
12705
|
+
* deposit address, skipping the separate setPaymentMethod round trip.
|
|
12706
|
+
*/
|
|
12707
|
+
paymentMethod?: FundingPaymentMethodInput;
|
|
12708
|
+
}
|
|
12709
|
+
interface FundingPaymentMethodBase {
|
|
12710
|
+
source: FundingSource;
|
|
12711
|
+
/**
|
|
12712
|
+
* Origin-chain refund address (refunds land on the source chain). Optional —
|
|
12713
|
+
* the server defaults it to the target address for same-VM routes, or to a
|
|
12714
|
+
* source-VM stand-in for cross-VM routes (e.g. an EVM source funding a Solana
|
|
12715
|
+
* wallet), where the destination address isn't valid on the source chain.
|
|
12716
|
+
*/
|
|
12717
|
+
refundTo?: string;
|
|
12718
|
+
}
|
|
12719
|
+
/**
|
|
12720
|
+
* The source route the user commits to. `evm` / `solana` are self-custody
|
|
12721
|
+
* transfers; `cex` is a guided withdrawal from a centralized exchange — the same
|
|
12722
|
+
* deposit address, plus withdrawal guidance (network, minimum, memo) and no
|
|
12723
|
+
* wallet deeplinks (exchanges don't expose them).
|
|
12724
|
+
*/
|
|
12725
|
+
type FundingPaymentMethodInput = (FundingPaymentMethodBase & {
|
|
12726
|
+
type: 'evm';
|
|
12727
|
+
}) | (FundingPaymentMethodBase & {
|
|
12728
|
+
type: 'solana';
|
|
12729
|
+
}) | (FundingPaymentMethodBase & {
|
|
12730
|
+
type: 'cex';
|
|
12731
|
+
/** Exchange id, e.g. "binance" | "coinbase". */
|
|
12732
|
+
cex: string;
|
|
12733
|
+
});
|
|
12734
|
+
type FundingSessionStatus = 'requires_payment_method' | 'waiting_payment' | 'processing' | 'succeeded' | 'bounced' | 'expired';
|
|
12735
|
+
interface FundingFee {
|
|
12736
|
+
kind: string;
|
|
12737
|
+
amount: string;
|
|
12738
|
+
currency: string;
|
|
12739
|
+
}
|
|
12740
|
+
interface FundingWalletDeeplink {
|
|
12741
|
+
app: string;
|
|
12742
|
+
label: string;
|
|
12743
|
+
url: string;
|
|
12744
|
+
}
|
|
12745
|
+
/** Withdrawal guidance for a `cex` payment method. */
|
|
12746
|
+
interface FundingCexGuidance {
|
|
12747
|
+
/** Exchange id, e.g. "binance" | "coinbase". */
|
|
12748
|
+
exchange: string;
|
|
12749
|
+
/** Network name as the exchange labels it, e.g. "Base", "Polygon". */
|
|
12750
|
+
network: string;
|
|
12751
|
+
/** Minimum withdrawal in source base units, if the exchange enforces one. */
|
|
12752
|
+
minWithdrawal: string | null;
|
|
12753
|
+
/** True when the network requires a destination tag / memo. */
|
|
12754
|
+
requiresMemo: boolean;
|
|
12755
|
+
}
|
|
12756
|
+
interface FundingPaymentMethod {
|
|
12757
|
+
type: string;
|
|
12758
|
+
source: FundingSource;
|
|
12759
|
+
receiverAddress: string;
|
|
12760
|
+
addressUri: string;
|
|
12761
|
+
deeplinks: FundingWalletDeeplink[];
|
|
12762
|
+
/** Withdrawal guidance; present only for `cex` payment methods, else null. */
|
|
12763
|
+
cex: FundingCexGuidance | null;
|
|
12764
|
+
fees: FundingFee[];
|
|
12765
|
+
minAmount: string | null;
|
|
12766
|
+
}
|
|
12767
|
+
interface FundingSession {
|
|
12768
|
+
id: string;
|
|
12769
|
+
object: string;
|
|
12770
|
+
status: FundingSessionStatus;
|
|
12771
|
+
clientSecret: string;
|
|
12772
|
+
target: FundingTarget;
|
|
12773
|
+
amountUnits: string | null;
|
|
12774
|
+
metadata: Record<string, string> | null;
|
|
12775
|
+
externalId: string | null;
|
|
12776
|
+
strict: boolean;
|
|
12777
|
+
paymentMethod: FundingPaymentMethod | null;
|
|
12778
|
+
createdAt: number;
|
|
12779
|
+
expiresAt: number;
|
|
12780
|
+
}
|
|
12781
|
+
/**
|
|
12782
|
+
* Parameters for a Coinbase "Transfer funds" pay-link. Session-bound: the
|
|
12783
|
+
* destination chain and address come from the session, so the link can't be
|
|
12784
|
+
* redirected — the client only chooses the amount.
|
|
12785
|
+
*/
|
|
12786
|
+
interface PayLinkParams {
|
|
12787
|
+
/** Funding session (starts with fnd_) whose wallet receives the funds. */
|
|
12788
|
+
sessionId: string;
|
|
12789
|
+
/**
|
|
12790
|
+
* The session's client secret. Optional when the session was created on this
|
|
12791
|
+
* SDK instance (remembered from create()); required for sessions created elsewhere.
|
|
12792
|
+
*/
|
|
12793
|
+
clientSecret?: string;
|
|
12794
|
+
/** Amount to deliver, in the asset's human units (Coinbase enforces a minimum). */
|
|
12795
|
+
amount: string;
|
|
12796
|
+
/** Destination asset ticker; defaults to "USDC" server-side. */
|
|
12797
|
+
asset?: string;
|
|
12798
|
+
}
|
|
12799
|
+
/** A source currency available on a chain. */
|
|
12800
|
+
interface FundingCurrency {
|
|
12801
|
+
symbol: string;
|
|
12802
|
+
/** Contract address, or the zero address for the chain's native asset. */
|
|
12803
|
+
address: string;
|
|
12804
|
+
decimals: number;
|
|
12805
|
+
logo: string | null;
|
|
12806
|
+
/** True for the chain's native currency (ETH, SOL, POL, …). */
|
|
12807
|
+
native: boolean;
|
|
12808
|
+
}
|
|
12809
|
+
/** A source chain the rail can route from, with its routable currencies. */
|
|
12810
|
+
interface FundingChain {
|
|
12811
|
+
/** CAIP-2 chain id, e.g. "eip155:8453". */
|
|
12812
|
+
id: string;
|
|
12813
|
+
name: string;
|
|
12814
|
+
logo: string | null;
|
|
12815
|
+
vmType: string;
|
|
12816
|
+
currencies: FundingCurrency[];
|
|
12817
|
+
}
|
|
12818
|
+
declare class FundingApi {
|
|
12819
|
+
private request;
|
|
12820
|
+
/**
|
|
12821
|
+
* Client secrets remembered from create() responses, so follow-up calls in
|
|
12822
|
+
* the same SDK instance don't need to thread the secret manually. Passing an
|
|
12823
|
+
* explicit `clientSecret` always overrides (e.g. sessions created elsewhere).
|
|
12824
|
+
*/
|
|
12825
|
+
private readonly secrets;
|
|
12826
|
+
private resolveSecret;
|
|
12827
|
+
private remember;
|
|
12828
|
+
/** Funding session sub-resource: create → setPaymentMethod → get/wait. */
|
|
12829
|
+
readonly sessions: {
|
|
12830
|
+
create: (params: CreateFundingSessionParams) => Promise<FundingSession>;
|
|
12831
|
+
setPaymentMethod: (sessionId: string, params: {
|
|
12832
|
+
paymentMethod: FundingPaymentMethodInput;
|
|
12833
|
+
clientSecret?: string;
|
|
12834
|
+
}) => Promise<FundingSession>;
|
|
12835
|
+
get: (sessionId: string, params?: {
|
|
12836
|
+
clientSecret?: string;
|
|
12837
|
+
}) => Promise<FundingSession>;
|
|
12838
|
+
/**
|
|
12839
|
+
* Poll a session until it reaches a terminal status (`succeeded`, `bounced`,
|
|
12840
|
+
* or `expired`). Resolves with the terminal session; rejects on timeout.
|
|
12841
|
+
*/
|
|
12842
|
+
wait: (sessionId: string, params?: {
|
|
12843
|
+
clientSecret?: string;
|
|
12844
|
+
pollMs?: number;
|
|
12845
|
+
timeoutMs?: number;
|
|
12846
|
+
}) => Promise<FundingSession>;
|
|
12847
|
+
};
|
|
12848
|
+
/**
|
|
12849
|
+
* One-call deposit: create a session with the payment method set, then poll
|
|
12850
|
+
* until it reaches a terminal status (`succeeded`, `bounced`, or `expired`).
|
|
12851
|
+
* Bundles `sessions.create` + `sessions.wait` — the headless equivalent of the
|
|
12852
|
+
* React `useFunding().fund()` flow. Resolves with the terminal session; rejects
|
|
12853
|
+
* on timeout.
|
|
12854
|
+
*/
|
|
12855
|
+
readonly fund: (params: {
|
|
12856
|
+
target: FundingTarget;
|
|
12857
|
+
paymentMethod: FundingPaymentMethodInput;
|
|
12858
|
+
/** Lock the deposit to a fixed amount (destination base units). */
|
|
12859
|
+
amountUnits?: string;
|
|
12860
|
+
metadata?: Record<string, string>;
|
|
12861
|
+
/** Idempotency/correlation key — reusing it returns the existing session. */
|
|
12862
|
+
externalId?: string;
|
|
12863
|
+
/** true = single-use deposit address; false (default) = open/reusable. */
|
|
12864
|
+
strict?: boolean;
|
|
12865
|
+
/** Poll interval and overall timeout for the wait phase. */
|
|
12866
|
+
wait?: {
|
|
12867
|
+
pollMs?: number;
|
|
12868
|
+
timeoutMs?: number;
|
|
12869
|
+
};
|
|
12870
|
+
}) => Promise<FundingSession>;
|
|
12871
|
+
/**
|
|
12872
|
+
* Resolve a prefilled Coinbase "Transfer funds" URL that delivers the asset to
|
|
12873
|
+
* the session's wallet. Session-bound — the destination comes from the session,
|
|
12874
|
+
* so the client only chooses the amount. Powers the "send from an exchange" path.
|
|
12875
|
+
*/
|
|
12876
|
+
readonly payLink: (params: PayLinkParams) => Promise<string>;
|
|
12877
|
+
/**
|
|
12878
|
+
* The source chains + currencies the rail can route from — a live passthrough
|
|
12879
|
+
* of the provider's supported routes, for building the source picker.
|
|
12880
|
+
*/
|
|
12881
|
+
readonly chains: () => Promise<FundingChain[]>;
|
|
12882
|
+
}
|
|
12883
|
+
|
|
12661
12884
|
declare class ProxyApi {
|
|
12662
12885
|
private backendApiClients;
|
|
12663
12886
|
private validateAndRefreshToken;
|
|
@@ -12844,6 +13067,7 @@ declare class Openfort {
|
|
|
12844
13067
|
private embeddedWalletInstance?;
|
|
12845
13068
|
private userInstance?;
|
|
12846
13069
|
private proxyInstance?;
|
|
13070
|
+
private fundingInstance?;
|
|
12847
13071
|
private configuration;
|
|
12848
13072
|
eventEmitter: TypedEventEmitter<OpenfortEventMap>;
|
|
12849
13073
|
private iPasskeyHandler;
|
|
@@ -12856,6 +13080,7 @@ declare class Openfort {
|
|
|
12856
13080
|
get embeddedWallet(): EmbeddedWalletApi;
|
|
12857
13081
|
get user(): UserApi;
|
|
12858
13082
|
get proxy(): ProxyApi;
|
|
13083
|
+
get funding(): FundingApi;
|
|
12859
13084
|
private initializeSynchronously;
|
|
12860
13085
|
constructor(sdkConfiguration: OpenfortSDKConfiguration);
|
|
12861
13086
|
/**
|
|
@@ -13298,4 +13523,4 @@ declare function cryptoDigest(algorithm: string, data: BufferSource): Promise<Ar
|
|
|
13298
13523
|
*/
|
|
13299
13524
|
declare const openfortEvents: TypedEventEmitter<OpenfortEventMap>;
|
|
13300
13525
|
|
|
13301
|
-
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeHandshakeTimeoutError, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
|
13526
|
+
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, CreateFundingSessionParams, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, FundingApi, FundingCexGuidance, FundingChain, FundingCurrency, FundingFee, FundingPaymentMethod, FundingPaymentMethodInput, FundingSession, FundingSessionStatus, FundingSource, FundingTarget, FundingWalletDeeplink, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeHandshakeTimeoutError, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, PayLinkParams, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
package/dist/index.d.ts
CHANGED
|
@@ -11856,6 +11856,13 @@ type OpenfortSDKConfiguration = {
|
|
|
11856
11856
|
overrides?: SDKOverrides;
|
|
11857
11857
|
thirdPartyAuth?: ThirdPartyAuthConfiguration;
|
|
11858
11858
|
debug?: boolean;
|
|
11859
|
+
/**
|
|
11860
|
+
* Disable anonymous error telemetry (Sentry). Telemetry is best-effort and
|
|
11861
|
+
* never throws, but you can turn it off entirely — for example in React
|
|
11862
|
+
* Native, where the telemetry SDK's dynamic import is unnecessary overhead.
|
|
11863
|
+
* Defaults to `false`.
|
|
11864
|
+
*/
|
|
11865
|
+
disableTelemetry?: boolean;
|
|
11859
11866
|
};
|
|
11860
11867
|
declare class SDKConfiguration {
|
|
11861
11868
|
readonly baseConfiguration: OpenfortConfiguration;
|
|
@@ -11867,8 +11874,9 @@ declare class SDKConfiguration {
|
|
|
11867
11874
|
readonly storage?: IStorage;
|
|
11868
11875
|
readonly nativeAppIdentifier?: string;
|
|
11869
11876
|
readonly debug?: boolean;
|
|
11877
|
+
readonly disableTelemetry?: boolean;
|
|
11870
11878
|
static instance: SDKConfiguration | null;
|
|
11871
|
-
constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug }: OpenfortSDKConfiguration);
|
|
11879
|
+
constructor({ baseConfiguration, shieldConfiguration, overrides, thirdPartyAuth, debug, disableTelemetry, }: OpenfortSDKConfiguration);
|
|
11872
11880
|
static getInstance(): SDKConfiguration | null;
|
|
11873
11881
|
}
|
|
11874
11882
|
|
|
@@ -12658,6 +12666,221 @@ declare class RequestError extends OpenfortError {
|
|
|
12658
12666
|
constructor(error_description: string, statusCode?: number | undefined);
|
|
12659
12667
|
}
|
|
12660
12668
|
|
|
12669
|
+
/**
|
|
12670
|
+
* Funding (cross-chain wallet deposit) resource.
|
|
12671
|
+
*
|
|
12672
|
+
* Wraps the API's `/v2/funding` session endpoints: create a session for a
|
|
12673
|
+
* destination, set a single payment method (a source route) to mint a Relay
|
|
12674
|
+
* deposit address, then poll until terminal. Sessions are guarded by a
|
|
12675
|
+
* per-session `clientSecret` and authenticated with the project publishable key.
|
|
12676
|
+
*
|
|
12677
|
+
* NOTE: This thin wrapper calls the backend directly. Once the API's funding
|
|
12678
|
+
* endpoints are part of the published OpenAPI spec, this can move onto the
|
|
12679
|
+
* generated `BackendApiClients.fundingApi` like the other resources.
|
|
12680
|
+
*/
|
|
12681
|
+
/** Where the funded crypto should land (CAIP-2 chain + token + wallet). */
|
|
12682
|
+
interface FundingTarget {
|
|
12683
|
+
chain: string;
|
|
12684
|
+
currency: string;
|
|
12685
|
+
address: string;
|
|
12686
|
+
}
|
|
12687
|
+
/** The source route the user commits to sending from. */
|
|
12688
|
+
interface FundingSource {
|
|
12689
|
+
chain: string;
|
|
12690
|
+
currency: string;
|
|
12691
|
+
amount: string;
|
|
12692
|
+
}
|
|
12693
|
+
interface CreateFundingSessionParams {
|
|
12694
|
+
target: FundingTarget;
|
|
12695
|
+
/** Lock the deposit to a fixed amount (destination base units). */
|
|
12696
|
+
amountUnits?: string;
|
|
12697
|
+
metadata?: Record<string, string>;
|
|
12698
|
+
/** Idempotency/correlation key — reusing it returns the existing session. */
|
|
12699
|
+
externalId?: string;
|
|
12700
|
+
/** true = single-use deposit address; false (default) = open/reusable. */
|
|
12701
|
+
strict?: boolean;
|
|
12702
|
+
/**
|
|
12703
|
+
* One-call funding: set the payment method at creation when the source route
|
|
12704
|
+
* is already known — the session comes back in `waiting_payment` with the
|
|
12705
|
+
* deposit address, skipping the separate setPaymentMethod round trip.
|
|
12706
|
+
*/
|
|
12707
|
+
paymentMethod?: FundingPaymentMethodInput;
|
|
12708
|
+
}
|
|
12709
|
+
interface FundingPaymentMethodBase {
|
|
12710
|
+
source: FundingSource;
|
|
12711
|
+
/**
|
|
12712
|
+
* Origin-chain refund address (refunds land on the source chain). Optional —
|
|
12713
|
+
* the server defaults it to the target address for same-VM routes, or to a
|
|
12714
|
+
* source-VM stand-in for cross-VM routes (e.g. an EVM source funding a Solana
|
|
12715
|
+
* wallet), where the destination address isn't valid on the source chain.
|
|
12716
|
+
*/
|
|
12717
|
+
refundTo?: string;
|
|
12718
|
+
}
|
|
12719
|
+
/**
|
|
12720
|
+
* The source route the user commits to. `evm` / `solana` are self-custody
|
|
12721
|
+
* transfers; `cex` is a guided withdrawal from a centralized exchange — the same
|
|
12722
|
+
* deposit address, plus withdrawal guidance (network, minimum, memo) and no
|
|
12723
|
+
* wallet deeplinks (exchanges don't expose them).
|
|
12724
|
+
*/
|
|
12725
|
+
type FundingPaymentMethodInput = (FundingPaymentMethodBase & {
|
|
12726
|
+
type: 'evm';
|
|
12727
|
+
}) | (FundingPaymentMethodBase & {
|
|
12728
|
+
type: 'solana';
|
|
12729
|
+
}) | (FundingPaymentMethodBase & {
|
|
12730
|
+
type: 'cex';
|
|
12731
|
+
/** Exchange id, e.g. "binance" | "coinbase". */
|
|
12732
|
+
cex: string;
|
|
12733
|
+
});
|
|
12734
|
+
type FundingSessionStatus = 'requires_payment_method' | 'waiting_payment' | 'processing' | 'succeeded' | 'bounced' | 'expired';
|
|
12735
|
+
interface FundingFee {
|
|
12736
|
+
kind: string;
|
|
12737
|
+
amount: string;
|
|
12738
|
+
currency: string;
|
|
12739
|
+
}
|
|
12740
|
+
interface FundingWalletDeeplink {
|
|
12741
|
+
app: string;
|
|
12742
|
+
label: string;
|
|
12743
|
+
url: string;
|
|
12744
|
+
}
|
|
12745
|
+
/** Withdrawal guidance for a `cex` payment method. */
|
|
12746
|
+
interface FundingCexGuidance {
|
|
12747
|
+
/** Exchange id, e.g. "binance" | "coinbase". */
|
|
12748
|
+
exchange: string;
|
|
12749
|
+
/** Network name as the exchange labels it, e.g. "Base", "Polygon". */
|
|
12750
|
+
network: string;
|
|
12751
|
+
/** Minimum withdrawal in source base units, if the exchange enforces one. */
|
|
12752
|
+
minWithdrawal: string | null;
|
|
12753
|
+
/** True when the network requires a destination tag / memo. */
|
|
12754
|
+
requiresMemo: boolean;
|
|
12755
|
+
}
|
|
12756
|
+
interface FundingPaymentMethod {
|
|
12757
|
+
type: string;
|
|
12758
|
+
source: FundingSource;
|
|
12759
|
+
receiverAddress: string;
|
|
12760
|
+
addressUri: string;
|
|
12761
|
+
deeplinks: FundingWalletDeeplink[];
|
|
12762
|
+
/** Withdrawal guidance; present only for `cex` payment methods, else null. */
|
|
12763
|
+
cex: FundingCexGuidance | null;
|
|
12764
|
+
fees: FundingFee[];
|
|
12765
|
+
minAmount: string | null;
|
|
12766
|
+
}
|
|
12767
|
+
interface FundingSession {
|
|
12768
|
+
id: string;
|
|
12769
|
+
object: string;
|
|
12770
|
+
status: FundingSessionStatus;
|
|
12771
|
+
clientSecret: string;
|
|
12772
|
+
target: FundingTarget;
|
|
12773
|
+
amountUnits: string | null;
|
|
12774
|
+
metadata: Record<string, string> | null;
|
|
12775
|
+
externalId: string | null;
|
|
12776
|
+
strict: boolean;
|
|
12777
|
+
paymentMethod: FundingPaymentMethod | null;
|
|
12778
|
+
createdAt: number;
|
|
12779
|
+
expiresAt: number;
|
|
12780
|
+
}
|
|
12781
|
+
/**
|
|
12782
|
+
* Parameters for a Coinbase "Transfer funds" pay-link. Session-bound: the
|
|
12783
|
+
* destination chain and address come from the session, so the link can't be
|
|
12784
|
+
* redirected — the client only chooses the amount.
|
|
12785
|
+
*/
|
|
12786
|
+
interface PayLinkParams {
|
|
12787
|
+
/** Funding session (starts with fnd_) whose wallet receives the funds. */
|
|
12788
|
+
sessionId: string;
|
|
12789
|
+
/**
|
|
12790
|
+
* The session's client secret. Optional when the session was created on this
|
|
12791
|
+
* SDK instance (remembered from create()); required for sessions created elsewhere.
|
|
12792
|
+
*/
|
|
12793
|
+
clientSecret?: string;
|
|
12794
|
+
/** Amount to deliver, in the asset's human units (Coinbase enforces a minimum). */
|
|
12795
|
+
amount: string;
|
|
12796
|
+
/** Destination asset ticker; defaults to "USDC" server-side. */
|
|
12797
|
+
asset?: string;
|
|
12798
|
+
}
|
|
12799
|
+
/** A source currency available on a chain. */
|
|
12800
|
+
interface FundingCurrency {
|
|
12801
|
+
symbol: string;
|
|
12802
|
+
/** Contract address, or the zero address for the chain's native asset. */
|
|
12803
|
+
address: string;
|
|
12804
|
+
decimals: number;
|
|
12805
|
+
logo: string | null;
|
|
12806
|
+
/** True for the chain's native currency (ETH, SOL, POL, …). */
|
|
12807
|
+
native: boolean;
|
|
12808
|
+
}
|
|
12809
|
+
/** A source chain the rail can route from, with its routable currencies. */
|
|
12810
|
+
interface FundingChain {
|
|
12811
|
+
/** CAIP-2 chain id, e.g. "eip155:8453". */
|
|
12812
|
+
id: string;
|
|
12813
|
+
name: string;
|
|
12814
|
+
logo: string | null;
|
|
12815
|
+
vmType: string;
|
|
12816
|
+
currencies: FundingCurrency[];
|
|
12817
|
+
}
|
|
12818
|
+
declare class FundingApi {
|
|
12819
|
+
private request;
|
|
12820
|
+
/**
|
|
12821
|
+
* Client secrets remembered from create() responses, so follow-up calls in
|
|
12822
|
+
* the same SDK instance don't need to thread the secret manually. Passing an
|
|
12823
|
+
* explicit `clientSecret` always overrides (e.g. sessions created elsewhere).
|
|
12824
|
+
*/
|
|
12825
|
+
private readonly secrets;
|
|
12826
|
+
private resolveSecret;
|
|
12827
|
+
private remember;
|
|
12828
|
+
/** Funding session sub-resource: create → setPaymentMethod → get/wait. */
|
|
12829
|
+
readonly sessions: {
|
|
12830
|
+
create: (params: CreateFundingSessionParams) => Promise<FundingSession>;
|
|
12831
|
+
setPaymentMethod: (sessionId: string, params: {
|
|
12832
|
+
paymentMethod: FundingPaymentMethodInput;
|
|
12833
|
+
clientSecret?: string;
|
|
12834
|
+
}) => Promise<FundingSession>;
|
|
12835
|
+
get: (sessionId: string, params?: {
|
|
12836
|
+
clientSecret?: string;
|
|
12837
|
+
}) => Promise<FundingSession>;
|
|
12838
|
+
/**
|
|
12839
|
+
* Poll a session until it reaches a terminal status (`succeeded`, `bounced`,
|
|
12840
|
+
* or `expired`). Resolves with the terminal session; rejects on timeout.
|
|
12841
|
+
*/
|
|
12842
|
+
wait: (sessionId: string, params?: {
|
|
12843
|
+
clientSecret?: string;
|
|
12844
|
+
pollMs?: number;
|
|
12845
|
+
timeoutMs?: number;
|
|
12846
|
+
}) => Promise<FundingSession>;
|
|
12847
|
+
};
|
|
12848
|
+
/**
|
|
12849
|
+
* One-call deposit: create a session with the payment method set, then poll
|
|
12850
|
+
* until it reaches a terminal status (`succeeded`, `bounced`, or `expired`).
|
|
12851
|
+
* Bundles `sessions.create` + `sessions.wait` — the headless equivalent of the
|
|
12852
|
+
* React `useFunding().fund()` flow. Resolves with the terminal session; rejects
|
|
12853
|
+
* on timeout.
|
|
12854
|
+
*/
|
|
12855
|
+
readonly fund: (params: {
|
|
12856
|
+
target: FundingTarget;
|
|
12857
|
+
paymentMethod: FundingPaymentMethodInput;
|
|
12858
|
+
/** Lock the deposit to a fixed amount (destination base units). */
|
|
12859
|
+
amountUnits?: string;
|
|
12860
|
+
metadata?: Record<string, string>;
|
|
12861
|
+
/** Idempotency/correlation key — reusing it returns the existing session. */
|
|
12862
|
+
externalId?: string;
|
|
12863
|
+
/** true = single-use deposit address; false (default) = open/reusable. */
|
|
12864
|
+
strict?: boolean;
|
|
12865
|
+
/** Poll interval and overall timeout for the wait phase. */
|
|
12866
|
+
wait?: {
|
|
12867
|
+
pollMs?: number;
|
|
12868
|
+
timeoutMs?: number;
|
|
12869
|
+
};
|
|
12870
|
+
}) => Promise<FundingSession>;
|
|
12871
|
+
/**
|
|
12872
|
+
* Resolve a prefilled Coinbase "Transfer funds" URL that delivers the asset to
|
|
12873
|
+
* the session's wallet. Session-bound — the destination comes from the session,
|
|
12874
|
+
* so the client only chooses the amount. Powers the "send from an exchange" path.
|
|
12875
|
+
*/
|
|
12876
|
+
readonly payLink: (params: PayLinkParams) => Promise<string>;
|
|
12877
|
+
/**
|
|
12878
|
+
* The source chains + currencies the rail can route from — a live passthrough
|
|
12879
|
+
* of the provider's supported routes, for building the source picker.
|
|
12880
|
+
*/
|
|
12881
|
+
readonly chains: () => Promise<FundingChain[]>;
|
|
12882
|
+
}
|
|
12883
|
+
|
|
12661
12884
|
declare class ProxyApi {
|
|
12662
12885
|
private backendApiClients;
|
|
12663
12886
|
private validateAndRefreshToken;
|
|
@@ -12844,6 +13067,7 @@ declare class Openfort {
|
|
|
12844
13067
|
private embeddedWalletInstance?;
|
|
12845
13068
|
private userInstance?;
|
|
12846
13069
|
private proxyInstance?;
|
|
13070
|
+
private fundingInstance?;
|
|
12847
13071
|
private configuration;
|
|
12848
13072
|
eventEmitter: TypedEventEmitter<OpenfortEventMap>;
|
|
12849
13073
|
private iPasskeyHandler;
|
|
@@ -12856,6 +13080,7 @@ declare class Openfort {
|
|
|
12856
13080
|
get embeddedWallet(): EmbeddedWalletApi;
|
|
12857
13081
|
get user(): UserApi;
|
|
12858
13082
|
get proxy(): ProxyApi;
|
|
13083
|
+
get funding(): FundingApi;
|
|
12859
13084
|
private initializeSynchronously;
|
|
12860
13085
|
constructor(sdkConfiguration: OpenfortSDKConfiguration);
|
|
12861
13086
|
/**
|
|
@@ -13298,4 +13523,4 @@ declare function cryptoDigest(algorithm: string, data: BufferSource): Promise<Ar
|
|
|
13298
13523
|
*/
|
|
13299
13524
|
declare const openfortEvents: TypedEventEmitter<OpenfortEventMap>;
|
|
13300
13525
|
|
|
13301
|
-
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeHandshakeTimeoutError, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
|
13526
|
+
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, CreateFundingSessionParams, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, FundingApi, FundingCexGuidance, FundingChain, FundingCurrency, FundingFee, FundingPaymentMethod, FundingPaymentMethodInput, FundingSession, FundingSessionStatus, FundingSource, FundingTarget, FundingWalletDeeplink, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeHandshakeTimeoutError, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, PayLinkParams, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SDKConfiguration as e}from"../core/config/config.js";import{ConfigurationError as t,RequestError as s}from"../core/errors/openfortError.js";class n{async request(n,r){const i=e.getInstance();if(!i)throw new t("Configuration not found");const o=await fetch(`${i.backendUrl}${n}`,{...r,headers:{Authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"Content-Type":"application/json",...r?.headers??{}},signal:AbortSignal.timeout(3e4)});if(!o.ok){const e=await o.json().catch(()=>({})),t="string"==typeof e.error?e.error:e.error?.message;throw new s(t??"Openfort funding request failed",o.status)}return o.json()}secrets=new Map;resolveSecret(e,t){const s=t??this.secrets.get(e);if(!s)throw new Error(`No clientSecret known for funding session ${e} — pass it explicitly (it was returned when the session was created)`);return s}remember(e){return e.clientSecret&&this.secrets.set(e.id,e.clientSecret),e}sessions={create:async e=>this.remember(await this.request("/v2/funding/sessions",{method:"POST",body:JSON.stringify(e)})),setPaymentMethod:async(e,t)=>this.request(`/v2/funding/sessions/${e}/payment_methods`,{method:"POST",body:JSON.stringify({clientSecret:this.resolveSecret(e,t.clientSecret),paymentMethod:t.paymentMethod})}),get:async(e,t)=>{const s=this.resolveSecret(e,t?.clientSecret);return this.request(`/v2/funding/sessions/${e}?clientSecret=${encodeURIComponent(s)}`)},wait:async(e,t)=>{const s=t?.pollMs??4e3,n=t?.timeoutMs??18e5,r=Date.now()+n;for(;;){const n=await this.sessions.get(e,t);if("succeeded"===n.status||"bounced"===n.status||"expired"===n.status)return n;if(Date.now()>=r)throw new Error(`Timed out waiting for funding session ${e} (last status: ${n.status})`);await new Promise(e=>setTimeout(e,s))}}};fund=async e=>{const t=await this.sessions.create({target:e.target,paymentMethod:e.paymentMethod,amountUnits:e.amountUnits,metadata:e.metadata,externalId:e.externalId,strict:e.strict});return this.sessions.wait(t.id,e.wait)};payLink=async e=>{const{url:t}=await this.request("/v2/funding/pay_link",{method:"POST",body:JSON.stringify({sessionId:e.sessionId,clientSecret:this.resolveSecret(e.sessionId,e.clientSecret),amount:e.amount,asset:e.asset})});return t};chains=async()=>{const{chains:e}=await this.request("/v2/funding/chains");return e}}export{n as FundingApi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class i{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class s{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:s,overrides:a,thirdPartyAuth:r,debug:h}){this.shieldConfiguration=s,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=h,s?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{i as OpenfortConfiguration,t as SDKConfiguration,s as ShieldConfiguration};
|
|
1
|
+
import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class i{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class s{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;disableTelemetry;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:s,overrides:a,thirdPartyAuth:r,debug:l,disableTelemetry:h}){this.shieldConfiguration=s,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=l,this.disableTelemetry=h,s?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{i as OpenfortConfiguration,t as SDKConfiguration,s as ShieldConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AxiosError as e}from"axios";import{PACKAGE as t,VERSION as s}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const s=t.getDsn();if(!s)throw new Error("Sentry DSN is not set");if(s.projectId!==r.split("https://")[1].split("/")[1]||s.host!==r.split("@")[1].split("/")[0]||s.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,r,o,a)=>{if(r instanceof e){if(400===r.response?.status||401===r.response?.status)return;r.name=s,t.captureException(r,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:s}}})}else t.captureException(r,o,a)},t.captureError=(e,s,r,o)=>{const a=s.statusCode;if(400===a||401===a)return;const c=s,i=c.error,u=c.error_description,p=r?.captureContext;t.captureException(s,{...r,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...n.baseTags,context:e,errorClass:s.constructor.name}}})},n.sentryInstance=t}static get sentry(){return n.proxy}static async init({sentry:e,configuration:o}){if(e)
|
|
1
|
+
import{AxiosError as e}from"axios";import{PACKAGE as t,VERSION as s}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const s=t.getDsn();if(!s)throw new Error("Sentry DSN is not set");if(s.projectId!==r.split("https://")[1].split("/")[1]||s.host!==r.split("@")[1].split("/")[0]||s.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,r,o,a)=>{if(r instanceof e){if(400===r.response?.status||401===r.response?.status)return;r.name=s,t.captureException(r,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:s}}})}else t.captureException(r,o,a)},t.captureError=(e,s,r,o)=>{const a=s.statusCode;if(400===a||401===a)return;const c=s,i=c.error,u=c.error_description,p=r?.captureContext;t.captureException(s,{...r,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...n.baseTags,context:e,errorClass:s.constructor.name}}})},n.sentryInstance=t}static get sentry(){return n.proxy}static async init({sentry:e,configuration:o}){if(e)n.sentry=e;else if(!o?.disableTelemetry)try{const e=await import("@sentry/browser");n.sentry=new e.BrowserClient({dsn:r,release:`${t}@${s}`,integrations:[],stackParser:e.defaultStackParser,transport:e.makeFetchTransport}),n.baseTags={projectId:o?.baseConfiguration.publishableKey??"",sdk:t,sdkVersion:s},n.processQueuedCalls()}catch{}}static proxy=new Proxy({},{get:(e,t)=>n.sentryInstance&&"function"==typeof n.sentryInstance[t]?(...e)=>n.sentryInstance[t](...e):(...e)=>{n.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof n.sentryInstance[e]&&n.sentryInstance[e](...t)}),n.queuedCalls=[])}}const{sentry:o}=n;export{n as InternalSentry,o as sentry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as t}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as t}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{FundingApi as n}from"../api/funding.js";import{ProxyApi as a}from"../api/proxy.js";import{UserApi as s}from"../api/user.js";import{AuthManager as r}from"../auth/authManager.js";import{StorageKeys as o}from"../storage/istorage.js";import{LazyStorage as h}from"../storage/lazyStorage.js";import l from"../utils/typedEventEmitter.js";import{SDKConfiguration as d}from"./config/config.js";import{OPENFORT_AUTH_ERROR_CODES as c,OPENFORT_ERROR_CODES as u}from"./errors/authErrorCodes.js";import{ConfigurationError as g,SignerError as f,RequestError as m,OpenfortError as p}from"./errors/openfortError.js";import{InternalSentry as w}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";import{PasskeyHandler as y}from"./passkey/handler.js";class b{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;fundingInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new g("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new g("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new g("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new g("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}get funding(){if(!this.fundingInstance)throw new g("Openfort SDK not initialized. Please await waitForInitialization() before accessing funding.");return this.fundingInstance}initializeSynchronously(){try{this.iAuthManager=new r,this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new s(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.fundingInstance=new n,this.proxyInstance=new a(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new f(c.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new g("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new d(e),this.storage=new h(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new l,b.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{b.globalEventEmitter?.emit(e,...t)})})}else b.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new y({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),w.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return b.globalEventEmitter||(b.globalEventEmitter=new l),b.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new m("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=o.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await b.isStorageAccessible(this.storage))throw new p("Storage is not accessible. The SDK needs a working key/value store to persist the session. On React Native, ensure the app is code-signed (an unsigned build cannot use the keychain) and that expo-secure-store — or your `overrides.storage` implementation — is installed and reachable.",u.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{b as Openfort};
|
package/dist/sdk/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{PASSKEY_ERROR_CODES,PasskeyAssertionFailedError,PasskeyCreationFailedError,PasskeyPRFNotSupportedError,PasskeySeedInvalidError,PasskeyUserCancelledError}from"./core/passkey/errors.js";export{PasskeyHandler}from"./core/passkey/handler.js";export{arrayBufferToBase64URL,base64ToArrayBuffer}from"./core/passkey/utils.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{IframeHandshakeTimeoutError,IframeSignEmptyResponseError,IframeSignTimeoutError,MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,SessionEndedBeforeSetupError,WrongPasskeyError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";export{cryptoDigest}from"./utils/crypto.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
|
|
1
|
+
import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{FundingApi}from"./api/funding.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{PASSKEY_ERROR_CODES,PasskeyAssertionFailedError,PasskeyCreationFailedError,PasskeyPRFNotSupportedError,PasskeySeedInvalidError,PasskeyUserCancelledError}from"./core/passkey/errors.js";export{PasskeyHandler}from"./core/passkey/handler.js";export{arrayBufferToBase64URL,base64ToArrayBuffer}from"./core/passkey/utils.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{IframeHandshakeTimeoutError,IframeSignEmptyResponseError,IframeSignTimeoutError,MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,SessionEndedBeforeSetupError,WrongPasskeyError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";export{cryptoDigest}from"./utils/crypto.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function t(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const n=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${n}`:n}).join("")}function r(t){return`0x${t.toString(16)}`}
|
|
1
|
+
function t(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const n=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${n}`:n}).join("")}function r(t){return`0x${t.toString(16)}`}let n;function e(t){n=t}async function o(t,r){if(n)return n(t,r);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(t,r);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")}export{o as cryptoDigest,r as numberToHex,t as randomUUID,e as setCryptoDigestOverride};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="1.
|
|
1
|
+
const o="1.5.0",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as s,AccountTypeEnum as a}from"../../types/types.js";import{defaultChainRpcs as i}from"../../utils/chains/index.js";import{numberToHex as r}from"../../utils/crypto.js";import o from"../../utils/typedEventEmitter.js";import{addEthereumChain as n}from"./addEthereumChain.js";import{estimateGas as h}from"./estimateGas.js";import{getAssets as c}from"./getAssets.js";import{getCallStatus as p}from"./getCallsStatus.js";import{JsonRpcError as d,ProviderErrorCode as m,RpcErrorCode as w}from"./JsonRpcError.js";import{
|
|
1
|
+
import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as s,AccountTypeEnum as a}from"../../types/types.js";import{defaultChainRpcs as i}from"../../utils/chains/index.js";import{numberToHex as r}from"../../utils/crypto.js";import o from"../../utils/typedEventEmitter.js";import{addEthereumChain as n}from"./addEthereumChain.js";import{estimateGas as h}from"./estimateGas.js";import{getAssets as c}from"./getAssets.js";import{getCallStatus as p}from"./getCallsStatus.js";import{JsonRpcError as d,ProviderErrorCode as m,RpcErrorCode as w}from"./JsonRpcError.js";import{normalizeRpcErrorMessage as u}from"./normalizeRpcError.js";import{personalSign as l}from"./personalSign.js";import{registerSession as g}from"./registerSession.js";import{revokeSession as f}from"./revokeSession.js";import{sendCallsSync as S}from"./sendCallSync.js";import{sendCalls as A}from"./sendCalls.js";import{signTypedDataV4 as R}from"./signTypedDataV4.js";import{ProviderEvent as v}from"./types.js";import{prepareEOATransaction as _,parseTransactionRequest as E}from"./walletHelpers.js";class C{#t;#e;#s;#a;updateFeeSponsorship(t){this.#e=t}#i;#r;#o=null;#n;isOpenfort=!0;#h;constructor({storage:t,backendApiClients:e,openfortEventEmitter:a,feeSponsorshipId:i,ensureSigner:r,chains:n,validateAndRefreshSession:h}){this.#h=r,this.#t=t,this.#s=n,this.#e=i,this.#i=h,this.#n=e,this.#r=new o,a.on(s.ON_LOGOUT,this.#c),a.on(s.ON_SWITCH_ACCOUNT,this.#p)}#d=async()=>(this.#a||(this.#a=await this.#h()),this.#a);#c=async()=>{this.#a=void 0,this.#r.emit(v.DISCONNECT,{code:4900,message:"Disconnected"}),this.#r.emit(v.ACCOUNTS_CHANGED,[])};#p=async t=>{this.#r.emit(v.ACCOUNTS_CHANGED,[t])};async getRpcProvider(){if(!this.#o){const e=await t.fromStorage(this.#t),s=e?.chainId||(this.#s?Number(Object.keys(this.#s)[0]):void 0)||8453;await import("@ethersproject/providers").then(t=>{const e=this.#s?this.#s[s]:void 0;this.#o=new t.StaticJsonRpcProvider(e??i[s])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#m(s){switch(s.method){case"eth_accounts":{const e=await t.fromStorage(this.#t);return e?[e.address]:[]}case"eth_requestAccounts":{const e=await t.fromStorage(this.#t);if(e){const t=await this.getRpcProvider(),{chainId:s}=await t.detectNetwork();return this.#r.emit(v.ACCOUNTS_CONNECT,{chainId:r(s)}),[e.address]}throw new d(m.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const a=await t.fromStorage(this.#t),i=await this.#d(),r=await e.fromStorage(this.#t);if(!a||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[h]=s.params||[];h.chainId||(h.chainId=n.toString());const c=E(h),{serialize:p}=await import("@ethersproject/transactions"),w=t=>({legacy:0,eip2930:1,eip1559:2}[t]),{gas:u,...l}=c,g={...l,gasLimit:u,to:c.to??void 0,type:w(c.type)},f=p(g),{keccak256:S}=await import("@ethersproject/keccak256"),A=S(f);await this.#i();const R=await i.sign(A,!1,!1),{splitSignature:v}=await import("@ethersproject/bytes");return p(g,v(R))}case"eth_sendTransaction":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#i(),i?.accountType===a.EOA){const[t]=s.params||[],e=await this.getRpcProvider(),a=await _(t,e,i.address),r=await this.#m({method:"eth_signTransaction",params:[a]});return this.#m({method:"eth_sendRawTransaction",params:[r]})}return(await S({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);return await this.#i(),await S({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})}case"eth_estimateGas":{const a=await t.fromStorage(this.#t),i=await e.fromStorage(this.#t);if(!a||!i)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await h({params:s.params||[],account:a,authentication:i,backendClient:this.#n,feeSponsorshipId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await t.fromStorage(this.#t),a=await this.#d();if(!e)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();const i=await this.getRpcProvider();return await R({method:s.method,params:s.params||[],signer:a,implementationType:e.implementationType||e.type,rpcProvider:i,account:e})}case"personal_sign":{const e=await t.fromStorage(this.#t);if(!e)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const a=await this.#d();return await this.#i(),await l({params:s.params||[],signer:a,account:e})}case"eth_chainId":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return r(e)}case"wallet_switchEthereumChain":{const t=await this.#d();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new d(w.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#i();try{const e=parseInt(s.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const s=this.#s?this.#s[e]:void 0;this.#o=new t.StaticJsonRpcProvider(s??i[e])}),this.#r.emit(v.CHAIN_CHANGED,r(e))}catch(t){const e=t;throw new d(w.INTERNAL_ERROR,`Failed to switch chain: ${e.message}`)}return null}case"wallet_addEthereumChain":{await this.#d();const t=await this.getRpcProvider();return await n({params:s.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const i=await t.fromStorage(this.#t);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const r=await e.fromStorage(this.#t);if(!i||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await p({params:s.params||{},authentication:r,backendClient:this.#n})}case"wallet_sendCalls":{const[i,r,o]=await Promise.all([t.fromStorage(this.#t),this.#d(),e.fromStorage(this.#t)]);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();return await A({params:s.params?s.params[0].calls:[],signer:r,account:i,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),feeSponsorshipId:this.#e})}case"wallet_grantPermissions":{const i=await t.fromStorage(this.#t);if(i?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const r=await this.#d(),o=await e.fromStorage(this.#t);if(!i||!o)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await g({params:s.params||[],signer:r,account:i,authentication:o,backendClient:this.#n,feeSponsorshipId:this.#e})}case"wallet_revokePermissions":{const a=await t.fromStorage(this.#t),i=await this.#d(),r=await e.fromStorage(this.#t);if(!a||!r)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await f({params:s.params||[],signer:i,account:a,authentication:r,backendClient:this.#n,feeSponsorshipId:this.#e})}case"wallet_getCapabilities":{const e=await t.fromStorage(this.#t);if(e?.accountType===a.EOA)throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await this.getRpcProvider(),{chainId:o}=await i.detectNetwork();return{[r(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const a=await t.fromStorage(this.#t),i=await e.fromStorage(this.#t);if(!a||!i)throw new d(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await c({params:s.params?.[0],account:a,authentication:i,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(s.method,s.params||[]);default:throw new d(m.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(t){try{return await this.#m(t)}catch(t){if(t instanceof d)throw t;if(t instanceof Error)throw new d(w.INTERNAL_ERROR,u(t.message));throw new d(w.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{C as EvmProvider};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){const n=e.toLowerCase();return n.includes("insufficient funds")?"Insufficient funds: the wallet doesn't have enough native token to cover gas (plus any value). Top up the wallet and try again.":n.includes("execution reverted")||n.includes("reverted")?"Transaction reverted: the contract rejected this call.":n.includes("nonce too low")||n.includes("replacement transaction underpriced")?"Nonce conflict: another transaction from this wallet is still pending. Wait for it to confirm, then retry.":n.includes("intrinsic gas too low")||n.includes("gas required exceeds")||n.includes("out of gas")?"Gas error: the transaction needs more gas than is available or allowed.":e}export{e as normalizeRpcErrorMessage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{JsonRpcError as e,RpcErrorCode as s}from"./JsonRpcError.js";import{signMessage as r}from"./walletHelpers.js";const a=async({params:a,signer:t,account:o})=>{const n=a[0],i=a[1];if(!i||!n)throw new e(s.INVALID_PARAMS,"personal_sign requires an address and a message");if(i.toLowerCase()!==o.address.toLowerCase())throw new e(s.INVALID_PARAMS,"personal_sign requires the signer to be the from address");const{hashMessage:d}=await import("@ethersproject/hash"),{arrayify:p,isHexString:h}=await import("@ethersproject/bytes"),m=h(n)?p(n):n;return await r({hash:d(m),implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:t,address:i,salt:o.salt,factoryAddress:o.factoryAddress,ownerAddress:o.ownerAddress})};export{a as personalSign};
|
package/package.json
CHANGED