Skip to content

Commit

Permalink
feat: rp theme api (#11423)
Browse files Browse the repository at this point in the history
* chore: rp api

* refactor: remove unused file

* refactor: code style

* chore: add loading status

* fix: type

* fix: theme-id

---------

Co-authored-by: nuanyang233 <[email protected]>
  • Loading branch information
guanbinrui and nuanyang233 authored Feb 22, 2024
1 parent 54db083 commit a7aacec
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 156 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ export function FireflyRedpacketConfirmDialog({
[settings.total, settings.token?.decimals],
)

const themes = useMemo(() => {
const { value: urls, loading: fetchUrlsLoading } = useAsync(async () => {
if (!currentAccount) return EMPTY_LIST
return FireflyRedPacket.getThemeSettings(
return FireflyRedPacket.getPayloadUrls(
isValidAddress(currentAccount) || isValidDomain(currentAccount) ? currentAccount : `@${currentAccount}`,
settings.total,
'fungible',
Expand All @@ -160,10 +160,10 @@ export function FireflyRedpacketConfirmDialog({
)
}, [currentAccount, settings.total, settings.token])

const { state, currentIndex, prev, next } = useStateList<FireflyRedPacketAPI.ThemeSettings | undefined>(themes)
const { state, currentIndex, prev, next } = useStateList<{ themeId: string; url: string } | undefined>(urls)

const isFirst = currentIndex === 0
const isLatest = themes?.length && currentIndex === themes.length - 1
const isLatest = urls?.length && currentIndex === urls.length - 1

const accounts = useMemo(() => {
const { currentFarcasterProfile, currentLensProfile } = fireflyContext
Expand Down Expand Up @@ -191,9 +191,9 @@ export function FireflyRedpacketConfirmDialog({
}, [account, fireflyContext, farcasterOwnerENS, lensOwnerENS, ensName])

const { loading: imageLoading } = useAsync(async () => {
if (!state?.payloadUrl) return
await fetch(state.payloadUrl)
}, [state?.payloadUrl])
if (!state?.url) return
await fetch(state.url)
}, [state?.url])

const { value, loading } = useAsync(async () => {
if (!state) return
Expand Down Expand Up @@ -253,9 +253,8 @@ export function FireflyRedpacketConfirmDialog({
])
: EMPTY_LIST

const publicKey = await FireflyRedPacket.createPublicKey(state.id, currentAccount, payload)
return {
publicKey,
publicKey: await FireflyRedPacket.createPublicKey(state.themeId, currentAccount, payload),
claimRequirements: payload,
}
}, [state, currentLensProfile, currentFarcasterProfile, fireflySettings, chainId, currentAccount])
Expand All @@ -265,7 +264,7 @@ export function FireflyRedpacketConfirmDialog({
'',
settings,
gasOption,
(payload: RedPacketJSONPayload) => onCreated(payload, state?.payloadUrl, value?.claimRequirements),
(payload: RedPacketJSONPayload) => onCreated(payload, state?.url, value?.claimRequirements),
onClose,
currentAccount,
)
Expand Down Expand Up @@ -388,16 +387,16 @@ export function FireflyRedpacketConfirmDialog({
{state ?
<Box py={2} display="flex" justifyContent="center">
<img
key={state.id}
key={state.themeId}
style={{
width: 288,
height: 202,
borderRadius: 16,
display: imageLoading ? 'none' : 'block',
display: imageLoading || fetchUrlsLoading ? 'none' : 'block',
}}
src={state.payloadUrl}
src={state.url}
/>
{imageLoading ?
{imageLoading || fetchUrlsLoading ?
<Skeleton style={{ width: 288, height: 202 }} variant="rounded" />
: null}
</Box>
Expand Down Expand Up @@ -428,7 +427,7 @@ export function FireflyRedpacketConfirmDialog({
</Box>
</Box>
<Box className={classes.footer}>
<ActionButton loading={isCreating || loading} onClick={createRedpacket} fullWidth>
<ActionButton loading={isCreating || loading || fetchUrlsLoading} onClick={createRedpacket} fullWidth>
{t.next_button()}
</ActionButton>
</Box>
Expand Down
47 changes: 24 additions & 23 deletions packages/plugins/RedPacket/src/SiteAdaptor/RedPacket/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { EMPTY_LIST, EnhanceableSite, NetworkPluginID, Sniffings } from '@maskne
import { makeStyles, parseColor } from '@masknet/theme'
import type { HappyRedPacketV4 } from '@masknet/web3-contracts/types/HappyRedPacketV4.js'
import { useChainContext, useNetwork, useNetworkContext } from '@masknet/web3-hooks-base'
import { EVMChainResolver } from '@masknet/web3-providers'
import { EVMChainResolver, FireflyRedPacket } from '@masknet/web3-providers'
import { RedPacketStatus, type RedPacketJSONPayload } from '@masknet/web3-providers/types'
import { TokenType, formatBalance, isZero, minus } from '@masknet/web3-shared-base'
import { TokenType, formatBalance, isZero, minus, toFixed } from '@masknet/web3-shared-base'
import { ChainId, isValidAddress, isValidDomain } from '@masknet/web3-shared-evm'
import { Card, Grow, Typography } from '@mui/material'
import { memo, useCallback, useMemo, useState } from 'react'
Expand All @@ -16,10 +16,9 @@ import { Requirements } from '../Requirements.js'
import { useAvailabilityComputed } from '../hooks/useAvailabilityComputed.js'
import { useClaimCallback } from '../hooks/useClaimCallback.js'
import { useRedPacketContract } from '../hooks/useRedPacketContract.js'
import { useCoverTheme } from '../hooks/useRedPacketCoverTheme.js'
import { useRefundCallback } from '../hooks/useRefundCallback.js'
import { getRedPacketCover } from '../utils/getRedPacketCover.js'
import { OperationFooter } from './OperationFooter.js'
import { useQuery } from '@tanstack/react-query'

const useStyles = makeStyles<{ outdated: boolean }>()((theme, { outdated }) => {
return {
Expand Down Expand Up @@ -228,29 +227,31 @@ export const RedPacket = memo(function RedPacket({ payload }: RedPacketProps) {
listOfStatus.includes(RedPacketStatus.empty) || (!canRefund && listOfStatus.includes(RedPacketStatus.expired))

const { classes } = useStyles({ outdated })
const theme = useCoverTheme(payload.rpid)
const cover = useMemo(() => {
if (!token?.symbol || !theme) return ''
const name = payload.sender.name

return getRedPacketCover({
theme,
symbol: token.symbol,
shares: payload.shares,
'remaining-shares': minus(payload.shares, availability?.claimed || 0).toNumber(),
amount: payload.total,
'remaining-amount': availability?.balance ?? payload.total,
decimals: token.decimals,
from:
const { data } = useQuery({
enabled: !!availability && !!payload.rpid && !!token?.symbol,
queryKey: ['red-packet', 'theme-id', payload.rpid],
queryFn: async () => {
const name = payload.sender.name

return FireflyRedPacket.getCoverUrlByRpid(
payload.rpid,
token?.symbol,
token?.decimals,
payload.shares,
payload.total,
[isValidAddress, isValidDomain, (n: string) => n.startsWith('@')].some((f) => f(name)) ? name : (
`@${name}`
),
message: payload.sender.message,
})
}, [token?.symbol, payload, availability, theme])
payload.sender.message,
availability?.balance ?? payload.total,
toFixed(minus(payload.shares, availability?.claimed || 0)),
)
},
})

// the red packet can fetch without account
if (!availability || !token || !cover) return <LoadingStatus minHeight={148} />
if (!availability || !token || !data?.url) return <LoadingStatus minHeight={148} />

const claimedOrEmpty =
listOfStatus.includes(RedPacketStatus.claimed) || listOfStatus.includes(RedPacketStatus.empty)
Expand All @@ -262,9 +263,9 @@ export const RedPacket = memo(function RedPacket({ payload }: RedPacketProps) {
component="article"
elevation={0}
style={{
backgroundImage: `url("${cover}")`,
backgroundImage: `url("${data.url}")`,
}}>
<img className={classes.cover} src={cover} />
<img className={classes.cover} src={data.url} />
<img
src={new URL('../assets/tokenLabel.png', import.meta.url).toString()}
className={classes.tokenLabel}
Expand Down
41 changes: 22 additions & 19 deletions packages/plugins/RedPacket/src/SiteAdaptor/RedPacketNft.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ import {
useNonFungibleAsset,
useWeb3Hub,
} from '@masknet/web3-hooks-base'
import { TokenType } from '@masknet/web3-shared-base'
import { TokenType, toFixed } from '@masknet/web3-shared-base'
import { Stack } from '@mui/system'
import { useRedPacketTrans } from '../locales/index.js'
import { Requirements } from './Requirements.js'
import { useAvailabilityNftRedPacket } from './hooks/useAvailabilityNftRedPacket.js'
import { useClaimNftRedpacketCallback } from './hooks/useClaimNftRedpacketCallback.js'
import { useClaimStrategyStatus } from './hooks/useClaimStrategyStatus.js'
import { useNftRedPacketContract } from './hooks/useNftRedPacketContract.js'
import { useCoverTheme } from './hooks/useRedPacketCoverTheme.js'
import { getRedPacketCover } from './utils/getRedPacketCover.js'
import { FireflyRedPacket } from '@masknet/web3-providers'
import { useQuery } from '@tanstack/react-query'

const useStyles = makeStyles<{ outdated: boolean }>()((theme, { outdated }) => ({
root: {
Expand Down Expand Up @@ -312,29 +312,32 @@ export function RedPacketNft({ payload }: RedPacketNftProps) {
}
}, [claimCallback, retryAvailability, recheckClaimStatus])

const theme = useCoverTheme(payload.id)
const cover = useMemo(() => {
if (!availability || !theme) return ''
return getRedPacketCover({
symbol: asset?.metadata?.symbol!,
theme,
shares: availability.totalAmount,
amount: availability.totalAmount,
from: `@${payload.senderName}`,
message: payload.message,
'remaining-amount': availability.balance,
'remaining-shares': availability.remaining,
})
}, [asset?.metadata?.symbol, availability, theme])
const { data } = useQuery({
enabled: !!availability && !!payload.id,
queryKey: ['red-packet', 'theme-id', payload.id],
queryFn: async () => {
return FireflyRedPacket.getCoverUrlByRpid(
payload.id,
asset?.metadata?.symbol!,
0,
availability?.totalAmount,
toFixed(availability?.totalAmount),
`@${payload.senderName}`,
payload.message,
availability?.balance,
toFixed(availability?.remaining),
)
},
})

if (availabilityError) return <ReloadStatus message={t.go_wrong()} onRetry={retryAvailability} />

if (!availability || loading || !cover) return <LoadingStatus minHeight={148} iconSize={24} />
if (!availability || loading || !data?.url) return <LoadingStatus minHeight={148} iconSize={24} />

return (
<div className={classes.root}>
<Card className={classes.card} component="article" elevation={0}>
<img className={classes.cover} src={cover} />
<img className={classes.cover} src={data.url} />
<img
src={new URL('./assets/nftLabel.png', import.meta.url).toString()}
className={classes.tokenLabel}
Expand Down

This file was deleted.

This file was deleted.

Loading

0 comments on commit a7aacec

Please sign in to comment.