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