UNPKG

@privy-io/js-sdk-core

Version:

Vanilla JS client for the Privy Auth API

2 lines (1 loc) 5.3 kB
import e from"eventemitter3";import{toHex as t}from"viem";import{toViemTransactionSerializable as r,STRING_TO_NUMBER_TXN_TYPE as a}from"@privy-io/ethereum";import{PrivyClientError as i}from"../Error.mjs";import{isUnifiedWallet as s}from"../wallet-api/unified-wallet.mjs";import{EmbeddedProviderError as n,errorIndicatesRecoveryIsNeeded as o}from"./errors.mjs";import{walletRpc as h}from"./stack/walletRpc.mjs";import{getPublicClient as c}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";let d=new Set(["eth_sign","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"]);class p extends e{async request(e){if(d.has(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_signTransaction":{let t=e.params?.[0];return this.handleSignTransaction(t)}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._client=c(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit("chainChanged",e))}async handlePopulateTransaction(e){let t=r(this.ensureChainId(e)),{type:i,...s}=await this._client.prepareTransactionRequest(t);return{...s,type:a[i]}}async handleSignTransaction(e){let r={...e};for(let e of Object.keys(r)){let a=r[e];a&&"bigint"==typeof a&&(r[e]=t(a))}return await this.handleIFrameRpc({method:"eth_signTransaction",params:[r]})}async handleSendTransaction(e){let t=await this.handlePopulateTransaction(e),r=await this.handleSignTransaction(t);return await this.handleJsonRpc({method:"eth_sendRawTransaction",params:[r]})}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");let t=e.params?.[0],a=r(this.ensureChainId(t));return await this._client.estimateGas(a)}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new n(`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 n(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.internalSwitchEthereumChain(t)}async handleIFrameRpc(e){try{let t=await this._privyInternal.getAccessTokenInternal();if(!t)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 r=this._account;if(s(r)){let{data:a}=await h({context:{app:this._appApi,fetchPrivyRoute:(...e)=>this._privyInternal.fetch(...e),getCompiledPath:(...e)=>this._privyInternal.getPath(...e),signRequest:({message:e})=>this._walletProxy.signWithUserSigner({accessToken:t,message:e})},account:r,rpcRequest:{chainType:"ethereum",request:e}});return a}try{await this._walletProxy.connect({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t})}catch(e){let r=o(e);if(r&&"privy"===this._account.recovery_method)await this._walletProxy.recover({entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,accessToken:t});else{if(!r||!this._onNeedsRecovery)throw e;{let e;await new Promise((async(t,r)=>{e=setTimeout((()=>r(new i({code:"embedded_wallet_recovery_error",error:"User-owned recovery timed out"}))),12e4),await(this._onNeedsRecovery?.({recoveryMethod:this._account.recovery_method,onRecovered:()=>t(!0)}))})).finally((()=>clearTimeout(e)))}}}return(await this._walletProxy.rpcWallet({accessToken:t,request:e,entropyId:this._entropyId,entropyIdVerifier:this._entropyIdVerifier,hdWalletIndex:this._account.wallet_index,chainType:"ethereum"})).response.data}catch(t){console.error(t);let r=t instanceof Error?t.message:"Unable to make wallet request";throw this._privyInternal.createAnalyticsEvent("embedded_wallet_sdk_rpc_failed",{method:e.method,address:this._account.address,error:r}),new i({code:"embedded_wallet_request_error",error:r})}}async handleJsonRpc(e){return this._client.request(e)}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:o=s[0].id,appApi:h}){super(),this._walletProxy=e,this._privyInternal=t,this._account=r,this._entropyId=a,this._entropyIdVerifier=i,this._chainId=o,this._chains=s,this._onNeedsRecovery=n,this._client=c(o,s,{rpcUrls:[]},{appId:h.appId}),this._appApi=h}}export{p as EmbeddedWalletProvider};