From f02161a32a702cf645d8cf1899d8e1deccfb04c4 Mon Sep 17 00:00:00 2001 From: "kas.eth" Date: Wed, 11 Nov 2026 23:34:53 +0000 Subject: [PATCH 1/2] Add Robinhood Chain (4663) market support and non-18-decimal collateral - New src/config/chains.js: per-chain RPCs, explorer, AMM flavour, Uniswap V3 and futarchy addresses; isUniswapChain() replaces chain === 1 branches. - Wagmi chain + transports, registry chain allowlist, candles endpoint, CHAIN_CONFIG, RPC maps and Reality config for chain 4663. - Uniswap quote/swap helpers take the chain's factory, QuoterV2 and Universal Router (non-canonical on 4663) and an Orbit-appropriate gas config. - TWAP widget reads on the market's chain and uses UniV3 observe() there. - Token decimals are read from the market instead of assumed 18: balances, split/merge/redeem amounts, max-amount raw units, swap amounts and sqrtPriceX96 prices (USDG and its outcome tokens have 6 decimals). --- auto-qa/tests/subgraph-endpoints.test.mjs | 8 + .../tests/unified-balance-fetcher.test.mjs | 6 +- src/adapters/registryAdapter.js | 3 +- src/adapters/subgraphConfigAdapter.js | 80 +++++-- src/components/common/WrongNetworkModal.jsx | 6 + src/components/debug/constants/chainConfig.js | 27 +++ .../companyList/components/ChainBadge.jsx | 7 + .../marketPage/AddLiquidityModal.jsx | 10 +- .../marketPage/ConfirmSwapModal.jsx | 69 ++++-- .../marketPage/MarketHistoryViewModel.jsx | 3 + .../marketPage/MarketPageShowcase.jsx | 49 +++-- .../marketPage/ShowcaseSwapComponent.jsx | 80 ++++--- .../collateralModal/CollateralModal.jsx | 27 ++- .../redeemTokens/RedemptionModal.jsx | 20 +- src/config/chains.js | 201 ++++++++++++++++++ src/config/subgraphEndpoints.js | 1 + src/hooks/useChainValidation.js | 2 + src/hooks/useContractConfig.js | 21 +- src/providers/providers.jsx | 19 +- src/spotPriceUtils/rpcProvider.js | 4 + src/utils/activeMarketLiquidity.js | 1 + src/utils/getBestRpc.js | 4 + src/utils/getRpcUrl.js | 8 + src/utils/tokenDecimals.js | 54 +++++ src/utils/unifiedBalanceFetcher.js | 33 +-- src/utils/uniswapSdk.js | 48 ++++- src/utils/uniswapV3Quote.mjs | 37 +++- 27 files changed, 691 insertions(+), 137 deletions(-) create mode 100644 src/config/chains.js create mode 100644 src/utils/tokenDecimals.js diff --git a/auto-qa/tests/subgraph-endpoints.test.mjs b/auto-qa/tests/subgraph-endpoints.test.mjs index 40e7f9cd..fad5ec0e 100644 --- a/auto-qa/tests/subgraph-endpoints.test.mjs +++ b/auto-qa/tests/subgraph-endpoints.test.mjs @@ -64,6 +64,14 @@ test('subgraphEndpoints — both chain endpoints point to api.futarchy.fi (pinne assert.equal(m100[1], 'https://api.futarchy.fi/candles/graphql'); }); +test('subgraphEndpoints — Robinhood Chain (4663) routes to the candles service with an explicit chainId', () => { + // Chain 4663 markets (Uniswap V3 on Robinhood Chain) are selected explicitly, + // like chain 1; dropping this entry makes the market page fall back to Gnosis. + const m = SRC.match(/\b4663\s*:\s*['"]([^'"]+)['"]/); + assert.ok(m, 'SUBGRAPH_ENDPOINTS missing chain id "4663" entry'); + assert.equal(m[1], 'https://api.futarchy.fi/candles/graphql?chainId=4663'); +}); + // --------------------------------------------------------------------------- // POOL_TYPES + OUTCOME_SIDES — frozen enums // --------------------------------------------------------------------------- diff --git a/auto-qa/tests/unified-balance-fetcher.test.mjs b/auto-qa/tests/unified-balance-fetcher.test.mjs index 1956fe6d..357df95f 100644 --- a/auto-qa/tests/unified-balance-fetcher.test.mjs +++ b/auto-qa/tests/unified-balance-fetcher.test.mjs @@ -319,9 +319,11 @@ test('source — positionIds batch is 4-tuple in canonical order: currencyYes, c test('source — positionBalances destructured in same order as positionIds (mapping invariant)', () => { // Pinned: positionBalances[0]=currencyYes, [1]=currencyNo, [2]=companyYes, - // [3]=companyNo. Drift here silently swaps balances. + // [3]=companyNo. Drift here silently swaps balances. Each side is formatted + // with its own decimals (currency vs company) — 6-decimal USDG on Robinhood + // Chain would otherwise display 1e-12 of the real balance. assert.match(SRC, - /currencyYes:\s*formatBalanceSafely\(positionBalances\[0\]\),\s*currencyNo:\s*formatBalanceSafely\(positionBalances\[1\]\),\s*companyYes:\s*formatBalanceSafely\(positionBalances\[2\]\),\s*companyNo:\s*formatBalanceSafely\(positionBalances\[3\]\)/, + /currencyYes:\s*formatBalanceSafely\(positionBalances\[0\],\s*currencyDecimals\),\s*currencyNo:\s*formatBalanceSafely\(positionBalances\[1\],\s*currencyDecimals\),\s*companyYes:\s*formatBalanceSafely\(positionBalances\[2\],\s*companyDecimals\),\s*companyNo:\s*formatBalanceSafely\(positionBalances\[3\],\s*companyDecimals\)/, `positionBalances destructure order drifted from [currencyYes, currencyNo, companyYes, companyNo]`); }); diff --git a/src/adapters/registryAdapter.js b/src/adapters/registryAdapter.js index 3fd90e57..15bb6f8e 100644 --- a/src/adapters/registryAdapter.js +++ b/src/adapters/registryAdapter.js @@ -5,6 +5,7 @@ import { AGGREGATOR_SUBGRAPH_URL as REGISTRY_SUBGRAPH_URL } from '../config/subgraphEndpoints'; +import { isSupportedChain } from '../config/chains'; // Default Aggregator address (Futarchy Finance production) const DEFAULT_AGGREGATOR = '0xc5eb43d53e2fe5fdde5faf400cc4167e5b5d4fc1'; @@ -94,7 +95,7 @@ export function extractChainFromMetadata(proposalEntity) { // Handle both number and string formats (100 or "100") const chainInt = typeof chain === 'string' ? parseInt(chain) : chain; - if (chainInt && (chainInt === 1 || chainInt === 100)) { + if (chainInt && isSupportedChain(chainInt)) { console.log('[Registry] Extracted chain from metadata:', chainInt); return chainInt; } diff --git a/src/adapters/subgraphConfigAdapter.js b/src/adapters/subgraphConfigAdapter.js index 2ada8ac3..f381afe6 100644 --- a/src/adapters/subgraphConfigAdapter.js +++ b/src/adapters/subgraphConfigAdapter.js @@ -8,6 +8,7 @@ import { createPublicClient, http, fallback } from 'viem'; import { gnosis, mainnet } from 'viem/chains'; import { SUBGRAPH_ENDPOINTS } from '../config/subgraphEndpoints'; +import { robinhoodChain, getDefaultCurrencySymbol } from '../config/chains'; // Re-export for backward compatibility export { SUBGRAPH_ENDPOINTS }; @@ -35,6 +36,19 @@ const CHAIN_CONFIG = { ammFactory: '0xA0864cCA6E114013AB0e27cbd5B6f4c8947da766', viemChain: gnosis, rpcUrls: ['https://gnosis.drpc.org', 'https://rpc.gnosischain.com', 'https://gnosis-rpc.publicnode.com', 'https://rpc.gnosis.gateway.fm'] + }, + // Robinhood Chain (Arbitrum Orbit L2) — Uniswap V3 at NON-canonical addresses + 4663: { + factoryAddress: '0xebb2bf1cbdd625a8118b720877a7e361696e7a14', + routerAddress: '0x7834bb7f4724393043701b2a944feae0496e00ad', + futarchyAdapter: '0x7834bb7f4724393043701b2a944feae0496e00ad', + conditionalTokens: '0x3aee58842a1d76c50f36eb5a34e79ef958d082c7', + wrapperService: '0x9d0bb3418b1834e40bd106c0dbb9318cdc847468', + ammFactory: '0x1f7d7550B1b028f7571E69A784071F0205FD2EfA', + // Fee tiers probed by the on-chain pool-discovery fallback (500 first) + poolFeeTiers: [500, 3000, 10000], + viemChain: robinhoodChain, + rpcUrls: ['https://rpc.mainnet.chain.robinhood.com', 'https://robinhood-rpc.publicnode.com'] } }; @@ -121,8 +135,15 @@ export async function fetchProposalFromChain(proposalAddress, chainId) { return null; } - // Read base + outcome token symbols (best-effort; default decimals 18). + // Read base + outcome token symbols and decimals (best-effort; default decimals 18). + // Decimals are read on-chain because they are NOT always 18: on Robinhood + // Chain (4663) USDG and its YES/NO outcome tokens have 6 decimals. const symbolOf = (addr) => client.readContract({ address: addr, abi: ERC20_SYMBOL_ABI, functionName: 'symbol' }).catch(() => null); + const decimalsOf = (addr) => client.readContract({ address: addr, abi: ERC20_SYMBOL_ABI, functionName: 'decimals' }) + .then(d => (Number.isFinite(Number(d)) ? Number(d) : 18)).catch(() => 18); + const [companyDec, currencyDec, yCoDec, nCoDec, yCuDec, nCuDec] = await Promise.all([ + decimalsOf(c1), decimalsOf(c2), decimalsOf(yesCompanyAddr), decimalsOf(noCompanyAddr), decimalsOf(yesCurrencyAddr), decimalsOf(noCurrencyAddr) + ]); const [companySym, currencySym, yCoSym, nCoSym, yCuSym, nCuSym] = await Promise.all([ symbolOf(c1), symbolOf(c2), symbolOf(yesCompanyAddr), symbolOf(noCompanyAddr), symbolOf(yesCurrencyAddr), symbolOf(noCurrencyAddr) ]); @@ -132,10 +153,15 @@ export async function fetchProposalFromChain(proposalAddress, chainId) { try { return await client.readContract({ address: cfg.ammFactory, abi: ALGEBRA_FACTORY_ABI, functionName: 'poolByPair', args: [tokenA, tokenB] }); } catch { - // UniV3 (Ethereum): default 1% fee tier used by these markets. - try { - return await client.readContract({ address: cfg.ammFactory, abi: UNIV3_FACTORY_ABI, functionName: 'getPool', args: [tokenA, tokenB, 10000] }); - } catch { return null; } + // UniV3: probe the chain's fee tiers (Ethereum default: the 1% tier + // used by those markets; Robinhood Chain: 0.05% first). + for (const fee of (cfg.poolFeeTiers || [10000])) { + try { + const pool = await client.readContract({ address: cfg.ammFactory, abi: UNIV3_FACTORY_ABI, functionName: 'getPool', args: [tokenA, tokenB, fee] }); + if (pool && pool !== ZERO_ADDR) return pool; + } catch { /* try next tier */ } + } + return null; } }; const [yesPool, noPool] = await Promise.all([ @@ -148,15 +174,15 @@ export async function fetchProposalFromChain(proposalAddress, chainId) { if (noPool && noPool !== ZERO_ADDR) pools.push({ id: noPool.toLowerCase(), name: 'CONDITIONAL_NO', type: 'CONDITIONAL', outcomeSide: 'NO', price: null }); const companySymbol = companySym || 'COMPANY'; - const currencySymbol = currencySym || (chainId === 1 ? 'USDS' : 'sDAI'); + const currencySymbol = currencySym || getDefaultCurrencySymbol(chainId); // Outcome-token symbols must match `${PREFIX}_${baseSymbol}` for // transformSubgraphToSupabaseFormat's findToken() to pair them. const outcomeTokens = [ - { id: yesCompanyAddr.toLowerCase(), symbol: yCoSym || `YES_${companySymbol}`, decimals: 18 }, - { id: noCompanyAddr.toLowerCase(), symbol: nCoSym || `NO_${companySymbol}`, decimals: 18 }, - { id: yesCurrencyAddr.toLowerCase(), symbol: yCuSym || `YES_${currencySymbol}`, decimals: 18 }, - { id: noCurrencyAddr.toLowerCase(), symbol: nCuSym || `NO_${currencySymbol}`, decimals: 18 }, + { id: yesCompanyAddr.toLowerCase(), symbol: yCoSym || `YES_${companySymbol}`, decimals: yCoDec }, + { id: noCompanyAddr.toLowerCase(), symbol: nCoSym || `NO_${companySymbol}`, decimals: nCoDec }, + { id: yesCurrencyAddr.toLowerCase(), symbol: yCuSym || `YES_${currencySymbol}`, decimals: yCuDec }, + { id: noCurrencyAddr.toLowerCase(), symbol: nCuSym || `NO_${currencySymbol}`, decimals: nCuDec }, ]; console.log(`[OnChainFallback] Assembled config for ${proposalAddress} (${pools.length} conditional pools found on-chain)`); @@ -164,8 +190,8 @@ export async function fetchProposalFromChain(proposalAddress, chainId) { return { id: proposalAddress.toLowerCase(), marketName: marketName || '', - companyToken: { id: c1.toLowerCase(), symbol: companySymbol, decimals: 18 }, - currencyToken: { id: c2.toLowerCase(), symbol: currencySymbol, decimals: 18 }, + companyToken: { id: c1.toLowerCase(), symbol: companySymbol, decimals: companyDec }, + currencyToken: { id: c2.toLowerCase(), symbol: currencySymbol, decimals: currencyDec }, outcomeTokens, pools, _fromChain: true, @@ -278,6 +304,10 @@ export async function fetchProposalFromSubgraph(proposalAddress, chainId) { // Default decimals to 18 (true for all current tokens; if a future token // differs we'll add an on-chain fallback). Outcome tokens carry their own. const decimalsDefault = yesCompany?.decimals ?? 18; + // Outcome tokens take their collateral's decimals on chains where they are + // not 18 (Robinhood Chain: USDG / YES_USDG / NO_USDG = 6), so derive the + // currency side from the currency outcome tokens, not the company side. + const currencyDecimals = yesCurrency?.decimals ?? noCurrency?.decimals ?? decimalsDefault; // Assemble a Graph-Node-style object so transformSubgraphToSupabaseFormat // doesn't need to know about the schema difference. @@ -294,7 +324,7 @@ export async function fetchProposalFromSubgraph(proposalAddress, chainId) { ? { id: companyAddr, symbol: companySymbol, decimals: decimalsDefault } : null, currencyToken: currencySymbol - ? { id: currencyAddr, symbol: currencySymbol, decimals: decimalsDefault } + ? { id: currencyAddr, symbol: currencySymbol, decimals: currencyDecimals } : null, outcomeTokens, pools: pools.map(p => ({ @@ -318,6 +348,12 @@ export async function fetchProposalFromSubgraph(proposalAddress, chainId) { * @param {number} chainId - The chain ID * @returns {Object} - Data in Supabase market_event format */ +// Token decimals as a number (indexer returns numbers or numeric strings); default 18. +function toDecimals(value) { + const n = Number(value); + return Number.isInteger(n) && n >= 0 && n <= 36 ? n : 18; +} + export function transformSubgraphToSupabaseFormat(subgraphData, proposalAddress, chainId) { if (!subgraphData) { return null; @@ -389,17 +425,20 @@ export function transformSubgraphToSupabaseFormat(subgraphData, proposalAddress, base: companyToken ? { tokenName: companyToken.symbol, tokenSymbol: companyToken.symbol, - wrappedCollateralTokenAddress: companyToken.id + wrappedCollateralTokenAddress: companyToken.id, + decimals: toDecimals(companyToken.decimals) } : null, yes: yesCompany ? { tokenName: yesCompany.symbol, tokenSymbol: yesCompany.symbol, - wrappedCollateralTokenAddress: yesCompany.id + wrappedCollateralTokenAddress: yesCompany.id, + decimals: toDecimals(yesCompany.decimals) } : null, no: noCompany ? { tokenName: noCompany.symbol, tokenSymbol: noCompany.symbol, - wrappedCollateralTokenAddress: noCompany.id + wrappedCollateralTokenAddress: noCompany.id, + decimals: toDecimals(noCompany.decimals) } : null }, @@ -407,17 +446,20 @@ export function transformSubgraphToSupabaseFormat(subgraphData, proposalAddress, base: currencyToken ? { tokenName: currencyToken.symbol, tokenSymbol: currencyToken.symbol, - wrappedCollateralTokenAddress: currencyToken.id + wrappedCollateralTokenAddress: currencyToken.id, + decimals: toDecimals(currencyToken.decimals) } : null, yes: yesCurrency ? { tokenName: yesCurrency.symbol, tokenSymbol: yesCurrency.symbol, - wrappedCollateralTokenAddress: yesCurrency.id + wrappedCollateralTokenAddress: yesCurrency.id, + decimals: toDecimals(yesCurrency.decimals) } : null, no: noCurrency ? { tokenName: noCurrency.symbol, tokenSymbol: noCurrency.symbol, - wrappedCollateralTokenAddress: noCurrency.id + wrappedCollateralTokenAddress: noCurrency.id, + decimals: toDecimals(noCurrency.decimals) } : null }, diff --git a/src/components/common/WrongNetworkModal.jsx b/src/components/common/WrongNetworkModal.jsx index eba93c44..34c3e5f4 100644 --- a/src/components/common/WrongNetworkModal.jsx +++ b/src/components/common/WrongNetworkModal.jsx @@ -16,6 +16,12 @@ const CHAIN_STYLE_MAP = { accentBg: 'bg-futarchyGreen3', accentBorder: 'border-futarchyGreen5', accentText: 'text-futarchyGreen11' + }, + 4663: { + name: 'Robinhood Chain', + accentBg: 'bg-futarchyGreen3', + accentBorder: 'border-futarchyGreen5', + accentText: 'text-futarchyGreen11' } }; diff --git a/src/components/debug/constants/chainConfig.js b/src/components/debug/constants/chainConfig.js index b84875c8..e6098e79 100644 --- a/src/components/debug/constants/chainConfig.js +++ b/src/components/debug/constants/chainConfig.js @@ -47,6 +47,29 @@ export const CHAIN_CONFIG = { symbol: 'sDAI' } } + }, + 4663: { + id: 4663, + name: 'Robinhood Chain', + rpcUrl: 'https://rpc.mainnet.chain.robinhood.com', + factoryAddress: '0xebb2bf1cbdd625a8118b720877a7e361696e7a14', + adapterAddress: '0x7834bb7f4724393043701b2a944feae0496e00ad', + positionManager: '0x73991a25c818bf1f1128deaab1492d45638de0d3', + poolFactory: '0x1f7d7550B1b028f7571E69A784071F0205FD2EfA', + amm: 'uniswap', + defaultFeeTier: 500, + explorerUrl: 'https://robinhoodchain.blockscout.com', + nativeCurrency: 'ETH', + defaultTokens: { + company: { + address: '0xd0601CE157Db5bdC3162BbaC2a2C8aF5320D9EEC', + symbol: 'NVDA' + }, + currency: { + address: '0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168', + symbol: 'USDG' + } + } } }; @@ -90,6 +113,10 @@ export const REALITY_CONFIG = { 100: { contract: '0xE78996A233895bE74a66F451f1019cA9734205cc', token: 'XDAI' + }, + 4663: { + contract: '0x13279f59e694369e1d591e95b08a3107b8520ed3', + token: 'ETH' } }; diff --git a/src/components/futarchyFi/companyList/components/ChainBadge.jsx b/src/components/futarchyFi/companyList/components/ChainBadge.jsx index 6149dc57..a9f10c83 100644 --- a/src/components/futarchyFi/companyList/components/ChainBadge.jsx +++ b/src/components/futarchyFi/companyList/components/ChainBadge.jsx @@ -16,6 +16,13 @@ const CHAIN_CONFIG = { borderColor: "border-emerald-300 dark:border-emerald-700", textColor: "text-emerald-700 dark:text-emerald-400", }, + 4663: { + name: "Robinhood Chain", + shortName: "Robinhood", + color: "bg-lime-100 dark:bg-lime-900/30", + borderColor: "border-lime-300 dark:border-lime-700", + textColor: "text-lime-700 dark:text-lime-400", + }, 137: { name: "Polygon", shortName: "Polygon", diff --git a/src/components/futarchyFi/marketPage/AddLiquidityModal.jsx b/src/components/futarchyFi/marketPage/AddLiquidityModal.jsx index 6482d76f..85f0e1d3 100644 --- a/src/components/futarchyFi/marketPage/AddLiquidityModal.jsx +++ b/src/components/futarchyFi/marketPage/AddLiquidityModal.jsx @@ -1,4 +1,5 @@ import React, { useState, useEffect } from 'react'; +import { isUniswapChain, getChainInfo } from '../../../config/chains'; import { motion, AnimatePresence } from 'framer-motion'; import { useAccount, usePublicClient } from 'wagmi'; import { ethers } from 'ethers'; @@ -15,7 +16,7 @@ const AddLiquidityModal = ({ isOpen, onClose, config }) => { // Fetch positions when modal opens useEffect(() => { const fetchPositions = async () => { - if (!isOpen || !isConnected || !config || !publicClient || config.chainId !== 1) { + if (!isOpen || !isConnected || !config || !publicClient || config.chainId !== 1) { // Ethereum-only position scan (canonical NFPM) setPositions([]); return; } @@ -120,12 +121,13 @@ const AddLiquidityModal = ({ isOpen, onClose, config }) => { const createLiquidityUrl = (tokenA, tokenB) => { // Use Uniswap V3 for Ethereum mainnet (chain 1), Swapr for other chains - if (config?.chainId === 1) { + if (isUniswapChain(config?.chainId)) { + const uniswapAppChain = getChainInfo(config.chainId)?.uniswapAppChain || 'ethereum'; // Uniswap V3 add liquidity URL format with proper fee structure const feeParam = encodeURIComponent(JSON.stringify({ feeAmount: 500, tickSpacing: 10, isDynamic: false })); const priceRangeParam = encodeURIComponent(JSON.stringify({ priceInverted: false, fullRange: true, minPrice: "", maxPrice: "", initialPrice: "" })); const depositParam = encodeURIComponent(JSON.stringify({ exactField: "TOKEN0", exactAmounts: {} })); - return `https://app.uniswap.org/positions/create/v3?currencyA=${tokenA}¤cyB=${tokenB}&chain=ethereum&fee=${feeParam}&hook=undefined&priceRangeState=${priceRangeParam}&depositState=${depositParam}`; + return `https://app.uniswap.org/positions/create/v3?currencyA=${tokenA}¤cyB=${tokenB}&chain=${uniswapAppChain}&fee=${feeParam}&hook=undefined&priceRangeState=${priceRangeParam}&depositState=${depositParam}`; } return `https://v3.swapr.eth.limo/#/add/${tokenA}/${tokenB}/select-pair`; }; @@ -249,7 +251,7 @@ const AddLiquidityModal = ({ isOpen, onClose, config }) => {
Add liquidity to earn fees from trades. - {config?.chainId === 1 + {isUniswapChain(config?.chainId) ? " Click on any pool to open Uniswap V3 and add liquidity." : " Click on any pool to open Swapr and add liquidity." } diff --git a/src/components/futarchyFi/marketPage/ConfirmSwapModal.jsx b/src/components/futarchyFi/marketPage/ConfirmSwapModal.jsx index 16263c4b..34b10ddc 100644 --- a/src/components/futarchyFi/marketPage/ConfirmSwapModal.jsx +++ b/src/components/futarchyFi/marketPage/ConfirmSwapModal.jsx @@ -54,6 +54,8 @@ import { getEthersSigner, getEthersProvider, isSafeWallet } from '../../../utils import { waitForSafeTxReceipt } from '../../../utils/waitForSafeTxReceipt'; import { useSubgraphRefresh } from '../../../contexts/SubgraphRefreshContext'; import { approvalAmountFor } from '../../../utils/approvalAmount'; +import { toSdkAmount, parseTokenAmount, normalizeDecimals } from '../../../utils/tokenDecimals'; +import { isUniswapChain, getUniswapAddresses, getExplorerUrl, getChainInfo } from '../../../config/chains'; // Define ERC20 ABI in viem-compatible format const ERC20_ABI_VIEM = [ @@ -650,8 +652,8 @@ const ConfirmSwapModal = memo(({ // Effect to update swap method when chain changes useEffect(() => { - if (chain?.id === 1) { - // Force UniswapSDK on Ethereum mainnet + if (isUniswapChain(chain?.id)) { + // Force UniswapSDK on Uniswap V3 chains (Ethereum mainnet, Robinhood Chain) setSelectedSwapMethod('uniswapSdk'); } else if (selectedSwapMethod === 'uniswapSdk' || selectedSwapMethod === 'uniswap') { // If switching away from Ethereum and using Uniswap, switch to Algebra @@ -659,9 +661,19 @@ const ConfirmSwapModal = memo(({ } }, [chain?.id, selectedSwapMethod]); + // Point the "View on explorer" link at the connected chain's explorer + // (Etherscan / Blockscout) instead of the GnosisScan default. + useEffect(() => { + const info = getChainInfo(chain?.id); + if (info && chain?.id !== 100) { + setUiExplorerUrl(`${info.explorer}/tx/`); + setUiExplorerName(info.explorerName || 'Explorer'); + } + }, [chain?.id]); + // Effect to save the selected swap method to localStorage useEffect(() => { - if (typeof window !== 'undefined' && selectedSwapMethod && chain?.id !== 1) { + if (typeof window !== 'undefined' && selectedSwapMethod && !isUniswapChain(chain?.id)) { // Only save preference for non-Ethereum chains localStorage.setItem('lastSwapMethod', selectedSwapMethod); } @@ -982,7 +994,15 @@ const ConfirmSwapModal = memo(({ }; // Add this helper function after the DEFAULT_PRECISION definition - const safeParseToWei = (value) => { + // Decimals of the token being sold: Sell spends company-side tokens; Buy / + // Redeem / Recover spend currency-side tokens. Outcome tokens share their + // collateral's decimals (18 on Gnosis/Ethereum, 6 for USDG on Robinhood Chain). + const inputDecimalsForAction = (action) => { + const baseCfg = config?.BASE_TOKENS_CONFIG || BASE_TOKENS_CONFIG || DEFAULT_BASE_TOKENS_CONFIG; + return normalizeDecimals(action === 'Sell' ? baseCfg?.company?.decimals : baseCfg?.currency?.decimals); + }; + + const safeParseToWei = (value, decimals = 18) => { console.log('=== safeParseToWei Input ===', { value, type: typeof value @@ -998,11 +1018,13 @@ const ConfirmSwapModal = memo(({ const decimalValue = new Decimal(value); console.log('Decimal value:', decimalValue.toString()); - const weiValue = decimalValue.times(new Decimal(10).pow(18)); + const tokenDecimals = normalizeDecimals(decimals); + const weiValue = decimalValue.times(new Decimal(10).pow(tokenDecimals)); console.log('Wei value:', weiValue.toString()); - // Convert to string and remove any decimal part (shouldn't have any, but just in case) - const weiString = weiValue.toFixed(0); + // Convert to string and remove any decimal part (shouldn't have any, but just in case). + // Non-18-decimal tokens (e.g. 6-decimal USDG) truncate so we never round above the balance. + const weiString = tokenDecimals === 18 ? weiValue.toFixed(0) : weiValue.toFixed(0, Decimal.ROUND_DOWN); console.log('Wei string:', weiString); // Convert to BigNumber for compatibility with ethers @@ -1257,7 +1279,8 @@ const ConfirmSwapModal = memo(({ const iterator = cartridge.completeSplit({ proposal: marketAddress, collateralToken: baseToken.address, - amount: amount.toString(), // Match CollateralModal exactly (relies on SDK parseEther) + // 18-decimal tokens: string (SDK parseEther). Others (e.g. 6-decimal USDG): raw bigint. + amount: toSdkAmount(amount, baseToken.decimals), exactApproval: !useUnlimitedApproval, useBlockExplorer }, { publicClient, walletClient, account }); @@ -1550,16 +1573,16 @@ const ConfirmSwapModal = memo(({ // This fixes the 2-wei precision issue that causes STF errors when swapping max balance const amountInWei = transactionData.amountInRaw ? ethers.BigNumber.from(transactionData.amountInRaw) - : safeParseToWei(amount); + : safeParseToWei(amount, inputDecimalsForAction(transactionData.action)); if (amountInWei.isZero()) throw new Error("Invalid amount"); console.log('[DEBUG] Amount precision:', { hasRawWei: !!transactionData.amountInRaw, rawWei: transactionData.amountInRaw, - parsedWei: safeParseToWei(amount).toString(), + parsedWei: safeParseToWei(amount, inputDecimalsForAction(transactionData.action)).toString(), usedWei: amountInWei.toString(), difference: transactionData.amountInRaw ? - ethers.BigNumber.from(transactionData.amountInRaw).sub(safeParseToWei(amount)).toString() : '0' + ethers.BigNumber.from(transactionData.amountInRaw).sub(safeParseToWei(amount, inputDecimalsForAction(transactionData.action))).toString() : '0' }); console.log('[DEBUG] Transaction data parsed:', { @@ -1637,8 +1660,8 @@ const ConfirmSwapModal = memo(({ console.log('[ConfirmSwapModal] Initializing UniswapRouterCartridge'); cartridge = new UniswapRouterCartridge({ chainId: chain?.id || 1, - routerAddress: UNISWAP_UNIVERSAL_ROUTER, - permit2Address: PERMIT2_ADDRESS + routerAddress: getUniswapAddresses(chain?.id)?.universalRouter || UNISWAP_UNIVERSAL_ROUTER, + permit2Address: getUniswapAddresses(chain?.id)?.permit2 || PERMIT2_ADDRESS }); const minAmountOut = minimumFromQuote( @@ -2909,7 +2932,7 @@ const ConfirmSwapModal = memo(({ // Prefer raw wei value to avoid precision loss (same fix as handleConfirmSwapToggle) const amountInWei = transactionData.amountInRaw ? ethers.BigNumber.from(transactionData.amountInRaw) - : safeParseToWei(amount); + : safeParseToWei(amount, inputDecimalsForAction(transactionData.action)); if (amountInWei.isZero()) throw new Error("Invalid amount"); let tokenIn, tokenOut; @@ -3092,8 +3115,12 @@ const ConfirmSwapModal = memo(({ shouldInvertPoolPrices = (tokenOut.toLowerCase() < tokenIn.toLowerCase()); } - const currentPrice = shouldInvertPoolPrices ? (1 / rawCurrentPrice) : rawCurrentPrice; - const poolPriceAfter = shouldInvertPoolPrices ? (1 / rawPoolPriceAfter) : rawPoolPriceAfter; + // sqrtPriceX96 prices are in raw base units; scale to human units when the + // two sides have different decimals (e.g. 18-decimal NVDA vs 6-decimal USDG). + const priceBaseCfg = config?.BASE_TOKENS_CONFIG || BASE_TOKENS_CONFIG || DEFAULT_BASE_TOKENS_CONFIG; + const priceDecimalsScale = 10 ** (normalizeDecimals(priceBaseCfg?.company?.decimals) - normalizeDecimals(priceBaseCfg?.currency?.decimals)); + const currentPrice = (shouldInvertPoolPrices ? (1 / rawCurrentPrice) : rawCurrentPrice) * priceDecimalsScale; + const poolPriceAfter = (shouldInvertPoolPrices ? (1 / rawPoolPriceAfter) : rawPoolPriceAfter) * priceDecimalsScale; // Execution price: rawExecutionPrice = output/input // For Buy: output=company, input=currency → rawExecutionPrice = company/currency → INVERT @@ -3622,7 +3649,7 @@ const ConfirmSwapModal = memo(({
{/* Only show UniswapSDK on Ethereum mainnet (chain 1) */} - {chain?.id === 1 ? ( + {isUniswapChain(chain?.id) ? (
@@ -5190,8 +5211,8 @@ const MarketPageShowcase = ({ hidden = false, debugMode = false, proposal = null chartFilters={chartFilters} onFilterClick={handleChartFilterClick} predictionMarketLink={config?.BASE_TOKENS_CONFIG?.currency?.address && config?.MERGE_CONFIG?.currencyPositions?.yes?.wrap?.wrappedCollateralTokenAddress - ? (config?.chainId === 1 - ? `https://app.uniswap.org/swap?inputCurrency=${config.BASE_TOKENS_CONFIG.currency.address}&outputCurrency=${config.MERGE_CONFIG.currencyPositions.yes.wrap.wrappedCollateralTokenAddress}` + ? (isUniswapChain(config?.chainId) + ? getUniswapSwapUrl(config.chainId, config.BASE_TOKENS_CONFIG.currency.address, config.MERGE_CONFIG.currencyPositions.yes.wrap.wrappedCollateralTokenAddress) : `https://v3.swapr.eth.limo/#/swap?inputCurrency=${config.BASE_TOKENS_CONFIG.currency.address}&outputCurrency=${config.MERGE_CONFIG.currencyPositions.yes.wrap.wrappedCollateralTokenAddress}`) : null} config={config} diff --git a/src/components/futarchyFi/marketPage/ShowcaseSwapComponent.jsx b/src/components/futarchyFi/marketPage/ShowcaseSwapComponent.jsx index 66a82b32..6b05019d 100644 --- a/src/components/futarchyFi/marketPage/ShowcaseSwapComponent.jsx +++ b/src/components/futarchyFi/marketPage/ShowcaseSwapComponent.jsx @@ -1,4 +1,6 @@ import React, { useState, useMemo, useCallback, useEffect } from 'react'; +import { isUniswapChain } from '../../../config/chains'; +import { normalizeDecimals, parseTokenAmount } from '../../../utils/tokenDecimals'; import ConfirmSwapModal from './ConfirmSwapModal'; import SwapNativeToCurrencyModal from './SwapNativeToCurrencyModal'; import { STEPS_CONFIG } from './constants/swapSteps'; @@ -146,6 +148,14 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal // Use the market's chain (from config/registry) for quoting, not the wallet's chain. // The wallet may be on Ethereum while viewing a Gnosis market. const chainId = config?.chainId || walletChainId; + // Uniswap V3 chains (Ethereum, Robinhood Chain) quote through QuoterV2; Gnosis uses Algebra. + const isUniswapMarket = isUniswapChain(chainId); + const hasOnchainQuoter = isUniswapMarket || chainId === 100; + // Token decimals per side (18 except e.g. 6-decimal USDG on Robinhood Chain). + const currencyDecimals = normalizeDecimals(config?.BASE_TOKENS_CONFIG?.currency?.decimals); + const companyDecimals = normalizeDecimals(config?.BASE_TOKENS_CONFIG?.company?.decimals); + // sqrtPriceX96 prices are raw base-unit ratios; this scales "currency per company" to human units. + const priceDecimalsScale = 10 ** (companyDecimals - currencyDecimals); const { signer, @@ -195,7 +205,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal // Debounced QuoterV2/Swapr SDK preview - for Ethereum (chainId === 1) and Gnosis (chainId === 100) useEffect(() => { // Only run on Ethereum mainnet or Gnosis Chain - if (chainId !== 1 && chainId !== 100) { + if (!hasOnchainQuoter) { setQuoterPreview({ isLoading: false, amountOut: null, error: null }); return; } @@ -353,7 +363,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal // Always fetch pool current price first (needed even if quote fails) let poolData; try { - poolData = await getPoolSqrtPrice(tokenIn, tokenOut, 500, ethersProvider, 1); + poolData = await getPoolSqrtPrice(tokenIn, tokenOut, 500, ethersProvider, chainId); currentPrice = sqrtPriceX96ToPrice(poolData.sqrtPriceX96); } catch (poolErr) { console.warn('[QUOTER SHOWCASE] Could not get pool price:', poolErr.message); @@ -365,7 +375,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal amountIn: amount, fee: 500, provider: ethersProvider, - chainId: 1, + chainId, slippageBps: 50 }); @@ -373,7 +383,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal // If pool price wasn't fetched above (different fee tier), try with the quoter's fee tier if (!poolData && quoteResult.feeTier !== 500) { - poolData = await getPoolSqrtPrice(tokenIn, tokenOut, quoteResult.feeTier, ethersProvider, 1); + poolData = await getPoolSqrtPrice(tokenIn, tokenOut, quoteResult.feeTier, ethersProvider, chainId); currentPrice = sqrtPriceX96ToPrice(poolData.sqrtPriceX96); } @@ -383,7 +393,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal // Determine if we need to invert based on action (Buy/Sell) // Goal: Always show prices as "currency per company" // Swapr SDK already returns displayPrice in the correct direction - if (chainId === 1) { + if (isUniswapMarket) { // Uniswap: Simplify using action const isBuy = selectedAction === 'Buy'; @@ -402,6 +412,9 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal currentPrice = 1 / currentPrice; executionPrice = 1 / executionPrice; } + // Raw base-unit ratio -> human "currency per company" (no-op when both sides are 18 decimals) + currentPrice = currentPrice * priceDecimalsScale; + executionPrice = executionPrice * priceDecimalsScale; console.log('[QUOTER SHOWCASE] Uniswap Prices:', { action: selectedAction, @@ -459,8 +472,8 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal try { const { getBestRpcProvider } = await import('../../../utils/getBestRpc'); const ethersProvider = await getBestRpcProvider(chainId); - if (chainId === 1) { - const poolData = await getPoolSqrtPrice(tokenIn, tokenOut, 500, ethersProvider, 1); + if (isUniswapMarket) { + const poolData = await getPoolSqrtPrice(tokenIn, tokenOut, 500, ethersProvider, chainId); fallbackPrice = sqrtPriceX96ToPrice(poolData.sqrtPriceX96); // Apply same inversion logic as the main path const isBuy = selectedAction === 'Buy'; @@ -468,6 +481,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal ? (tokenIn.toLowerCase() < tokenOut.toLowerCase()) : (tokenOut.toLowerCase() < tokenIn.toLowerCase()); if (shouldInvert) fallbackPrice = 1 / fallbackPrice; + fallbackPrice = fallbackPrice * priceDecimalsScale; } else if (chainId === 100) { // Gnosis: try the Algebra pool const { getAlgebraQuoteWithSlippage } = await import('../../../utils/algebraQuoter'); @@ -507,6 +521,9 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal // Handle max amount click without formatting const handleMaxClick = useCallback(() => { + // Raw base units must use the decimals of the token being spent + // (Buy spends currency-side tokens, Sell spends company-side tokens). + const rawInputDecimals = selectedAction === 'Buy' ? currencyDecimals : companyDecimals; try { let totalAvailable; @@ -575,8 +592,8 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal ? (positions?.currencyYes?.total || '0') : (positions?.currencyNo?.total || '0'); const baseBalance = balances?.currencyBalance || balances?.sdaiBalance || '0'; - const outcomeBN = ethers.utils.parseUnits(outcomeBalance, 18); - const baseBN = ethers.utils.parseUnits(baseBalance, 18); + const outcomeBN = parseTokenAmount(outcomeBalance, rawInputDecimals); + const baseBN = parseTokenAmount(baseBalance, rawInputDecimals); rawWeiValue = outcomeBN.add(baseBN).toString(); } else if (selectedCurrency === 'WXDAI') { if (redirectToCOW) { @@ -584,8 +601,8 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal ? (positions?.currencyYes?.total || '0') : (positions?.currencyNo?.total || '0'); const baseBalance = balances?.sdaiBalance || '0'; - const outcomeBN = ethers.utils.parseUnits(outcomeBalance, 18); - const baseBN = ethers.utils.parseUnits(baseBalance, 18); + const outcomeBN = parseTokenAmount(outcomeBalance, rawInputDecimals); + const baseBN = parseTokenAmount(baseBalance, rawInputDecimals); rawWeiValue = outcomeBN.add(baseBN).toString(); } else { rawWeiValue = ethers.utils.parseUnits(balances?.nativeBalance || '0', 18).toString(); @@ -595,8 +612,8 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal ? (positions?.currencyYes?.total || '0') : (positions?.currencyNo?.total || '0'); const baseBalance = positions?.wxdai || '0'; - const outcomeBN = ethers.utils.parseUnits(outcomeBalance, 18); - const baseBN = ethers.utils.parseUnits(baseBalance, 18); + const outcomeBN = parseTokenAmount(outcomeBalance, rawInputDecimals); + const baseBN = parseTokenAmount(baseBalance, rawInputDecimals); rawWeiValue = outcomeBN.add(baseBN).toString(); } } else { @@ -604,8 +621,8 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal ? (positions?.companyYes?.total || '0') : (positions?.companyNo?.total || '0'); const baseBalance = positions?.faot || '0'; - const outcomeBN = ethers.utils.parseUnits(outcomeBalance, 18); - const baseBN = ethers.utils.parseUnits(baseBalance, 18); + const outcomeBN = parseTokenAmount(outcomeBalance, rawInputDecimals); + const baseBN = parseTokenAmount(baseBalance, rawInputDecimals); rawWeiValue = outcomeBN.add(baseBN).toString(); } setAmountRawWei(rawWeiValue); @@ -622,12 +639,12 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal setAmount(fallbackBalance); // Also set raw wei for fallback try { - setAmountRawWei(ethers.utils.parseUnits(fallbackBalance, 18).toString()); + setAmountRawWei(parseTokenAmount(fallbackBalance, rawInputDecimals).toString()); } catch (e) { setAmountRawWei(null); } } - }, [selectedAction, selectedOutcome, selectedCurrency, positions, balances, redirectToCOW, getCurrencySymbol]); + }, [selectedAction, selectedOutcome, selectedCurrency, positions, balances, redirectToCOW, getCurrencySymbol, currencyDecimals, companyDecimals]); // Memoized transaction data object const transactionData = useMemo(() => ({ @@ -642,7 +659,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal console.error("Invalid amount entered"); return; } - if ((chainId === 1 || chainId === 100) && (quoterPreview.isLoading || quoterPreview.quotedAmountIn !== amount || !quoterPreview.amountOut)) { + if (hasOnchainQuoter && (quoterPreview.isLoading || quoterPreview.quotedAmountIn !== amount || !quoterPreview.amountOut)) { console.error('A current on-chain pool quote is required'); return; } @@ -677,7 +694,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal } else { receiveToken = getCurrencySymbol(); } - } else if (chainId !== 1 && chainId !== 100 && currentPrice && currentPrice > 0) { + } else if (!hasOnchainQuoter && currentPrice && currentPrice > 0) { // Fallback to legacy calc — spot price estimate with conservative fee deduction const APPROX_POOL_FEE = 0.01; // 1% conservative estimate for pool fees if (selectedAction === 'Buy') { @@ -727,6 +744,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal isApproximate: !(USING_FUTARCHY_QUOTER && quoterPreview?.amountOut && !quoterPreview.error), insufficientLiquidity: quoterPreview?.insufficientLiquidity || false, outputDecimals: quoterPreview?.decimalsOut || 18, + inputDecimals: selectedAction === 'Buy' ? currencyDecimals : companyDecimals, tradeAnywayAcknowledged, }; console.log("Opening ConfirmSwapModal directly with data:", directConfirmData); @@ -1228,7 +1246,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal const displayedPriceImpact = Number(quoterPreview.priceImpactPct); const hasPriceImpact = Number.isFinite(displayedPriceImpact); const priceImpactTooHigh = hasPriceImpact && displayedPriceImpact > 15; - const quoteUnavailable = (chainId === 1 || chainId === 100) && (quoterPreview.quotedAmountIn !== amount || !quoterPreview.amountOut); + const quoteUnavailable = hasOnchainQuoter && (quoterPreview.quotedAmountIn !== amount || !quoterPreview.amountOut); return ( <> @@ -1485,7 +1503,7 @@ const ShowcaseSwapComponent = ({ positions, prices, walletBalances, isLoadingBal Outcomes {/* Show toggle on Ethereum mainnet and Gnosis Chain when quote data is available */} - {(chainId === 1 || chainId === 100) && quoterPreview.currentPrice && ( + {hasOnchainQuoter && quoterPreview.currentPrice && (