Skip to content

Conversation

@gomesalexandre
Copy link
Contributor

@gomesalexandre gomesalexandre commented Sep 2, 2025

Description

This PR:

  • Does a bit of cleanup across the board
  • Adds new fiat buy quote method as groundwork of https://linear.app/shapeshift-dao/issue/SS-4861/implement-onramper (unconsumed for the time being)
  • While at it, removes onramper static mapping in profit of dynamic fetching of Onramper-supported assets (except for native assets, which use the mapping still) - this will actually make us closer to what we want to eventually achieve with the new fiat ramps functionality, and has the added benefit of bringing a lot more assets in 🎉

Issue (if applicable)

Risk

High Risk PRs Require 2 approvals

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

Low/Medium: Isolated to Onramper, though could absolutely be borked

Testing

  • Solana fiat ramps should have a lot more available (a few other EVM chains also have a few more assets available to select)
  • Go to fiat ramps, select Ethereum (native asset + tokens), any other EVM chain, and other native assets i.e DOGE, LTC RUNE etc, and confirm you're still properly routed to Onramper

Engineering

  • ☝🏽

Operations

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

Screenshots (if applicable)

https://jam.dev/c/4e0c4521-cec8-46c8-8000-df327127944d

Summary by CodeRabbit

  • New Features

    • Broader fiat currency and network support for Onramper purchases.
    • Dynamic asset detection to enable more assets in fiat-to-crypto flows.
    • Improved buy-quote retrieval for more reliable quotes.
  • Bug Fixes

    • Clearer errors when assets aren’t supported or currencies can’t be fetched.
    • More reliable currency and asset mapping, reducing failed ramp attempts.
  • Refactor

    • Onramper integration moved to centralized constants and utilities for maintainability.

@gomesalexandre gomesalexandre requested a review from a team as a code owner September 2, 2025 14:04
@gomesalexandre gomesalexandre marked this pull request as draft September 2, 2025 14:04
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

📝 Walkthrough

Walkthrough

Refactors Onramper integration: adds constants for supported fiats and network mappings, introduces types and utilities to fetch supported currencies and buy quotes, updates provider to resolve tokens dynamically and construct URLs, and switches config to use the new fiat constant.

Changes

Cohort / File(s) Summary of Changes
Onramper utilities
src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts
New helpers: getSupportedOnramperCurrencies, getOnramperBuyQuote, findOnramperTokenIdByAssetId, findAssetIdByOnramperCrypto; perform API calls, map between Onramper payloads and AssetId, and log errors.
Onramper types
src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
New exported types: Crypto, OnRamperGatewaysResponse, OnramperBuyQuote, OnramperBuyQuoteResponse; internal types for fiat items, payment methods, limits, errors, and KYC.
Onramper constants & mappings
src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts
New exports: SUPPORTED_ONRAMPER_FIAT_CURRENCIES, CHAIN_ID_TO_ONRAMPER_NETWORK, ONRAMPER_NETWORK_TO_CHAIN_ID, and getChainIdFromOnramperNetwork.
Onramper provider refactor
src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts
Replaced inline/static gateway fetch and fiat list with utility-driven retrieval; use getSupportedOnramperCurrencies and new mapping helpers; updated token resolution and URL creation with added error handling; removed getSupportedOnRamperFiatCurrencies.
Fiat ramps config wiring
src/components/Modals/FiatRamps/config.ts
Replaced function-based fiat retrieval with import of SUPPORTED_ONRAMPER_FIAT_CURRENCIES.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as Fiat Ramps UI
  participant Provider as Onramper Provider
  participant Utils as onramper/utils
  participant Config as getConfig

  User->>UI: choose buy (asset, fiat, amount)
  UI->>Provider: createOnRamperUrl(assetId, fiat, amount)
  Provider->>Utils: getSupportedOnramperCurrencies()
  Utils->>Config: fetch API URL & key
  Config-->>Utils: URL & key
  Utils-->>Provider: supported currencies payload
  Provider->>Utils: find mapping via adapters
  alt direct mapping found
    Utils-->>Provider: token symbol/id
  else try payload lookup
    Provider->>Utils: findOnramperTokenIdByAssetId(assetId, payload)
    Utils-->>Provider: tokenId or undefined
  end
  alt token resolved
    Provider-->>UI: constructed Onramper URL
  else token not resolved
    Provider-->>UI: error "Asset not supported by OnRamper"
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I thump and scout the codey ground,
New maps and lists hop all around,
Tokens found where carrots hide,
URLs stitched for every ride,
Old fetches trimmed, new paths abound 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat_onramper_queries

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts (1)

32-54: Critical: Don’t embed signing key in the client — move HMAC signing server-side

VITE_ONRAMPER_SIGNING_KEY in browser code exposes a secret. Generate the signature on a trusted backend/API route and call it from here.

-const generateSignature = async (data: string): Promise<string> => {
-  const secretKey = getConfig().VITE_ONRAMPER_SIGNING_KEY
-  const encoder = new TextEncoder()
-  const keyData = encoder.encode(secretKey)
-  const message = encoder.encode(data)
-  const cryptoKey = await crypto.subtle.importKey(
-    'raw',
-    keyData,
-    { name: 'HMAC', hash: 'SHA-256' },
-    false,
-    ['sign'],
-  )
-  const signature = await crypto.subtle.sign('HMAC', cryptoKey, message)
-  return Array.from(new Uint8Array(signature)).map(b => b.toString(16).padStart(2, '0')).join('')
-}
+// Delegate signing to a backend route to keep secrets off the client
+const requestSignature = async (walletParam: string): Promise<string> => {
+  const resp = await fetch('/api/fiatramps/onramper/sign', {
+    method: 'POST',
+    headers: { 'Content-Type': 'application/json' },
+    body: JSON.stringify({ walletParam }),
+    // consider including a CSRF token if applicable
+  })
+  if (!resp.ok) throw new Error('Failed to sign Onramper params')
+  const { signature } = (await resp.json()) as { signature: string }
+  return signature
+}

And below:

-const walletParam = `wallets=${defaultCrypto}:${address}`
-const signature = await generateSignature(walletParam)
+const walletParam = `wallets=${defaultCrypto}:${address}`
+const signature = await requestSignature(walletParam)

If you want, I can provide a minimal Node/Cloudflare Worker handler for the sign endpoint.

🧹 Nitpick comments (12)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts (4)

22-108: Freeze and type the fiat list to prevent accidental mutation and drift

Make the list readonly and validated at compile-time against CommonFiatCurrencies.

-export const SUPPORTED_ONRAMPER_FIAT_CURRENCIES: CommonFiatCurrencies[] = [
+export const SUPPORTED_ONRAMPER_FIAT_CURRENCIES =
+  [
     'AOA',
     'AUD',
     'BBD',
     'BZD',
     'BMD',
     'BRL',
     'GBP',
     'BND',
     'BGN',
     'CAD',
     'XAF',
     'CLP',
     'CNY',
     'COP',
     'KMF',
     'CRC',
     'HRK',
     'CZK',
     'DKK',
     'DJF',
     'DOP',
     'XCD',
     'EGP',
     'EUR',
     'FKP',
     'FJD',
     'GEL',
     'GHS',
     'GIP',
     'GTQ',
     'HNL',
     'HKD',
     'HUF',
     'ISK',
     'IDR',
     'ILS',
     'JMD',
     'JPY',
     'JOD',
     'KZT',
     'KES',
     'KWD',
     'KGS',
     'MGA',
     'MWK',
     'MYR',
     'MRU',
     'MXN',
     'MDL',
     'MAD',
     'MZN',
     'TWD',
     'NZD',
     'NGN',
     'NOK',
     'OMR',
     'PKR',
     'PGK',
     'PYG',
     'PEN',
     'PHP',
     'PLN',
     'RON',
     'RWF',
     'STN',
     'SCR',
     'SGD',
     'SBD',
     'ZAR',
     'KRW',
     'LKR',
     'SRD',
     'SZL',
     'SEK',
     'CHF',
     'TJS',
     'TZS',
     'THB',
     'TOP',
     'TRY',
     'TMT',
     'UGX',
     'USD',
     'UYU',
     'VND',
-]
+] as const satisfies ReadonlyArray<CommonFiatCurrencies>

111-134: Strongly type Onramper networks with a string enum/union

Avoid raw strings; enforce allowed values at compile time and improve DX.

+export const ONRAMPER_NETWORK = {
+  BITCOIN: 'bitcoin',
+  BITCOINCASH: 'bitcoincash',
+  DOGECOIN: 'dogecoin',
+  LITECOIN: 'litecoin',
+  ETHEREUM: 'ethereum',
+  AVAXC: 'avaxc',
+  OPTIMISM: 'optimism',
+  BSC: 'bsc',
+  POLYGON: 'polygon',
+  GNOSIS: 'gnosis',
+  ARBITRUM: 'arbitrum',
+  BASE: 'base',
+  COSMOS: 'cosmos',
+  THORCHAIN: 'thorchain',
+  SOLANA: 'solana',
+} as const
+export type OnramperNetwork = typeof ONRAMPER_NETWORK[keyof typeof ONRAMPER_NETWORK]
-
-export const CHAIN_ID_TO_ONRAMPER_NETWORK: Record<ChainId, string> = {
+export const CHAIN_ID_TO_ONRAMPER_NETWORK: Record<ChainId, OnramperNetwork> = {
   [btcChainId]: 'bitcoin',
   [bchChainId]: 'bitcoincash',
   [dogeChainId]: 'dogecoin',
   [ltcChainId]: 'litecoin',
   [ethChainId]: 'ethereum',
   [avalancheChainId]: 'avaxc',
   [optimismChainId]: 'optimism',
   [bscChainId]: 'bsc',
   [polygonChainId]: 'polygon',
   [gnosisChainId]: 'gnosis',
   [arbitrumChainId]: 'arbitrum',
   [baseChainId]: 'base',
   [cosmosChainId]: 'cosmos',
   [thorchainChainId]: 'thorchain',
   [solanaChainId]: 'solana',
 } as const

137-139: Type the reverse mapping with the network union and guard against duplicates

Use the union type and a reducer to detect accidental duplicate keys at build time.

-export const ONRAMPER_NETWORK_TO_CHAIN_ID: Record<string, ChainId> = Object.fromEntries(
-  Object.entries(CHAIN_ID_TO_ONRAMPER_NETWORK).map(([chainId, network]) => [network, chainId]),
-)
+export const ONRAMPER_NETWORK_TO_CHAIN_ID: Record<OnramperNetwork, ChainId> = Object.entries(
+  CHAIN_ID_TO_ONRAMPER_NETWORK,
+).reduce((acc, [chainId, network]) => {
+  if (acc[network as OnramperNetwork]) {
+    // Duplicate protection during dev
+    throw new Error(`Duplicate Onramper network detected: ${network}`)
+  }
+  acc[network as OnramperNetwork] = chainId as ChainId
+  return acc
+}, {} as Record<OnramperNetwork, ChainId>)

142-149: Narrow helper function types to OnramperNetwork

Return precise types and avoid generic string usage.

-export const getChainIdFromOnramperNetwork = (network: string): ChainId | undefined => {
+export const getChainIdFromOnramperNetwork = (network: OnramperNetwork): ChainId | undefined => {
   return ONRAMPER_NETWORK_TO_CHAIN_ID[network]
 }
 
 // Helper function to get Onramper network from chainId
-export const getOnramperNetworkFromChainId = (chainId: ChainId): string | undefined => {
+export const getOnramperNetworkFromChainId = (chainId: ChainId): OnramperNetwork | undefined => {
   return CHAIN_ID_TO_ONRAMPER_NETWORK[chainId]
 }
src/components/Modals/FiatRamps/config.ts (1)

97-97: Static fiat list may drift from provider — consider periodic verification

Keeping a static list is fine, but add a lightweight health check or unit test to detect drift vs. Onramper’s /supported response.

I can add a test that asserts SUPPORTED_ONRAMPER_FIAT_CURRENCIES is a subset of the provider’s returned fiat codes (skipped on CI without the API key). Want me to open a follow-up?

src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts (3)

1-13: Type network as a union for compile-time safety

If you introduce OnramperNetwork (constants.ts), use it here to avoid arbitrary strings.

-export type Crypto = {
+export type Crypto = {
   id: string
   code: string
   name: string
   symbol: string
-  network: string
+  network: import('./constants').OnramperNetwork
   decimals?: number
   address?: string
   chainId?: number
   icon: string
   networkDisplayName?: string
 }

30-49: Tighten stringly-typed fields with string enums where feasible

paymentTypeId, currencyStatus and known limit keys can benefit from string enums to reduce runtime mistakes.


65-79: Confirm numeric vs string fields per API

On some aggregators, rate/fees/payout arrive as strings. If Onramper sends strings, parse on the edge and type accordingly.

src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts (2)

85-106: Minor: avoid lodash/head and redundant comment

Use native indexing; simplify the guard.

-const defaultCrypto = head(onRamperSymbols)
-// This should not happen really, head() is just strongly typed in favour of safety but we should have at least one symbol really
-// Unless we don't? I mean that's what safety is for, hey
-if (!defaultCrypto) throw new Error('Failed to get onRamperSymbols head')
+const defaultCrypto = onRamperSymbols[0]
+if (!defaultCrypto) throw new Error('onramper.defaultCryptoMissing')

112-115: Sign only the exact param string the backend expects

Ensure the server signs the raw query fragment without URL-encoding discrepancies. Current code derives walletParam correctly; keep this invariant documented.

src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts (2)

30-38: Nit: avoid shadowing the global crypto; prefer a more descriptive param name.

Rename the parameter to cryptoId (or cryptoCode) to avoid confusion with the global Web Crypto API and better convey intent.

-export const getOnramperBuyQuote = async ({
-  fiat,
-  crypto,
-  fiatAmount,
+export const getOnramperBuyQuote = async ({
+  fiat,
+  crypto: cryptoId,
+  fiatAmount,
 }: {
   fiat: CommonFiatCurrencies
-  crypto: string
+  crypto: string
   fiatAmount: number
 }): Promise<...> => {
-  // ...
-  const url = `${baseUrl}quotes/${encodeURIComponent(fiat.toLowerCase())}/${encodeURIComponent(
-    crypto.toLowerCase(),
-  )}?amount=${fiatAmount}`
+  const url = `${baseUrl}quotes/${encodeURIComponent(fiat.toLowerCase())}/${encodeURIComponent(
+    cryptoId.toLowerCase(),
+  )}?amount=${fiatAmount}`

57-85: Optional: pre-index Onramper currencies for O(1) lookups.

Repeated linear scans on message.crypto can be avoided by building a Map keyed by ${chainId}:${addressLower} once and reusing it.

Example helper outside this function:

type OnramperIndex = Map<string, string> // key -> tokenId
export const buildOnramperIndex = (r: OnRamperGatewaysResponse): OnramperIndex => {
  const m = new Map<string, string>()
  for (const c of r.message.crypto) {
    if (!c.network || !c.address) continue
    const cid = getChainIdFromOnramperNetwork(c.network)
    if (!cid) continue
    m.set(`${cid}:${c.address.toLowerCase()}`, c.id)
  }
  return m
}

Then in findOnramperTokenIdByAssetId, prefer the index when available.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9f20dac and 249f9ce.

📒 Files selected for processing (5)
  • src/components/Modals/FiatRamps/config.ts (2 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts (1 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts (3 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts (1 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{ts,tsx}: ALWAYS use Result<T, E> pattern for error handling in swappers and APIs
ALWAYS use Ok() and Err() from @sniptt/monads for monadic error handling
ALWAYS use custom error classes from @shapeshiftoss/errors
ALWAYS provide meaningful error codes for internationalization
ALWAYS include relevant details in error objects
ALWAYS wrap async operations in try-catch blocks
ALWAYS use AsyncResultOf utility for converting promises to Results
ALWAYS provide fallback error handling
ALWAYS use timeoutMonadic for API calls
ALWAYS provide appropriate timeout values for API calls
ALWAYS handle timeout errors gracefully
ALWAYS validate inputs before processing
ALWAYS provide clear validation error messages
ALWAYS use early returns for validation failures
ALWAYS log errors for debugging
ALWAYS use structured logging for errors
ALWAYS include relevant context in error logs
Throwing errors instead of using monadic patterns is an anti-pattern
Missing try-catch blocks for async operations is an anti-pattern
Generic error messages without context are an anti-pattern
Not handling specific error types is an anti-pattern
Missing timeout handling is an anti-pattern
No input validation is an anti-pattern
Poor error logging is an anti-pattern
Using any for error types is an anti-pattern
Missing error codes for internationalization is an anti-pattern
No fallback error handling is an anti-pattern
Console.error without structured logging is an anti-pattern

**/*.{ts,tsx}: ALWAYS use camelCase for variables, functions, and methods
ALWAYS use descriptive names that explain the purpose for variables and functions
ALWAYS use verb prefixes for functions that perform actions
ALWAYS use PascalCase for types, interfaces, and enums
ALWAYS use descriptive names that indicate the structure for types, interfaces, and enums
ALWAYS use suffixes like Props, State, Config, Type when appropriate for types and interfaces
ALWAYS use UPPER_SNAKE_CASE for constants and configuration values
ALWAYS use d...

Files:

  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
  • src/components/Modals/FiatRamps/config.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts
**/*

📄 CodeRabbit inference engine (.cursor/rules/naming-conventions.mdc)

**/*: ALWAYS use appropriate file extensions
Flag files without kebab-case

Files:

  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
  • src/components/Modals/FiatRamps/config.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/react-best-practices.mdc)

USE Redux only for global state shared across multiple places

Files:

  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
  • src/components/Modals/FiatRamps/config.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: gomesalexandre
PR: shapeshift/web#10206
File: src/config.ts:127-128
Timestamp: 2025-08-07T11:20:44.614Z
Learning: gomesalexandre prefers required environment variables without default values in the config file (src/config.ts). They want explicit configuration and fail-fast behavior when environment variables are missing, rather than having fallback defaults.
Learnt from: gomesalexandre
PR: shapeshift/web#10249
File: src/pages/ThorChainLP/components/ReusableLpStatus/TransactionRow.tsx:447-503
Timestamp: 2025-08-13T17:07:10.763Z
Learning: gomesalexandre prefers relying on TypeScript's type system for validation rather than adding defensive runtime null checks when types are properly defined. They favor a TypeScript-first approach over defensive programming with runtime validations.
Learnt from: gomesalexandre
PR: shapeshift/web#10276
File: src/hooks/useActionCenterSubscribers/useThorchainLpDepositActionSubscriber.tsx:61-66
Timestamp: 2025-08-14T17:51:47.556Z
Learning: gomesalexandre is not concerned about structured logging and prefers to keep console.error usage as-is rather than implementing structured logging patterns, even when project guidelines suggest otherwise.
Learnt from: gomesalexandre
PR: shapeshift/web#10276
File: src/pages/ThorChainLP/components/ReusableLpStatus/TransactionRow.tsx:396-402
Timestamp: 2025-08-14T17:55:57.490Z
Learning: gomesalexandre is comfortable with functions/variables that return undefined or true (tri-state) when only the truthy case matters, preferring to rely on JavaScript's truthy/falsy behavior rather than explicitly returning boolean values.
Learnt from: gomesalexandre
PR: shapeshift/web#10206
File: src/lib/moralis.ts:47-85
Timestamp: 2025-08-07T11:22:16.983Z
Learning: gomesalexandre prefers console.error over structured logging for Moralis API integration debugging, as they find it more conventional and prefer to examine XHR requests directly rather than rely on structured logs for troubleshooting.
Learnt from: gomesalexandre
PR: shapeshift/web#10276
File: src/hooks/useActionCenterSubscribers/useThorchainLpActionSubscriber.tsx:46-53
Timestamp: 2025-08-14T19:21:45.426Z
Learning: gomesalexandre does not like code patterns being labeled as "technical debt" and prefers neutral language when discussing existing code patterns that were intentionally moved/maintained for consistency.
🧬 Code graph analysis (4)
src/components/Modals/FiatRamps/config.ts (1)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts (1)
  • SUPPORTED_ONRAMPER_FIAT_CURRENCIES (22-108)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts (2)
src/components/Modals/FiatRamps/config.ts (1)
  • CommonFiatCurrencies (38-38)
packages/caip/src/constants.ts (15)
  • btcChainId (55-55)
  • bchChainId (56-56)
  • dogeChainId (57-57)
  • ltcChainId (58-58)
  • ethChainId (60-60)
  • avalancheChainId (61-61)
  • optimismChainId (62-62)
  • bscChainId (63-63)
  • polygonChainId (64-64)
  • gnosisChainId (65-65)
  • arbitrumChainId (66-66)
  • baseChainId (68-68)
  • cosmosChainId (70-70)
  • thorchainChainId (71-71)
  • solanaChainId (75-75)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts (6)
src/config.ts (1)
  • getConfig (201-203)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts (3)
  • OnRamperGatewaysResponse (23-28)
  • OnramperBuyQuoteResponse (79-79)
  • Crypto (2-13)
src/components/Modals/FiatRamps/config.ts (1)
  • CommonFiatCurrencies (38-38)
packages/caip/src/assetId/assetId.ts (3)
  • AssetId (17-17)
  • fromAssetId (143-178)
  • toAssetId (59-130)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts (1)
  • getChainIdFromOnramperNetwork (142-144)
packages/caip/src/constants.ts (1)
  • ASSET_NAMESPACE (109-118)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts (2)
packages/caip/src/assetId/assetId.ts (1)
  • AssetId (17-17)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts (3)
  • getSupportedOnramperCurrencies (13-27)
  • findAssetIdByOnramperCrypto (86-133)
  • findOnramperTokenIdByAssetId (58-84)
⏰ 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). (1)
  • GitHub Check: Install and Cache
🔇 Additional comments (2)
src/components/Modals/FiatRamps/config.ts (1)

16-17: Imports align with new modularization — good move

Switching to the consolidated Onramper module and constants improves cohesion.

src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts (1)

1-11: The scripts will locate the logger utility and its export. Once we have the exact path and export signature, I’ll update the import suggestion accordingly.

@gomesalexandre gomesalexandre marked this pull request as ready for review September 2, 2025 14:28
Copy link
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: 0

🧹 Nitpick comments (4)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts (4)

23-28: Normalize “Onramper” casing for consistency.

Type name mixes “OnRamper” here vs “Onramper” elsewhere (e.g., OnramperBuyQuote). Recommend standardizing to OnramperGatewaysResponse.

-export type OnRamperGatewaysResponse = {
+export type OnramperGatewaysResponse = {
   message: {
     crypto: Crypto[]
     fiat: Fiat[]
   }
 }

Note: update downstream imports accordingly if you choose to rename.


35-41: Simplify limits typing to avoid redundant intersection.

Current intersection makes aggregatedLimit both an index key and explicit prop. Use a single index signature plus explicit prop.

 type PaymentMethodDetails = {
   currencyStatus: string
-  limits: Record<string, PaymentLimits> & {
-    aggregatedLimit: PaymentLimits
-  }
+  limits: {
+    [currencyCode: string]: PaymentLimits
+    aggregatedLimit: PaymentLimits
+  }
 }

15-21: Export Fiat only if consumers need it.

If other modules will reference Fiat, export it now; otherwise keeping it internal is fine. Provided diff if you choose to export.

-type Fiat = {
+export type Fiat = {
   id: string
   code: string
   name: string
   symbol: string
   icon: string
 }

1-1: Pin the upstream reference link.

Linking to master can drift. Consider pinning to a commit SHA or adding a short note “shape adapted from Onramper widget types as of YYYY-MM-DD”.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 249f9ce and fb842f1.

📒 Files selected for processing (4)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts (1 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts (3 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts (1 hunks)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/constants.ts
  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/index.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{ts,tsx}: ALWAYS use Result<T, E> pattern for error handling in swappers and APIs
ALWAYS use Ok() and Err() from @sniptt/monads for monadic error handling
ALWAYS use custom error classes from @shapeshiftoss/errors
ALWAYS provide meaningful error codes for internationalization
ALWAYS include relevant details in error objects
ALWAYS wrap async operations in try-catch blocks
ALWAYS use AsyncResultOf utility for converting promises to Results
ALWAYS provide fallback error handling
ALWAYS use timeoutMonadic for API calls
ALWAYS provide appropriate timeout values for API calls
ALWAYS handle timeout errors gracefully
ALWAYS validate inputs before processing
ALWAYS provide clear validation error messages
ALWAYS use early returns for validation failures
ALWAYS log errors for debugging
ALWAYS use structured logging for errors
ALWAYS include relevant context in error logs
Throwing errors instead of using monadic patterns is an anti-pattern
Missing try-catch blocks for async operations is an anti-pattern
Generic error messages without context are an anti-pattern
Not handling specific error types is an anti-pattern
Missing timeout handling is an anti-pattern
No input validation is an anti-pattern
Poor error logging is an anti-pattern
Using any for error types is an anti-pattern
Missing error codes for internationalization is an anti-pattern
No fallback error handling is an anti-pattern
Console.error without structured logging is an anti-pattern

**/*.{ts,tsx}: ALWAYS use camelCase for variables, functions, and methods
ALWAYS use descriptive names that explain the purpose for variables and functions
ALWAYS use verb prefixes for functions that perform actions
ALWAYS use PascalCase for types, interfaces, and enums
ALWAYS use descriptive names that indicate the structure for types, interfaces, and enums
ALWAYS use suffixes like Props, State, Config, Type when appropriate for types and interfaces
ALWAYS use UPPER_SNAKE_CASE for constants and configuration values
ALWAYS use d...

Files:

  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
**/*

📄 CodeRabbit inference engine (.cursor/rules/naming-conventions.mdc)

**/*: ALWAYS use appropriate file extensions
Flag files without kebab-case

Files:

  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/react-best-practices.mdc)

USE Redux only for global state shared across multiple places

Files:

  • src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: gomesalexandre
PR: shapeshift/web#10206
File: src/config.ts:127-128
Timestamp: 2025-08-07T11:20:44.614Z
Learning: gomesalexandre prefers required environment variables without default values in the config file (src/config.ts). They want explicit configuration and fail-fast behavior when environment variables are missing, rather than having fallback defaults.
Learnt from: gomesalexandre
PR: shapeshift/web#10249
File: src/pages/ThorChainLP/components/ReusableLpStatus/TransactionRow.tsx:447-503
Timestamp: 2025-08-13T17:07:10.763Z
Learning: gomesalexandre prefers relying on TypeScript's type system for validation rather than adding defensive runtime null checks when types are properly defined. They favor a TypeScript-first approach over defensive programming with runtime validations.
Learnt from: gomesalexandre
PR: shapeshift/web#10276
File: src/hooks/useActionCenterSubscribers/useThorchainLpDepositActionSubscriber.tsx:61-66
Timestamp: 2025-08-14T17:51:47.556Z
Learning: gomesalexandre is not concerned about structured logging and prefers to keep console.error usage as-is rather than implementing structured logging patterns, even when project guidelines suggest otherwise.
Learnt from: gomesalexandre
PR: shapeshift/web#10413
File: src/components/Modals/FiatRamps/fiatRampProviders/onramper/utils.ts:29-55
Timestamp: 2025-09-02T14:26:19.001Z
Learning: gomesalexandre prefers to keep preparatory/reference code simple until it's actively consumed, rather than implementing comprehensive error handling, validation, and robustness improvements upfront. They prefer to add these improvements when the code is actually being used in production.
Learnt from: gomesalexandre
PR: shapeshift/web#10276
File: src/pages/ThorChainLP/components/ReusableLpStatus/TransactionRow.tsx:396-402
Timestamp: 2025-08-14T17:55:57.490Z
Learning: gomesalexandre is comfortable with functions/variables that return undefined or true (tri-state) when only the truthy case matters, preferring to rely on JavaScript's truthy/falsy behavior rather than explicitly returning boolean values.
Learnt from: gomesalexandre
PR: shapeshift/web#10206
File: src/lib/moralis.ts:47-85
Timestamp: 2025-08-07T11:22:16.983Z
Learning: gomesalexandre prefers console.error over structured logging for Moralis API integration debugging, as they find it more conventional and prefer to examine XHR requests directly rather than rely on structured logs for troubleshooting.
Learnt from: gomesalexandre
PR: shapeshift/web#10276
File: src/hooks/useActionCenterSubscribers/useThorchainLpActionSubscriber.tsx:46-53
Timestamp: 2025-08-14T19:21:45.426Z
Learning: gomesalexandre does not like code patterns being labeled as "technical debt" and prefers neutral language when discussing existing code patterns that were intentionally moved/maintained for consistency.
⏰ 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). (1)
  • GitHub Check: Install and Cache
🔇 Additional comments (3)
src/components/Modals/FiatRamps/fiatRampProviders/onramper/types.ts (3)

1-79: Overall LGTM for a first pass of prep types.

Keeping your preference for minimal prep code in mind; suggestions below are light nits and consistency tweaks.


2-13: Double-check numeric vs string shapes from the API.

Confirm decimals and chainId are numbers in the payloads you receive; some providers return numeric fields as strings.

Would you like me to add a small fixture-based test to lock this down?


64-76: Fields verified against Onramper API docs – no changes needed. rate, networkFee, transactionFee and payout match the official schema as numeric properties, and availablePaymentMethods aligns with the quotes response (limits are fetched from the payment-types endpoints).

Copy link
Collaborator

@NeOMakinG NeOMakinG left a comment

Choose a reason for hiding this comment

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

https://jam.dev/c/c94ecdc3-698e-4c61-bd9e-9032565e5825

Looks like working as expected! 👍

@NeOMakinG NeOMakinG enabled auto-merge (squash) September 5, 2025 11:37
@NeOMakinG NeOMakinG merged commit 7c01d24 into develop Sep 5, 2025
4 checks passed
@NeOMakinG NeOMakinG deleted the feat_onramper_queries branch September 5, 2025 11:45
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.

3 participants