harb/tests/e2e/05-optimizer-integration.spec.ts

178 lines
6.7 KiB
TypeScript
Raw Normal View History

import { expect, test } from '@playwright/test';
import { getStackConfig, validateStackHealthy } from '../setup/stack';
const STACK_CONFIG = getStackConfig();
const STACK_RPC_URL = STACK_CONFIG.rpcUrl;
// Solidity function selectors
const GET_LIQUIDITY_PARAMS_SELECTOR = '0xbd53c0dc'; // getLiquidityParams()
const POSITIONS_SELECTOR = '0xf86aafc0'; // positions(uint8)
// OptimizerV3 known bear-market parameters
const BEAR_ANCHOR_SHARE = 3n * 10n ** 17n; // 3e17 = 30%
const BEAR_ANCHOR_WIDTH = 100n;
const BEAR_DISCOVERY_DEPTH = 3n * 10n ** 17n; // 3e17
// Position stages
const STAGE_FLOOR = 0;
const STAGE_ANCHOR = 1;
const STAGE_DISCOVERY = 2;
// TICK_SPACING from ThreePositionStrategy
const TICK_SPACING = 200;
interface LiquidityParams {
capitalInefficiency: bigint;
anchorShare: bigint;
anchorWidth: bigint;
discoveryDepth: bigint;
}
async function rpcCall(method: string, params: unknown[]): Promise<unknown> {
const response = await fetch(STACK_RPC_URL, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
});
const data = await response.json();
if (data.error) throw new Error(`RPC error: ${data.error.message}`);
return data.result;
}
async function readLiquidityParams(optimizerAddress: string): Promise<LiquidityParams> {
const result = (await rpcCall('eth_call', [
{ to: optimizerAddress, data: GET_LIQUIDITY_PARAMS_SELECTOR },
'latest',
])) as string;
return {
capitalInefficiency: BigInt('0x' + result.slice(2, 66)),
anchorShare: BigInt('0x' + result.slice(66, 130)),
anchorWidth: BigInt('0x' + result.slice(130, 194)),
discoveryDepth: BigInt('0x' + result.slice(194, 258)),
};
}
function toInt24(val: bigint): number {
const n = Number(val & 0xffffffn);
return n >= 0x800000 ? n - 0x1000000 : n;
}
test.describe('Optimizer Integration', () => {
test.beforeAll(async () => {
await validateStackHealthy(STACK_CONFIG);
});
test('OptimizerV3 proxy returns valid bear-market parameters', async () => {
const optimizerAddress = STACK_CONFIG.contracts.OptimizerProxy;
if (!optimizerAddress) {
console.log(
'[TEST] SKIP: OptimizerProxy not in deployments-local.json (older deployment)',
);
test.skip();
return;
}
console.log(`[TEST] OptimizerProxy: ${optimizerAddress}`);
const params = await readLiquidityParams(optimizerAddress);
console.log(`[TEST] capitalInefficiency: ${params.capitalInefficiency}`);
console.log(`[TEST] anchorShare: ${params.anchorShare}`);
console.log(`[TEST] anchorWidth: ${params.anchorWidth}`);
console.log(`[TEST] discoveryDepth: ${params.discoveryDepth}`);
// With no staking activity, OptimizerV3 should return bear-market defaults
expect(params.capitalInefficiency).toBe(0n);
expect(params.anchorShare).toBe(BEAR_ANCHOR_SHARE);
expect(params.anchorWidth).toBe(BEAR_ANCHOR_WIDTH);
expect(params.discoveryDepth).toBe(BEAR_DISCOVERY_DEPTH);
console.log('[TEST] OptimizerV3 returns correct bear-market parameters');
});
test('bootstrap positions reflect optimizer anchorWidth=100 parameter', async () => {
const lmAddress = STACK_CONFIG.contracts.LiquidityManager;
const optimizerAddress = STACK_CONFIG.contracts.OptimizerProxy;
if (!optimizerAddress) {
test.skip();
return;
}
// Read optimizer params
const params = await readLiquidityParams(optimizerAddress);
const anchorWidth = Number(params.anchorWidth);
console.log(`[TEST] Optimizer anchorWidth: ${anchorWidth}`);
// Read anchor position from LM (created by bootstrap's recenter call)
const anchorResult = (await rpcCall('eth_call', [
{
to: lmAddress,
data: `${POSITIONS_SELECTOR}${'1'.padStart(64, '0')}`, // Stage.ANCHOR = 1
},
'latest',
])) as string;
const tickLower = toInt24(BigInt('0x' + anchorResult.slice(66, 130)));
const tickUpper = toInt24(BigInt('0x' + anchorResult.slice(130, 194)));
const anchorSpread = tickUpper - tickLower;
console.log(`[TEST] Anchor position: ticks=[${tickLower}, ${tickUpper}], spread=${anchorSpread}`);
// Verify the anchor spread matches the optimizer formula:
// anchorSpacing = TICK_SPACING + (34 * anchorWidth * TICK_SPACING / 100)
// For anchorWidth=100: anchorSpacing = 200 + (34 * 100 * 200 / 100) = 200 + 6800 = 7000
// Full anchor = 2 * anchorSpacing = 14000 ticks
const expectedSpacing = TICK_SPACING + (34 * anchorWidth * TICK_SPACING) / 100;
const expectedSpread = expectedSpacing * 2;
console.log(`[TEST] Expected anchor spread: ${expectedSpread} (anchorSpacing=${expectedSpacing})`);
expect(anchorSpread).toBe(expectedSpread);
console.log('[TEST] Anchor spread matches optimizer anchorWidth=100 formula');
});
test('all three positions have valid relative sizing', async () => {
const lmAddress = STACK_CONFIG.contracts.LiquidityManager;
const optimizerAddress = STACK_CONFIG.contracts.OptimizerProxy;
if (!optimizerAddress) {
test.skip();
return;
}
// Read all three positions
const positions = [];
const stageNames = ['FLOOR', 'ANCHOR', 'DISCOVERY'];
for (const stage of [STAGE_FLOOR, STAGE_ANCHOR, STAGE_DISCOVERY]) {
const stageHex = stage.toString(16).padStart(64, '0');
const result = (await rpcCall('eth_call', [
{ to: lmAddress, data: `${POSITIONS_SELECTOR}${stageHex}` },
'latest',
])) as string;
const liquidity = BigInt('0x' + result.slice(2, 66));
const tickLower = toInt24(BigInt('0x' + result.slice(66, 130)));
const tickUpper = toInt24(BigInt('0x' + result.slice(130, 194)));
const spread = tickUpper - tickLower;
positions.push({ liquidity, tickLower, tickUpper, spread });
console.log(`[TEST] ${stageNames[stage]}: spread=${spread}, liquidity=${liquidity}`);
}
// Floor should be narrow (TICK_SPACING width = 200 ticks)
expect(positions[0].spread).toBe(TICK_SPACING);
console.log('[TEST] Floor has expected narrow width (200 ticks)');
// Anchor should be wider than floor
expect(positions[1].spread).toBeGreaterThan(positions[0].spread);
console.log('[TEST] Anchor is wider than floor');
// Discovery should have significant spread
expect(positions[2].spread).toBeGreaterThan(0);
console.log('[TEST] Discovery has positive spread');
// Floor liquidity should be highest (concentrated in narrow range)
expect(positions[0].liquidity).toBeGreaterThan(positions[1].liquidity);
console.log('[TEST] Floor liquidity > anchor liquidity (as expected for concentrated position)');
console.log('[TEST] All position sizing validated against optimizer parameters');
});
});