Skip to content

Commit

Permalink
fix: authorize fetching (#113)
Browse files Browse the repository at this point in the history
* fix: authorize fetching

* fix: token icon
  • Loading branch information
swkatmask authored May 28, 2024
1 parent 121a009 commit 1e68394
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 59 deletions.
7 changes: 3 additions & 4 deletions src/components/StakeMaskStatusCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ import No1SVG from '@/assets/no-1.svg?react'
import PlusSVG from '@/assets/plus.svg?react'
import QuestionSVG from '@/assets/question.svg?react'
import RightArrow from '@/assets/right-arrow.svg?react'
import Rss3EthSVG from '@/assets/rss3-eth.svg?react'
import TonEthSVG from '@/assets/ton-eth.svg?react'
import { ActivityStatusTag } from '@/components/StakeMaskStatusCard/ActivityStatusTag.tsx'
import { TokenIcon } from '@/components/TokenIcon'
import { Tooltip } from '@/components/Tooltip.tsx'
import { formatMarketCap } from '@/helpers/formatMarketCap.ts'
import { formatNumber } from '@/helpers/formatNumber.ts'
Expand Down Expand Up @@ -154,7 +153,7 @@ export const StakeMaskStatusCard: ComponentType<StakeMaskStatusCardProps> = ({ .
h={{ base: 'auto', md: '56px' }}
>
<HStack spacing={1}>
<Icon as={Rss3EthSVG} w="12" h="12" />
<TokenIcon src={new URL('../../assets/rss3.svg', import.meta.url).href} />
<VStack spacing={0} color="neutrals.8" align="start">
{rss3 ? (
<Box fontSize="24px" lineHeight="32px" fontWeight={700}>
Expand All @@ -170,7 +169,7 @@ export const StakeMaskStatusCard: ComponentType<StakeMaskStatusCardProps> = ({ .
</HStack>
<Icon as={PlusSVG} w="6" h="6" />
<HStack spacing={1}>
<Icon as={TonEthSVG} w="12" h="12" />
<TokenIcon src={new URL('../../assets/ton.svg', import.meta.url).href} />
<VStack spacing={0} color="neutrals.8" align="start">
{ton ? (
<Box fontSize="24px" lineHeight="32px" fontWeight={700}>
Expand Down
39 changes: 39 additions & 0 deletions src/hooks/useAuthFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { useCallback } from 'react'
import { useAccount } from 'wagmi'

import { fetchJSON } from '@/helpers/fetchJSON'
import { useLogin } from '@/hooks/useLogin'
import { useAccountStore } from '@/store/accountStore'
import { Response } from '@/types/api'

export function useAuthFetch<T extends Response<unknown>>() {
const login = useLogin()
const { token } = useAccountStore()
const account = useAccount()
return useCallback<typeof fetchJSON<T>>(
async (input, init) => {
const address = account.address
if (!address) throw new Error('No wallet connected')
let jwtToken = token
if (!jwtToken) {
jwtToken = await login.mutateAsync()
}

function send() {
return fetchJSON<T>(input, {
...init,
headers: {
Authorization: `Bearer ${jwtToken}`,
},
})
}

const res = await send()
if (res.code === 401) {
jwtToken = await login.mutateAsync()
}
return await send()
},
[account.address, login, token],
)
}
26 changes: 4 additions & 22 deletions src/hooks/useCheckStats.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,19 @@
import { useCallback } from 'react'
import urlcat from 'urlcat'
import { useAccount } from 'wagmi'

import { FIREFLY_API_ROOT } from '@/constants/api'
import { fetchJSON } from '@/helpers/fetchJSON'
import { useLogin } from '@/hooks/useLogin'
import { useAccountStore } from '@/store/accountStore'
import { useAuthFetch } from '@/hooks/useAuthFetch'
import { CheckTokenResponse } from '@/types/api'

export function useCheckStats() {
const account = useAccount()

const { token } = useAccountStore()
const login = useLogin()

const authFetch = useAuthFetch<CheckTokenResponse>()
return useCallback(async () => {
const address = account.address
if (!address) return
try {
let jwtToken = token
if (!jwtToken) {
jwtToken = await login.mutateAsync()
}

const url = urlcat(FIREFLY_API_ROOT, 'v1/mask_stake/check_token')
const res = await fetchJSON<CheckTokenResponse>(url, {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
})
const res = await authFetch(url)
return res.data
} catch {
//
}
}, [account.address, token, login])
}, [authFetch])
}
20 changes: 4 additions & 16 deletions src/hooks/useLinkTwitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,26 @@ import urlcat from 'urlcat'
import { useAccount } from 'wagmi'

import { FIREFLY_API_ROOT } from '@/constants/api'
import { fetchJSON } from '@/helpers/fetchJSON'
import { useAuthFetch } from '@/hooks/useAuthFetch'
import { useHandleError } from '@/hooks/useHandleError'
import { useLogin } from '@/hooks/useLogin'
import { useToast } from '@/hooks/useToast'
import { useAccountStore } from '@/store/accountStore'
import { TwitterAuthorizeResponse } from '@/types/api'

export function useLinkTwitter() {
const account = useAccount()
const toast = useToast()
const handleError = useHandleError()

const { token } = useAccountStore()
const login = useLogin()
const authFetch = useAuthFetch<TwitterAuthorizeResponse>()

return useAsyncFn(async () => {
const address = account.address
if (!address) return
try {
let jwtToken = token
if (!jwtToken) {
jwtToken = await login.mutateAsync()
}

const url = urlcat(FIREFLY_API_ROOT, '/v1/mask_stake/twitter/authorize', {
wallet_address: address,
})
const res = await fetchJSON<TwitterAuthorizeResponse>(url, {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
})
const res = await authFetch(url)
if (res.code !== 200) {
console.error('Failed to get twitter authorize', res.message, res.reason)
toast({
Expand All @@ -49,5 +37,5 @@ export function useLinkTwitter() {
if (handleError(err)) return
throw err
}
}, [account.address, handleError, token, login.mutateAsync])
}, [account.address, handleError])
}
1 change: 1 addition & 0 deletions src/hooks/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function useLogin() {
const { signMessageAsync } = useSignMessage()
const { updateToken } = useAccountStore()
return useMutation({
mutationKey: ['login', account.address],
mutationFn: async () => {
const message = `Login stake.mask.io at ${new Date().toString()}`
const signed = await signMessageAsync({ message })
Expand Down
18 changes: 3 additions & 15 deletions src/hooks/useUpdateUserInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,22 @@ import urlcat from 'urlcat'
import { useAccount } from 'wagmi'

import { FIREFLY_API_ROOT } from '@/constants/api'
import { fetchJSON } from '@/helpers/fetchJSON'
import { isSameAddress } from '@/helpers/isSameAddress'
import { useLogin } from '@/hooks/useLogin'
import { useAccountStore } from '@/store/accountStore'
import { useAuthFetch } from '@/hooks/useAuthFetch'
import { usePoolStore } from '@/store/poolStore'
import { StakeRankItem, UpdateUserInfoParams, UpdateUserInfoResponse } from '@/types/api'

export function useUpdateUserInfo() {
const queryClient = useQueryClient()
const account = useAccount()
const { token } = useAccountStore()
const { poolId } = usePoolStore()
const login = useLogin()
const authFetch = useAuthFetch<UpdateUserInfoResponse>()
return useMutation({
mutationKey: ['update-user-info', account.address],
mutationFn: async (params: Pick<UpdateUserInfoParams, 'show_avatar' | 'display_username'>) => {
if (!account.address) return
let jwtToken = token
if (!token) {
jwtToken = await login.mutateAsync()
}

const url = urlcat(FIREFLY_API_ROOT, '/v1/mask_stake/twitter/update')
return fetchJSON<UpdateUserInfoResponse>(url, {
return authFetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${jwtToken}`,
},
body: JSON.stringify(params),
})
},
Expand Down
2 changes: 1 addition & 1 deletion src/modals/ProfileModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function ProfileModal(props: ModalProps) {
return
}
const res = await updateUserInfo.mutateAsync({
display_username: username,
display_username: username.trim(),
show_avatar: !!showAvatar,
})
if (res?.code !== 200 && res?.reason) {
Expand Down
2 changes: 1 addition & 1 deletion src/types/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
interface Response<T> {
export interface Response<T> {
code: number
reason: string
message: string
Expand Down

0 comments on commit 1e68394

Please sign in to comment.