Repository Public
1// GMX v2 trading (v8) — wiring for the rest of the API service: the process-wide engine on the real signer client, the2// registry RPC endpoints and the read adapter's market data, and its tracking worker. Disabled by construction: nothing is3// prepared unless SPW_DERIV_LIVE_MAINNET=on AND SPW_DERIV_GMX_LIVE=on, and the owner approved a venue policy with a passkey.4import { listCreds } from '../auth.ts';5import { config } from '../config.ts';6import { signer } from '../signer-client.ts';7import { loop } from '../worker.ts';8import { realGmxChain } from './gmx-chain.ts';9import { GmxService, GMX_STEP_MS, type GmxDeps, type GmxMarketPort } from './gmx-exec.ts';10import { derivatives } from './index.ts';11import { mainnetLiveEnabled } from './live.ts';1213/** venue-specific server setting, read at every use: anything but the exact value `on` keeps GMX trading closed (default off) */14export const gmxLiveEnabled = (): boolean => process.env.SPW_DERIV_GMX_LIVE === 'on';1516const realMarket = (): GmxMarketPort => ({17 market: async (instrument) => { const m = await derivatives().data.market(instrument); return { instrument: m.instrument, ticker: m.ticker, liquidity: m.liquidity }; },18 apiPositions: async (account) => (await derivatives().data.watch('gmx', account)).positions,19});2021/** tests pass a scripted chain, an in-process signer, fixture market data and a clock */22export function createGmx(o: Partial<GmxDeps> = {}): GmxService {23 const now = o.now ?? Date.now;24 return new GmxService({ chain: o.chain ?? realGmxChain(now), signer: o.signer ?? signer, market: o.market ?? realMarket(), now, rpId: o.rpId ?? config.rpId,25 credentials: o.credentials ?? (async () => (await listCreds()).map((c) => ({ id: c.id, transports: c.transports }))),26 settings: o.settings ?? (() => ({ liveMainnet: mainnetLiveEnabled(), gmxLive: gmxLiveEnabled() })) });27}2829let shared: GmxService | null = null;30export function gmx(): GmxService { return (shared ??= createGmx()); }3132/** ONE tracking worker: operations in flight (approval mined → order sent → created → executed / cancelled / frozen). It never signs. */33export function startGmxWorker(g: GmxService = gmx()): void {34 let last = '';35 loop('deriv-gmx', async () => {36 const s = await g.step();37 const err = s.errors[0] ?? '';38 if (err && err !== last) console.log(`[derivatives] gmx: ${s.errors.length} error(s) (${err})`);39 last = err;40 }, GMX_STEP_MS);41}42