UNPKG

@privy-io/js-sdk-core

Version:

Vanilla JS client for the Privy Auth API

2 lines (1 loc) 5.85 kB
import e from"eventemitter3";import{PrivyClientError as t}from"../Error.mjs";import{isUnifiedWallet as r}from"../wallet-api/unified-wallet.mjs";import{EmbeddedProviderError as a,errorIndicatesRecoveryIsNeeded as i}from"./errors.mjs";import{isSupportedIframeRpcMethod as s}from"./methods.mjs";import{walletRpc as n}from"./stack/walletRpc.mjs";import{getJsonRpcProvider as o,populateTransactionRequest as h}from"./utils/index.mjs";import"./types.mjs";import"../utils/encodings.mjs";import"../wallet-api/rpc.mjs";import"@privy-io/public-api";import"../wallet-api/generate-authorization-signature.mjs";import"canonicalize";import"./stack/wallet-api-eth-transaction.mjs";import"./stack/wallet-api-eth-typed-data.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 c 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=o(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit("chainChanged",e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e);return h(this._account.address,t,this._jsonRpcProvider)}async handleSendTransaction(e){let t=this.ensureChainId(e),r=await h(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 a(`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 a(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{let a=await this._privyInternal.getAccessToken();if(!a)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});let s=this._account;if(r(s)){let{data:t}=await n({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:e})=>this._walletProxy.signWithUserSigner({accessToken:a,message:e})},account:s,rpcRequest:{chainType:"ethereum",request:e}});return t}try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:a})}catch(e){let r=i(e);if(r&&"privy"===this._account.recovery_method)await this._walletProxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:a});else{if(!r||!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:a,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:i,chains:s,onNeedsRecovery:n,chainId:h=s[0].id,appApi:c}){super(),this._walletProxy=e,this._privyInternal=t,this._account=r,this._entropyId=a,this._entropyIdVerifier=i,this._chainId=h,this._chains=s,this._onNeedsRecovery=n,this._jsonRpcProvider=o(h,s,{rpcUrls:[]},{appId:c.appId}),this._appApi=c}}export{c as EmbeddedWalletProvider};