@privy-io/js-sdk-core 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +1 -1
- package/dist/index.d.ts +614 -54
- package/dist/index.js +1 -1
- package/package.json +30 -2
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var s=class{async syncWithToken(n){return null}};var i=class{async sendCode(n){return null}async loginWithCode(n,t){return null}async linkWithCode(n,t){return null}async unlink(n){return null}};var o=class{async sendCode(n){return null}async loginWithCode(n,t){return null}async linkWithCode(n,t){return null}async unlink(n){return null}};var l=class{constructor(){this.customProvider=new s,this.phone=new o,this.email=new i}async logout(){return null}};import c from"eventemitter3";var r=class extends c{constructor(){super(...arguments);this.request=async t=>t}};var a=class{async create(n){return new r}async getProvider(n){return new r}async getURL(){return null}async getMessageHandler(){return null}};var d=class{async get(){return null}};var u=class{constructor(){this.user=new d,this.auth=new l,this.embeddedWallet=new a}};var W=u;export{W as default};
|
|
1
|
+
var ne=(a,e,t)=>{if(!e.has(a))throw TypeError("Cannot "+t)};var r=(a,e,t)=>(ne(a,e,"read from private field"),t?t.call(a):e.get(a)),n=(a,e,t)=>{if(e.has(a))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(a):e.set(a,t)},o=(a,e,t,s)=>(ne(a,e,"write to private field"),s?s.call(a,t):e.set(a,t),t);var _=(a,e,t)=>(ne(a,e,"access private method"),t);import{TextEncoder as Et}from"text-encoding";import{logout as st}from"@privy-io/core-api";import{authenticateCustomJwtAccount as Ve}from"@privy-io/core-api";var w,A=class{constructor(e){n(this,w,void 0);o(this,w,e)}async syncWithToken(e){let t=await r(this,w).fetch(Ve,{body:{token:e}});return r(this,w).session.storeToken(t.token),r(this,w).session.storeRefreshToken(t.refresh_token),t}};w=new WeakMap;import{passwordlessAuthenticate as ze,passwordlessInit as Ye,passwordlessLink as Qe,passwordlessUnlink as Xe}from"@privy-io/core-api";var y,q=class{constructor(e){n(this,y,void 0);o(this,y,e)}async sendCode(e,t){return r(this,y).fetch(Ye,{body:{email:e,token:t}})}async loginWithCode(e,t){let s=await r(this,y).fetch(ze,{body:{email:e,code:t}});return r(this,y).session.storeToken(s.token),r(this,y).session.storeRefreshToken(s.refresh_token),s}async linkWithCode(e,t){return r(this,y).fetch(Qe,{body:{email:e,code:t}})}async unlink(e){return r(this,y).fetch(Xe,{body:{address:e}})}};y=new WeakMap;import{passwordlessSmsAuthenticate as Ze,passwordlessSmsInit as et,passwordlessSmsLink as tt,passwordlessSmsUnlink as rt}from"@privy-io/core-api";var m,U=class{constructor(e){n(this,m,void 0);o(this,m,e)}async sendCode(e,t){return r(this,m).fetch(et,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t){let s=await r(this,m).fetch(Ze,{body:{phoneNumber:e,code:t}});return r(this,m).session.storeToken(s.token),r(this,m).session.storeRefreshToken(s.refresh_token),s}async linkWithCode(e,t){return r(this,m).fetch(tt,{body:{phoneNumber:e,code:t}})}async unlink(e){return r(this,m).fetch(rt,{body:{phoneNumber:e}})}};m=new WeakMap;var u,O=class{constructor(e){n(this,u,void 0);o(this,u,e),this.phone=new U(r(this,u)),this.email=new q(r(this,u)),this.customProvider=new A(r(this,u))}async logout(){try{await r(this,u).fetch(st,{body:{refresh_token:r(this,u).session.refreshToken??void 0}})}catch{console.warn("Error destroying session")}r(this,u).session.destroyLocalState()}};u=new WeakMap;var ue={id:42161,name:"Arbitrum One",network:"arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]},default:{http:["https://arb1.arbitrum.io/rpc"]},public:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://arbiscan.io"},default:{name:"Arbiscan",url:"https://arbiscan.io"}}};var ve={id:421613,name:"Arbitrum Goerli",network:"arbitrum-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"AGOR",decimals:18},rpcUrls:{alchemy:{http:["https://arb-goerli.g.alchemy.com/v2"],webSocket:["wss://arb-goerli.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-goerli.infura.io/v3"],webSocket:["wss://arbitrum-goerli.infura.io/ws/v3"]},default:{http:["https://goerli-rollup.arbitrum.io/rpc"]},public:{http:["https://goerli-rollup.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"},default:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"}},testnet:!0};var fe={id:43114,name:"Avalanche",network:"avalanche",nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]},public:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://snowtrace.io"},default:{name:"SnowTrace",url:"https://snowtrace.io"}}};var ge={id:43113,name:"Avalanche Fuji",network:"avalanche-fuji",nativeCurrency:{decimals:18,name:"Avalanche Fuji",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax-test.network/ext/bc/C/rpc"]},public:{http:["https://api.avax-test.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://testnet.snowtrace.io"},default:{name:"SnowTrace",url:"https://testnet.snowtrace.io"}},testnet:!0};var be={id:8453,network:"base",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{blast:{http:["https://base-mainnet.blastapi.io"],webSocket:["wss://base-mainnet.blastapi.io"]},default:{http:["https://mainnet.base.org"]},public:{http:["https://mainnet.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://basescan.org"},default:{name:"Basescan",url:"https://basescan.org"}},testnet:!0};var Re={id:84531,network:"base-goerli",name:"Base Goerli Testnet",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{blast:{http:["https://base-goerli.blastapi.io"],webSocket:["wss://base-goerli.blastapi.io"]},default:{http:["https://goerli.base.org"]},public:{http:["https://goerli.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://goerli.basescan.org"},default:{name:"Basescan",url:"https://goerli.basescan.org"}},testnet:!0};var Te={id:42220,name:"Celo Mainnet",network:"celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]},infura:{http:["https://celo-mainnet.infura.io/v3"]},public:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/mainnet"},etherscan:{name:"CeloScan",url:"https://celoscan.io"}},testnet:!1};var we={id:44787,name:"Celo Alfajores Testnet",network:"celo-alfajores",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://alfajores-forno.celo-testnet.org"]},infura:{http:["https://celo-alfajores.infura.io/v3"]},public:{http:["https://alfajores-forno.celo-testnet.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/alfajores"},etherscan:{name:"CeloScan",url:"https://alfajores.celoscan.io/"}},testnet:!0};var Ee={id:314,name:"Filecoin - Mainnet",network:"filecoin-mainnet",nativeCurrency:{decimals:18,name:"filecoin",symbol:"FIL"},rpcUrls:{default:{http:["https://api.node.glif.io/rpc/v1"]},public:{http:["https://api.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filfox",url:"https://filfox.info/en"},filscan:{name:"Filscan",url:"https://filscan.io"},filscout:{name:"Filscout",url:"https://filscout.io/en"},glif:{name:"Glif",url:"https://explorer.glif.io"}}};var ke={id:314159,name:"Filecoin - Calibration testnet",network:"filecoin-calibration",nativeCurrency:{decimals:18,name:"testnet filecoin",symbol:"tFIL"},rpcUrls:{default:{http:["https://api.calibration.node.glif.io/rpc/v1"]},public:{http:["https://api.calibration.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filscan",url:"https://calibration.filscan.io"}}};var Pe={id:5,network:"goerli",name:"Goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://eth-goerli.g.alchemy.com/v2"],webSocket:["wss://eth-goerli.g.alchemy.com/v2"]},infura:{http:["https://goerli.infura.io/v3"],webSocket:["wss://goerli.infura.io/ws/v3"]},default:{http:["https://rpc.ankr.com/eth_goerli"]},public:{http:["https://rpc.ankr.com/eth_goerli"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://goerli.etherscan.io"},default:{name:"Etherscan",url:"https://goerli.etherscan.io"}},testnet:!0};var _e={id:59144,network:"linea-mainnet",name:"Linea Mainnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-mainnet.infura.io/v3"],webSocket:["wss://linea-mainnet.infura.io/ws/v3"]},default:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]},public:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://lineascan.build"},etherscan:{name:"Etherscan",url:"https://lineascan.build"}},testnet:!1};var Ce={id:59140,network:"linea-testnet",name:"Linea Goerli Testnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-goerli.infura.io/v3"],webSocket:["wss://linea-goerli.infura.io/ws/v3"]},default:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]},public:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.lineascan.build"},etherscan:{name:"Etherscan",url:"https://goerli.lineascan.build"}},testnet:!0};var xe={id:1,network:"homestead",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]},default:{http:["https://cloudflare-eth.com"]},public:{http:["https://cloudflare-eth.com"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://etherscan.io"},default:{name:"Etherscan",url:"https://etherscan.io"}}};var Ie={id:10,name:"OP Mainnet",network:"optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://opt-mainnet.g.alchemy.com/v2"],webSocket:["wss://opt-mainnet.g.alchemy.com/v2"]},infura:{http:["https://optimism-mainnet.infura.io/v3"],webSocket:["wss://optimism-mainnet.infura.io/ws/v3"]},default:{http:["https://mainnet.optimism.io"]},public:{http:["https://mainnet.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://optimistic.etherscan.io"},default:{name:"Optimism Explorer",url:"https://explorer.optimism.io"}}};var Se={id:420,name:"Optimism Goerli Testnet",network:"optimism-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://opt-goerli.g.alchemy.com/v2"],webSocket:["wss://opt-goerli.g.alchemy.com/v2"]},infura:{http:["https://optimism-goerli.infura.io/v3"],webSocket:["wss://optimism-goerli.infura.io/ws/v3"]},default:{http:["https://goerli.optimism.io"]},public:{http:["https://goerli.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"},default:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"}},testnet:!0};var We={id:137,name:"Polygon Mainnet",network:"matic",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{alchemy:{http:["https://polygon-mainnet.g.alchemy.com/v2"],webSocket:["wss://polygon-mainnet.g.alchemy.com/v2"]},infura:{http:["https://polygon-mainnet.infura.io/v3"],webSocket:["wss://polygon-mainnet.infura.io/ws/v3"]},default:{http:["https://polygon-rpc.com"]},public:{http:["https://polygon-rpc.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://polygonscan.com"},default:{name:"PolygonScan",url:"https://polygonscan.com"}}};var De={id:80001,name:"Mumbai",network:"maticmum",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{alchemy:{http:["https://polygon-mumbai.g.alchemy.com/v2"],webSocket:["wss://polygon-mumbai.g.alchemy.com/v2"]},infura:{http:["https://polygon-mumbai.infura.io/v3"],webSocket:["wss://polygon-mumbai.infura.io/ws/v3"]},default:{http:["https://matic-mumbai.chainstacklabs.com"]},public:{http:["https://matic-mumbai.chainstacklabs.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"},default:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"}},testnet:!0};var Ae={id:11155111,network:"sepolia",name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"SEP",decimals:18},rpcUrls:{alchemy:{http:["https://eth-sepolia.g.alchemy.com/v2"],webSocket:["wss://eth-sepolia.g.alchemy.com/v2"]},infura:{http:["https://sepolia.infura.io/v3"],webSocket:["wss://sepolia.infura.io/ws/v3"]},default:{http:["https://rpc.sepolia.org"]},public:{http:["https://rpc.sepolia.org"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://sepolia.etherscan.io"},default:{name:"Etherscan",url:"https://sepolia.etherscan.io"}},testnet:!0};var oe=[ue,ve,Pe,Ae,xe,Ie,Se,We,De,Te,we,Ee,ke,be,Re,_e,Ce,fe,ge],kr=new Set(oe.map(a=>a.id));import{StaticJsonRpcProvider as Me}from"@ethersproject/providers";import lt from"eventemitter3";var qe=["error","invalid_request_arguments","wallet_not_on_device","invalid_recovery_pin","insufficient_funds"];var ie=class extends Error{constructor(t,s,i){super(t);s instanceof Error&&(this.cause=s),this.privyErrorCode=i}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}};var g=class extends Error{constructor(t,s){super(s);this.type=t}},M=class extends ie{constructor(t,s,i){super(t,s,i);this.type="connector_error"}},N=class extends Error{constructor(t,s,i){super(t);this.code=s,this.data=i}};function at(a){let e=a.type;return typeof e=="string"&&qe.includes(e)}function pe(a){return at(a)&&a.type==="wallet_not_on_device"}var nt=["eth_accounts","eth_requestAccounts","eth_chainId","eth_estimateGas","wallet_switchEthereumChain"],ot=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4"],Ue=a=>ot.includes(a),Oe=a=>nt.includes(a);var it="4df5e2316331463a9130964bd6078dfa",pt="fe9c30fc-3bc5-4064-91e2-6ab5887f8f4d",le=(a,e,t)=>{let s=Number(a),i=e.find(l=>l.id===s);if(!i)throw new M(`Unsupported chainId ${a}`,4901);let p;if(t.rpcUrls[s]?p=t.rpcUrls[s]:i.rpcUrls.infura?.http[0]?p=i.rpcUrls.infura.http[0]+"/"+it:i.rpcUrls.blast?.http[0]?p=i.rpcUrls.blast.http[0]+"/"+pt:p=i.rpcUrls.default?.http[0],!p)throw new M(`No RPC url found for ${a}`);return p};var j,L,E,b,H,R,k=class extends lt{constructor({walletProxy:t,privyInternal:s,address:i,chains:p,chainId:l=1}){super();n(this,j,void 0);n(this,L,void 0);n(this,E,void 0);n(this,b,void 0);n(this,H,void 0);n(this,R,void 0);o(this,j,t),o(this,L,s),o(this,E,i),o(this,b,l),o(this,H,p),o(this,R,new Me(le(l,p,{rpcUrls:[]})))}async request(t){return Ue(t.method)?this.handleIFrameRpc(t):Oe(t.method)?this.handleStatic(t):t.method==="eth_estimateGas"?this.handleEstimateGas(t):this.handleJsonRpc(t)}async handleStatic(t){switch(t.method){case"eth_accounts":case"eth_requestAccounts":return r(this,E)?[r(this,E)]:[];case"eth_chainId":return`0x${r(this,b).toString(16)}`;case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(t)}}async handleEstimateGas(t){if(!t.params||!Array.isArray(t.params))throw new Error("Invalid params for eth_estimateGas");delete t.params[0].gasPrice,delete t.params[0].maxFeePerGas,delete t.params[0].maxPriorityFeePerGas;let s={...t.params[0],chainId:`0x${r(this,b).toString(16)}`};try{return await r(this,R).send("eth_estimateGas",[s])}catch{return delete s.from,await r(this,R).send("eth_estimateGas",[s])}}handleSwitchEthereumChain(t){if(!t.params||!Array.isArray(t.params))throw new N(`Invalid params for ${t.method}`,4200);let s;if(typeof t.params[0]=="string")s=t.params[0];else if("chainId"in t.params[0]&&typeof t.params[0].chainId=="string")s=t.params[0].chainId;else throw new N(`Invalid params for ${t.method}`,4200);o(this,b,Number(s)),o(this,R,new Me(le(r(this,b),r(this,H),{rpcUrls:[]}))),this.emit("chainChanged",s)}async handleIFrameRpc(t){try{let s=await r(this,L).getAccessToken();if(!s)throw new Error("Missing privy token. User must be logged in");return(await r(this,j).rpc({request:t,address:r(this,E),accessToken:s})).response.data}catch(s){throw console.error(s),new Error("Unable to make wallet request")}}async handleJsonRpc(t){return r(this,R).send(t.method,t.params??[])}};j=new WeakMap,L=new WeakMap,E=new WeakMap,b=new WeakMap,H=new WeakMap,R=new WeakMap;var X=class{constructor(){this.callbacks={}}enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let s=this.callbacks[t];if(!s)throw new Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":return s;case"privy:wallet:create":return s;case"privy:wallet:connect":return s;case"privy:wallet:recover":return s;case"privy:wallet:rpc":return s;default:throw new Error(`invalid wallet event type ${e}`)}}};var F=15e3;function C(a){return a.error!==void 0}var ct=function(a){return()=>`id-${a++}`}(0),dt=(a,e)=>typeof e=="bigint"?e.toString():e,ht=(a,e)=>`${a}${JSON.stringify(e,dt)}`,yt=a=>new Promise(e=>{setTimeout(e,a)}),G=(a,e)=>Promise.race([a,new Promise((t,s)=>{setTimeout(s,e)})]),v,x=class{constructor(e){n(this,v,void 0);this.ready=!1,this.cache=new Map,this.eventCallbacks=new X,o(this,v,e)}async create(e,t=F){return await this.waitForReady(),G(this.invoke("privy:wallet:create",e,r(this,v)),t)}async connect(e,t=F){return await this.waitForReady(),G(this.invoke("privy:wallet:connect",e,r(this,v)),t)}async recover(e,t=F){return await this.waitForReady(),G(this.invoke("privy:wallet:recover",e,r(this,v)),t)}async setPassword(e,t=F){return await this.waitForReady(),G(this.invoke("privy:wallet:set-recovery-password",e,r(this,v)),t)}async rpc(e,t=F){return await this.waitForReady(),G(this.invoke("privy:wallet:rpc",e,r(this,v)),t)}handleEmbeddedWalletMessages(e){switch(e.event){case"privy:iframe:ready":let t=this.eventCallbacks.dequeue(e.event,e.id);return C(e)?t.reject(new g(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":let s=this.eventCallbacks.dequeue(e.event,e.id);return C(e)?s.reject(new g(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:connect":let i=this.eventCallbacks.dequeue(e.event,e.id);return C(e)?i.reject(new g(e.error.type,e.error.message)):i.resolve(e.data);case"privy:wallet:recover":let p=this.eventCallbacks.dequeue(e.event,e.id);return C(e)?p.reject(new g(e.error.type,e.error.message)):p.resolve(e.data);case"privy:wallet:rpc":let l=this.eventCallbacks.dequeue(e.event,e.id);return C(e)?l.reject(new g(e.error.type,e.error.message)):l.resolve(e.data);case"privy:wallet:set-recovery-password":let f=this.eventCallbacks.dequeue(e.event,e.id);return C(e)?f.reject(new g(e.error.type,e.error.message)):f.resolve(e.data)}}async waitForReady(){if(!this.ready)return new Promise(async(e,t)=>{for(;!this.ready;)this.invoke("privy:iframe:ready",{},r(this,v)).then(()=>{this.ready=!0,e(null)}).catch(t),await yt(150)})}async invoke(e,t,s){let i=ht(e,t);if(e==="privy:wallet:create"){let l=this.cache.get(i);if(l)return l}let p=new Promise((l,f)=>{let ae=ct();this.eventCallbacks.enqueue(ae,{resolve:l,reject:f}),s.postMessage({id:ae,event:e,data:t},"*")}).finally(()=>{this.cache.delete(i)});return this.cache.set(i,p),p}};v=new WeakMap;var d,c,I,B,ce,$=class{constructor(e,t){n(this,B);n(this,d,void 0);n(this,c,void 0);n(this,I,oe.map(e=>e));o(this,d,e),t&&o(this,c,new x(t))}setMessagePoster(e){o(this,c,new x(e))}async create(e){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");if(!e&&r(this,d).config?.embedded_wallet_config.require_user_password_on_create)throw new Error("Password not provided yet is required by App configuration");let t=await r(this,d).getAccessToken();if(!t)throw new Error("User must be logged in to create an embedded wallet");let{address:s}=await r(this,c).create({accessToken:t,recoveryPassword:e});if(!s)throw new Error("Failed to create wallet");return new k({address:s,privyInternal:r(this,d),chains:r(this,I),walletProxy:r(this,c)})}async getProvider(e){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");let t=await _(this,B,ce).call(this,e);return new k({address:t,privyInternal:r(this,d),chains:r(this,I),walletProxy:r(this,c)})}async setPassword(e,t){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");let s=await _(this,B,ce).call(this,t),i=await r(this,d).getAccessToken();if(!i)throw new Error("User must be logged in to create an embedded wallet");return await r(this,c).setPassword({accessToken:i,address:s,recoveryPassword:e}),new k({address:s,privyInternal:r(this,d),chains:r(this,I),walletProxy:r(this,c)})}getURL(){return`${r(this,d).baseUrl}/apps/${r(this,d).appId}/embedded-wallets`}getMessageHandler(){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");return r(this,c).handleEmbeddedWalletMessages.bind(r(this,c))}};d=new WeakMap,c=new WeakMap,I=new WeakMap,B=new WeakSet,ce=async function(e){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");let{user:t,token:s}=await r(this,d).refreshSession();if(!s)throw new Error("User must be logged in to interact with embedded wallets");let i=t?.linked_accounts.find(l=>l.type==="wallet"&&l.connector_type==="embedded"&&l.wallet_client_type==="privy");if(!i)throw new Error("User doesn't have an embedded wallet. Create one first.");let p=i.address;try{return await r(this,c).connect({accessToken:s,address:p}),p}catch(l){if(pe(l)&&i.recovery_method==="privy")return await r(this,c).recover({accessToken:s,address:p,recoveryPassword:e}),p;throw pe(l)&&!e?new Error("User recovery password required"):l}};import $e from"fetch-retry";import{v4 as gt}from"uuid";import{getAppConfig as bt,recordAnalyticsEvent as Rt,refreshSession as Tt}from"@privy-io/core-api";var Ne="0.0.1";import J from"js-cookie";import*as je from"jose";var T=class{static parse(e){try{return new T(e)}catch{return null}}constructor(e){this.value=e,this._decoded=je.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){let t=Date.now(),s=(this.expiration-e)*1e3;return t>=s}};var de="privy:token",Le="privy-token",he="privy:refresh_token",He="privy-refresh-token",ut="privy-session",Fe="privy:session_transfer_token",vt=30,h,S,Z=class{constructor(e){n(this,h,void 0);n(this,S,!1);o(this,h,e.storage)}set isUsingServerCookies(e){o(this,S,e)}get token(){try{let e=r(this,h).get(de);return typeof e=="string"?new T(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=r(this,h).get(he);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get forkedToken(){try{let e=r(this,h).get(Fe);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get mightHaveServerCookies(){try{let e=J.get(ut);return e!==void 0&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(){return this.mightHaveServerCookies||typeof this.token=="string"&&typeof this.refreshToken=="string"}hasRecoveryCredentials(){return typeof this.forkedToken=="string"}hasActiveToken(){let e=T.parse(this.token);return e!==null&&!e.isExpired(vt)}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null),this.clearForkedToken()}storeToken(e){if(typeof e=="string"){if(r(this,h).put(de,e),!r(this,S)){let t=T.parse(e)?.expiration;J.set(Le,e,{sameSite:"Strict",secure:!0,expires:t?new Date(t*1e3):void 0})}}else r(this,h).del(de),J.remove(Le)}storeRefreshToken(e){typeof e=="string"?(r(this,h).put(he,e),r(this,S)||J.set(He,e,{sameSite:"Strict",secure:!0,expires:30})):(r(this,h).del(he),J.remove(He))}clearForkedToken(){r(this,h).del(Fe)}};h=new WeakMap,S=new WeakMap;var ft=a=>{let e=new AbortController;return setTimeout(()=>e.abort(),a),e.signal},Ge=ft;var wt="https://auth.privy.io",K,V,W,D,te,Be,re,Je,se,Ke,ee=class{constructor(e){n(this,te);n(this,re);n(this,se);n(this,K,void 0);n(this,V,void 0);n(this,W,`js-sdk-core:${Ne}`);n(this,D,void 0);this.baseUrl=e.baseUrl??wt,this.appId=e.appId,o(this,K,e.storage),o(this,V,gt()),o(this,W,e.sdkVersion??r(this,W)),this.session=new Z({storage:r(this,K),isUsingServerCookies:!1}),o(this,D,$e(fetch,{retries:3,retryDelay:500}))}async fetch(e,{body:t,params:s=void 0,options:i={onRequest:_(this,se,Ke).bind(this)}}){let p=new Request(`${this.baseUrl}${e.constructPath({params:s})}`,{method:e.method,body:JSON.stringify(t)}),l=await i.onRequest(p),f=await r(this,D).call(this,p,l);if(f.status!==e.expectedStatusCode)throw console.warn(`Privy: Expected status code ${e.expectedStatusCode}, received ${f.status}`),await f.json();return await f.json()}beforeRequestWithoutRefresh(e){let t=this.session.token,s=new Headers(e.headers);return s.set("privy-app-id",this.appId),s.set("privy-client",r(this,W)),s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json"),{signal:Ge(3e3),headers:s,credentials:"include"}}async getAppConfig(){return this.fetch(bt,{params:{app_id:this.appId},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}async createAnalyticsEvent(e,t){return this.fetch(Rt,{body:{event_name:e,client_id:r(this,V),payload:t}})}async refreshSession(){let e=await this.fetch(Tt,{body:{refresh_token:this.session.refreshToken??void 0},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}});return this.session.storeToken(e.token),this.session.storeRefreshToken(e.refresh_token),e}async getAccessToken(){let e=this.session.token;if(e&&!this.session.hasActiveToken&&this.session.hasRefreshCredentials()){let{token:t}=await this.refreshSession();return t}return e}};K=new WeakMap,V=new WeakMap,W=new WeakMap,D=new WeakMap,te=new WeakSet,Be=function(){return!!this.config},re=new WeakSet,Je=async function(){r(this,te,Be)||(this.config=await this.getAppConfig(),this.config?.custom_api_url&&(this.baseUrl=this.config.custom_api_url,o(this,D,$e(fetch,{retries:3,retryDelay:500})),this.session.isUsingServerCookies=!0),this.createAnalyticsEvent("sdk_initialize",{}))},se=new WeakSet,Ke=async function(e){return await _(this,re,Je).call(this),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)};var Y,z=class{constructor(e){n(this,Y,void 0);o(this,Y,e)}async get(){return await r(this,Y).refreshSession()}};Y=new WeakMap;var P,Q=class{constructor(e){n(this,P,void 0);o(this,P,new ee(e)),this.user=new z(r(this,P)),this.auth=new O(r(this,P)),this.embeddedWallet=new $(r(this,P),e.embeddedWalletMessagePoster)}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}};P=new WeakMap;var ye=class{get(e){let t=localStorage.getItem(e);return t===null?void 0:JSON.parse(t)}put(e,t){t!==void 0?localStorage.setItem(e,JSON.stringify(t)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}};var me=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,t){t!==void 0?this._cache[e]=t:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}};globalThis.TextEncoder??=Et;var Ps=Q;export{me as InMemoryCache,ye as LocalStorage,Ps as default};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,63 +1,602 @@
|
|
|
1
|
+
import { InferRouteTypes } from '@privy-io/api-base';
|
|
2
|
+
import { refreshSession } from '@privy-io/core-api';
|
|
1
3
|
import EventEmitter from 'eventemitter3';
|
|
2
4
|
|
|
3
5
|
declare class CustomProvider {
|
|
6
|
+
#private;
|
|
4
7
|
/**
|
|
5
8
|
* Logs a user in via a custom JWT from another (non-Privy) service
|
|
6
9
|
*
|
|
7
|
-
* @param token The JWT
|
|
10
|
+
* @param token The JWT from the non-Privy service
|
|
8
11
|
*/
|
|
9
|
-
syncWithToken(
|
|
12
|
+
syncWithToken(token: string): Promise<{
|
|
13
|
+
token: string | null;
|
|
14
|
+
refresh_token: string | null;
|
|
15
|
+
user: {
|
|
16
|
+
id: string;
|
|
17
|
+
created_at: number;
|
|
18
|
+
linked_accounts: ({
|
|
19
|
+
type: "email";
|
|
20
|
+
address: string;
|
|
21
|
+
verified_at: number;
|
|
22
|
+
} | {
|
|
23
|
+
type: "phone";
|
|
24
|
+
phoneNumber: string;
|
|
25
|
+
verified_at: number;
|
|
26
|
+
} | {
|
|
27
|
+
type: "wallet";
|
|
28
|
+
address: string;
|
|
29
|
+
chain_type: "ethereum";
|
|
30
|
+
verified_at: number;
|
|
31
|
+
wallet_client: "unknown";
|
|
32
|
+
chain_id?: string | undefined;
|
|
33
|
+
wallet_client_type?: string | undefined;
|
|
34
|
+
connector_type?: string | undefined;
|
|
35
|
+
} | {
|
|
36
|
+
type: "wallet";
|
|
37
|
+
address: string;
|
|
38
|
+
chain_type: "ethereum";
|
|
39
|
+
verified_at: number;
|
|
40
|
+
chain_id: "eip155:1";
|
|
41
|
+
wallet_client: "privy";
|
|
42
|
+
wallet_client_type: "privy";
|
|
43
|
+
connector_type: "embedded";
|
|
44
|
+
recovery_method: "privy" | "user-passcode";
|
|
45
|
+
} | {
|
|
46
|
+
type: "google_oauth";
|
|
47
|
+
name: string | null;
|
|
48
|
+
email: string;
|
|
49
|
+
subject: string;
|
|
50
|
+
verified_at: number;
|
|
51
|
+
} | {
|
|
52
|
+
type: "twitter_oauth";
|
|
53
|
+
name: string | null;
|
|
54
|
+
subject: string;
|
|
55
|
+
username: string | null;
|
|
56
|
+
verified_at: number;
|
|
57
|
+
} | {
|
|
58
|
+
type: "discord_oauth";
|
|
59
|
+
email: string | null;
|
|
60
|
+
subject: string;
|
|
61
|
+
username: string | null;
|
|
62
|
+
verified_at: number;
|
|
63
|
+
} | {
|
|
64
|
+
type: "github_oauth";
|
|
65
|
+
name: string | null;
|
|
66
|
+
email: string | null;
|
|
67
|
+
subject: string;
|
|
68
|
+
username: string | null;
|
|
69
|
+
verified_at: number;
|
|
70
|
+
} | {
|
|
71
|
+
type: "apple_oauth";
|
|
72
|
+
email: string | null;
|
|
73
|
+
subject: string;
|
|
74
|
+
verified_at: number;
|
|
75
|
+
} | {
|
|
76
|
+
type: "custom_auth";
|
|
77
|
+
custom_user_id: string;
|
|
78
|
+
verified_at: number;
|
|
79
|
+
})[];
|
|
80
|
+
};
|
|
81
|
+
is_new_user?: boolean | undefined;
|
|
82
|
+
}>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* We support a subset of the provider methods found here:
|
|
87
|
+
*
|
|
88
|
+
* https://ethereum.org/en/developers/docs/apis/json-rpc/#json-rpc-methods
|
|
89
|
+
*
|
|
90
|
+
* For now, we're focused on signing-related methods because the iframe (this code)
|
|
91
|
+
* is the only place that has access to the private key and thus is the only one
|
|
92
|
+
* who can create signatures. All other methods do not need the private key and
|
|
93
|
+
* can therefore be implemented by clients of the iframe.
|
|
94
|
+
*/
|
|
95
|
+
|
|
96
|
+
type Quantity = string | number | bigint;
|
|
97
|
+
type UnsignedTransactionRequest = {
|
|
98
|
+
from?: string;
|
|
99
|
+
to?: string;
|
|
100
|
+
nonce?: Quantity;
|
|
101
|
+
gasLimit?: Quantity;
|
|
102
|
+
gasPrice?: Quantity;
|
|
103
|
+
data?: ArrayLike<number> | string;
|
|
104
|
+
value?: Quantity;
|
|
105
|
+
chainId?: number;
|
|
106
|
+
type?: number;
|
|
107
|
+
accessList?: Array<{
|
|
108
|
+
address: string;
|
|
109
|
+
storageKeys: Array<string>;
|
|
110
|
+
}> | Array<[string, Array<string>]> | Record<string, Array<string>>;
|
|
111
|
+
maxPriorityFeePerGas?: Quantity;
|
|
112
|
+
maxFeePerGas?: Quantity;
|
|
113
|
+
};
|
|
114
|
+
interface eth_populateTransactionRequestResponse {
|
|
115
|
+
method: 'eth_populateTransactionRequest';
|
|
116
|
+
data: UnsignedTransactionRequest;
|
|
117
|
+
}
|
|
118
|
+
interface eth_signResponse {
|
|
119
|
+
method: 'eth_sign';
|
|
120
|
+
data: string;
|
|
121
|
+
}
|
|
122
|
+
interface personal_signResponse {
|
|
123
|
+
method: 'personal_sign';
|
|
124
|
+
data: string;
|
|
125
|
+
}
|
|
126
|
+
interface eth_signTransactionResponse {
|
|
127
|
+
method: 'eth_signTransaction';
|
|
128
|
+
data: string;
|
|
129
|
+
}
|
|
130
|
+
interface eth_signTypedData_v4Response {
|
|
131
|
+
method: 'eth_signTypedData_v4';
|
|
132
|
+
data: string;
|
|
133
|
+
}
|
|
134
|
+
type RpcResponseType = eth_signTransactionResponse | eth_populateTransactionRequestResponse | eth_signResponse | personal_signResponse | eth_signTypedData_v4Response;
|
|
135
|
+
type PrivyEventType = 'privy:iframe:ready' | 'privy:wallet:create' | 'privy:wallet:connect' | 'privy:wallet:recover' | 'privy:wallet:rpc' | 'privy:wallet:set-recovery-password';
|
|
136
|
+
type IframeReadyResponseDataType = Record<string, never>;
|
|
137
|
+
type WalletCreateResponseDataType = {
|
|
138
|
+
address: string;
|
|
139
|
+
};
|
|
140
|
+
type WalletConnectResponseDataType = {
|
|
141
|
+
address: string;
|
|
142
|
+
};
|
|
143
|
+
type WalletRecoverResponseDataType = {
|
|
144
|
+
address: string;
|
|
145
|
+
};
|
|
146
|
+
type WalletSetRecoveryPasswordResponseDataType = {
|
|
147
|
+
address: string;
|
|
148
|
+
};
|
|
149
|
+
type WalletRpcResponseDataType = {
|
|
150
|
+
address: string;
|
|
151
|
+
response: RpcResponseType;
|
|
152
|
+
};
|
|
153
|
+
declare const PrivyIframeErrorTypes: readonly ["error", "invalid_request_arguments", "wallet_not_on_device", "invalid_recovery_pin", "insufficient_funds"];
|
|
154
|
+
type PrivyIframeErrorTypesType = (typeof PrivyIframeErrorTypes)[number];
|
|
155
|
+
interface PrivyResponseBaseEventType {
|
|
156
|
+
id: string;
|
|
157
|
+
event: PrivyEventType;
|
|
158
|
+
}
|
|
159
|
+
interface PrivyErrorResponseEventType extends PrivyResponseBaseEventType {
|
|
160
|
+
error: {
|
|
161
|
+
type: PrivyIframeErrorTypesType;
|
|
162
|
+
message: string;
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
interface IframeReadyResponseEventType extends PrivyResponseBaseEventType {
|
|
166
|
+
event: 'privy:iframe:ready';
|
|
167
|
+
data: IframeReadyResponseDataType;
|
|
168
|
+
}
|
|
169
|
+
interface WalletCreateResponseEventType extends PrivyResponseBaseEventType {
|
|
170
|
+
event: 'privy:wallet:create';
|
|
171
|
+
data: WalletCreateResponseDataType;
|
|
172
|
+
}
|
|
173
|
+
interface WalletConnectResponseEventType extends PrivyResponseBaseEventType {
|
|
174
|
+
event: 'privy:wallet:connect';
|
|
175
|
+
data: WalletConnectResponseDataType;
|
|
176
|
+
}
|
|
177
|
+
interface WalletRecoverResponseEventType extends PrivyResponseBaseEventType {
|
|
178
|
+
event: 'privy:wallet:recover';
|
|
179
|
+
data: WalletRecoverResponseDataType;
|
|
180
|
+
}
|
|
181
|
+
interface WalletSetRecoveryPasswordResponseEventType extends PrivyResponseBaseEventType {
|
|
182
|
+
event: 'privy:wallet:set-recovery-password';
|
|
183
|
+
data: WalletSetRecoveryPasswordResponseDataType;
|
|
10
184
|
}
|
|
185
|
+
interface WalletRpcResponseEventType extends PrivyResponseBaseEventType {
|
|
186
|
+
event: 'privy:wallet:rpc';
|
|
187
|
+
data: WalletRpcResponseDataType;
|
|
188
|
+
}
|
|
189
|
+
type PrivyResponseEvent = IframeReadyResponseEventType | PrivyErrorResponseEventType | WalletCreateResponseEventType | WalletConnectResponseEventType | WalletRecoverResponseEventType | WalletSetRecoveryPasswordResponseEventType | WalletRpcResponseEventType;
|
|
190
|
+
type EmbeddedWalletMessagePoster = {
|
|
191
|
+
postMessage: (message: any, targetOrigin: string, transfer?: Transferable) => void;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
declare enum PrivyErrorCode {
|
|
195
|
+
MISSING_OR_INVALID_PRIVY_APP_ID = "missing_or_invalid_privy_app_id",
|
|
196
|
+
MISSING_OR_INVALID_PRIVY_ACCOUNT_ID = "missing_or_invalid_privy_account_id",
|
|
197
|
+
INVALID_DATA = "invalid_data",
|
|
198
|
+
LINKED_TO_ANOTHER_USER = "linked_to_another_user",
|
|
199
|
+
ALLOWLIST_REJECTED = "allowlist_rejected",
|
|
200
|
+
OAUTH_USER_DENIED = "oauth_user_denied",
|
|
201
|
+
UNKNOWN_AUTH_ERROR = "unknown_auth_error",
|
|
202
|
+
USER_EXITED_AUTH_FLOW = "exited_auth_flow",
|
|
203
|
+
MUST_BE_AUTHENTICATED = "must_be_authenticated",
|
|
204
|
+
UNKNOWN_CONNECT_WALLET_ERROR = "unknown_connect_wallet_error",
|
|
205
|
+
GENERIC_CONNECT_WALLET_ERROR = "generic_connect_wallet_error",
|
|
206
|
+
CLIENT_REQUEST_TIMEOUT = "client_request_timeout",
|
|
207
|
+
INVALID_CREDENTIALS = "invalid_credentials"
|
|
208
|
+
}
|
|
209
|
+
declare abstract class PrivyError extends Error {
|
|
210
|
+
/**
|
|
211
|
+
* Privy error type.
|
|
212
|
+
*/
|
|
213
|
+
abstract type: string;
|
|
214
|
+
/**
|
|
215
|
+
* Original Error object, it the error originated client-side.
|
|
216
|
+
*/
|
|
217
|
+
cause?: Error;
|
|
218
|
+
/**
|
|
219
|
+
* An optional error code, often included in Privy API responses.
|
|
220
|
+
*/
|
|
221
|
+
privyErrorCode?: PrivyErrorCode;
|
|
222
|
+
/**
|
|
223
|
+
* @param type Privy error type.
|
|
224
|
+
* @param message Human-readable message.
|
|
225
|
+
* @param cause Source of this error.
|
|
226
|
+
*/
|
|
227
|
+
protected constructor(message: string, cause?: unknown, privyErrorCode?: PrivyErrorCode);
|
|
228
|
+
toString(): string;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* A ProviderRpcError combines the necessary bits of the {PrivyError} with the
|
|
232
|
+
* EIP-compliant ProviderRpcError. This is meant to be a type around errors raised
|
|
233
|
+
* by the ethereum provider.
|
|
234
|
+
*/
|
|
235
|
+
declare class ProviderRpcError extends PrivyError {
|
|
236
|
+
type: string;
|
|
237
|
+
readonly code: number;
|
|
238
|
+
readonly data?: unknown;
|
|
239
|
+
constructor(message: string, code: number, data?: unknown);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
type ProviderConnectInfo = {
|
|
243
|
+
chainId: string;
|
|
244
|
+
};
|
|
245
|
+
type OnConnectEventHandler = (connectInfo: ProviderConnectInfo) => void;
|
|
246
|
+
type OnDisconnectEventHandler = (error: ProviderRpcError) => void;
|
|
247
|
+
type OnChainChangedEventHandler = (chainId: string | number) => void;
|
|
248
|
+
type OnAccountsChangedEventHandler = (accounts: string[]) => void;
|
|
249
|
+
type ProviderMessage = {
|
|
250
|
+
type: string;
|
|
251
|
+
data: unknown;
|
|
252
|
+
};
|
|
253
|
+
type OnMessageEventHandler = (message: ProviderMessage) => void;
|
|
254
|
+
type EIP1193OnEventHandler = OnConnectEventHandler | OnDisconnectEventHandler | OnChainChangedEventHandler | OnAccountsChangedEventHandler | OnMessageEventHandler;
|
|
255
|
+
interface EIP1193Provider {
|
|
256
|
+
request: (request: {
|
|
257
|
+
method: string;
|
|
258
|
+
params?: Array<unknown> | undefined;
|
|
259
|
+
}) => Promise<unknown>;
|
|
260
|
+
on: (eventName: string, listener: EIP1193OnEventHandler) => unknown;
|
|
261
|
+
removeListener: (eventName: string | symbol, listener: (...args: unknown[]) => void) => unknown;
|
|
262
|
+
}
|
|
263
|
+
type RequestArguments = {
|
|
264
|
+
method: string;
|
|
265
|
+
params?: Array<any> | undefined;
|
|
266
|
+
};
|
|
267
|
+
declare class EmbeddedWalletProvider extends EventEmitter implements EIP1193Provider {
|
|
268
|
+
#private;
|
|
269
|
+
request(request: RequestArguments): Promise<any>;
|
|
270
|
+
private handleStatic;
|
|
271
|
+
private handleEstimateGas;
|
|
272
|
+
private handleSwitchEthereumChain;
|
|
273
|
+
private handleIFrameRpc;
|
|
274
|
+
private handleJsonRpc;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
type AuthenticatedUser = InferRouteTypes<typeof refreshSession>['expectedResponse'];
|
|
278
|
+
type User$1 = NonNullable<AuthenticatedUser['user']>;
|
|
279
|
+
type LinkedAccount = User$1['linked_accounts'];
|
|
280
|
+
type PrivyEmbeddedWalletProvider = EmbeddedWalletProvider;
|
|
11
281
|
|
|
12
282
|
declare class Email {
|
|
283
|
+
#private;
|
|
13
284
|
/**
|
|
14
285
|
* Sends a one time login code to a user's email address
|
|
15
286
|
*
|
|
16
287
|
* @param email The email address to send the one time login code
|
|
288
|
+
* @param token A CAPTCHA token
|
|
17
289
|
*/
|
|
18
|
-
sendCode(
|
|
290
|
+
sendCode(email: string, token?: string): Promise<{
|
|
291
|
+
success: boolean;
|
|
292
|
+
}>;
|
|
19
293
|
/**
|
|
20
|
-
* Logs a user in via an email and one time code
|
|
294
|
+
* Logs a user in via an email address and one time code
|
|
21
295
|
*
|
|
22
|
-
* @param
|
|
296
|
+
* @param email The email address that the one time code was sent to
|
|
23
297
|
* @param code The one time code
|
|
24
298
|
*/
|
|
25
|
-
loginWithCode(
|
|
299
|
+
loginWithCode(email: string, code: string): Promise<AuthenticatedUser>;
|
|
26
300
|
/**
|
|
27
|
-
* Links an email
|
|
301
|
+
* Links an email adress to an existing user
|
|
28
302
|
*
|
|
29
|
-
* @param
|
|
303
|
+
* @param email The email address that the one time code was sent to
|
|
30
304
|
* @param code The one time code
|
|
31
305
|
*/
|
|
32
|
-
linkWithCode(
|
|
33
|
-
|
|
306
|
+
linkWithCode(email: string, code: string): Promise<{
|
|
307
|
+
id: string;
|
|
308
|
+
created_at: number;
|
|
309
|
+
linked_accounts: ({
|
|
310
|
+
type: "email";
|
|
311
|
+
address: string;
|
|
312
|
+
verified_at: number;
|
|
313
|
+
} | {
|
|
314
|
+
type: "phone";
|
|
315
|
+
phoneNumber: string;
|
|
316
|
+
verified_at: number;
|
|
317
|
+
} | {
|
|
318
|
+
type: "wallet";
|
|
319
|
+
address: string;
|
|
320
|
+
chain_type: "ethereum";
|
|
321
|
+
verified_at: number;
|
|
322
|
+
wallet_client: "unknown";
|
|
323
|
+
chain_id?: string | undefined;
|
|
324
|
+
wallet_client_type?: string | undefined;
|
|
325
|
+
connector_type?: string | undefined;
|
|
326
|
+
} | {
|
|
327
|
+
type: "wallet";
|
|
328
|
+
address: string;
|
|
329
|
+
chain_type: "ethereum";
|
|
330
|
+
verified_at: number;
|
|
331
|
+
chain_id: "eip155:1";
|
|
332
|
+
wallet_client: "privy";
|
|
333
|
+
wallet_client_type: "privy";
|
|
334
|
+
connector_type: "embedded";
|
|
335
|
+
recovery_method: "privy" | "user-passcode";
|
|
336
|
+
} | {
|
|
337
|
+
type: "google_oauth";
|
|
338
|
+
name: string | null;
|
|
339
|
+
email: string;
|
|
340
|
+
subject: string;
|
|
341
|
+
verified_at: number;
|
|
342
|
+
} | {
|
|
343
|
+
type: "twitter_oauth";
|
|
344
|
+
name: string | null;
|
|
345
|
+
subject: string;
|
|
346
|
+
username: string | null;
|
|
347
|
+
verified_at: number;
|
|
348
|
+
} | {
|
|
349
|
+
type: "discord_oauth";
|
|
350
|
+
email: string | null;
|
|
351
|
+
subject: string;
|
|
352
|
+
username: string | null;
|
|
353
|
+
verified_at: number;
|
|
354
|
+
} | {
|
|
355
|
+
type: "github_oauth";
|
|
356
|
+
name: string | null;
|
|
357
|
+
email: string | null;
|
|
358
|
+
subject: string;
|
|
359
|
+
username: string | null;
|
|
360
|
+
verified_at: number;
|
|
361
|
+
} | {
|
|
362
|
+
type: "apple_oauth";
|
|
363
|
+
email: string | null;
|
|
364
|
+
subject: string;
|
|
365
|
+
verified_at: number;
|
|
366
|
+
} | {
|
|
367
|
+
type: "custom_auth";
|
|
368
|
+
custom_user_id: string;
|
|
369
|
+
verified_at: number;
|
|
370
|
+
})[];
|
|
371
|
+
}>;
|
|
372
|
+
unlink(email: string): Promise<{
|
|
373
|
+
id: string;
|
|
374
|
+
created_at: number;
|
|
375
|
+
linked_accounts: ({
|
|
376
|
+
type: "email";
|
|
377
|
+
address: string;
|
|
378
|
+
verified_at: number;
|
|
379
|
+
} | {
|
|
380
|
+
type: "phone";
|
|
381
|
+
phoneNumber: string;
|
|
382
|
+
verified_at: number;
|
|
383
|
+
} | {
|
|
384
|
+
type: "wallet";
|
|
385
|
+
address: string;
|
|
386
|
+
chain_type: "ethereum";
|
|
387
|
+
verified_at: number;
|
|
388
|
+
wallet_client: "unknown";
|
|
389
|
+
chain_id?: string | undefined;
|
|
390
|
+
wallet_client_type?: string | undefined;
|
|
391
|
+
connector_type?: string | undefined;
|
|
392
|
+
} | {
|
|
393
|
+
type: "wallet";
|
|
394
|
+
address: string;
|
|
395
|
+
chain_type: "ethereum";
|
|
396
|
+
verified_at: number;
|
|
397
|
+
chain_id: "eip155:1";
|
|
398
|
+
wallet_client: "privy";
|
|
399
|
+
wallet_client_type: "privy";
|
|
400
|
+
connector_type: "embedded";
|
|
401
|
+
recovery_method: "privy" | "user-passcode";
|
|
402
|
+
} | {
|
|
403
|
+
type: "google_oauth";
|
|
404
|
+
name: string | null;
|
|
405
|
+
email: string;
|
|
406
|
+
subject: string;
|
|
407
|
+
verified_at: number;
|
|
408
|
+
} | {
|
|
409
|
+
type: "twitter_oauth";
|
|
410
|
+
name: string | null;
|
|
411
|
+
subject: string;
|
|
412
|
+
username: string | null;
|
|
413
|
+
verified_at: number;
|
|
414
|
+
} | {
|
|
415
|
+
type: "discord_oauth";
|
|
416
|
+
email: string | null;
|
|
417
|
+
subject: string;
|
|
418
|
+
username: string | null;
|
|
419
|
+
verified_at: number;
|
|
420
|
+
} | {
|
|
421
|
+
type: "github_oauth";
|
|
422
|
+
name: string | null;
|
|
423
|
+
email: string | null;
|
|
424
|
+
subject: string;
|
|
425
|
+
username: string | null;
|
|
426
|
+
verified_at: number;
|
|
427
|
+
} | {
|
|
428
|
+
type: "apple_oauth";
|
|
429
|
+
email: string | null;
|
|
430
|
+
subject: string;
|
|
431
|
+
verified_at: number;
|
|
432
|
+
} | {
|
|
433
|
+
type: "custom_auth";
|
|
434
|
+
custom_user_id: string;
|
|
435
|
+
verified_at: number;
|
|
436
|
+
})[];
|
|
437
|
+
}>;
|
|
34
438
|
}
|
|
35
439
|
|
|
36
440
|
declare class Phone {
|
|
441
|
+
#private;
|
|
37
442
|
/**
|
|
38
443
|
* Sends a one time login code to a user's phone number via sms
|
|
39
444
|
*
|
|
40
445
|
* @param phoneNumber The phone number to send the one time login code
|
|
446
|
+
* @param token A CAPTCHA token
|
|
41
447
|
*/
|
|
42
|
-
sendCode(
|
|
448
|
+
sendCode(phoneNumber: string, token?: string): Promise<{
|
|
449
|
+
success: boolean;
|
|
450
|
+
}>;
|
|
43
451
|
/**
|
|
44
452
|
* Logs a user in via a phone number and one time code
|
|
45
453
|
*
|
|
46
454
|
* @param phoneNumber The phone number that the one time code was sent to
|
|
47
455
|
* @param code The one time code
|
|
48
456
|
*/
|
|
49
|
-
loginWithCode(
|
|
457
|
+
loginWithCode(phoneNumber: string, code: string): Promise<AuthenticatedUser>;
|
|
50
458
|
/**
|
|
51
459
|
* Links a phone number to an existing user
|
|
52
460
|
*
|
|
53
461
|
* @param phoneNumber The phone number that the one time code was sent to
|
|
54
462
|
* @param code The one time code
|
|
55
463
|
*/
|
|
56
|
-
linkWithCode(
|
|
57
|
-
|
|
464
|
+
linkWithCode(phoneNumber: string, code: string): Promise<{
|
|
465
|
+
id: string;
|
|
466
|
+
created_at: number;
|
|
467
|
+
linked_accounts: ({
|
|
468
|
+
type: "email";
|
|
469
|
+
address: string;
|
|
470
|
+
verified_at: number;
|
|
471
|
+
} | {
|
|
472
|
+
type: "phone";
|
|
473
|
+
phoneNumber: string;
|
|
474
|
+
verified_at: number;
|
|
475
|
+
} | {
|
|
476
|
+
type: "wallet";
|
|
477
|
+
address: string;
|
|
478
|
+
chain_type: "ethereum";
|
|
479
|
+
verified_at: number;
|
|
480
|
+
wallet_client: "unknown";
|
|
481
|
+
chain_id?: string | undefined;
|
|
482
|
+
wallet_client_type?: string | undefined;
|
|
483
|
+
connector_type?: string | undefined;
|
|
484
|
+
} | {
|
|
485
|
+
type: "wallet";
|
|
486
|
+
address: string;
|
|
487
|
+
chain_type: "ethereum";
|
|
488
|
+
verified_at: number;
|
|
489
|
+
chain_id: "eip155:1";
|
|
490
|
+
wallet_client: "privy";
|
|
491
|
+
wallet_client_type: "privy";
|
|
492
|
+
connector_type: "embedded";
|
|
493
|
+
recovery_method: "privy" | "user-passcode";
|
|
494
|
+
} | {
|
|
495
|
+
type: "google_oauth";
|
|
496
|
+
name: string | null;
|
|
497
|
+
email: string;
|
|
498
|
+
subject: string;
|
|
499
|
+
verified_at: number;
|
|
500
|
+
} | {
|
|
501
|
+
type: "twitter_oauth";
|
|
502
|
+
name: string | null;
|
|
503
|
+
subject: string;
|
|
504
|
+
username: string | null;
|
|
505
|
+
verified_at: number;
|
|
506
|
+
} | {
|
|
507
|
+
type: "discord_oauth";
|
|
508
|
+
email: string | null;
|
|
509
|
+
subject: string;
|
|
510
|
+
username: string | null;
|
|
511
|
+
verified_at: number;
|
|
512
|
+
} | {
|
|
513
|
+
type: "github_oauth";
|
|
514
|
+
name: string | null;
|
|
515
|
+
email: string | null;
|
|
516
|
+
subject: string;
|
|
517
|
+
username: string | null;
|
|
518
|
+
verified_at: number;
|
|
519
|
+
} | {
|
|
520
|
+
type: "apple_oauth";
|
|
521
|
+
email: string | null;
|
|
522
|
+
subject: string;
|
|
523
|
+
verified_at: number;
|
|
524
|
+
} | {
|
|
525
|
+
type: "custom_auth";
|
|
526
|
+
custom_user_id: string;
|
|
527
|
+
verified_at: number;
|
|
528
|
+
})[];
|
|
529
|
+
}>;
|
|
530
|
+
unlink(phoneNumber: string): Promise<{
|
|
531
|
+
id: string;
|
|
532
|
+
created_at: number;
|
|
533
|
+
linked_accounts: ({
|
|
534
|
+
type: "email";
|
|
535
|
+
address: string;
|
|
536
|
+
verified_at: number;
|
|
537
|
+
} | {
|
|
538
|
+
type: "phone";
|
|
539
|
+
phoneNumber: string;
|
|
540
|
+
verified_at: number;
|
|
541
|
+
} | {
|
|
542
|
+
type: "wallet";
|
|
543
|
+
address: string;
|
|
544
|
+
chain_type: "ethereum";
|
|
545
|
+
verified_at: number;
|
|
546
|
+
wallet_client: "unknown";
|
|
547
|
+
chain_id?: string | undefined;
|
|
548
|
+
wallet_client_type?: string | undefined;
|
|
549
|
+
connector_type?: string | undefined;
|
|
550
|
+
} | {
|
|
551
|
+
type: "wallet";
|
|
552
|
+
address: string;
|
|
553
|
+
chain_type: "ethereum";
|
|
554
|
+
verified_at: number;
|
|
555
|
+
chain_id: "eip155:1";
|
|
556
|
+
wallet_client: "privy";
|
|
557
|
+
wallet_client_type: "privy";
|
|
558
|
+
connector_type: "embedded";
|
|
559
|
+
recovery_method: "privy" | "user-passcode";
|
|
560
|
+
} | {
|
|
561
|
+
type: "google_oauth";
|
|
562
|
+
name: string | null;
|
|
563
|
+
email: string;
|
|
564
|
+
subject: string;
|
|
565
|
+
verified_at: number;
|
|
566
|
+
} | {
|
|
567
|
+
type: "twitter_oauth";
|
|
568
|
+
name: string | null;
|
|
569
|
+
subject: string;
|
|
570
|
+
username: string | null;
|
|
571
|
+
verified_at: number;
|
|
572
|
+
} | {
|
|
573
|
+
type: "discord_oauth";
|
|
574
|
+
email: string | null;
|
|
575
|
+
subject: string;
|
|
576
|
+
username: string | null;
|
|
577
|
+
verified_at: number;
|
|
578
|
+
} | {
|
|
579
|
+
type: "github_oauth";
|
|
580
|
+
name: string | null;
|
|
581
|
+
email: string | null;
|
|
582
|
+
subject: string;
|
|
583
|
+
username: string | null;
|
|
584
|
+
verified_at: number;
|
|
585
|
+
} | {
|
|
586
|
+
type: "apple_oauth";
|
|
587
|
+
email: string | null;
|
|
588
|
+
subject: string;
|
|
589
|
+
verified_at: number;
|
|
590
|
+
} | {
|
|
591
|
+
type: "custom_auth";
|
|
592
|
+
custom_user_id: string;
|
|
593
|
+
verified_at: number;
|
|
594
|
+
})[];
|
|
595
|
+
}>;
|
|
58
596
|
}
|
|
59
597
|
|
|
60
598
|
declare class Auth {
|
|
599
|
+
#private;
|
|
61
600
|
/**
|
|
62
601
|
* APIs for login with a custom JWT
|
|
63
602
|
*/
|
|
@@ -70,52 +609,22 @@ declare class Auth {
|
|
|
70
609
|
* APIs for passwordless login with email
|
|
71
610
|
*/
|
|
72
611
|
readonly email: Email;
|
|
73
|
-
constructor();
|
|
74
612
|
/**
|
|
75
613
|
* Logs the current user out.
|
|
76
614
|
*/
|
|
77
|
-
logout(): Promise<
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
type ProviderConnectInfo = {
|
|
81
|
-
chainId: string;
|
|
82
|
-
};
|
|
83
|
-
type OnConnectEventHandler = (connectInfo: ProviderConnectInfo) => void;
|
|
84
|
-
type OnDisconnectEventHandler = (error: Error) => void;
|
|
85
|
-
type OnChainChangedEventHandler = (chainId: string | number) => void;
|
|
86
|
-
type OnAccountsChangedEventHandler = (accounts: string[]) => void;
|
|
87
|
-
type ProviderMessage = {
|
|
88
|
-
type: string;
|
|
89
|
-
data: unknown;
|
|
90
|
-
};
|
|
91
|
-
type OnMessageEventHandler = (message: ProviderMessage) => void;
|
|
92
|
-
type EIP1193OnEventHandler = OnConnectEventHandler | OnDisconnectEventHandler | OnChainChangedEventHandler | OnAccountsChangedEventHandler | OnMessageEventHandler;
|
|
93
|
-
interface EIP1193Provider {
|
|
94
|
-
request: (request: {
|
|
95
|
-
method: string;
|
|
96
|
-
params?: Array<unknown> | undefined;
|
|
97
|
-
}) => Promise<unknown>;
|
|
98
|
-
on: (eventName: string, listener: EIP1193OnEventHandler) => unknown;
|
|
99
|
-
removeListener: (eventName: string | symbol, listener: (...args: unknown[]) => void) => unknown;
|
|
100
|
-
}
|
|
101
|
-
declare class EmbeddedWalletProvider extends EventEmitter implements EIP1193Provider {
|
|
102
|
-
request: (request: {
|
|
103
|
-
method: string;
|
|
104
|
-
params?: Array<unknown> | undefined;
|
|
105
|
-
}) => Promise<{
|
|
106
|
-
method: string;
|
|
107
|
-
params?: Array<unknown> | undefined;
|
|
108
|
-
}>;
|
|
615
|
+
logout(): Promise<void>;
|
|
109
616
|
}
|
|
110
617
|
|
|
111
618
|
declare class EmbeddedWallet {
|
|
619
|
+
#private;
|
|
620
|
+
setMessagePoster(poster: EmbeddedWalletMessagePoster): void;
|
|
112
621
|
/**
|
|
113
622
|
* Creates an embedded wallet
|
|
114
623
|
*
|
|
115
624
|
* @param password Recovery password for the embedded wallet
|
|
116
625
|
* @returns EmbeddedWalletProvider implementing EIP1193Provider
|
|
117
626
|
*/
|
|
118
|
-
create(
|
|
627
|
+
create(password?: string): Promise<EmbeddedWalletProvider>;
|
|
119
628
|
/**
|
|
120
629
|
* Retrieve this users embedded wallet.
|
|
121
630
|
* If the wallet has never been used on this device recover.
|
|
@@ -123,11 +632,19 @@ declare class EmbeddedWallet {
|
|
|
123
632
|
* @param password Recovery password for the embedded wallet
|
|
124
633
|
* @returns EmbeddedWalletProvider implementing EIP1193Provider
|
|
125
634
|
*/
|
|
126
|
-
getProvider(
|
|
635
|
+
getProvider(password?: string): Promise<EmbeddedWalletProvider>;
|
|
636
|
+
/**
|
|
637
|
+
* Add or change the password used to recover an embedded wallet.
|
|
638
|
+
*
|
|
639
|
+
* @param password New recovery password
|
|
640
|
+
* @param currentPassword Current recovery password used to recover the embedded wallet
|
|
641
|
+
* @returns EmbeddedWalletProvider implementing EIP1193Provider
|
|
642
|
+
*/
|
|
643
|
+
setPassword(password: string, currentPassword?: string): Promise<EmbeddedWalletProvider>;
|
|
127
644
|
/**
|
|
128
645
|
* @returns URL to load in the embedded wallet iframe
|
|
129
646
|
*/
|
|
130
|
-
getURL():
|
|
647
|
+
getURL(): string;
|
|
131
648
|
/**
|
|
132
649
|
* @returns Allows the user to subscribe
|
|
133
650
|
* to the response events from the embedded wallet iframe
|
|
@@ -136,17 +653,41 @@ declare class EmbeddedWallet {
|
|
|
136
653
|
* const handler = privy.wallet.getMessageHandler()
|
|
137
654
|
* window.addEventListener('message', handler)
|
|
138
655
|
*/
|
|
139
|
-
getMessageHandler():
|
|
656
|
+
getMessageHandler(): (event: PrivyResponseEvent) => void;
|
|
140
657
|
}
|
|
141
658
|
|
|
142
659
|
declare class User {
|
|
660
|
+
#private;
|
|
143
661
|
/**
|
|
144
662
|
* Get the logged in user.
|
|
145
663
|
*/
|
|
146
|
-
get(): Promise<
|
|
664
|
+
get(): Promise<AuthenticatedUser>;
|
|
147
665
|
}
|
|
148
666
|
|
|
667
|
+
interface Storage {
|
|
668
|
+
get(key: string): unknown;
|
|
669
|
+
put(key: string, value: unknown): void;
|
|
670
|
+
del(key: string): void;
|
|
671
|
+
getKeys(): string[];
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* `PrivyOptions` to setup the `Privy` SDK
|
|
676
|
+
*/
|
|
677
|
+
type PrivyOptions = {
|
|
678
|
+
/** The `Storage` instance to be used */
|
|
679
|
+
storage: Storage;
|
|
680
|
+
/** The application ID */
|
|
681
|
+
appId: string;
|
|
682
|
+
/** A reference the the embedded wallet iframe content window */
|
|
683
|
+
embeddedWalletMessagePoster?: EmbeddedWalletMessagePoster;
|
|
684
|
+
};
|
|
685
|
+
/**
|
|
686
|
+
* Class definition for `Privy`
|
|
687
|
+
* TODO: need doc pass
|
|
688
|
+
*/
|
|
149
689
|
declare class Privy {
|
|
690
|
+
#private;
|
|
150
691
|
/**
|
|
151
692
|
* APIs for interacting with a user's embedded wallet
|
|
152
693
|
*/
|
|
@@ -159,7 +700,26 @@ declare class Privy {
|
|
|
159
700
|
* APIs for interacting with a user's embedded wallet
|
|
160
701
|
*/
|
|
161
702
|
readonly embeddedWallet: EmbeddedWallet;
|
|
162
|
-
|
|
703
|
+
/** Create a new `Privy` Client */
|
|
704
|
+
constructor(o: PrivyOptions);
|
|
705
|
+
setMessagePoster(poster: EmbeddedWalletMessagePoster): void;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
declare class LocalStorage implements Storage {
|
|
709
|
+
get(key: string): any;
|
|
710
|
+
put(key: string, val: unknown): void;
|
|
711
|
+
del(key: string): void;
|
|
712
|
+
getKeys(): string[];
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
declare class InMemoryCache implements Storage {
|
|
716
|
+
_cache: {
|
|
717
|
+
[key: string]: unknown;
|
|
718
|
+
};
|
|
719
|
+
get(key: string): unknown;
|
|
720
|
+
put(key: string, val: unknown): void;
|
|
721
|
+
del(key: string): void;
|
|
722
|
+
getKeys(): string[];
|
|
163
723
|
}
|
|
164
724
|
|
|
165
|
-
export { Privy as default };
|
|
725
|
+
export { AuthenticatedUser, InMemoryCache, LinkedAccount, LocalStorage, PrivyEmbeddedWalletProvider, User$1 as User, Privy as default };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var v=Object.create;var p=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var E=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var P=(e,n)=>{for(var r in n)p(e,r,{get:n[r],enumerable:!0})},g=(e,n,r,m)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of f(n))!b.call(e,s)&&s!==r&&p(e,s,{get:()=>n[s],enumerable:!(m=h(n,s))||m.enumerable});return e};var _=(e,n,r)=>(r=e!=null?v(E(e)):{},g(n||!e||!e.__esModule?p(r,"default",{value:e,enumerable:!0}):r,e)),C=e=>g(p({},"__esModule",{value:!0}),e);var H={};P(H,{default:()=>w});module.exports=C(H);var i=class{async syncWithToken(n){return null}};var o=class{async sendCode(n){return null}async loginWithCode(n,r){return null}async linkWithCode(n,r){return null}async unlink(n){return null}};var l=class{async sendCode(n){return null}async loginWithCode(n,r){return null}async linkWithCode(n,r){return null}async unlink(n){return null}};var a=class{constructor(){this.customProvider=new i,this.phone=new l,this.email=new o}async logout(){return null}};var y=_(require("eventemitter3")),t=class extends y.default{constructor(){super(...arguments);this.request=async r=>r}};var d=class{async create(n){return new t}async getProvider(n){return new t}async getURL(){return null}async getMessageHandler(){return null}};var u=class{async get(){return null}};var c=class{constructor(){this.user=new u,this.auth=new a,this.embeddedWallet=new d}};var w=c;
|
|
1
|
+
"use strict";var nt=Object.create;var te=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty;var ct=(a,e)=>{for(var t in e)te(a,t,{get:e[t],enumerable:!0})},we=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of it(e))!lt.call(a,n)&&n!==t&&te(a,n,{get:()=>e[n],enumerable:!(s=ot(e,n))||s.enumerable});return a};var re=(a,e,t)=>(t=a!=null?nt(pt(a)):{},we(e||!a||!a.__esModule?te(t,"default",{value:a,enumerable:!0}):t,a)),dt=a=>we(te({},"__esModule",{value:!0}),a);var he=(a,e,t)=>{if(!e.has(a))throw TypeError("Cannot "+t)};var r=(a,e,t)=>(he(a,e,"read from private field"),t?t.call(a):e.get(a)),o=(a,e,t)=>{if(e.has(a))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(a):e.set(a,t)},i=(a,e,t,s)=>(he(a,e,"write to private field"),s?s.call(a,t):e.set(a,t),t);var x=(a,e,t)=>(he(a,e,"access private method"),t);var Ct={};ct(Ct,{InMemoryCache:()=>ce,LocalStorage:()=>le,default:()=>_t});module.exports=dt(Ct);var at=require("text-encoding");var ke=require("@privy-io/core-api");var Ee=require("@privy-io/core-api");var k,M=class{constructor(e){o(this,k,void 0);i(this,k,e)}async syncWithToken(e){let t=await r(this,k).fetch(Ee.authenticateCustomJwtAccount,{body:{token:e}});return r(this,k).session.storeToken(t.token),r(this,k).session.storeRefreshToken(t.refresh_token),t}};k=new WeakMap;var b=require("@privy-io/core-api");var y,N=class{constructor(e){o(this,y,void 0);i(this,y,e)}async sendCode(e,t){return r(this,y).fetch(b.passwordlessInit,{body:{email:e,token:t}})}async loginWithCode(e,t){let s=await r(this,y).fetch(b.passwordlessAuthenticate,{body:{email:e,code:t}});return r(this,y).session.storeToken(s.token),r(this,y).session.storeRefreshToken(s.refresh_token),s}async linkWithCode(e,t){return r(this,y).fetch(b.passwordlessLink,{body:{email:e,code:t}})}async unlink(e){return r(this,y).fetch(b.passwordlessUnlink,{body:{address:e}})}};y=new WeakMap;var R=require("@privy-io/core-api");var m,j=class{constructor(e){o(this,m,void 0);i(this,m,e)}async sendCode(e,t){return r(this,m).fetch(R.passwordlessSmsInit,{body:{phoneNumber:e,token:t}})}async loginWithCode(e,t){let s=await r(this,m).fetch(R.passwordlessSmsAuthenticate,{body:{phoneNumber:e,code:t}});return r(this,m).session.storeToken(s.token),r(this,m).session.storeRefreshToken(s.refresh_token),s}async linkWithCode(e,t){return r(this,m).fetch(R.passwordlessSmsLink,{body:{phoneNumber:e,code:t}})}async unlink(e){return r(this,m).fetch(R.passwordlessSmsUnlink,{body:{phoneNumber:e}})}};m=new WeakMap;var u,L=class{constructor(e){o(this,u,void 0);i(this,u,e),this.phone=new j(r(this,u)),this.email=new N(r(this,u)),this.customProvider=new M(r(this,u))}async logout(){try{await r(this,u).fetch(ke.logout,{body:{refresh_token:r(this,u).session.refreshToken??void 0}})}catch{console.warn("Error destroying session")}r(this,u).session.destroyLocalState()}};u=new WeakMap;var Pe={id:42161,name:"Arbitrum One",network:"arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]},default:{http:["https://arb1.arbitrum.io/rpc"]},public:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://arbiscan.io"},default:{name:"Arbiscan",url:"https://arbiscan.io"}}};var _e={id:421613,name:"Arbitrum Goerli",network:"arbitrum-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"AGOR",decimals:18},rpcUrls:{alchemy:{http:["https://arb-goerli.g.alchemy.com/v2"],webSocket:["wss://arb-goerli.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-goerli.infura.io/v3"],webSocket:["wss://arbitrum-goerli.infura.io/ws/v3"]},default:{http:["https://goerli-rollup.arbitrum.io/rpc"]},public:{http:["https://goerli-rollup.arbitrum.io/rpc"]}},blockExplorers:{etherscan:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"},default:{name:"Arbiscan",url:"https://goerli.arbiscan.io/"}},testnet:!0};var Ce={id:43114,name:"Avalanche",network:"avalanche",nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]},public:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://snowtrace.io"},default:{name:"SnowTrace",url:"https://snowtrace.io"}}};var xe={id:43113,name:"Avalanche Fuji",network:"avalanche-fuji",nativeCurrency:{decimals:18,name:"Avalanche Fuji",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax-test.network/ext/bc/C/rpc"]},public:{http:["https://api.avax-test.network/ext/bc/C/rpc"]}},blockExplorers:{etherscan:{name:"SnowTrace",url:"https://testnet.snowtrace.io"},default:{name:"SnowTrace",url:"https://testnet.snowtrace.io"}},testnet:!0};var Ie={id:8453,network:"base",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{blast:{http:["https://base-mainnet.blastapi.io"],webSocket:["wss://base-mainnet.blastapi.io"]},default:{http:["https://mainnet.base.org"]},public:{http:["https://mainnet.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://basescan.org"},default:{name:"Basescan",url:"https://basescan.org"}},testnet:!0};var Se={id:84531,network:"base-goerli",name:"Base Goerli Testnet",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{blast:{http:["https://base-goerli.blastapi.io"],webSocket:["wss://base-goerli.blastapi.io"]},default:{http:["https://goerli.base.org"]},public:{http:["https://goerli.base.org"]}},blockExplorers:{etherscan:{name:"Basescan",url:"https://goerli.basescan.org"},default:{name:"Basescan",url:"https://goerli.basescan.org"}},testnet:!0};var We={id:42220,name:"Celo Mainnet",network:"celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]},infura:{http:["https://celo-mainnet.infura.io/v3"]},public:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/mainnet"},etherscan:{name:"CeloScan",url:"https://celoscan.io"}},testnet:!1};var De={id:44787,name:"Celo Alfajores Testnet",network:"celo-alfajores",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://alfajores-forno.celo-testnet.org"]},infura:{http:["https://celo-alfajores.infura.io/v3"]},public:{http:["https://alfajores-forno.celo-testnet.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://explorer.celo.org/alfajores"},etherscan:{name:"CeloScan",url:"https://alfajores.celoscan.io/"}},testnet:!0};var Ae={id:314,name:"Filecoin - Mainnet",network:"filecoin-mainnet",nativeCurrency:{decimals:18,name:"filecoin",symbol:"FIL"},rpcUrls:{default:{http:["https://api.node.glif.io/rpc/v1"]},public:{http:["https://api.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filfox",url:"https://filfox.info/en"},filscan:{name:"Filscan",url:"https://filscan.io"},filscout:{name:"Filscout",url:"https://filscout.io/en"},glif:{name:"Glif",url:"https://explorer.glif.io"}}};var qe={id:314159,name:"Filecoin - Calibration testnet",network:"filecoin-calibration",nativeCurrency:{decimals:18,name:"testnet filecoin",symbol:"tFIL"},rpcUrls:{default:{http:["https://api.calibration.node.glif.io/rpc/v1"]},public:{http:["https://api.calibration.node.glif.io/rpc/v1"]}},blockExplorers:{default:{name:"Filscan",url:"https://calibration.filscan.io"}}};var Ue={id:5,network:"goerli",name:"Goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://eth-goerli.g.alchemy.com/v2"],webSocket:["wss://eth-goerli.g.alchemy.com/v2"]},infura:{http:["https://goerli.infura.io/v3"],webSocket:["wss://goerli.infura.io/ws/v3"]},default:{http:["https://rpc.ankr.com/eth_goerli"]},public:{http:["https://rpc.ankr.com/eth_goerli"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://goerli.etherscan.io"},default:{name:"Etherscan",url:"https://goerli.etherscan.io"}},testnet:!0};var Oe={id:59144,network:"linea-mainnet",name:"Linea Mainnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-mainnet.infura.io/v3"],webSocket:["wss://linea-mainnet.infura.io/ws/v3"]},default:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]},public:{http:["https://rpc.linea.build"],webSocket:["wss://rpc.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://lineascan.build"},etherscan:{name:"Etherscan",url:"https://lineascan.build"}},testnet:!1};var Me={id:59140,network:"linea-testnet",name:"Linea Goerli Testnet",nativeCurrency:{name:"Linea Ether",symbol:"ETH",decimals:18},rpcUrls:{infura:{http:["https://linea-goerli.infura.io/v3"],webSocket:["wss://linea-goerli.infura.io/ws/v3"]},default:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]},public:{http:["https://rpc.goerli.linea.build"],webSocket:["wss://rpc.goerli.linea.build"]}},blockExplorers:{default:{name:"Etherscan",url:"https://goerli.lineascan.build"},etherscan:{name:"Etherscan",url:"https://goerli.lineascan.build"}},testnet:!0};var Ne={id:1,network:"homestead",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]},default:{http:["https://cloudflare-eth.com"]},public:{http:["https://cloudflare-eth.com"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://etherscan.io"},default:{name:"Etherscan",url:"https://etherscan.io"}}};var je={id:10,name:"OP Mainnet",network:"optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://opt-mainnet.g.alchemy.com/v2"],webSocket:["wss://opt-mainnet.g.alchemy.com/v2"]},infura:{http:["https://optimism-mainnet.infura.io/v3"],webSocket:["wss://optimism-mainnet.infura.io/ws/v3"]},default:{http:["https://mainnet.optimism.io"]},public:{http:["https://mainnet.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://optimistic.etherscan.io"},default:{name:"Optimism Explorer",url:"https://explorer.optimism.io"}}};var Le={id:420,name:"Optimism Goerli Testnet",network:"optimism-goerli",nativeCurrency:{name:"Goerli Ether",symbol:"ETH",decimals:18},rpcUrls:{alchemy:{http:["https://opt-goerli.g.alchemy.com/v2"],webSocket:["wss://opt-goerli.g.alchemy.com/v2"]},infura:{http:["https://optimism-goerli.infura.io/v3"],webSocket:["wss://optimism-goerli.infura.io/ws/v3"]},default:{http:["https://goerli.optimism.io"]},public:{http:["https://goerli.optimism.io"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"},default:{name:"Etherscan",url:"https://goerli-optimism.etherscan.io"}},testnet:!0};var He={id:137,name:"Polygon Mainnet",network:"matic",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{alchemy:{http:["https://polygon-mainnet.g.alchemy.com/v2"],webSocket:["wss://polygon-mainnet.g.alchemy.com/v2"]},infura:{http:["https://polygon-mainnet.infura.io/v3"],webSocket:["wss://polygon-mainnet.infura.io/ws/v3"]},default:{http:["https://polygon-rpc.com"]},public:{http:["https://polygon-rpc.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://polygonscan.com"},default:{name:"PolygonScan",url:"https://polygonscan.com"}}};var Fe={id:80001,name:"Mumbai",network:"maticmum",nativeCurrency:{name:"MATIC",symbol:"MATIC",decimals:18},rpcUrls:{alchemy:{http:["https://polygon-mumbai.g.alchemy.com/v2"],webSocket:["wss://polygon-mumbai.g.alchemy.com/v2"]},infura:{http:["https://polygon-mumbai.infura.io/v3"],webSocket:["wss://polygon-mumbai.infura.io/ws/v3"]},default:{http:["https://matic-mumbai.chainstacklabs.com"]},public:{http:["https://matic-mumbai.chainstacklabs.com"]}},blockExplorers:{etherscan:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"},default:{name:"PolygonScan",url:"https://mumbai.polygonscan.com"}},testnet:!0};var Ge={id:11155111,network:"sepolia",name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"SEP",decimals:18},rpcUrls:{alchemy:{http:["https://eth-sepolia.g.alchemy.com/v2"],webSocket:["wss://eth-sepolia.g.alchemy.com/v2"]},infura:{http:["https://sepolia.infura.io/v3"],webSocket:["wss://sepolia.infura.io/ws/v3"]},default:{http:["https://rpc.sepolia.org"]},public:{http:["https://rpc.sepolia.org"]}},blockExplorers:{etherscan:{name:"Etherscan",url:"https://sepolia.etherscan.io"},default:{name:"Etherscan",url:"https://sepolia.etherscan.io"}},testnet:!0};var ye=[Pe,_e,Ue,Ge,Ne,je,Le,He,Fe,We,De,Ae,qe,Ie,Se,Oe,Me,Ce,xe],kr=new Set(ye.map(a=>a.id));var fe=require("@ethersproject/providers"),Ke=re(require("eventemitter3"));var $e=["error","invalid_request_arguments","wallet_not_on_device","invalid_recovery_pin","insufficient_funds"];var me=class extends Error{constructor(t,s,n){super(t);s instanceof Error&&(this.cause=s),this.privyErrorCode=n}toString(){return`${this.type}${this.privyErrorCode?`-${this.privyErrorCode}`:""}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}};var g=class extends Error{constructor(t,s){super(s);this.type=t}},H=class extends me{constructor(t,s,n){super(t,s,n);this.type="connector_error"}},F=class extends Error{constructor(t,s,n){super(t);this.code=s,this.data=n}};function ht(a){let e=a.type;return typeof e=="string"&&$e.includes(e)}function ue(a){return ht(a)&&a.type==="wallet_not_on_device"}var yt=["eth_accounts","eth_requestAccounts","eth_chainId","eth_estimateGas","wallet_switchEthereumChain"],mt=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4"],Be=a=>mt.includes(a),Je=a=>yt.includes(a);var ut="4df5e2316331463a9130964bd6078dfa",vt="fe9c30fc-3bc5-4064-91e2-6ab5887f8f4d",ve=(a,e,t)=>{let s=Number(a),n=e.find(l=>l.id===s);if(!n)throw new H(`Unsupported chainId ${a}`,4901);let p;if(t.rpcUrls[s]?p=t.rpcUrls[s]:n.rpcUrls.infura?.http[0]?p=n.rpcUrls.infura.http[0]+"/"+ut:n.rpcUrls.blast?.http[0]?p=n.rpcUrls.blast.http[0]+"/"+vt:p=n.rpcUrls.default?.http[0],!p)throw new H(`No RPC url found for ${a}`);return p};var G,$,P,T,B,w,_=class extends Ke.default{constructor({walletProxy:t,privyInternal:s,address:n,chains:p,chainId:l=1}){super();o(this,G,void 0);o(this,$,void 0);o(this,P,void 0);o(this,T,void 0);o(this,B,void 0);o(this,w,void 0);i(this,G,t),i(this,$,s),i(this,P,n),i(this,T,l),i(this,B,p),i(this,w,new fe.StaticJsonRpcProvider(ve(l,p,{rpcUrls:[]})))}async request(t){return Be(t.method)?this.handleIFrameRpc(t):Je(t.method)?this.handleStatic(t):t.method==="eth_estimateGas"?this.handleEstimateGas(t):this.handleJsonRpc(t)}async handleStatic(t){switch(t.method){case"eth_accounts":case"eth_requestAccounts":return r(this,P)?[r(this,P)]:[];case"eth_chainId":return`0x${r(this,T).toString(16)}`;case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(t)}}async handleEstimateGas(t){if(!t.params||!Array.isArray(t.params))throw new Error("Invalid params for eth_estimateGas");delete t.params[0].gasPrice,delete t.params[0].maxFeePerGas,delete t.params[0].maxPriorityFeePerGas;let s={...t.params[0],chainId:`0x${r(this,T).toString(16)}`};try{return await r(this,w).send("eth_estimateGas",[s])}catch{return delete s.from,await r(this,w).send("eth_estimateGas",[s])}}handleSwitchEthereumChain(t){if(!t.params||!Array.isArray(t.params))throw new F(`Invalid params for ${t.method}`,4200);let s;if(typeof t.params[0]=="string")s=t.params[0];else if("chainId"in t.params[0]&&typeof t.params[0].chainId=="string")s=t.params[0].chainId;else throw new F(`Invalid params for ${t.method}`,4200);i(this,T,Number(s)),i(this,w,new fe.StaticJsonRpcProvider(ve(r(this,T),r(this,B),{rpcUrls:[]}))),this.emit("chainChanged",s)}async handleIFrameRpc(t){try{let s=await r(this,$).getAccessToken();if(!s)throw new Error("Missing privy token. User must be logged in");return(await r(this,G).rpc({request:t,address:r(this,P),accessToken:s})).response.data}catch(s){throw console.error(s),new Error("Unable to make wallet request")}}async handleJsonRpc(t){return r(this,w).send(t.method,t.params??[])}};G=new WeakMap,$=new WeakMap,P=new WeakMap,T=new WeakMap,B=new WeakMap,w=new WeakMap;var se=class{constructor(){this.callbacks={}}enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let s=this.callbacks[t];if(!s)throw new Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":return s;case"privy:wallet:create":return s;case"privy:wallet:connect":return s;case"privy:wallet:recover":return s;case"privy:wallet:rpc":return s;default:throw new Error(`invalid wallet event type ${e}`)}}};var J=15e3;function I(a){return a.error!==void 0}var ft=function(a){return()=>`id-${a++}`}(0),gt=(a,e)=>typeof e=="bigint"?e.toString():e,bt=(a,e)=>`${a}${JSON.stringify(e,gt)}`,Rt=a=>new Promise(e=>{setTimeout(e,a)}),K=(a,e)=>Promise.race([a,new Promise((t,s)=>{setTimeout(s,e)})]),v,S=class{constructor(e){o(this,v,void 0);this.ready=!1,this.cache=new Map,this.eventCallbacks=new se,i(this,v,e)}async create(e,t=J){return await this.waitForReady(),K(this.invoke("privy:wallet:create",e,r(this,v)),t)}async connect(e,t=J){return await this.waitForReady(),K(this.invoke("privy:wallet:connect",e,r(this,v)),t)}async recover(e,t=J){return await this.waitForReady(),K(this.invoke("privy:wallet:recover",e,r(this,v)),t)}async setPassword(e,t=J){return await this.waitForReady(),K(this.invoke("privy:wallet:set-recovery-password",e,r(this,v)),t)}async rpc(e,t=J){return await this.waitForReady(),K(this.invoke("privy:wallet:rpc",e,r(this,v)),t)}handleEmbeddedWalletMessages(e){switch(e.event){case"privy:iframe:ready":let t=this.eventCallbacks.dequeue(e.event,e.id);return I(e)?t.reject(new g(e.error.type,e.error.message)):t.resolve(e.data);case"privy:wallet:create":let s=this.eventCallbacks.dequeue(e.event,e.id);return I(e)?s.reject(new g(e.error.type,e.error.message)):s.resolve(e.data);case"privy:wallet:connect":let n=this.eventCallbacks.dequeue(e.event,e.id);return I(e)?n.reject(new g(e.error.type,e.error.message)):n.resolve(e.data);case"privy:wallet:recover":let p=this.eventCallbacks.dequeue(e.event,e.id);return I(e)?p.reject(new g(e.error.type,e.error.message)):p.resolve(e.data);case"privy:wallet:rpc":let l=this.eventCallbacks.dequeue(e.event,e.id);return I(e)?l.reject(new g(e.error.type,e.error.message)):l.resolve(e.data);case"privy:wallet:set-recovery-password":let f=this.eventCallbacks.dequeue(e.event,e.id);return I(e)?f.reject(new g(e.error.type,e.error.message)):f.resolve(e.data)}}async waitForReady(){if(!this.ready)return new Promise(async(e,t)=>{for(;!this.ready;)this.invoke("privy:iframe:ready",{},r(this,v)).then(()=>{this.ready=!0,e(null)}).catch(t),await Rt(150)})}async invoke(e,t,s){let n=bt(e,t);if(e==="privy:wallet:create"){let l=this.cache.get(n);if(l)return l}let p=new Promise((l,f)=>{let de=ft();this.eventCallbacks.enqueue(de,{resolve:l,reject:f}),s.postMessage({id:de,event:e,data:t},"*")}).finally(()=>{this.cache.delete(n)});return this.cache.set(n,p),p}};v=new WeakMap;var d,c,W,z,ge,V=class{constructor(e,t){o(this,z);o(this,d,void 0);o(this,c,void 0);o(this,W,ye.map(e=>e));i(this,d,e),t&&i(this,c,new S(t))}setMessagePoster(e){i(this,c,new S(e))}async create(e){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");if(!e&&r(this,d).config?.embedded_wallet_config.require_user_password_on_create)throw new Error("Password not provided yet is required by App configuration");let t=await r(this,d).getAccessToken();if(!t)throw new Error("User must be logged in to create an embedded wallet");let{address:s}=await r(this,c).create({accessToken:t,recoveryPassword:e});if(!s)throw new Error("Failed to create wallet");return new _({address:s,privyInternal:r(this,d),chains:r(this,W),walletProxy:r(this,c)})}async getProvider(e){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");let t=await x(this,z,ge).call(this,e);return new _({address:t,privyInternal:r(this,d),chains:r(this,W),walletProxy:r(this,c)})}async setPassword(e,t){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");let s=await x(this,z,ge).call(this,t),n=await r(this,d).getAccessToken();if(!n)throw new Error("User must be logged in to create an embedded wallet");return await r(this,c).setPassword({accessToken:n,address:s,recoveryPassword:e}),new _({address:s,privyInternal:r(this,d),chains:r(this,W),walletProxy:r(this,c)})}getURL(){return`${r(this,d).baseUrl}/apps/${r(this,d).appId}/embedded-wallets`}getMessageHandler(){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");return r(this,c).handleEmbeddedWalletMessages.bind(r(this,c))}};d=new WeakMap,c=new WeakMap,W=new WeakMap,z=new WeakSet,ge=async function(e){if(!r(this,c))throw new Error("Embedded wallet proxy not initialized");let{user:t,token:s}=await r(this,d).refreshSession();if(!s)throw new Error("User must be logged in to interact with embedded wallets");let n=t?.linked_accounts.find(l=>l.type==="wallet"&&l.connector_type==="embedded"&&l.wallet_client_type==="privy");if(!n)throw new Error("User doesn't have an embedded wallet. Create one first.");let p=n.address;try{return await r(this,c).connect({accessToken:s,address:p}),p}catch(l){if(ue(l)&&n.recovery_method==="privy")return await r(this,c).recover({accessToken:s,address:p,recoveryPassword:e}),p;throw ue(l)&&!e?new Error("User recovery password required"):l}};var Te=re(require("fetch-retry")),et=require("uuid"),O=require("@privy-io/core-api");var Ve="0.0.1";var D=re(require("js-cookie"));var ze=re(require("jose")),E=class{static parse(e){try{return new E(e)}catch{return null}}constructor(e){this.value=e,this._decoded=ze.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){let t=Date.now(),s=(this.expiration-e)*1e3;return t>=s}};var be="privy:token",Ye="privy-token",Re="privy:refresh_token",Qe="privy-refresh-token",wt="privy-session",Xe="privy:session_transfer_token",Et=30,h,A,ae=class{constructor(e){o(this,h,void 0);o(this,A,!1);i(this,h,e.storage)}set isUsingServerCookies(e){i(this,A,e)}get token(){try{let e=r(this,h).get(be);return typeof e=="string"?new E(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=r(this,h).get(Re);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get forkedToken(){try{let e=r(this,h).get(Xe);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get mightHaveServerCookies(){try{let e=D.default.get(wt);return e!==void 0&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(){return this.mightHaveServerCookies||typeof this.token=="string"&&typeof this.refreshToken=="string"}hasRecoveryCredentials(){return typeof this.forkedToken=="string"}hasActiveToken(){let e=E.parse(this.token);return e!==null&&!e.isExpired(Et)}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null),this.clearForkedToken()}storeToken(e){if(typeof e=="string"){if(r(this,h).put(be,e),!r(this,A)){let t=E.parse(e)?.expiration;D.default.set(Ye,e,{sameSite:"Strict",secure:!0,expires:t?new Date(t*1e3):void 0})}}else r(this,h).del(be),D.default.remove(Ye)}storeRefreshToken(e){typeof e=="string"?(r(this,h).put(Re,e),r(this,A)||D.default.set(Qe,e,{sameSite:"Strict",secure:!0,expires:30})):(r(this,h).del(Re),D.default.remove(Qe))}clearForkedToken(){r(this,h).del(Xe)}};h=new WeakMap,A=new WeakMap;var kt=a=>{let e=new AbortController;return setTimeout(()=>e.abort(),a),e.signal},Ze=kt;var Pt="https://auth.privy.io",Y,Q,q,U,oe,tt,ie,rt,pe,st,ne=class{constructor(e){o(this,oe);o(this,ie);o(this,pe);o(this,Y,void 0);o(this,Q,void 0);o(this,q,`js-sdk-core:${Ve}`);o(this,U,void 0);this.baseUrl=e.baseUrl??Pt,this.appId=e.appId,i(this,Y,e.storage),i(this,Q,(0,et.v4)()),i(this,q,e.sdkVersion??r(this,q)),this.session=new ae({storage:r(this,Y),isUsingServerCookies:!1}),i(this,U,(0,Te.default)(fetch,{retries:3,retryDelay:500}))}async fetch(e,{body:t,params:s=void 0,options:n={onRequest:x(this,pe,st).bind(this)}}){let p=new Request(`${this.baseUrl}${e.constructPath({params:s})}`,{method:e.method,body:JSON.stringify(t)}),l=await n.onRequest(p),f=await r(this,U).call(this,p,l);if(f.status!==e.expectedStatusCode)throw console.warn(`Privy: Expected status code ${e.expectedStatusCode}, received ${f.status}`),await f.json();return await f.json()}beforeRequestWithoutRefresh(e){let t=this.session.token,s=new Headers(e.headers);return s.set("privy-app-id",this.appId),s.set("privy-client",r(this,q)),s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json"),{signal:Ze(3e3),headers:s,credentials:"include"}}async getAppConfig(){return this.fetch(O.getAppConfig,{params:{app_id:this.appId},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}async createAnalyticsEvent(e,t){return this.fetch(O.recordAnalyticsEvent,{body:{event_name:e,client_id:r(this,Q),payload:t}})}async refreshSession(){let e=await this.fetch(O.refreshSession,{body:{refresh_token:this.session.refreshToken??void 0},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}});return this.session.storeToken(e.token),this.session.storeRefreshToken(e.refresh_token),e}async getAccessToken(){let e=this.session.token;if(e&&!this.session.hasActiveToken&&this.session.hasRefreshCredentials()){let{token:t}=await this.refreshSession();return t}return e}};Y=new WeakMap,Q=new WeakMap,q=new WeakMap,U=new WeakMap,oe=new WeakSet,tt=function(){return!!this.config},ie=new WeakSet,rt=async function(){r(this,oe,tt)||(this.config=await this.getAppConfig(),this.config?.custom_api_url&&(this.baseUrl=this.config.custom_api_url,i(this,U,(0,Te.default)(fetch,{retries:3,retryDelay:500})),this.session.isUsingServerCookies=!0),this.createAnalyticsEvent("sdk_initialize",{}))},pe=new WeakSet,st=async function(e){return await x(this,ie,rt).call(this),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)};var Z,X=class{constructor(e){o(this,Z,void 0);i(this,Z,e)}async get(){return await r(this,Z).refreshSession()}};Z=new WeakMap;var C,ee=class{constructor(e){o(this,C,void 0);i(this,C,new ne(e)),this.user=new X(r(this,C)),this.auth=new L(r(this,C)),this.embeddedWallet=new V(r(this,C),e.embeddedWalletMessagePoster)}setMessagePoster(e){this.embeddedWallet.setMessagePoster(e)}};C=new WeakMap;var le=class{get(e){let t=localStorage.getItem(e);return t===null?void 0:JSON.parse(t)}put(e,t){t!==void 0?localStorage.setItem(e,JSON.stringify(t)):this.del(e)}del(e){localStorage.removeItem(e)}getKeys(){return Object.entries(localStorage).map(([e])=>e)}};var ce=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,t){t!==void 0?this._cache[e]=t:this.del(e)}del(e){delete this._cache[e]}getKeys(){return Object.keys(this._cache)}};globalThis.TextEncoder??=at.TextEncoder;var _t=ee;0&&(module.exports={InMemoryCache,LocalStorage});
|
package/package.json
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@privy-io/js-sdk-core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Vanilla JS client for the Privy Auth API",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"authentication",
|
|
7
|
+
"authorization",
|
|
8
|
+
"identity",
|
|
9
|
+
"privacy",
|
|
10
|
+
"privy",
|
|
11
|
+
"user data",
|
|
12
|
+
"web3"
|
|
13
|
+
],
|
|
4
14
|
"license": "Apache-2.0",
|
|
5
15
|
"main": "./dist/index.js",
|
|
6
16
|
"module": "./dist/esm/index.js",
|
|
@@ -32,9 +42,27 @@
|
|
|
32
42
|
},
|
|
33
43
|
"devDependencies": {
|
|
34
44
|
"@privy-io/tsconfig": "*",
|
|
45
|
+
"@tsconfig/node16-strictest-esm": "^1.0.3",
|
|
46
|
+
"@types/text-encoding": "^0.0.37",
|
|
35
47
|
"tsup": "^6.2.3"
|
|
36
48
|
},
|
|
37
49
|
"dependencies": {
|
|
38
|
-
"
|
|
50
|
+
"@ethersproject/providers": "^5.7.2",
|
|
51
|
+
"@privy-io/core-api": "*",
|
|
52
|
+
"eventemitter3": "^5.0.1",
|
|
53
|
+
"fetch-retry": "^5.0.6",
|
|
54
|
+
"jose": "^4.11.2",
|
|
55
|
+
"js-cookie": "^3.0.5",
|
|
56
|
+
"text-encoding": "^0.7.0",
|
|
57
|
+
"uuid": ">=8 <10"
|
|
58
|
+
},
|
|
59
|
+
"author": "privy.io",
|
|
60
|
+
"browserslist": [
|
|
61
|
+
"defaults",
|
|
62
|
+
"node >= 18",
|
|
63
|
+
"not op_mini all"
|
|
64
|
+
],
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public"
|
|
39
67
|
}
|
|
40
68
|
}
|