feat(tron): integrate Tron network support#549
Conversation
- Added configuration for Tron network in .env.example. - Implemented Tron mainnet details in mocks and integrated it into the network selection. - Updated context and providers to include Tron functionality. - Enhanced wallet management to support Tron wallet creation and balance fetching. - Adjusted transaction forms and UI components to accommodate Tron-specific logic, including off-ramp restrictions. - Added validation for Tron addresses and updated utility functions accordingly. This commit introduces comprehensive support for the Tron network, enhancing the overall functionality of the application.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (12)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (10)
📝 WalkthroughWalkthroughAdds Tron support across feature gating, wallet creation, balance and address routing, network switching, and transaction form handling. Tron is treated as a non-EVM, off-ramp-only network with its own validation, explorer/RPC helpers, and Privy wallet flow. ChangesTron network support
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
app/utils.ts (1)
1623-1633: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winComment contradicts the actual precedence for Tron.
The doc comment states "Explicit
sidewins; else Tron/Starknet default to off-ramp," but the earlyif (!networkSupportsOnramp(chain)) return "offramp"runs before thesideparam is read. So for Tron,?side=buyis silently ignored and forced to off-ramp. This is likely intended (Tron has no on-ramp), but the comment is misleading. Either reword the comment to reflect that unsupported on-ramp networks override thesideparam, or move the check after thesideread if explicitsideshould still win.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/utils.ts` around lines 1623 - 1633, The precedence in initialSwapModeForHomeForm is inconsistent with the doc comment: the early networkSupportsOnramp(chain) guard overrides swapModeFromSideParam(searchParams.get("side")), so explicit side is not actually winning on unsupported networks like Tron. Update the comment near initialSwapModeForHomeForm to match the real behavior, or move the networkSupportsOnramp check below the side parsing if explicit side should take priority; keep the note aligned with isStarknetChain and the off-ramp fallback.app/components/SettingsDropdown.tsx (1)
171-174: 🔒 Security & Privacy | 🟡 MinorClear Tron wallet keys during logout
clearUserSessionData()removes several session keys, but it does not removetron_walletId_${user.id}ortron_address_${user.id}. Add those Tron keys to the shared logout cleanup so stale wallet state doesn’t persist into the next session.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/components/SettingsDropdown.tsx` around lines 171 - 174, The shared logout cleanup in clearUserSessionData() is missing the Tron session keys, so stale Tron wallet state can survive across logouts. Update the same localStorage removal block that already clears starknet_walletId_ and starknet_address_ to also remove tron_walletId_${user?.id} and tron_address_${user?.id}, keeping the logout cleanup centralized in SettingsDropdown.tsx.
🧹 Nitpick comments (2)
app/utils.ts (1)
1180-1183: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a timeout/abort to the TronGrid fetch.
fetchhas no timeout, so a slow/hung TronGrid response can stall the balance-fetch path indefinitely (this is reached fromBalanceContext). Wrap withAbortSignal.timeout(...)(or anAbortController) so a stuck request fails fast and falls back to the empty-balance result.♻️ Suggested change
const response = await fetch( `https://api.trongrid.io/v1/accounts/${encodeURIComponent(address)}`, - { headers }, + { headers, signal: AbortSignal.timeout(10_000) }, );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/utils.ts` around lines 1180 - 1183, The TronGrid request in the balance fetch path can hang indefinitely because the `fetch` call has no timeout. Update the `fetch` in the account lookup flow (the `getTron...`/balance-related helper in `app/utils.ts`, reached from `BalanceContext`) to use an abortable request via `AbortSignal.timeout(...)` or an `AbortController`, and make sure timeout errors are handled by falling back to the existing empty-balance result rather than blocking the caller.app/api/tron/create-wallet/route.ts (1)
59-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueInner try/catch is redundant.
The block only logs and re-throws, duplicating the outer catch's logging at Line 125. If the intent was just to annotate the failure source, the extra layer adds little; otherwise it can be removed so the outer handler manages it uniformly.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/api/tron/create-wallet/route.ts` around lines 59 - 96, The inner try/catch around privy.getUser and the existingTronWallet lookup is redundant because it only logs and re-throws before the outer handler logs the same failure. Remove this extra catch in create-wallet route handling, or fold any source-specific context into the outer error path so the route’s main catch manages the error uniformly without duplicate logging.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.env.example:
- Line 92: Add the missing Tron environment variables to the example env file by
documenting NEXT_PUBLIC_TRON_RPC_URL and NEXT_PUBLIC_TRONGRID_API_KEY alongside
NEXT_PUBLIC_TRON_ENABLED. Update the .env.example entries so developers can
configure Tron explicitly instead of relying on the default
https://api.trongrid.io fallback without an API key.
In `@app/api/tron/create-wallet/route.ts`:
- Around line 35-37: The JWT validation in create-wallet’s route handler is
letting invalid or expired tokens fall into the outer error path, so update the
auth block around verifyJWT in route.ts to catch token verification failures
explicitly and return a 401 response instead of surfacing them as 500s. Use the
existing auth flow variables like authHeader, token, verifyJWT, and authUserId
to keep the change localized, and reserve the outer catch for unexpected server
errors only.
In `@app/context/TronContext.tsx`:
- Around line 159-179: ensureWalletExists is swallowing wallet-creation
failures, so handleNetworkSwitch cannot abort the network change on Tron
failure. Update TronContext’s ensureWalletExists to let the error propagate
instead of only logging it in the outer catch, while keeping the existing
toast/error handling around createWallet. Make sure the awaited callback path
used by handleNetworkSwitch in app/utils.ts receives a rejection when wallet
creation fails, matching the Starknet flow.
In `@app/mocks.ts`:
- Around line 37-62: The injected-wallet network switch path in NetworksContext
still treats every selected chain as EVM, so Tron’s string id from tronMainnet
gets converted into an invalid hex chain id and breaks
wallet_switchEthereumChain. Update the injected-wallet selection logic in the
network switch flow to skip Tron or route tronMainnet through the non-EVM wallet
handling instead of calling the EVM chain-switch conversion on its id.
In `@app/pages/TransactionForm.tsx`:
- Around line 967-985: The Buy button is being fully disabled in
TransactionForm, which prevents its onClick guard from firing and stops the Tron
toast from appearing. Update the button logic around the onClick/disabled
handling so the click still reaches the existing onrampSupported check in
TransactionForm, using aria-disabled or another non-blocking state instead of
disabled, or move the Tron explanation to visible helper text/tooltip while
keeping the guard in place.
- Around line 202-210: The balance routing in TransactionForm’s activeBalance
selection only checks selectedNetwork.chain.name for Tron, so Tron networks
identified by network (for example tron-mainnet) can fall through to EVM
balances. Update the ternary branch to use the same shared Tron classifier as
networkSupportsOnramp, or otherwise centralize the Tron check in a reusable
helper, so tronWalletBalance is selected for all Tron variants.
---
Outside diff comments:
In `@app/components/SettingsDropdown.tsx`:
- Around line 171-174: The shared logout cleanup in clearUserSessionData() is
missing the Tron session keys, so stale Tron wallet state can survive across
logouts. Update the same localStorage removal block that already clears
starknet_walletId_ and starknet_address_ to also remove
tron_walletId_${user?.id} and tron_address_${user?.id}, keeping the logout
cleanup centralized in SettingsDropdown.tsx.
In `@app/utils.ts`:
- Around line 1623-1633: The precedence in initialSwapModeForHomeForm is
inconsistent with the doc comment: the early networkSupportsOnramp(chain) guard
overrides swapModeFromSideParam(searchParams.get("side")), so explicit side is
not actually winning on unsupported networks like Tron. Update the comment near
initialSwapModeForHomeForm to match the real behavior, or move the
networkSupportsOnramp check below the side parsing if explicit side should take
priority; keep the note aligned with isStarknetChain and the off-ramp fallback.
---
Nitpick comments:
In `@app/api/tron/create-wallet/route.ts`:
- Around line 59-96: The inner try/catch around privy.getUser and the
existingTronWallet lookup is redundant because it only logs and re-throws before
the outer handler logs the same failure. Remove this extra catch in
create-wallet route handling, or fold any source-specific context into the outer
error path so the route’s main catch manages the error uniformly without
duplicate logging.
In `@app/utils.ts`:
- Around line 1180-1183: The TronGrid request in the balance fetch path can hang
indefinitely because the `fetch` call has no timeout. Update the `fetch` in the
account lookup flow (the `getTron...`/balance-related helper in `app/utils.ts`,
reached from `BalanceContext`) to use an abortable request via
`AbortSignal.timeout(...)` or an `AbortController`, and make sure timeout errors
are handled by falling back to the existing empty-balance result rather than
blocking the caller.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9be95396-d3b0-467c-a31c-7632ff018daa
📒 Files selected for processing (21)
.env.exampleapp/api/tron/create-wallet/route.tsapp/components/MainPageContent.tsxapp/components/MobileDropdown.tsxapp/components/Navbar.tsxapp/components/NetworkSelectionModal.tsxapp/components/NetworksDropdown.tsxapp/components/SettingsDropdown.tsxapp/components/WalletDetails.tsxapp/context/BalanceContext.tsxapp/context/TronContext.tsxapp/context/index.tsapp/hooks/useWalletAddress.tsapp/lib/config.tsapp/lib/validation.tsapp/mocks.tsapp/pages/TransactionForm.tsxapp/pages/TransactionStatus.tsxapp/providers.tsxapp/types.tsapp/utils.ts
- Updated .env.example to include optional Tron RPC URL and API key configurations. - Improved error handling in the Tron wallet creation process, ensuring better user feedback on failures. - Refactored network change logic to accommodate non-EVM chains like Tron, preventing invalid network switches. - Enhanced transaction form to correctly handle balances for Tron and Starknet chains. This commit further solidifies Tron network support within the application, improving user experience and wallet management.
This commit introduces comprehensive support for the Tron network, enhancing the overall functionality of the application.
Description
References
Closes: #488
Testing
Checklist
mainBy submitting a PR, I agree to Paycrest's Contributor Code of Conduct and Contribution Guide.
Summary by CodeRabbit
NEXT_PUBLIC_TRON_ENABLEDfeature flag (default off) with optional Tron RPC and TronGrid API key placeholders.