UNPKG

@privy-io/js-sdk-core

Version:

Vanilla JS client for the Privy Auth API

2 lines (1 loc) 5.12 kB
import e from"eventemitter3";import{PrivyClientError as t}from"../Error.mjs";import{EmbeddedProviderError as r,errorIndicatesRecoveryIsNeeded as a}from"./errors.mjs";import{isSupportedIframeRpcMethod as s}from"./methods.mjs";import{getJsonRpcProvider as i,populateTransactionRequest as n}from"./utils/index.mjs";import"./types.mjs";import"@ethersproject/abstract-signer";import"@ethersproject/providers";import"./gas/arbitrum.mjs";import"@ethersproject/bignumber";import"@privy-io/chains";import"./utils/ethers.mjs";import"./gas/bsc.mjs";import"./gas/op-stack.mjs";import"@ethersproject/contracts";import"@ethersproject/transactions";import"./gas/polygon.mjs";import"@ethersproject/units";import"fetch-retry";import"./utils/gas.mjs";class o extends e{async request(e){if(s(e.method))return this.handleIFrameRpc(e);switch(e.method){case"eth_accounts":case"eth_requestAccounts":return this._account.address?[this._account.address]:[];case"eth_chainId":return`0x${this._chainId.toString(16)}`;case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":{let t=e.params?.[0];return this.handleSendTransaction(t)}case"eth_populateTransactionRequest":{let t=e.params?.[0];return this.handlePopulateTransaction(t)}default:return this.handleJsonRpc(e)}}ensureChainId(e){let t={chainId:this._chainId,...e};return this.internalSwitchEthereumChain(t.chainId),t}internalSwitchEthereumChain(e){e&&Number(e)!==this._chainId&&(this._chainId=Number(e),this._jsonRpcProvider=i(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit("chainChanged",e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e);return n(this._account.address,t,this._jsonRpcProvider)}async handleSendTransaction(e){let t=this.ensureChainId(e),r=await n(this._account.address,t,this._jsonRpcProvider),a=await this.handleIFrameRpc({method:"eth_signTransaction",params:[r]});return await this.handleJsonRpc({method:"eth_sendRawTransaction",params:[a]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:`0x${this._chainId.toString(16)}`};this.internalSwitchEthereumChain(t.chainId);try{return await this._jsonRpcProvider.send("eth_estimateGas",[t])}catch(e){console.warn(`Gas estimation failed with error: ${e}. Retrying gas estimation by omitting the 'from' address`);try{return delete t.from,await this._jsonRpcProvider.send("eth_estimateGas",[t])}catch(t){throw console.warn(`Gas estimation failed with error: ${t} when omitting the 'from' address`),e}}}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new r(`Invalid params for ${e.method}`,4200);if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new r(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{let r=await this._privyInternal.getAccessToken();if(!r)throw Error("Missing privy token. User must be logged in");this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_started",{method:e.method,address:this._account.address});try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:r})}catch(e){let s=a(e);if(s&&"privy"===this._account.recovery_method)await this._walletProxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:r});else{if(!s||!this._onNeedsRecovery)throw e;{let e;await new Promise((async(r,a)=>{e=setTimeout((()=>a(new t({code:"embedded_wallet_recovery_error",error:"User-owned recovery timed out"}))),12e4),await(this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>r(!0)}))})).finally((()=>clearTimeout(e)))}}}return(await this._walletProxy.rpcWallet({accessToken:r,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:"ethereum"})).response.data}catch(r){console.error(r);let a=r instanceof Error?r.message:"Unable to make wallet request";throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_failed",{method:e.method,address:this._account.address,error:a}),new t({code:"embedded_wallet_request_error",error:a})}}async handleJsonRpc(e){return this._jsonRpcProvider.send(e.method,e.params??[])}toJSON(){return`PrivyEIP1193Provider { address: '${this._account.address}', chainId: ${this._chainId}, request: [Function] }`}constructor({walletProxy:e,privyInternal:t,account:r,entropyId:a,entropyIdVerifier:s,chains:n,onNeedsRecovery:o,chainId:h=n[0].id}){super(),this._walletProxy=e,this._privyInternal=t,this._account=r,this._entropyId=a,this._entropyIdVerifier=s,this._chainId=h,this._chains=n,this._onNeedsRecovery=o,this._jsonRpcProvider=i(h,n,{rpcUrls:[]},{appId:this._privyInternal.appId})}}export{o as EmbeddedWalletProvider};