@orderly.network/ui-connector
Version:
13 lines (11 loc) • 12.9 kB
JavaScript
import { useState, useEffect, useMemo } from 'react';
import { registerSimpleDialog, registerSimpleSheet, Box, Text, Divider, Flex, Switch, toast, TextField, inputFormatter, Tooltip, modal, Match, Button, CheckedCircleFillIcon, Spinner, capitalizeFirstLetter, cn, Either, useScreen, DataTable, ExtensionSlot, ExtensionPositionEnum, EmptyDataState } from '@orderly.network/ui';
import { AccountStatusEnum, MEDIA_TABLET } from '@orderly.network/types';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useAccount, useLazyQuery, useGetReferralCode, useMutation, useEventEmitter, useLocalStorage, useMediaQuery } from '@orderly.network/hooks';
import { useAppContext, useDataTap } from '@orderly.network/react-app';
import { ChainSelectorSheetId, ChainSelectorDialogId } from '@orderly.network/ui-chain-selector';
var V=e=>{let{title:t,description:n}=e;return jsxs(Box,{position:"relative",className:"oui-pl-8",children:[jsxs(Box,{children:[jsx(Text,{as:"div",intensity:98,size:"sm",children:t}),jsx(Text,{as:"div",intensity:54,size:"2xs",children:n})]}),jsx(me,{...e})]})},me=e=>{let{active:t,isLoading:n,isCompleted:i}=e;return jsx(Match,{className:"oui-absolute oui-left-0 oui-top-1 oui-z-10",value:()=>i?"completed":n?"loading":t?"active":"normal",case:{loading:jsx("div",{children:jsx(Spinner,{size:"sm",className:"oui-ml-1"})}),completed:jsx("div",{children:jsx(CheckedCircleFillIcon,{opacity:1,className:"oui-text-primary"})})},default:jsx(fe,{active:!!t})})},fe=({active:e,className:t})=>jsx("div",{className:cn("oui-w-[8.3px] oui-h-[8.3px] oui-rounded-full oui-ml-2 oui-mt-1",t,e?"oui-bg-primary-light":"oui-bg-base-2")});var B=e=>{let{initAccountState:t=AccountStatusEnum.NotConnected}=e,[n,i]=useState(true),o=useEventEmitter(),{state:u,account:g}=useAccount(),[c,d]=useState(t),[r,m]=useState(0),[s,p]=useState(false),[x]=useLocalStorage("orderly-first-show-wallet-connector-dialog",void 0);useEffect(()=>()=>{localStorage.setItem("orderly-first-show-wallet-connector-dialog","1");},[]),useEffect(()=>{d(u.status);},[u]);let y=useMemo(()=>{let a=[];return t<AccountStatusEnum.SignedIn&&a.push({key:"signIn",title:"Sign In",description:"Confirm you are the owner of this wallet"}),t<AccountStatusEnum.EnableTrading&&a.push({key:"enableTrading",title:"Enable Trading",description:"Enable secure access to our API for lightning fast trading"}),a},[t]),I=()=>(p(true),e.enableTrading(n).then(async a=>{p(false),m(C=>C+1);try{await e.enableTradingComplted?.();}catch{}typeof e.onCompleted=="function"?e.onCompleted():typeof e.close=="function"&&e.close();},a=>{if(p(false),a!==-1){if(a.message.indexOf("Signing off chain messages with Ledger is not yet supported")!==-1){o.emit("wallet:sign-message-with-ledger-error",{message:a.message,userAddress:g.address});return}toast.error(Y(a));}}).catch(a=>{p(false);})),P=()=>(p(true),e.signIn().then(a=>{m(C=>C+1),I();},a=>{if(p(false),a!==-1){if(a.message.indexOf("Signing off chain messages with Ledger is not yet supported")!==-1){o.emit("wallet:sign-message-with-ledger-error",{message:a.message,userAddress:g.address});return}toast.error(Y(a));}}).catch(a=>{p(false);}));return jsxs(Box,{id:"oui-wallet-connect-dialog-content",className:"oui-font-semibold",children:[jsx(Text,{intensity:54,size:"xs",children:"Your previous access has expired, you will receive a signature request to enable trading. Signing is free and will not send a transaction."}),jsxs(Box,{p:4,my:6,intensity:600,r:"lg",className:"oui-space-y-5",position:"relative",children:[y.map((a,C)=>jsx(V,{title:a.title,description:a.description,isCompleted:r>C,active:r===C,isLoading:s&&r===C},a.key)),y.length>1&&jsx(Box,{position:"absolute",height:"38px",left:28,top:18,zIndex:0,children:jsx(Divider,{lineStyle:"dashed",direction:"vertical",intensity:16,className:"oui-h-full"})})]}),e.showRefCodeInput&&y.length==2&&jsx(Ae,{...e}),x&&jsxs(Flex,{justify:"between",itemAlign:"center",children:[jsx(Ne,{}),jsx(Switch,{color:"primary",checked:n,onCheckedChange:i,disabled:s,className:"data-[state=checked]:oui-bg-primary-darken"})]}),jsx(Flex,{justify:"center",mt:8,children:jsx(Box,{width:"45%",children:jsx(Ee,{state:c,signIn:P,enableTrading:I,loading:s,disabled:c>=AccountStatusEnum.EnableTrading})})})]})},Ee=({state:e,signIn:t,enableTrading:n,loading:i,disabled:o})=>jsx(Match,{value:()=>e<=AccountStatusEnum.NotSignedIn?"signIn":"enableTrading",case:{signIn:jsx(Button,{fullWidth:true,onClick:()=>t(),loading:i,disabled:o,children:"Sign In"}),enableTrading:jsx(Button,{fullWidth:true,onClick:()=>n(),loading:i,disabled:o,children:"Enable Trading"})}}),Ae=e=>jsx(TextField,{placeholder:"Referral code (Optional)",fullWidth:true,label:"",value:e.refCode,onChange:t=>{e.setRefCode(t.target.value);},classNames:{label:"oui-text-base-contrast-54 oui-text-xs",input:"placeholder:oui-text-base-contrast-20 placeholder:oui-text-sm"},formatters:[inputFormatter.createRegexInputFormatter(/[^A-Z0-9]/g)],onClear:()=>{e.setRefCode("");},autoComplete:"off",helpText:e.helpText,className:"oui-mb-4",color:e.helpText?"danger":void 0}),Ne=()=>jsx(Tooltip,{content:"Toggle this option to skip these steps next time you want to trade.",className:"oui-max-w-[300px]",children:jsx("button",{onClick:()=>{window.innerWidth>768||modal.alert({title:"Remember me",message:jsx("span",{className:"oui-text-2xs oui-text-base-contrast/60",children:"Toggle this option to skip these steps next time you want to trade."})});},children:jsx(Text,{intensity:54,size:"xs",className:"oui-underline oui-underline-offset-4 oui-decoration-dashed oui-decoration-base-contrast-36",children:"Remember me"})})});function Y(e){Object.keys(e).forEach(n=>{});let t="Something went wrong";return e.toString().includes("rejected")&&(t="User rejected the request."),capitalizeFirstLetter(t)??t}var L=()=>{let{account:e,state:t,createOrderlyKey:n,createAccount:i}=useAccount(),[o,u]=useState(""),[g,c]=useState(""),{trigger:d}=useLazyQuery(`/v1/public/referral/verify_ref_code?referral_code=${o}`);useEffect(()=>{let w=localStorage.getItem("referral_code");w!=null&&u(w);},[]);let{referral_code:r,isLoading:m}=useGetReferralCode(e.accountId),[s,{error:p,isMutating:x}]=useMutation("/v1/referral/bind","POST");useEffect(()=>{o.length===0&&c("");},[o]);let y=()=>{toast.success("Wallet connected"),o.length>=4&&o.length<=10&&s({referral_code:o}).finally(()=>{localStorage.removeItem("referral_code");});},I=async()=>{if(o.length===0)return Promise.resolve(void 0);if(o.length>0&&(o.length<4||o.length>10))return Promise.resolve("The referral_code must be 4 to 10 characters long, only accept upper case roman characters and numbers");let{exist:w}=await d();return w===false?Promise.resolve("This referral code does not exist."):Promise.resolve(void 0)},P=(r?.length||0)===0&&!m,a=async()=>{if(P){let w=await I();if(typeof w<"u")return c(w),Promise.reject(-1)}return c(""),i()};return {enableTrading:async w=>{if(P){let F=await I();if(typeof F<"u")return c(F),Promise.reject(-1)}return c(""),n(w)},initAccountState:t.status,signIn:a,enableTradingComplted:y,refCode:o,setRefCode:u,helpText:g,showRefCodeInput:P}};var v="walletConnector",R="walletConnectorSheet",O=e=>{let t=L();return jsx(B,{...t,...e})};registerSimpleDialog(v,O,{size:"sm",title:"Connect wallet"});registerSimpleSheet(R,O,{title:"Connect wallet"});var X={connectWallet:"Connect wallet",switchChain:"Wrong network",enableTrading:"Enable trading",signin:"Sign in"},j={connectWallet:"Please Connect wallet before starting to trade",switchChain:"Please switch to a supported network to continue",enableTrading:"Please Enable trading before starting to trade",signin:"Please sign in before starting to trade"};var T=e=>{let{status:t,buttonProps:n,fallback:i,descriptions:o,classNames:u,networkId:g,id:c,bridgeLessOnly:d}=e,{state:r}=useAccount(),{wrongNetwork:m,disabledConnect:s}=useAppContext(),p=useMemo(()=>t===void 0?r.status===AccountStatusEnum.EnableTradingWithoutConnected?AccountStatusEnum.EnableTradingWithoutConnected:AccountStatusEnum.EnableTrading:t,[t,r.status]),x={...X,...e.labels},y=useMemo(()=>typeof i<"u"?i({validating:r.validating,status:r.status,wrongNetwork:m}):r.validating&&!s?jsx(E,{angle:45,disabled:true,loading:true,description:o?.connectWallet,id:c,type:"button",...n,children:x.connectWallet}):jsx(Ze,{bridgeLessOnly:d,status:r.status,buttonProps:{...n,id:c,type:"button"},wrongNetwork:m,networkId:e.networkId,labels:x,descriptions:o,disabledConnect:s}),[r.status,r.validating,n,m]);return jsx(Either,{value:r.status>=p&&!m&&!s,left:y,children:e.children})},Ze=e=>{let{buttonProps:t,labels:n,descriptions:i}=e,{connectWallet:o}=useAppContext(),{account:u}=useAccount(),{isMobile:g}=useScreen(),c=useMediaQuery(MEDIA_TABLET),d=()=>{modal.show(c?R:v).then(s=>{},s=>{});},r=async()=>{let s=await o();s&&(s.wrongNetwork?m():(s?.status??AccountStatusEnum.NotConnected)<AccountStatusEnum.EnableTrading&&d());},m=()=>{u.once("validate:end",s=>{s<AccountStatusEnum.EnableTrading?d():toast.success("Wallet connected");}),modal.show(g?ChainSelectorSheetId:ChainSelectorDialogId,{networkId:e.networkId,bridgeLessOnly:e.bridgeLessOnly}).then(s=>{s.wrongNetwork||e.status>=AccountStatusEnum.Connected&&(e.status<AccountStatusEnum.EnableTrading?d():toast.success("Wallet connected"));},s=>{});};return e.wrongNetwork&&!e.disabledConnect?jsx(E,{color:"warning",onClick:()=>{m();},description:i?.switchChain,...t,children:n.switchChain}):jsx(Match,{value:e.status,case:s=>{if(s<=AccountStatusEnum.NotConnected||e.disabledConnect)return jsx(E,{size:"lg",onClick:()=>{r();},variant:e.disabledConnect?void 0:"gradient",angle:45,description:i?.connectWallet,disabled:e.disabledConnect,...t,children:n.connectWallet});if(s<=AccountStatusEnum.NotSignedIn)return jsx(E,{size:"lg",onClick:()=>{d();},angle:45,description:i?.signin,...t,children:n.signin})},default:jsx(E,{size:"lg",description:i?.enableTrading,...t,onClick:()=>d(),children:n.enableTrading})})};T.displayName="AuthGuard";var E=e=>{let{description:t,...n}=e;return jsxs(Flex,{direction:"column",children:[jsx(Button,{...n}),!!t&&jsx(Box,{mt:4,className:"oui-leading-none",style:{lineHeight:0},children:jsx(Text,{size:"2xs",intensity:36,children:t})})]})};var rt=e=>{let{status:t,labels:n,description:i,dataSource:o,...u}=e,{state:g}=useAccount(),{wrongNetwork:c,disabledConnect:d}=useAppContext(),r=useMemo(()=>t===void 0?g.status===AccountStatusEnum.EnableTradingWithoutConnected?AccountStatusEnum.EnableTradingWithoutConnected:AccountStatusEnum.EnableTrading:t,[t,g.status]),m=useDataTap(o,{accountStatus:r}),s=c||d||g.status<r||e.ignoreLoadingCheck;return jsx(DataTable,{dataSource:m,ignoreLoadingCheck:s,emptyView:jsx(at,{status:r,description:i,labels:n,className:e.classNames?.authGuardDescription,visible:!g.validating}),manualPagination:true,...u})},at=e=>{let t={...j,...e.description};return e.visible?jsx(Flex,{py:8,children:jsx(T,{status:e.status,labels:e.labels,descriptions:t,buttonProps:{size:"md"},children:jsx(ExtensionSlot,{position:ExtensionPositionEnum.EmptyDataIdentifier})})}):null};var re=e=>{let{hint:t={connectWallet:"Please connect wallet before starting to trade",signIn:"Please sign in before starting to trade",enableTrading:"Please sign in before starting to trade",wrongNetwork:"Please switch to a supported network to continue."},status:n}=e;return jsx(Box,{my:8,children:jsx(T,{status:n,descriptions:{...t,switchChain:t.wrongNetwork},children:e.children||jsx(EmptyDataState,{})})})};re.displayName="AuthGuardEmpty";var le=e=>{let{opactiy:t=90,tooltip:n={connectWallet:"Please connect wallet before set up",signIn:"Please sign in before set up",enableTrading:"Please enable trading before set up",wrongNetwork:"Please switch to a supported network to set up"}}=e,[i,o]=useState(false),{state:u}=useAccount(),g=true,{wrongNetwork:c}=useAppContext(),d=useMemo(()=>{if(c)return n?.wrongNetwork;switch(u.status){case AccountStatusEnum.NotConnected:return n?.connectWallet;case AccountStatusEnum.NotSignedIn:return n?.signIn;case AccountStatusEnum.DisabledTrading:return n?.enableTrading;case AccountStatusEnum.EnableTrading:return "";default:return e.content}},[e.content,u,g,n]),r=useMemo(()=>{switch(u.status){case AccountStatusEnum.NotConnected:case AccountStatusEnum.NotSignedIn:return t;case AccountStatusEnum.EnableTrading:return;default:return}},[e.opactiy,u,g]);return jsx(Tooltip,{open:d?i:false,onOpenChange:o,content:d,className:"oui-text-2xs",align:e.align,alignOffset:e.alignOffset,side:e.side,sideOffset:e.sideOffset,children:jsx("div",{style:{opacity:r},children:e.children})})};le.displayName="AuthGuardTooltip";
export { T as AuthGuard, rt as AuthGuardDataTable, re as AuthGuardEmpty, le as AuthGuardTooltip, B as WalletConnectContent, v as WalletConnectorModalId, R as WalletConnectorSheetId, O as WalletConnectorWidget, L as useWalletConnectorBuilder };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.mjs.map