-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathuseAvailability.ts
More file actions
71 lines (68 loc) · 2.6 KB
/
Copy pathuseAvailability.ts
File metadata and controls
71 lines (68 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import type { ChainId, ProviderType, Transaction } from '@masknet/web3-shared-evm'
import type { BaseConnectionOptions } from '@masknet/web3-providers/types'
import { EVMContract } from '@masknet/web3-providers'
import { useChainContext } from '@masknet/web3-hooks-base'
import type { NetworkPluginID } from '@masknet/shared-base'
import { asHappyRedPacketV4Contract, useRedPacketContract } from './useRedPacketContract.js'
import { useQuery } from '@tanstack/react-query'
import type { Hex } from 'viem'
export type RedPacketAvailability = {
token_address: string
balance: string
total: string
claimed: string
expired: boolean
claimed_amount: string
}
export function formatRedPacketAvailability(value: unknown): RedPacketAvailability | null {
if (!Array.isArray(value)) return null
const [tokenAddress, balance, total, claimed, expired, claimedAmountOrIfClaimed] = value
return {
token_address: String(tokenAddress ?? ''),
balance: String(balance ?? '0'),
total: String(total ?? '0'),
claimed: String(claimed ?? '0'),
expired: Boolean(expired),
claimed_amount:
typeof claimedAmountOrIfClaimed === 'boolean' ?
claimedAmountOrIfClaimed ? '1'
: '0'
: String(claimedAmountOrIfClaimed ?? '0'),
}
}
export function useAvailability(
id: string,
version: number,
options?: BaseConnectionOptions<ChainId, ProviderType, Transaction>,
) {
const { account, chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>({
account: options?.account,
chainId: options?.chainId,
})
const redPacketContract = useRedPacketContract(chainId, version)
return useQuery({
// eslint-disable-next-line @tanstack/query/exhaustive-deps
queryKey: ['red-packet', 'check-availability', chainId, version, id, account],
queryFn: async () => {
if (!id || !redPacketContract) return null
return formatRedPacketAvailability(
await EVMContract.readContract(
asHappyRedPacketV4Contract(redPacketContract),
'check_availability',
[id as Hex],
{
chainId,
// check availability is ok w/o account
from: account,
},
),
)
},
refetchInterval(query) {
const { data } = query.state
if (!data) return 30_000
if (data.expired || !data.balance) return false
return 30_000
},
})
}