@privy-io/cross-app-connect
Version:
Privy cross app wallet connectors for wagmi and RainbowKit
2 lines (1 loc) • 2.46 kB
JavaScript
import{getCrossAppProviderDetails as t}from"./getCrossAppProviderDetails.mjs";import{sendRequestToPopup as e,PopupRequestError as i}from"./request.mjs";import{sendConnectionRequestToPopup as r}from"./sendConnectionRequestToPopup.mjs";import s from"./storage.mjs";import"./crypto.mjs";import"@noble/curves/secp256k1";import"@scure/base";import"buffer";import"fflate";import"./triggerPopup.mjs";const o=({providerAppId:t,chains:e,chainId:i,apiUrl:r,connectionOpts:s})=>new p(t,e,i,r,s);class p{get STORAGE_CONNECTION_KEY(){let{smartWalletMode:t}=this._connectionOpts??{};return`privy-caw:${this.providerAppId}:connection${t?":smart-wallet":""}`}get STORAGE_CHAIN_ID_KEY(){let{smartWalletMode:t}=this._connectionOpts??{};return`privy-caw:${this.providerAppId}:connection_chain_id${t?":smart-wallet":""}`}async getProviderUrl(){if(!this._providerUrl){let{url:e}=await t({providerAppId:this.providerAppId,apiUrl:this._apiUrl});this._providerUrl=e}return this._providerUrl}clearConnection(){this._sharedSecret=void 0,this._publicKey=void 0,this._address=void 0,s.del(this.STORAGE_CONNECTION_KEY),s.del(this.STORAGE_CHAIN_ID_KEY)}get chain(){return this.chains.find((({id:t})=>t===this.chainId))}get address(){return this._address}async requestConnection(){let{address:t,sharedSecret:e,publicKey:i,exp:o}=await r({providerAppId:this.providerAppId,providerUrl:await this.getProviderUrl(),connectionOpts:this._connectionOpts});s.put(this.STORAGE_CONNECTION_KEY,{address:t,sharedSecret:e,publicKey:i,exp:o}),this._address=t,this._sharedSecret=e,this._publicKey=i}switchChain({id:t}){this.chainId=t,s.put(this.STORAGE_CHAIN_ID_KEY,this.chainId)}async sendRequest(t,r){if(!this._sharedSecret||!this._publicKey)throw Error(`Must call 'eth_requestAccounts' before ${t}`);try{return await e({request:{method:t,params:r,chainId:this.chainId},apiUrl:await this.getProviderUrl(),publicKey:this._publicKey,providerAppId:this.providerAppId,sharedSecret:this._sharedSecret})}catch(t){throw t instanceof i&&"clear"===t.action&&this.clearConnection(),t}}constructor(t,e,i,r,o){this.providerAppId=t,this.chains=e,this._apiUrl=r??"https://auth.privy.io",this._connectionOpts=o;let p=s.get(this.STORAGE_CONNECTION_KEY),h=p&&p.exp>(new Date).getTime(),c=s.get(this.STORAGE_CHAIN_ID_KEY);this.chainId=i??c??e[0].id,h?(this._sharedSecret=p.sharedSecret,this._publicKey=p.publicKey,this._address=p.address):this.clearConnection(),this.getProviderUrl()}}export{o as createPrivyCrossAppClient};