-
Notifications
You must be signed in to change notification settings - Fork 9
Feat: Token Registry Usage #551
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: fix/centralize-urls
Are you sure you want to change the base?
Conversation
📝 WalkthroughWalkthroughThe PR introduces a new token registry hook that fetches and caches VeChain token registry data, and refactors the token balances hook to use a registry-driven, batched approach instead of hard-coded token addresses. Token metadata support and VTHO energy representation are now included. Changes
Sequence DiagramsequenceDiagram
participant Component
participant useTokenBalances
participant useTokenRegistry
participant QueryAPI
participant RegistryURL
Component->>useTokenBalances: Call hook (address, tokens)
useTokenBalances->>useTokenRegistry: Read registry (with context)
useTokenRegistry->>RegistryURL: Fetch registry JSON
RegistryURL-->>useTokenRegistry: Return TokenRegistryInfo[]
useTokenRegistry-->>useTokenBalances: Registry data + loading
rect rgb(220, 240, 255)
Note over useTokenBalances: For each registry token
useTokenBalances->>QueryAPI: Batch fetch ERC20 balances<br/>(useQueries)
QueryAPI-->>useTokenBalances: Token balances + metadata
end
useTokenBalances->>useTokenBalances: Aggregate VET + VTHO<br/>+ registry tokens
useTokenBalances-->>Component: Formatted token balances[]
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20-25 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🚀 Preview environment deployed!Preview URL: https://preview.vechainkit.vechain.org/feattoken-registry |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
packages/vechain-kit/src/hooks/api/wallet/useTokenBalances.ts (1)
66-78: Consider always including VTHO balance.Currently, VTHO is only added if it exists in the registry. If the registry is incomplete or VTHO is missing, users won't see their VTHO balance (VET energy). Consider either:
- Always including VTHO with a fallback when not in registry, or
- Documenting that VTHO visibility depends on registry inclusion.
Apply this diff if you want to always include VTHO:
- const vthoToken = registryTokens?.find( - (t) => t.symbol.toLowerCase() === 'vtho', - ); - if (vthoToken) { - allBalances.push({ - address: vthoToken.address, - symbol: vthoToken.symbol, - name: vthoToken.name, - balance: vetData?.energy || '0', - decimals: vthoToken.decimals, - }); - } + const vthoToken = registryTokens?.find( + (t) => t.symbol.toLowerCase() === 'vtho', + ); + // Always include VTHO (VET energy) + allBalances.push({ + address: vthoToken?.address || '0x0000000000000000000000000000456E65726779', + symbol: 'VTHO', + name: vthoToken?.name || 'VeThor', + balance: vetData?.energy || '0', + decimals: vthoToken?.decimals || 18, + });packages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.ts (1)
61-68: Consider validating token data structure.The code validates that the response is an array but doesn't verify that items have the required fields (
address,symbol,name,decimals). Consider adding basic validation to ensure data integrity.Apply this diff to add item validation:
// Validate that we received an array if (!Array.isArray(data)) { throw new Error('Invalid token registry format: expected an array'); } + + // Validate that items have required fields + for (const item of data) { + if ( + typeof item !== 'object' || + !item.address || + !item.symbol || + !item.name || + typeof item.decimals !== 'number' + ) { + throw new Error( + 'Invalid token registry format: items must have address, symbol, name, and decimals', + ); + } + } return data as TokenRegistryInfo[];
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/vechain-kit/src/hooks/api/wallet/index.ts(1 hunks)packages/vechain-kit/src/hooks/api/wallet/useTokenBalances.ts(1 hunks)packages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/migration-guide-to-v2.mdc)
**/*.{ts,tsx}: In VeChain Kit Version 2, useuseThorinstead ofuseConnexfor contract interactions
For single contract read operations, use theuseCallClausehook with the pattern: import dependencies, define ABI and method as const, create query key function usinggetCallClauseQueryKeyWithArgs, and wrap with useCallClause including data transformation in the select option
For multiple parallel contract calls, use theexecuteMultipleClausesCallutility wrapped in auseQueryhook with the pattern: define query key function, useexecuteMultipleClausesCallin queryFn mapping items to clause objects, and transform results
For transaction building and sending, use theuseBuildTransactionhook with a clauseBuilder function that returns an array of clauses with optional comment fields describing the transaction action
Always provide an arguments array for contract calls, even when no parameters are required - use an empty array for parameter-less functions to enable TypeScript type checking
Always conditionally enable queries using theenabledproperty to prevent unnecessary contract calls, checking for all required parameters:enabled: !!requiredParam && !!otherRequiredParam
Use theselectoption in useCallClause or transform data in queryFn to handle data transformation, particularly for converting BigInt values to strings and normalizing contract return data
Maintain consistent query key patterns: usegetCallClauseQueryKeyWithArgsfor contract calls with arguments andgetCallClauseQueryKeyfor calls without arguments to ensure proper caching and invalidation
Use TypeScriptas constassertions for method names andas0x${string}`` assertions for Ethereum addresses to ensure type safety in contract interactions
Files:
packages/vechain-kit/src/hooks/api/wallet/index.tspackages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.tspackages/vechain-kit/src/hooks/api/wallet/useTokenBalances.ts
🧠 Learnings (1)
📚 Learning: 2025-12-01T13:01:33.771Z
Learnt from: CR
Repo: vechain/vechain-kit PR: 0
File: .cursor/rules/migration-guide-to-v2.mdc:0-0
Timestamp: 2025-12-01T13:01:33.771Z
Learning: Applies to **/*.{ts,tsx} : In VeChain Kit Version 2, use `useThor` instead of `useConnex` for contract interactions
Applied to files:
packages/vechain-kit/src/hooks/api/wallet/index.tspackages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.tspackages/vechain-kit/src/hooks/api/wallet/useTokenBalances.ts
🧬 Code graph analysis (2)
packages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.ts (2)
packages/vechain-kit/src/config/network.ts (1)
NETWORK_TYPE(6-6)packages/vechain-kit/src/providers/VeChainKitProvider.tsx (1)
useVeChainKitConfig(204-210)
packages/vechain-kit/src/hooks/api/wallet/useTokenBalances.ts (5)
packages/vechain-kit/src/providers/VeChainKitProvider.tsx (1)
useVeChainKitConfig(204-210)packages/vechain-kit/src/hooks/thor/accounts/useAccountBalance.ts (1)
useAccountBalance(26-34)packages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.ts (1)
useTokenRegistry(106-135)packages/vechain-kit/src/hooks/api/wallet/useGetErc20Balance.ts (1)
getErc20BalanceQueryKey(7-10)packages/vechain-kit/src/utils/formattingUtils.tsx (1)
formatTokenBalance(95-103)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
- GitHub Check: e2e-test
- GitHub Check: build-size-check
- GitHub Check: Lint & Build
- GitHub Check: deploy
🔇 Additional comments (10)
packages/vechain-kit/src/hooks/api/wallet/index.ts (1)
17-17: LGTM! Clean public API extension.The new export properly extends the public API surface for the token registry hook.
packages/vechain-kit/src/hooks/api/wallet/useTokenBalances.ts (5)
1-18: LGTM! Type extension is backward compatible.The imports align with the registry-driven refactor, and the optional
nameanddecimalsfields maintain backward compatibility.
23-27: LGTM! Registry-driven token list.The refactor correctly fetches VET balance with energy and obtains the token list from the registry.
80-95: LGTM! Proper deduplication and metadata inclusion.The logic correctly skips VTHO to avoid duplication and includes full token metadata from the registry.
98-103: LGTM! Comprehensive loading state.The
useMemodependencies and loading state correctly track all async data sources.
29-49: The getErc20Balance usage from @vechain/contract-getters v1.0.3 is correct.The implementation follows the expected API signature:
getErc20Balance(tokenAddress, address, { networkUrl })returns an array with the balance as the first element. The pattern used across useGetErc20Balance.ts, useTokenBalances.ts, and useGetCustomTokenBalances.ts is consistent and correct. No changes needed.packages/vechain-kit/src/hooks/api/wallet/useTokenRegistry.ts (4)
1-25: LGTM! Comprehensive token metadata interface.The
TokenRegistryInfointerface is well-structured with required fields and optional metadata.
78-81: LGTM! Proper query key factory.The query key correctly scopes the cache by network type.
106-134: LGTM! Well-configured React Query hook.The hook properly:
- Guards execution with
enabled: !!network.type- Validates network type in
queryFn- Configures appropriate caching (1h staleTime, 24h gcTime)
- Implements smart retry logic (skip validation errors, retry network failures)
35-38: No action needed; solo network registry mapping is correct.The solo network (a local development environment) correctly maps to
test.jsonsince no separate registry exists for local networks. The VeChain token registry only servesmain.jsonandtest.jsonfor public networks at vechain.github.io/token-registry;solo.jsondoes not exist (404 confirmed). The current implementation appropriately treats solo as a development/test network.
|
Size Change: +6.54 kB (+0.11%) Total Size: 5.77 MB
ℹ️ View Unchanged
|
Description
Refactors token handling to use VeChain's official token registry instead of hardcoded token lists. This change makes the the code more maintainable and automatically supports new tokens as they're added to the registry.
Key Changes:
useTokenRegistryhook: Fetches tokens dynamically from VeChain's official token registry (main.json/test.json) with icon URL resolution and 24-hour cachinguseTokenBalances: Replaced individual token balance queries with a unified approach that fetches balances for all registry tokensTOKEN_LOGOSandTOKEN_LOGO_COMPONENTSfrom constantsDocs
This brings some refactor to return types, so we may need to align docs or keep the return type keys the same.
eg.
Demo
Screen.Recording.2026-01-02.at.11.17.27.mov