Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions auto-qa/tests/subgraph-endpoints.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
// ---------------------------------------------------------------------------
Expand Down
6 changes: 4 additions & 2 deletions auto-qa/tests/unified-balance-fetcher.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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]`);
});

Expand Down
2 changes: 2 additions & 0 deletions futarchy-sdk/refactorCreateProposal/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
57 changes: 55 additions & 2 deletions futarchy-sdk/refactorCreateProposal/config/chains.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"POOL_FACTORY": "0x1F98431c8aD98523631AE4a59f267346ea31F984",
"FUTARCHY_FACTORY": "0xf9369c0F7a84CAC3b7Ef78c837cF7313309D3678",
"DEFAULT_ADAPTER": "0xAc9Bf8EbA6Bd31f8E8c76f8E8B2AAd0BD93f98Dc"
},
},
"tokens": {
"DEFAULT_COMPANY_TOKEN": {
"symbol": "WETH",
Expand Down Expand Up @@ -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,
Expand All @@ -158,4 +211,4 @@
"SLIPPAGE_TOLERANCE": 0.01,
"DEADLINE_MINUTES": 20
}
}
}
Original file line number Diff line number Diff line change
@@ -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"
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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));

Expand Down
16 changes: 12 additions & 4 deletions futarchy-sdk/refactorCreateProposal/modules/poolManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
Expand Down Expand Up @@ -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;
Expand All @@ -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`);

Expand Down Expand Up @@ -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;
Expand Down
14 changes: 7 additions & 7 deletions futarchy-sdk/refactorCreateProposal/utils/priceCalculations.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion futarchy-sdk/refactorCreateProposal/utils/tokens.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 2 additions & 1 deletion src/adapters/registryAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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;
}
Expand Down
Loading
Loading