import type { Address } from "viem"; import { createNonceManager, jsonRpc, type NonceManager } from "viem/nonce"; /** The identity whose local sends must reach terminal broadcast results in order. */ export interface LocalSendKey { readonly address: Address; readonly chainId: number; } /** Owner-held nonce and send coordination shared by every derived trader. */ export interface WriterRuntime { readonly nonceManager: NonceManager; readonly runLocalSend: (key: LocalSendKey, task: () => Promise) => Promise; } /** Build the writer state owned by one configured Markets client. */ export function makeWriterRuntime(): WriterRuntime { const nonceManager = createNonceManager({ source: jsonRpc() }); const tails = new Map>(); function runLocalSend({ address, chainId }: LocalSendKey, task: () => Promise): Promise { const key = `${chainId}:${address.toLowerCase()}`; const previous = tails.get(key) ?? Promise.resolve(); const result = previous.then(task); const tail = result.then( () => undefined, () => undefined, ); tails.set(key, tail); void tail.then(() => { if (tails.get(key) === tail) tails.delete(key); }); return result; } return { nonceManager, runLocalSend }; }