Skip to content

feat(public-api): evm validation, on-chain allowance, partner code timeout#12283

Merged
kaladinlight merged 6 commits intodevelopfrom
chore/public-api-quote-improvements
Apr 15, 2026
Merged

feat(public-api): evm validation, on-chain allowance, partner code timeout#12283
kaladinlight merged 6 commits intodevelopfrom
chore/public-api-quote-improvements

Conversation

@kaladinlight
Copy link
Copy Markdown
Contributor

@kaladinlight kaladinlight commented Apr 15, 2026

Description

Several independent improvements to public-api's quote/rates flow. Split into three commits:

  1. fix(public-api): timeout partner code resolution after 5s — add an AbortController with a 5s timeout to the partner-code lookup against swap-service, so slow/hung responses can't stall every incoming request.

  2. feat(public-api): support optional EVM node URL env vars — add optional VITE_<CHAIN>_NODE_URL env vars for first-class EVM chains (ETH, BSC, AVAX, ARB, OP, GNO, POLY, BASE). These are consumed by @shapeshiftoss/contracts viem clients via process.env.VITE_*_NODE_URL. When unset, the clients fall back to the public RPCs bundled in @shapeshiftoss/contracts. Adds @shapeshiftoss/contracts and viem as workspace deps so we can reuse the client factory instead of reimplementing it.

  3. feat(public-api): validate EVM inputs and check on-chain allowance

    • Reject EVM sell requests without a sendAddress (400 MISSING_SEND_ADDRESS) or on unsupported chains (400 UNSUPPORTED_CHAIN) instead of crashing downstream.
    • buildApprovalInfo now reads the ERC-20 allowance on-chain via the viem client and only flags approval as required when allowance < sellAmount. Previously we returned isRequired: true for every ERC-20 quote regardless of existing allowance, forcing the widget to always prompt for approval even when one was already in place.
    • Replace the affiliateBps! non-null assertions with a DEFAULT_AFFILIATE_BPS fallback so unattributed swaps don't explode at runtime.

Why

  • Slow swap-service partner lookups were propagating into request latency with no bound.
  • public-api needs its own transport to sell assets that aren't hitting a SwapServer private RPC; exposing the bundled public RPCs via @shapeshiftoss/contracts keeps env-var overhead minimal and gives us working clients out of the box for all supported EVM chains.
  • The prior approval-required logic was purely structural ("is this an ERC-20? → require approval") and forced unnecessary approvals in the widget when allowance already existed.

Issue (if applicable)

closes #

Risk

Medium — changes the contract of /quote for EVM sells (now requires sendAddress), adds a network call per ERC-20 quote (on-chain allowance read), and introduces a new transport path (public RPCs) when private node URLs are unset.

What protocols, transaction types, wallets or contract interactions might be affected by this PR?

All EVM swaps routed through public-api. Non-EVM chains are unaffected.

Testing

Engineering

  • pnpm run type-check passes
  • pnpm run lint passes
  • /quote with EVM sell + no sendAddress → 400 MISSING_SEND_ADDRESS
  • /quote with an unsupported EVM chain → 400 UNSUPPORTED_CHAIN
  • /quote with an ERC-20 sell where allowance is already sufficient → approval.isRequired: false
  • /quote with an ERC-20 sell where allowance is insufficient → approval.isRequired: true, correct spender
  • /quote with native EVM sell → approval.isRequired: false
  • Slow/unreachable swap-service partner endpoint does not stall requests past ~5s
  • Missing VITE_<CHAIN>_NODE_URL → viem client still works via public RPC fallback

Operations

  • 🏁 My feature is behind a flag and doesn't require operations testing (yet)

Screenshots (if applicable)

Summary by CodeRabbit

  • New Features

    • Extended support for configurable node endpoints across multiple EVM networks (Ethereum, BNB Smart Chain, Avalanche, Arbitrum, Optimism, Gnosis, Polygon, and Base).
    • Enhanced approval handling with on-chain allowance verification.
  • Bug Fixes

    • Added timeout protection for partner code resolution requests.
    • Improved chain validation for quote requests with better error handling.
    • Enhanced fallback logic for affiliate fee calculations.
  • Chores

    • Added external dependencies to support EVM network integration.
    • Updated environment configuration templates.

kaladinlight and others added 3 commits April 15, 2026 12:02
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add optional VITE_<CHAIN>_NODE_URL env vars for first-class EVM chains,
consumed by @shapeshiftoss/contracts viem clients. When unset, clients
fall back to bundled public RPC URLs. Adds @shapeshiftoss/contracts and
viem as workspace deps.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Reject EVM sell requests without sendAddress or on unsupported chains
- buildApprovalInfo now reads the ERC-20 allowance on-chain via the viem
  client and only flags approval as required when allowance < sellAmount
- Replace non-null assertions on affiliateBps with DEFAULT_AFFILIATE_BPS
  fallback for unattributed swaps

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@kaladinlight kaladinlight requested a review from a team as a code owner April 15, 2026 18:02
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 15, 2026

Warning

Rate limit exceeded

@kaladinlight has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 49 minutes and 20 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 49 minutes and 20 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2111be8f-3f7e-4a5c-9987-9b751e0868b7

📥 Commits

Reviewing files that changed from the base of the PR and between 8929356 and de07edf.

📒 Files selected for processing (1)
  • packages/public-api/src/middleware/auth.ts
📝 Walkthrough

Walkthrough

The changes add EVM node configuration support, integrate the viem library for on-chain interactions, and implement dynamic ERC-20 allowance checking for quote operations. They also replace non-null assertions with fallback values in quote and rates endpoints and add timeout handling to the auth middleware.

Changes

Cohort / File(s) Summary
Environment & Dependencies
.env.example, packages/public-api/env.ts, packages/public-api/package.json
Updated Mayachain node URL endpoint; added eight optional EVM node URL environment variables for Ethereum, BNB Smart Chain, Avalanche, Arbitrum, Optimism, Gnosis, Polygon, and Base; added @shapeshiftoss/contracts workspace and viem external dependencies.
Authentication Middleware
packages/public-api/src/middleware/auth.ts
Introduced 5-second timeout for partner-code resolution using AbortController with setTimeout and added cleanup logic.
Quote Handler & Approval Logic
packages/public-api/src/routes/quote/getQuote.ts, packages/public-api/src/routes/quote/utils.ts
Added EVM sell asset validation and chain support checks; converted buildApprovalInfo to async function with owner parameter; implemented dynamic on-chain ERC-20 allowance checking via viem; replaced non-null assertions with fallback values for affiliateBps.
Rates Handler
packages/public-api/src/routes/rates/getRates.ts
Replaced non-null assertions on affiliateBps with nullish-coalescing fallback to env.DEFAULT_AFFILIATE_BPS in rate computations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 With EVM chains now in our sight,
And allowances checked just right,
Viem clients dancing, timeouts too,
Fallbacks guard what assertions flew!
A quote that flows through chains so bright!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title accurately reflects the main changes: EVM validation for quote requests, dynamic on-chain allowance checks, and a 5-second timeout for partner code resolution.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/public-api-quote-improvements

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@kaladinlight kaladinlight changed the title feat(public-api): harden quote flow with EVM validation, on-chain allowance check, and partner code timeout feat(public-api): EVM validation, on-chain allowance, partner code timeout Apr 15, 2026
@kaladinlight kaladinlight changed the title feat(public-api): EVM validation, on-chain allowance, partner code timeout feat(public-api): evm validation, on-chain allowance, partner code timeout Apr 15, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/public-api/src/routes/quote/utils.ts (1)

43-69: Well-implemented on-chain allowance check.

The logic correctly:

  1. Gates the check with CHAIN_NAMESPACE.Evm, isToken(), and presence of allowanceContract
  2. Uses viem's readContract with erc20Abi for the allowance read
  3. Compares against BigInt for precision

One minor defensive consideration: viemClientByChainId[step.sellAsset.chainId] at line 57 assumes the client exists. While getQuote.ts validates this upstream for sellAsset.chainId, adding a guard here would make buildApprovalInfo safer if called from other contexts in the future.

🛡️ Optional: Add defensive client check
   if (!needsAllowanceCheck) return { isRequired: false, spender: '' }
 
   const spender = step.allowanceContract
   const client = viemClientByChainId[step.sellAsset.chainId]
+
+  if (!client) return { isRequired: false, spender: '' }
 
   const allowance = await client.readContract({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/public-api/src/routes/quote/utils.ts` around lines 43 - 69, In
buildApprovalInfo, defensively check that
viemClientByChainId[step.sellAsset.chainId] exists before using it: retrieve the
client into a local (e.g., const client =
viemClientByChainId[step.sellAsset.chainId]) and if falsy return a safe default
like { isRequired: false, spender: '' } (or optionally throw a descriptive
error) so the function does not assume a client is always present when called
from other contexts; keep the rest of the allowance logic unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/public-api/src/middleware/auth.ts`:
- Around line 31-32: The catch block that currently swallows all errors and
returns null should instead log the failure with structured context before
returning null: inside the catch in the partner-resolution function (e.g., the
catch in resolvePartner / fetch partner block in middleware/auth.ts) capture the
caught error and call the module's logger (processLogger / logger) with a
structured message including partner code, endpoint URL, configured timeout, and
error.name and error.message (and error.stack if available), then return null as
before; ensure the log uses key/value fields for each piece of context to
satisfy the "ALWAYS log errors" guideline.

---

Nitpick comments:
In `@packages/public-api/src/routes/quote/utils.ts`:
- Around line 43-69: In buildApprovalInfo, defensively check that
viemClientByChainId[step.sellAsset.chainId] exists before using it: retrieve the
client into a local (e.g., const client =
viemClientByChainId[step.sellAsset.chainId]) and if falsy return a safe default
like { isRequired: false, spender: '' } (or optionally throw a descriptive
error) so the function does not assume a client is always present when called
from other contexts; keep the rest of the allowance logic unchanged.
🪄 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: cc137006-1559-4b22-aa73-53acd8ce607f

📥 Commits

Reviewing files that changed from the base of the PR and between 3612870 and 8929356.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • packages/public-api/.env.example
  • packages/public-api/package.json
  • packages/public-api/src/env.ts
  • packages/public-api/src/middleware/auth.ts
  • packages/public-api/src/routes/quote/getQuote.ts
  • packages/public-api/src/routes/quote/utils.ts
  • packages/public-api/src/routes/rates/getRates.ts

Comment thread packages/public-api/src/middleware/auth.ts Outdated
kaladinlight and others added 2 commits April 15, 2026 12:51
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@kaladinlight kaladinlight merged commit aa2e5d5 into develop Apr 15, 2026
4 checks passed
@kaladinlight kaladinlight deleted the chore/public-api-quote-improvements branch April 15, 2026 19:09
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