Skip to content

feat: add Tron chain support to lintent.org#49

Open
reednaa wants to merge 11 commits into
developfrom
feature/api-525-add-tron-chain-support-to-lintentorg
Open

feat: add Tron chain support to lintent.org#49
reednaa wants to merge 11 commits into
developfrom
feature/api-525-add-tron-chain-support-to-lintentorg

Conversation

@reednaa
Copy link
Copy Markdown
Member

@reednaa reednaa commented May 8, 2026

Summary

  • Adds full Tron (TRC-20) chain support across the application — wallet connection via TronLink, intent issuance, filling, and settlement
  • Introduces tronSolver.ts and tronExecution.ts for Tron-specific order handling, along with tronlink.ts utilities and chain-type helpers
  • Refactors monorepo into a single top-level app, migrates from web3-onboard to wagmi wallet connector, and bumps @lifi/intent to 0.1.2
  • Hardens server routes (security fixes), removes all as any casts, adds new unit and e2e tests (Tron support, wallet client switching, recipient field, order validation)
  • Updates DB schema/migrations, deployment config (wrangler.toml + GitHub Actions deploy workflow), and UI components for multi-chain support

Test plan

  • Verify TronLink wallet connects and displays correct address
  • Issue a Tron intent and confirm it appears in intent list
  • Fill a Tron intent from a solver wallet
  • Confirm EVM flows (Ethereum, Polygon, etc.) still work end-to-end
  • Run bun test — all unit tests pass including new Tron tests
  • Run e2e tests via Playwright (escrow-standard-blackbox, escrow-standard-live)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Tron wallet integration support via TronLink connection option
  • Documentation

    • Updated testing guide with unit, integration, and E2E test commands
    • Added local Playwright E2E setup instructions
  • Chores

    • Updated code formatting to use spaces instead of tabs
    • Added wallet integration dependencies and libraries
    • Configured E2E test environment variables

reednaa and others added 5 commits May 8, 2026 16:51
New files:
- tronExecution.ts: open escrow, approve tokens, get block timestamp
- tronSolver.ts: fill outputs, claim, validate proofs, read state
- chainType.ts: isTronChain / isEvmChain helpers
- tronlink.ts: TronLink connection utilities
- WalletStatus.svelte: wallet status component
- tronSupport.test.ts: unit tests for chain type utilities

Bug fixes:
- solver.ts: use eth_getBlockByNumber instead of eth_getBlockByHash
  (blockByHash is unreliable on many public RPCs); add Tron-aware
  fill timestamp path for EVM->Tron outputs

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- config.ts: add Tron chain config, TRON_MAINNET_INPUT/OUTPUT_SETTLER
- app.d.ts: add TronWeb type declarations
- state.svelte.ts: add TronLink account tracking, accountForChain()
- intentFactory.ts: use intent.inputSettler (not store.inputSettler)
  to correctly save TRON_MAINNET_INPUT_SETTLER for Tron source intents
- flowProgress.ts: add Tron branch in isInputChainFinalised()
- intentExecution.ts: route Tron source intents to openTronEscrowIntent
- ConnectWallet.svelte: show TronLink connect option
- FillIntent.svelte: Tron-aware isFilled() via readTronFillRecord
- ReceiveMessage.svelte: Tron-aware receipt/timestamp in isValidated()
- Finalise.svelte: handle Tron source chain claim
- IssueIntent.svelte: handle Tron input token approval/open
- +page.svelte: guard account() for disconnected TronLink
- FlowStepTracker.svelte: display Tron chain steps
- intent.ts: containerToIntent dispatches to Tron intent type
- vite.config.ts: add TronLink global polyfill

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Switches from local file: reference to the published npm package.
0.1.2 fixes Polymer oracle resolution for Tron->EVM intents
(output.oracle now resolves from the input chain, not the output chain).

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
tronExecution.ts was missing getTronBlockTimestamp (needed by solver.ts
and ReceiveMessage.svelte for Tron fill timestamp lookups). Also fixes
orderToTronTuple to convert user and inputOracle to Tron base58 format
— TronLink encodes address-typed fields incorrectly when given 0x hex.

app.d.ts: add TronWeb.trx.getBlock type declaration.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 8, 2026

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2680c888-3cd0-4d7f-b186-dc5f7d833c88

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR performs a major architectural migration from a local intent library and chain-name-based configuration to @lifi/intent with numeric chain ID indexing throughout. The changes refactor the intent generation, execution, and validation layers; restructure database schemas around chain IDs; update all Svelte components to modern runes syntax; add Tron blockchain support; and replace OrderServer with IntentApi for quote/order submission.

Changes

Intent Library Migration & Configuration

Layer / File(s) Summary
Environment & Build Configuration
.env.e2e.example, .env.example, package.json, .prettierrc, .lintstagedrc.json, drizzle.config.ts
Example E2E and public API environment variables added; package version bumped to 0.1.0; build tool configuration updated with Prettier spaces-over-tabs, lint-staged integration, and wallet integration library replacements (@web3-onboard/*wagmi, @walletconnect/*, @coinbase/wallet-sdk, etc.).
CI/CD Workflows & Documentation
.github/workflows/deploy.yml, .github/workflows/test.yml, README.md, playwright.config.ts
New production/preview/cleanup deployment workflow for Cloudflare Workers with pinned action versions and secret-based environment variable injection; test workflow pins Bun setup to commit SHA and adds Polymer/Wallet Connect credentials; Playwright config changes to single-worker execution with conditional video recording and HTML reporter; README testing section clarified with unit/E2E test commands and E2E setup requirements.
Version Control & Type System
.gitignore, src/app.d.ts, src/app.html
Gitignore expanded to cover SvelteKit/Vite artifacts (.svelte-kit, .wrangler, etc.) and E2E env exception; TypeScript environment augmented with Tron browser globals (TronWeb, TronLink, BigInt.toJSON).
Database Schema & Migrations
drizzle/ migration files, drizzle/meta/
Drizzle migrations consolidate table definitions into a single 0000_brief_corsair.sql with tokens indexed by (address, chain_id), intents keyed by order_id, and transaction receipts linked to chain IDs; migration snapshots and journal updated accordingly.
Chain ID Refactoring
src/lib/config.ts
Major overhaul: migrate Token.chainToken.chainId; shift all exports to ID-keyed structures (chainById, chainNameById, clientsById); add tron and arcTestnet chains; introduce routemeshRpc(chainId) fallback transport; update helpers (getChain, getChainName, getClient, normalizeChainId, isChainIdTestnet) to operate on numeric IDs; extend oracle maps to use Partial<Record<number, ...>> keying.
Application Types
src/lib/appTypes.ts
New AppTokenContext (token + bigint amount) and AppCreateIntentOptions types bridge app code and @lifi/intent core, specifying app-specific token context, verifier, and account function signature.
Intent Library Removal & Execution
src/lib/libraries/intent.ts (removed), src/lib/libraries/intentExecution.ts (added)
Delete local Intent, StandardOrderIntent, MultichainOrderIntent classes and orderToIntent overloads; add execution helpers signIntentCompact, depositAndRegisterCompact, openEscrowIntent, finaliseIntent using @lifi/intent core and settler ABIs.
Core Dependencies
src/lib/libraries/coreDeps.ts
New module exports intentDeps and orderValidationDeps for intent construction and order validation, injecting configured oracle addresses (POLYMER_ORACLE, WORMHOLE_ORACLE) and settler constraints by chain ID.
Intent Factory Refactoring
src/lib/libraries/intentFactory.ts
Migrate from OrderServer to IntentApi; add toCoreTokenContext / toCoreCreateIntentOptions helpers; apply applySameChainTimings and applyExclusivityOverride mutations; wire execution helpers; replace direct execution with signIntentCompact, depositAndRegisterCompact, openEscrowIntent, finaliseIntent calls; update escrowApprove to route Tron vs EVM.
Database Initialization
src/lib/db.ts
Initialize Drizzle instance in local variable before migration; change type suppression to @ts-expect-error.
Compact Library
src/lib/libraries/compactLib.ts
Switch to @lifi/intent helpers (toId, addressToBytes32, ResetPeriod); accept AppTokenContext with chainId; use getClient(chainId) instead of chain-name lookup.
Flow Progress
src/lib/libraries/flowProgress.ts
Import utilities from @lifi/intent (compactTypes, getOutputHash, encodeMandateOutput, containerToIntent); split block timestamp handling for Tron (via getTronBlockTimestamp) vs other chains; update mandate output encoding to object shape.
Intent List Rendering
src/lib/libraries/intentList.ts
Inject orderValidationDeps for validation; use containerToIntent to derive order ID; switch coin lookup to getCoin({ address, chainId }); update chain name resolution to handle ID-based lookup.

Svelte Components & UI

Layer / File(s) Summary
Component Type Updates
src/lib/components/GetQuote.svelte, src/lib/components/OutputTokenModal.svelte
Switch token type from TokenContext[] to AppTokenContext[] in component props; add useProductionApi prop to GetQuote; update OutputTokenModal to work with chainId-based token selection.
Token Selection Refactor
src/lib/components/InputTokenModal.svelte, src/lib/components/OutputTokenModal.svelte
Use ${chainId}:${address} keying for token state; derive tokens from store.availableTokens; fetch balances by chainId and address; display chain names via getChainName(chainId); convert amounts using toBigIntWithDecimals from @lifi/intent.
Quote Component
src/lib/components/GetQuote.svelte
Switch from OrderServer to IntentApi; use userChainId and chainId fields instead of chain names; add useProductionApi prop to control API environment; simplified quote expiry logic (30s fixed window); update token types to AppTokenContext[].
New Wallet Component
src/lib/components/WalletStatus.svelte
Add component displaying connected wallet status for EVM and Tron; provide UI for connecting either wallet type; include address truncation and connection error logging via console.warn.
Flow UI
src/lib/components/ui/FlowStepTracker.svelte, src/lib/components/ui/FlowProgressList.svelte
Update FlowStepTracker to use @lifi/intent OrderContainer; gate on store.anyWalletConnected; allow step completion via currentScreenIndex thresholds; improve FlowProgressList responsive layout with CSS variables for connector fill and md:flex-col breakpoint.
Form Components
src/lib/components/ui/FormControl.svelte, src/lib/components/ui/ScreenFrame.svelte, src/lib/components/ui/SectionCard.svelte, src/lib/components/ui/SegmentedControl.svelte, etc.
Migrate to Svelte runes syntax ($props(), $derived()); make ScreenFrame props (title, description) optional; no logic changes, formatting/structure updates only.
Utilities & ABIs
src/lib/libraries/assetSelection.ts, src/lib/abi/*
Reformat AssetSelection and all ABI constant definitions (ERC20_ABI, SETTLER_ESCROW_ABI, MULTICHAIN_SETTLER_COMPACT_ABI, etc.) for consistency; no semantic changes to ABI entries, function signatures, or exported constants.

🎯 4 (Complex) | ⏱️ ~75 minutes

🐰 The local intents have moved to the intent store,
Chain names are now just numbers—a cleaner sort!
Tron joins the party, wallets connect with flair,
And runes make components lighter than air.
OrderServer bows out to IntentApi's grace,
Config is ID-keyed all over the place!

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/api-525-add-tron-chain-support-to-lintentorg

@reednaa reednaa changed the base branch from main to develop May 8, 2026 16:11
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 8, 2026

🚀 Preview deployed!

Worker: lintent-pr-49
URL: https://lintent-pr-49.li-fi374.workers.dev

…-lintentorg

# Conflicts:
#	src/lib/config.ts
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 8, 2026

🚀 Preview deployed!

Worker: lintent-pr-49
URL: https://lintent-pr-49.li-fi374.workers.dev

getClient() throws for Tron chainId (not in clientsById), causing
getOrderProgressChecks to always return all-false for any Tron-involved
order. Add Tron-specific branches in isOutputFilled, isOutputValidatedOnChain,
and isInputChainFinalised using TronWeb helpers instead of viem.

Add readTronIsOutputFilled and getTronTransactionFrom to tronSolver.ts,
and declare getTransaction on the TronWeb.trx type stub in app.d.ts.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 8, 2026

🚀 Preview deployed!

Worker: lintent-pr-49
URL: https://lintent-pr-49.li-fi374.workers.dev

readTronOrderStatus hits TronGrid (api.trongrid.io) without an API key
and gets 429 on the first call. The catch handler previously discarded the
error leaving claimedByChain[chainId] as undefined, which rendered the
greyed "Finalise" placeholder instead of the active "Claim" button.

- Cache the Tron orderStatus call via getOrFetchRpc (30s TTL) to avoid
  hammering TronGrid on repeated polls
- On any error, set claimedByChain[chainId] = false so the button falls
  through to the active Claim path instead of staying in the loading state

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 8, 2026

🚀 Preview deployed!

Worker: lintent-pr-49
URL: https://lintent-pr-49.li-fi374.workers.dev

Add 15s error backoff to rpcCache so 429 failures don't immediately
retry and create a thundering herd. Also use 2min/3min TTLs for Tron
balance/allowance checks instead of 30s/60s to reduce request frequency
against api.trongrid.io's rate-limited public endpoint.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

const cache = new Map<string, CacheEntry<unknown>>();
const inflight = new Map<string, Promise<unknown>>();
const errorBackoff = new Map<string, number>(); // key -> backoff expiry timestamp
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Module-level Map errorBackoff stores per-RPC backoff state across requests; consider scoping it to an explicit cache service or making its lifetime/request-scope explicit to avoid unintended cross-request state.

Details

✨ AI Reasoning
​A new in-memory Map named errorBackoff is defined at module scope and used to track per-RPC backoff state. Module-scope Maps persist for the lifetime of the process and can unintentionally retain request-specific or caller-specific state across requests, leading to data leakage and cross-request interference. This was introduced in the recent changes and increases global caching beyond the existing cache and inflight maps.

🔧 How do I fix it?
Avoid storing request-specific data in module-level variables. Use request-scoped variables or explicitly mark shared caches as intentional.

Reply @AikidoSec feedback: [FEEDBACK] to get better review comments in the future.
Reply @AikidoSec ignore: [REASON] to ignore this issue.
More info

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 8, 2026

🚀 Preview deployed!

Worker: lintent-pr-49
URL: https://lintent-pr-49.li-fi374.workers.dev

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 8, 2026

🚀 Preview deployed!

Worker: lintent-pr-49
URL: https://lintent-pr-49.li-fi374.workers.dev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant