UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

2 lines (1 loc) 9.87 kB
"use strict";var e=require("./paths-B00ZrFQm.js"),r=require("@privy-io/js-sdk-core"),t=require("react"),n=require("./privy-context-C4y2c3Ko.js"),a=require("./SignRequestScreen-CN1o6lNS.js"),i=require("./internal-context-DNWjSiYq.js");function o(e){let r=e.replace("eip155:","");if(r)return parseInt(r);throw Error("Chain ID not compatible with CAIP-2 format.")}const l=e=>e.filter((e=>"wallets"===e.method||("exchange"===e.method?"coinbase"===e.provider:"card"===e.method||"payment-request"===e.method?"coinbase"===e.provider||"moonpay"===e.provider:(e.method,!1)))),d={[r.mainnet.id]:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",[r.sepolia.id]:"0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",[r.optimism.id]:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",[r.optimismSepolia.id]:"0x5fd84259d66Cd46123540766Be93DFE6D43130D7",[r.polygon.id]:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",[r.polygonAmoy.id]:"0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582",[r.base.id]:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",[r.baseSepolia.id]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[r.avalanche.id]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[r.avalancheFuji.id]:"0x5425890298aed601595a70ab815c96711a31bc65",[r.arbitrum.id]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[r.arbitrumSepolia.id]:"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d"};const s=e=>e.reduce(((e,r)=>!e||e.walletIndex<r.walletIndex?r:e),null),c=async({appConfig:r,getAccessToken:t,initializeWalletProxy:n,user:i,privy:o,emitPrivyEvent:l,recoverEmbeddedWallet:d,setModalData:c,openModal:p,setUser:E,options:f,timeoutDuration:h,refreshSessionAndUser:y,chainType:m})=>{let[v,C]=await Promise.all([n(h),t()]);if(!C||!i)throw l("createWallet","onError",e.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");if(!v&&r.customAuth?.enabled)throw l("createWallet","onError",e.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(f&&"walletIndex"in f&&"number"==typeof f.walletIndex){if("user-controlled-server-wallets-only"===r.embeddedWallets.mode)throw l("createWallet","onError",e.PrivyErrorCode.INVALID_DATA),Error("Invalid input, use `createAdditional` instead of `walletIndex` to create additional wallets.");return u({accessToken:C,appConfig:r,privy:o,emitPrivyEvent:l,openModal:p,proxy:v,refreshSessionAndUser:y,recoverEmbeddedWallet:d,setModalData:c,user:i,walletIndex:f.walletIndex,chainType:m,setUser:E})}let g=f&&"createAdditional"in f&&f.createAdditional,W=a.getPrivyWalletsWithFilter(i,{chainType:m});if(W[0]&&!g)throw l("createWallet","onError",e.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");return u({accessToken:C,appConfig:r,privy:o,emitPrivyEvent:l,openModal:p,proxy:v,recoverEmbeddedWallet:d,setModalData:c,user:i,walletIndex:(s(W)?.walletIndex??-1)+1,chainType:m,refreshSessionAndUser:y,setUser:E})};let u=async({accessToken:r,appConfig:t,privy:i,emitPrivyEvent:o,proxy:l,refreshSessionAndUser:d,recoverEmbeddedWallet:s,user:c,walletIndex:u,setModalData:E,openModal:f,chainType:h,setUser:y})=>{if(u<0)throw o("createWallet","onError",e.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${u}) is invalid.`);let m=n.getPrivyPrimaryWallet(c);if(u>0&&!m)throw o("createWallet","onError",e.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have an existing embedded wallet to create an additional wallet.");if(t.embeddedWallets.requireUserOwnedRecoveryOnCreate&&"user-controlled-server-wallets-only"===t.embeddedWallets.mode)throw o("createWallet","onError",e.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("User owned recovery not yet supported for this app.");if(!m&&t.embeddedWallets.requireUserOwnedRecoveryOnCreate)return await p({emitPrivyEvent:o,setModalData:E,openModal:f,chainType:h});let v=a.getPrivyWalletsWithFilter(c,{chainType:h,walletIndex:u})[0];if(v)return{user:c,account:v};if(0===u&&!l)return p({emitPrivyEvent:o,setModalData:E,openModal:f,chainType:h});if(!l)throw o("createWallet","onError",e.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return a.createWalletAtIndex({appConfig:t,walletIndex:u,chainType:h,user:c,accessToken:r,proxy:l,refreshSessionAndUser:d,privy:i,recoverEmbeddedWallet:s,setUser:y})},p=async({emitPrivyEvent:r,setModalData:t,openModal:n,chainType:i})=>new Promise(((o,l)=>{t({createWallet:{onSuccess:({user:e,account:t})=>{r("createWallet","onSuccess",{wallet:t}),o({user:e,account:t})},onFailure:t=>{r("createWallet","onError",e.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),l(t)},callAuthOnSuccessOnClose:!1,shouldCreateEth:"ethereum"===i,shouldCreateSol:"solana"===i}}),n(a.EmbeddedWalletOnAccountCreateScreen)}));const E=()=>{let r=a.useAppConfig(),t=a.useEmitPrivyEvent(),{setModalData:n}=a.usePrivyModal(),{initializeWalletProxy:o,recoverEmbeddedWallet:l,setUser:d,openModal:s,refreshSessionAndUser:u,privy:p,client:E}=i.usePrivyInternal();return{create:async({chainType:i,options:f,latestUser:h})=>{let y=h;if(y||(y=await u()),!y)throw t("createWallet","onError",e.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return await c({appConfig:r,privy:p,getAccessToken:()=>E.getAccessToken(),refreshSessionAndUser:u,initializeWalletProxy:o,user:y,emitPrivyEvent:t,recoverEmbeddedWallet:l,setModalData:n,openModal:s,setUser:d,options:f,timeoutDuration:a.WALLET_PROXY_TIMEOUT,chainType:i})}}};function f(e){let{create:r}=E();return a.usePrivyEventSubscription("createWallet",e),{createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let{account:t}=await r({chainType:"ethereum",options:e});return t}}}const h=async({emitPrivyEvent:r,getAccessToken:t,initializeWalletProxy:a,refreshSessionAndUser:i,user:o,appConfig:l},{privateKey:d,chainType:s})=>{if(!o)throw r("linkAccount","onError",e.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new e.PrivyClientError("User must be authenticated before linking an account.");let[c,u]=await Promise.all([t(),a(15e3)]);if(!u||!c)throw r("linkAccount","onError",e.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:"siwe"}),new e.PrivyClientError("User must be authenticated before linking an account.");await u.importWallet({privateKey:d,accessToken:c,chainType:s,mode:"user-controlled-server-wallets-only"===l.embeddedWallets.mode?"tee":"on-device"});let p=await i(),E="solana"===s?n.getImportedPrivySolanaWallet(p):n.getImportedPrivyEthereumWallet(p);if(!E)throw r("createWallet","onError",e.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to import wallet");return r("createWallet","onSuccess",{wallet:E}),E},y=()=>{let{user:e}=n.usePrivyContext(),{client:r,refreshSessionAndUser:o,initializeWalletProxy:l}=i.usePrivyInternal(),d=a.useEmitPrivyEvent(),s=a.useAppConfig();return{importWallet:t.useCallback((({privateKey:t})=>h({getAccessToken:()=>r.getAccessToken(),user:e,initializeWalletProxy:l,refreshSessionAndUser:o,emitPrivyEvent:d,appConfig:s},{privateKey:t,chainType:"ethereum"})),[e,r,o,l,d])}};exports.extractChainIdFromCAIP2=o,exports.filterSupportedOptions=l,exports.importWallet=h,exports.isFirstClassChainWallet=function(e){return["ethereum","solana"].includes(e.chainType)},exports.prepareFundingModalData=({address:r,appConfig:t,fundWalletConfig:n,methodScreen:a,chainIdOverride:i,comingFromSendTransactionScreen:s=!1})=>{let c,u;if(!t.fundingConfig)throw Error("Wallet funding is not enabled");let p=l(t.fundingConfig.options);if(p.length<1)throw Error("Wallet funding is not enabled");c=i||(n?.chain?n.chain.id:o(t.fundingConfig.defaultRecommendedCurrency.chain));let E=t.chains.find((e=>e.id===c));if(!E)throw new e.PrivyClientError(`Funding chain ${c} is not in PrivyProvider chains list`);let f=n?.amount??t.fundingConfig.defaultRecommendedAmount,h=!1;function y(){if(!c)return;let e=d[c];p.find((e=>"wallets"===e.method))&&!e&&console.warn("Attempting to fund with USDC on chain where USDC address is not known. Funding via external wallet will be disabled."),u=e,h=!0}var m;n&&"asset"in n?"USDC"===n.asset?y():"string"!=typeof n.asset&&"erc20"in n.asset&&(m=u=n.asset.erc20,h=m===d[E.id]):"USDC"===t.fundingConfig.defaultRecommendedCurrency.asset&&y();let v=n?.defaultFundingMethod;return{chainType:"ethereum",address:r,amount:f,chain:E,erc20Address:u,erc20ContractInfo:h?{symbol:"USDC",decimals:6}:void 0,isUSDC:h,methodScreen:a,supportedOptions:p,comingFromSendTransactionScreen:s,defaultFundingMethod:v,usingDefaultFundingMethod:!!v,preferredCardProvider:n?.card?.preferredProvider,crossChainBridgingEnabled:t.fundingConfig.crossChainBridgingEnabled??!1,solanaChain:"solana:mainnet",uiConfig:n&&"uiConfig"in n?n.uiConfig:void 0,externalSolanaFundingScreen:null}},exports.prepareSolanaFundingModalData=function({address:e,fundWalletConfig:r,appConfig:t,comingFromSendTransactionScreen:n,externalSolanaFundingScreen:a,methodScreen:i}){if(!t.fundingConfig)throw Error("Wallet funding is not enabled");let o=l(t.fundingConfig.options);if(o.length<1)throw Error("Wallet funding is not enabled");if("USDC"===r?.asset&&"solana:testnet"===r?.chain)throw Error("USDC funding is not supported on the Solana testnet");let d=r?.amount??t.fundingConfig.defaultRecommendedAmount,s=r?.defaultFundingMethod;return{chainType:"solana",address:e,supportedOptions:o,amount:d,isUSDC:"USDC"===r?.asset,methodScreen:i,comingFromSendTransactionScreen:n,chain:r?.chain||"solana:mainnet",crossChainBridgingEnabled:t.fundingConfig.crossChainBridgingEnabled??!1,defaultFundingMethod:s,preferredCardProvider:r?.card?.preferredProvider,usingDefaultFundingMethod:!!s,uiConfig:r?.uiConfig,externalSolanaFundingScreen:a}},exports.useCreateWallet=f,exports.useCreateWalletInternal=E,exports.useImportWallet=y,exports.usePrivy=()=>{let{importWallet:e}=y(),{createWallet:r}=f();return{...t.useContext(n.PrivyContext),importWallet:e,createWallet:r}};