Skip to content

Commit

Permalink
Fix NFT display; reduce API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
h0ngcha0 committed Aug 14, 2024
1 parent ed93f07 commit f375463
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 14 deletions.
5 changes: 4 additions & 1 deletion packages/extension/src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import browser from "webextension-polyfill"
import { getAccountSelector, withoutHiddenSelector } from "../shared/account/selectors"

import { accountStore, getAccounts } from "../shared/account/store"
import { globalActionQueueStore } from "../shared/actionQueue/store"
Expand Down Expand Up @@ -44,7 +45,9 @@ setTokenListUpdateAlarm()
browser.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === transactionTrackerHistoryAlarm) {
console.info("~> fetching transaction history")
await transactionTracker.loadHistory(await getAccounts())
const selectedAccount = await walletStore.get("selected")
const accountSelector = selectedAccount ? getAccountSelector(selectedAccount) : withoutHiddenSelector
await transactionTracker.loadHistory(await getAccounts(accountSelector))
}

if (alarm.name === transactionTrackerUpdateAlarm) {
Expand Down
2 changes: 1 addition & 1 deletion packages/extension/src/background/networkStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const swrStorage = new KeyValueStorage<Record<SwrCacheKey, any>>(
// see: https://github.com/jperasmus/stale-while-revalidate-cache#configuration
const swr = createStaleWhileRevalidateCache({
storage: swrStorage, // can be any object with getItem and setItem methods
minTimeToStale: 60e3, // 1 minute
minTimeToStale: 2 * 60e3, // 2 minutes
maxTimeToLive: 30 * 60e3, // 30 minutes
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@ import { NFTCollection } from "./alephium-nft.model"
import { Network } from "../../../shared/network"
import { ExplorerProvider, NodeProvider } from "@alephium/web3"
import { fetchImmutable } from "../../../shared/utils/fetchImmutable"
import { chunk } from 'lodash'

export const fetchCollectionAndNfts = async (
nonFungibleTokenIds: string[],
network: Network
): Promise<CollectionAndNFTMap> => {
const maxSizeTokens = 80
const explorerProvider = new ExplorerProvider(network.explorerApiUrl)
const parentAndTokenIds: CollectionAndNFTMap = {}
const nftMetadataz = await explorerProvider.tokens.postTokensNftMetadata(nonFungibleTokenIds)

const nftMetadataz = (await Promise.all(
chunk(nonFungibleTokenIds, maxSizeTokens).map((nftIds) =>
explorerProvider.tokens.postTokensNftMetadata(nftIds)
)
)).flat()

for (const nftMetadata of nftMetadataz) {
const tokenId = nftMetadata.id
const collectionId = nftMetadata.collectionId
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const useCollectionAndNFTs = (
() => fetchCollectionAndNfts(nonFungibleTokenIds, network),
{
...config,
dedupingInterval: 5000,
refreshInterval: 30000,
}
)
Expand Down
34 changes: 23 additions & 11 deletions packages/extension/src/ui/features/accountTokens/tokens.state.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ALPH_TOKEN_ID, HexString, NodeProvider } from "@alephium/web3"
import { ALPH_TOKEN_ID, NodeProvider } from "@alephium/web3"
import { BigNumber } from "ethers"
import { memoize } from "lodash-es"
import { useEffect, useMemo, useRef } from "react"
Expand Down Expand Up @@ -268,6 +268,7 @@ export const useAllTokensWithBalance = (
},
{
refreshInterval: 30000,
dedupingInterval: 5000,
shouldRetryOnError: (error: any) => {
const errorCode = error?.status || error?.errorCode
const suppressError =
Expand Down Expand Up @@ -337,17 +338,28 @@ async function fetchFungibleTokenFromFullNode(network: Network, tokenId: string)
return undefined
}

const metadata = await fetchImmutable(`${tokenId}-token-metadata`, () => nodeProvider.fetchFungibleTokenMetaData(tokenId))
const token: Token = {
id: tokenId,
networkId: network.id,
name: Buffer.from(metadata.name, 'hex').toString('utf8'),
symbol: Buffer.from(metadata.symbol, 'hex').toString('utf8'),
decimals: metadata.decimals,
verified: false
const metadata = await fetchImmutable(`${tokenId}-token-metadata`, async () => {
try {
return (await nodeProvider.fetchFungibleTokenMetaData(tokenId))
} catch (e: any) {
if (e.message.startsWith('Failed to call contract')) {
return { name: undefined, symbol: undefined, decimals: 0 }
} else {
throw e
}
}
})

if (metadata.name && metadata.symbol) {
return {
id: tokenId,
networkId: network.id,
name: Buffer.from(metadata.name, 'hex').toString('utf8'),
symbol: Buffer.from(metadata.symbol, 'hex').toString('utf8'),
decimals: metadata.decimals,
verified: false
}
}

return token
} catch (e) {
console.debug(`Failed to fetch token metadata for ${tokenId}`, e)
return undefined
Expand Down

0 comments on commit f375463

Please sign in to comment.