@privy-io/wagmi-connector
Version:
A connector for Privy <> WAGMI.sh
2 lines (1 loc) • 6.69 kB
JavaScript
"use strict";var W=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var O=(t,e)=>{for(var r in e)W(t,r,{get:e[r],enumerable:!0})},Y=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!M.call(t,i)&&i!==r&&W(t,i,{get:()=>e[i],enumerable:!(n=q(e,i))||n.enumerable});return t};var B=t=>Y(W({},"__esModule",{value:!0}),t);var K={};O(K,{PrivyConnector:()=>h,PrivyWagmiConnector:()=>k,usePrivyWagmi:()=>F,useSwitchNetwork:()=>L});module.exports=B(K);var d=require("wagmi"),s=require("viem");function b(t){return typeof t=="string"?Number.parseInt(t,t.trim().substring(0,2)==="0x"?16:10):typeof t=="bigint"?Number(t):t}var h=class extends d.Connector{id="privy";name="Privy";activeWallet;provider;logoutFromPrivy;constructor({logout:e,chains:r,activeWallet:n}){super({chains:r,options:void 0}),this.logoutFromPrivy=e,this.activeWallet=n}get ready(){return!!this.activeWallet}getActiveWallet(){return this.activeWallet}async setActiveWallet(e){this.activeWallet=e;let r=await this.getChainId();await this.#t();let n=await this.getChainId();if(r&&r!==n)try{await this.switchChain(r)}catch{console.warn("Unable to switch new active wallet to the network of previously active wallet.")}this.onAccountsChanged([this.activeWallet.address])}async connect({chainId:e}={}){this.emit("message",{type:"connecting"});let r=await this.getAccount();await this.#t();let n=await this.getChainId(),i=this.isChainUnsupported(n);return e&&n!==e&&(n=(await this.switchChain(e)).id,i=this.isChainUnsupported(n)),{account:r,chain:{id:n,unsupported:i}}}async disconnect(){this.provider&&this.#e(this.provider)}async getAccount(){if(!this.activeWallet)throw new d.ConnectorNotFoundError;return(0,s.getAddress)(this.activeWallet.address)}async getChainId(){let r=await(await this.getProvider()).request({method:"eth_chainId"});return b(r)}async getProvider(){if(!this.activeWallet)throw new d.ConnectorNotFoundError;if(!this.provider)try{let e=await this.activeWallet.getEthereumProvider();this.provider=e}catch{throw new d.ConnectorNotFoundError}return this.provider}async getWalletClient({chainId:e}={}){let[r,n]=await Promise.all([this.getProvider(),this.getAccount()]),i=this.chains.find(o=>o.id===e);return(0,s.createWalletClient)({account:n,chain:i,transport:(0,s.custom)(r)})}async isAuthorized(){let[e,r,n]=await Promise.all([this.getProvider(),this.getAccount(),this.activeWallet?.isConnected()]);return!!r&&!!e&&!!n}async switchChain(e){let r=await this.getProvider(),n=(0,s.numberToHex)(e);try{let i=new Promise(o=>{let c=({chain:u})=>{u?.id===e&&(this.off("change",c),o())};this.on("change",c)});return await Promise.all([i,r.request({method:"wallet_switchEthereumChain",params:[{chainId:n.toString()}]})]),this.chains.find(o=>o.id===e)??{id:e,name:`Chain ${n}`,network:`${n}`,nativeCurrency:{name:"Ether",decimals:18,symbol:"ETH"},rpcUrls:{default:{http:[""]},public:{http:[""]}}}}catch(i){let o=this.chains.find(c=>c.id===e);if(!o)throw new d.ChainNotConfiguredError({chainId:e,connectorId:this.id});if(i.code===4902)try{return await r.request({method:"wallet_addEthereumChain",params:[{chainId:n,chainName:o.name,nativeCurrency:o.nativeCurrency,rpcUrls:[o.rpcUrls.public?.http[0]??""],blockExplorerUrls:this.getBlockExplorerUrls(o)}]}),o}catch(c){throw new s.UserRejectedRequestError(c)}throw this.#r(i)?new s.UserRejectedRequestError(i):new s.SwitchChainError(i)}}onAccountsChanged(e){e.length===0?this.emit("disconnect"):this.emit("change",{account:(0,s.getAddress)(this.activeWallet.address)})}onChainChanged=e=>{let r=b(e),n=this.isChainUnsupported(r);this.emit("change",{chain:{id:r,unsupported:n}})};async onDisconnect(e){e?.code===1013&&await this.getProvider()&&await this.getAccount()||this.emit("disconnect")}#r(e){return/(user rejected)/i.test(e.message)}#n(e){e.on("accountsChanged",this.onAccountsChanged.bind(this)),e.on("chainChanged",this.onChainChanged),e.on("disconnect",this.onDisconnect.bind(this))}#e(e){e.removeListener("accountsChanged",this.onAccountsChanged.bind(this)),e.removeListener("chainChanged",this.onChainChanged),e.removeListener("disconnect",this.onDisconnect.bind(this))}async#t(){let e=this.provider;this.provider=void 0;let r=await this.getProvider();e&&this.#e(e),this.#n(r)}};var a=require("react"),p=require("wagmi");var f=require("@privy-io/react-auth");var x=require("react");var m=require("wagmi"),g=require("react/jsx-runtime"),T=({children:t})=>{let{connector:e}=R(),{refetch:r}=(0,m.useWalletClient)(),{isConnected:n}=(0,m.useAccount)(),{connect:i,connectors:o,isLoading:c}=(0,m.useConnect)({connector:e});return(0,x.useEffect)(()=>{!n&&!c&&o.length&&e?.activeWallet&&i(),r()},[e?.activeWallet]),(0,g.jsx)(g.Fragment,{children:t})};var P="privy:wagmi:selected-wallet",S="privy:wagmi:selected-wallet-timestamp",G=t=>JSON.stringify({address:t.address,walletClientType:t.walletClientType,connectorType:t.connectorType}),H=t=>{try{return JSON.parse(t)}catch{return null}},I=(t,e=localStorage)=>{e.setItem(P,G(t)),e.setItem(S,Date.now().toString())},N=(t=localStorage)=>{t.removeItem(P),t.removeItem(S)},U=(t=localStorage)=>{let e=t.getItem(P),r=t.getItem(S);if(!e||!r)return null;let n=H(e);return n?{value:n,storedAt:Number(r)}:null};var y=require("react/jsx-runtime"),J=()=>{throw new Error("You must wrap your application with the `PrivyWagmiConnector` to invoke `setActiveWallet`")},E=(0,a.createContext)({setActiveWallet:J}),R=()=>{let{connector:t}=(0,a.useContext)(E);return{connector:t}},k=({wagmiChainsConfig:{chains:t,publicClient:e},privyConnectorOverride:r,children:n})=>{let{logout:i}=(0,f.usePrivy)(),{wallets:o}=(0,f.useWallets)(),[c,u]=(0,a.useState)(),A=(0,a.useCallback)(l=>{l?(I(l),u(l)):(N(),u(void 0))},[u]);(0,a.useEffect)(()=>{let l=U();if(!l)return;if(c&&o[0]&&l.storedAt<o[0].connectedAt){A(void 0);return}let D=o.find(w=>w.address===l.value.address&&w.connectorType===l.value.connectorType&&w.walletClientType===l.value.walletClientType);u(D)},[o]);let v=c??o[0],C=(0,a.useMemo)(()=>r instanceof h?r:new h({logout:i,chains:t}),[r]),_=(0,a.useMemo)(()=>(0,p.createConfig)({autoConnect:!0,connectors:[C],publicClient:e}),[C]);return(0,a.useEffect)(()=>{v&&C.setActiveWallet(v)},[v]),(0,y.jsx)(E.Provider,{value:{connector:C,activeWallet:v,setActiveWallet:A},children:(0,y.jsx)(p.WagmiConfig,{config:_,children:(0,y.jsx)(T,{children:n})})})},F=()=>{let{connector:t,activeWallet:e,setActiveWallet:r}=(0,a.useContext)(E);return{ready:t.ready,wallet:e,setActiveWallet:r}},L=(t={})=>(0,p.useSwitchNetwork)({throwForSwitchChainNotSupported:!0,...t});0&&(module.exports={PrivyConnector,PrivyWagmiConnector,usePrivyWagmi,useSwitchNetwork});