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/futarchy-sdk/refactorCreateProposal/cli.js b/futarchy-sdk/refactorCreateProposal/cli.js index ac319050..83948789 100644 --- a/futarchy-sdk/refactorCreateProposal/cli.js +++ b/futarchy-sdk/refactorCreateProposal/cli.js @@ -174,6 +174,8 @@ class FutarchyCLI { category: config.category, // Use category from config if provided language: config.language // Use language from config if provided }; + // Reality.eth minimum bond in wei of the chain's native token (default 1e18 from chains.config.json) + if (config.minBond !== undefined && config.minBond !== null) proposalConfig.minBond = config.minBond; const result = await this.proposalCreator.createProposal(proposalConfig); diff --git a/futarchy-sdk/refactorCreateProposal/config/chains.config.json b/futarchy-sdk/refactorCreateProposal/config/chains.config.json index 498102f4..dc470751 100644 --- a/futarchy-sdk/refactorCreateProposal/config/chains.config.json +++ b/futarchy-sdk/refactorCreateProposal/config/chains.config.json @@ -20,7 +20,7 @@ "POOL_FACTORY": "0x1F98431c8aD98523631AE4a59f267346ea31F984", "FUTARCHY_FACTORY": "0xf9369c0F7a84CAC3b7Ef78c837cF7313309D3678", "DEFAULT_ADAPTER": "0xAc9Bf8EbA6Bd31f8E8c76f8E8B2AAd0BD93f98Dc" - }, + }, "tokens": { "DEFAULT_COMPANY_TOKEN": { "symbol": "WETH", @@ -144,6 +144,59 @@ }, "gasPriceGwei": "20.0", "explorer": "https://polygonscan.com" + }, + "4663": { + "name": "Robinhood Chain", + "chainId": 4663, + "rpcUrl": "https://rpc.mainnet.chain.robinhood.com", + "defaultAMM": "uniswap", + "contractsByAMM": { + "uniswap": { + "POSITION_MANAGER": "0x73991a25c818bf1f1128deaab1492d45638de0d3", + "SWAP_ROUTER": "0xcaf681a66d020601342297493863e78c959e5cb2", + "POOL_FACTORY": "0x1f7d7550B1b028f7571E69A784071F0205FD2EfA", + "FUTARCHY_FACTORY": "0xebb2bf1cbdd625a8118b720877a7e361696e7a14", + "DEFAULT_ADAPTER": "0x7834bb7f4724393043701b2a944feae0496e00ad", + "QUOTER_V2": "0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7", + "UNIVERSAL_ROUTER": "0x8876789976decbfcbbbe364623c63652db8c0904", + "PERMIT2": "0x000000000022D473030F116dDEE9F6B43aC78BA3" + } + }, + "contracts": { + "POSITION_MANAGER": "0x73991a25c818bf1f1128deaab1492d45638de0d3", + "SWAP_ROUTER": "0xcaf681a66d020601342297493863e78c959e5cb2", + "POOL_FACTORY": "0x1f7d7550B1b028f7571E69A784071F0205FD2EfA", + "FUTARCHY_FACTORY": "0xebb2bf1cbdd625a8118b720877a7e361696e7a14", + "DEFAULT_ADAPTER": "0x7834bb7f4724393043701b2a944feae0496e00ad", + "QUOTER_V2": "0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7", + "UNIVERSAL_ROUTER": "0x8876789976decbfcbbbe364623c63652db8c0904", + "PERMIT2": "0x000000000022D473030F116dDEE9F6B43aC78BA3" + }, + "tokens": { + "DEFAULT_COMPANY_TOKEN": { + "symbol": "NVDA", + "address": "0xd0601CE157Db5bdC3162BbaC2a2C8aF5320D9EEC" + }, + "DEFAULT_CURRENCY_TOKEN": { + "symbol": "USDG", + "address": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168" + } + }, + "gasSettings": { + "CREATE_PROPOSAL": 5000000, + "CREATE_POOL": 5100000, + "MINT_POSITION": 1000000, + "SWAP": 350000, + "SPLIT": 1000000, + "MERGE": 15000000, + "APPROVE": 100000, + "COLLECT": 500000, + "DECREASE_LIQUIDITY": 500000, + "BURN": 500000 + }, + "gasPriceGwei": "0.05", + "maxFeePerGasGwei": "0.5", + "explorer": "https://robinhoodchain.blockscout.com" } }, "defaultChain": 100, @@ -158,4 +211,4 @@ "SLIPPAGE_TOLERANCE": 0.01, "DEADLINE_MINUTES": 20 } -} +} \ No newline at end of file diff --git a/futarchy-sdk/refactorCreateProposal/config/test-nvda-robinhood.json b/futarchy-sdk/refactorCreateProposal/config/test-nvda-robinhood.json new file mode 100644 index 00000000..c5c7ff20 --- /dev/null +++ b/futarchy-sdk/refactorCreateProposal/config/test-nvda-robinhood.json @@ -0,0 +1,22 @@ +{ + "chainId": 4663, + "amm": "uniswap", + "marketName": "TEST MARKET, please ignore: plumbing test of the futarchy stack on Robinhood Chain (NVDA/USDG). Not a real question; resolves No.", + "description": "Plumbing test. Not a real question.", + "openingTime": 1794526773, + "minBond": "100000000000000", + "display_text_1": "TEST MARKET: plumbing test", + "display_text_2": "on Robinhood Chain (ignore)", + "companyToken": {"symbol": "NVDA", "address": "0xd0601CE157Db5bdC3162BbaC2a2C8aF5320D9EEC"}, + "currencyToken": {"symbol": "USDG", "address": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}, + "spotPrice": 160.9, + "eventProbability": 0.5, + "impact": -5, + "liquidityAmounts": [1, 1, 1, 1, 1, 1], + "forceAddLiquidity": [], + "adapterAddress": "0x7834bb7f4724393043701b2a944feae0496e00ad", + "companyId": "0", + "feeTier": 500, + "category": "governance", + "language": "en" +} diff --git a/futarchy-sdk/refactorCreateProposal/modules/futarchyAdapter.js b/futarchy-sdk/refactorCreateProposal/modules/futarchyAdapter.js index 71e4ea38..ab0f174a 100644 --- a/futarchy-sdk/refactorCreateProposal/modules/futarchyAdapter.js +++ b/futarchy-sdk/refactorCreateProposal/modules/futarchyAdapter.js @@ -51,7 +51,7 @@ class FutarchyAdapter { const feeData = await this.wallet.provider.getFeeData().catch(() => ({})); const chainId = (await this.wallet.provider.getNetwork()).chainId; // Ultra-low for Ethereum when gas is cheap, higher for Polygon - const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : '2'); + const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : (chainId === 4663n ? '0.01' : '2')); const minTip = ethers.parseUnits(minTipGwei, 'gwei'); let maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? minTip; if (maxPriorityFeePerGas < minTip) maxPriorityFeePerGas = minTip; @@ -132,7 +132,7 @@ class FutarchyAdapter { // Execute merge with chain-appropriate gas settings const feeData2 = await this.wallet.provider.getFeeData().catch(() => ({})); const chainId = (await this.wallet.provider.getNetwork()).chainId; - const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : '2'); + const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : (chainId === 4663n ? '0.01' : '2')); const minTip = ethers.parseUnits(minTipGwei, 'gwei'); let maxPriorityFeePerGas2 = feeData2.maxPriorityFeePerGas ?? minTip; if (maxPriorityFeePerGas2 < minTip) maxPriorityFeePerGas2 = minTip; diff --git a/futarchy-sdk/refactorCreateProposal/modules/liquidityOrchestrator.js b/futarchy-sdk/refactorCreateProposal/modules/liquidityOrchestrator.js index 8e524652..7002dd42 100644 --- a/futarchy-sdk/refactorCreateProposal/modules/liquidityOrchestrator.js +++ b/futarchy-sdk/refactorCreateProposal/modules/liquidityOrchestrator.js @@ -101,14 +101,28 @@ class LiquidityOrchestrator { console.log(` NO Price: ${conditionalPrices.noPriceFormatted}`); console.log('─'.repeat(40)); - // Calculate pool configurations (default 18 decimals for both tokens) + // Calculate pool configurations with the real decimals of each token. Outcome tokens are read + // on-chain too: some factories give them 18 decimals, others the collateral's decimals. + const [companyInfo, currencyInfo, yesCurrencyInfo] = await Promise.all([ + this.tokenManager.loadToken(companyToken.address), + this.tokenManager.loadToken(currencyToken.address), + this.tokenManager.loadToken(proposal.yesCurrencyToken) + ]); + const companyTokenDecimals = Number(companyInfo.decimals); + const currencyTokenDecimals = Number(currencyInfo.decimals); + const conditionalDecimalsFollowCollateral = Number(yesCurrencyInfo.decimals) === currencyTokenDecimals && currencyTokenDecimals !== 18; + if (!conditionalDecimalsFollowCollateral && (companyTokenDecimals !== 18 || currencyTokenDecimals !== 18)) { + throw new Error(`Outcome tokens have 18 decimals but collateral has ${companyTokenDecimals}/${currencyTokenDecimals}: amounts and pool prices would be mis-scaled. Use a factory that gives outcome tokens the collateral's decimals.`); + } + console.log(`Decimals: company ${companyTokenDecimals}, currency ${currencyTokenDecimals}, outcome tokens follow collateral: ${conditionalDecimalsFollowCollateral}`); const poolConfigs = this.priceCalculator.calculatePoolConfigurations({ spotPrice, eventProbability, impactPercentage: impact, liquidityAmounts, - companyTokenDecimals: 18, - currencyTokenDecimals: 18 + companyTokenDecimals, + currencyTokenDecimals, + conditionalDecimalsFollowCollateral }); // Capture global fee tier once to avoid shadowing inside loop @@ -133,8 +147,8 @@ class LiquidityOrchestrator { console.log(` Price: 1 ${config.token0} = ${config.targetPrice.toFixed(6)} ${config.token1}`); console.log(` Liquidity (${config.token1}): ${config.liquidity}`); console.log(` Required amounts:`); - console.log(` ${config.token0}: ${ethers.formatEther(config.amount0Wei)}`); - console.log(` ${config.token1}: ${ethers.formatEther(config.amount1Wei)}`); + console.log(` ${config.token0}: ${ethers.formatUnits(config.amount0Wei, config.decimals0)}`); + console.log(` ${config.token1}: ${ethers.formatUnits(config.amount1Wei, config.decimals1)}`); } console.log('='.repeat(60)); diff --git a/futarchy-sdk/refactorCreateProposal/modules/poolManager.js b/futarchy-sdk/refactorCreateProposal/modules/poolManager.js index e892e0fc..b34ed831 100644 --- a/futarchy-sdk/refactorCreateProposal/modules/poolManager.js +++ b/futarchy-sdk/refactorCreateProposal/modules/poolManager.js @@ -155,7 +155,15 @@ class PoolManager { let sqrtPriceX96; if (logicalPrice && Number(logicalPrice) > 0) { // AMM price is token1 per token0 in AMM order; convert from logical price if needed - const ammPrice = needsReorder ? (1 / Number(logicalPrice)) : Number(logicalPrice); + // logicalPrice is in human units (token1 per token0, logical order). The pool price is in raw + // units, so scale by the decimals difference: raw = human * 10^(dec1 - dec0). + const [logical0Info, logical1Info] = await Promise.all([ + this.tokenManager.loadToken(token0Address), + this.tokenManager.loadToken(token1Address) + ]); + const decimalsShift = Number(logical1Info.decimals) - Number(logical0Info.decimals); + const rawLogicalPrice = Number(logicalPrice) * (10 ** decimalsShift); + const ammPrice = needsReorder ? (1 / rawLogicalPrice) : rawLogicalPrice; // sqrtPriceX96 = sqrt(ammPrice) * 2^96 const sqrtRatio = Math.sqrt(ammPrice); sqrtPriceX96 = BigInt(Math.floor(sqrtRatio * (2 ** 96))); @@ -209,7 +217,7 @@ class PoolManager { // EIP-1559 fee with chain-appropriate minimums const feeData = await this.wallet.provider.getFeeData().catch(() => ({})); const chainId = (await this.wallet.provider.getNetwork()).chainId; - const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : '2'); + const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : (chainId === 4663n ? '0.01' : '2')); const minTip = ethers.parseUnits(minTipGwei, 'gwei'); let maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? minTip; if (maxPriorityFeePerGas < minTip) maxPriorityFeePerGas = minTip; @@ -235,7 +243,7 @@ class PoolManager { const maxAffordableTotal = ethBalance * 95n / 100n; // Use 95% of balance, leave 5% buffer const maxAffordableGasPrice = maxAffordableTotal / createGasLimit; - console.log(` ⛽ Gas limit: ${createGasLimit} (needs ${gasNeeded} + 10% margin)`); + console.log(` ⛽ Gas limit: ${createGasLimit}`); console.log(` ⛽ Network gas prices (with 10% boost): Base ${ethers.formatUnits(baseFee, 'gwei')} Gwei, Priority ${ethers.formatUnits(maxPriorityFeePerGas, 'gwei')} Gwei, Max ${ethers.formatUnits(maxFeePerGas, 'gwei')} Gwei`); console.log(` ⛽ Max affordable gas price: ${ethers.formatUnits(maxAffordableGasPrice, 'gwei')} Gwei`); @@ -568,7 +576,7 @@ class PoolManager { // EIP-1559 fee data with chain-appropriate minimums const feeData = await this.wallet.provider.getFeeData().catch(() => ({})); const chainId = (await this.wallet.provider.getNetwork()).chainId; - const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : '2'); + const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : (chainId === 4663n ? '0.01' : '2')); const minTip = ethers.parseUnits(minTipGwei, 'gwei'); let maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? minTip; if (maxPriorityFeePerGas < minTip) maxPriorityFeePerGas = minTip; diff --git a/futarchy-sdk/refactorCreateProposal/utils/priceCalculations.js b/futarchy-sdk/refactorCreateProposal/utils/priceCalculations.js index bfae711f..99963e30 100644 --- a/futarchy-sdk/refactorCreateProposal/utils/priceCalculations.js +++ b/futarchy-sdk/refactorCreateProposal/utils/priceCalculations.js @@ -139,7 +139,8 @@ class PriceCalculator { impactPercentage, liquidityAmounts, // Array of 6 values companyTokenDecimals = 18, - currencyTokenDecimals = 18 + currencyTokenDecimals = 18, + conditionalDecimalsFollowCollateral = false } = params; const conditionalPrices = this.calculateConditionalPrices(spotPrice, eventProbability, impactPercentage); @@ -200,12 +201,11 @@ class PriceCalculator { return pools.map(pool => { const isCond0 = pool.token0.startsWith('YES') || pool.token0.startsWith('NO'); const isCond1 = pool.token1.startsWith('YES') || pool.token1.startsWith('NO'); - const decimals0 = isCond0 - ? 18 - : (pool.token0.includes('Company') ? companyTokenDecimals : currencyTokenDecimals); - const decimals1 = isCond1 - ? 18 - : (pool.token1.includes('Company') ? companyTokenDecimals : currencyTokenDecimals); + // Outcome tokens normally carry 18 decimals (Seer factory default). Factories that give outcome + // tokens their collateral's decimals pass conditionalDecimalsFollowCollateral = true. + const collateralDecimals = (name) => (name.includes('Company') ? companyTokenDecimals : currencyTokenDecimals); + const decimals0 = (isCond0 && !conditionalDecimalsFollowCollateral) ? 18 : collateralDecimals(pool.token0); + const decimals1 = (isCond1 && !conditionalDecimalsFollowCollateral) ? 18 : collateralDecimals(pool.token1); // The liquidity amount is always for token1 (sDAI or conditional sDAI) const amounts = this.calculateLiquidityAmounts( diff --git a/futarchy-sdk/refactorCreateProposal/utils/tokens.js b/futarchy-sdk/refactorCreateProposal/utils/tokens.js index daa052c4..6c24cbad 100644 --- a/futarchy-sdk/refactorCreateProposal/utils/tokens.js +++ b/futarchy-sdk/refactorCreateProposal/utils/tokens.js @@ -78,7 +78,7 @@ class TokenManager { // Use lower minimums for Ethereum (chainId 1), higher for Polygon (chainId 137) const chainId = (await this.provider.getNetwork()).chainId; // Ultra-low for Ethereum when gas is cheap, normal for Polygon - const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : '2'); + const minTipGwei = chainId === 1n ? '0.04' : (chainId === 137n ? '25' : (chainId === 4663n ? '0.01' : '2')); const minTip = ethers.parseUnits(minTipGwei, 'gwei'); let maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? minTip; if (maxPriorityFeePerGas < minTip) maxPriorityFeePerGas = minTip; 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 && (