UNPKG

@privy-io/js-sdk-core

Version:

Vanilla JS client for the Privy Auth API

2 lines (1 loc) 5.56 kB
"use strict";var e=require("eventemitter3"),t=require("viem"),r=require("@privy-io/ethereum"),a=require("../Error.js"),i=require("../wallet-api/unified-wallet.js"),s=require("./errors.js"),n=require("./stack/walletRpc.js"),c=require("./utils/index.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("./types.js"),require("../utils/encodings.js"),require("../wallet-api/rpc.js"),require("@privy-io/routes"),require("../wallet-api/generate-authorization-signature.js"),require("canonicalize"),require("./stack/wallet-api-eth-transaction.js"),require("./stack/wallet-api-eth-typed-data.js");var o=/*#__PURE__*/h(e);let d=new Set(["eth_sign","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"]);class l extends o.default{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.getPublicClient(this._chainId,this._chains,{rpcUrls:[]},{appId:this._privyInternal.appId}),this.emit("chainChanged",e))}async handlePopulateTransaction(e){let t=this.ensureChainId(e),a=r.toViemTransactionSerializable(t),{type:i,...s}=await this._client.prepareTransactionRequest({account:t.from??this._account.address,...a});return{...s,type:r.STRING_TO_NUMBER_TXN_TYPE[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.toHex(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=this.ensureChainId(t),i=r.toViemTransactionSerializable(a);return await this._client.estimateGas({account:a.from??this._account.address,...i})}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new s.EmbeddedProviderError(`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 s.EmbeddedProviderError(`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(i.isUnifiedWallet(r)){let{data:a}=await n.walletRpc({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=s.errorIndicatesRecoveryIsNeeded(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 a.PrivyClientError({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 a.PrivyClientError({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:h=s[0].id,appApi:o}){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._client=c.getPublicClient(h,s,{rpcUrls:[]},{appId:o.appId}),this._appApi=o}}exports.EmbeddedWalletProvider=l;