unrip/archive/implementation/20260408T162514Z-cow-protocol-intent-based-venue-integration-proof.md
philipp fb547f24d9
All checks were successful
deploy / deploy (push) Successful in 48s
fix: scope inventory fetch by submission time window to prevent OOM
Instead of fetching up to 50k inventory snapshots (~442MB), scope the
query to only the time range of the current submission batch with a
15-minute buffer. For a typical 1-hour batch this drops from 50k rows
to ~300 rows, well within the 1280Mi pod memory limit.

The coalesced_at_idx on intent_inventory_snapshots covers the BETWEEN
clause so this remains efficient.

Proof: history-writer OOM kills from refreshQuoteOutcomes inventory fetch
Assumptions: 15min buffer covers the attribution window for all submissions
Still fake: heuristic gap outcomes may attribute trades imprecisely
2026-06-16 17:17:19 +02:00

168 lines
11 KiB
Markdown

# Implementation Proof: CoW Protocol intent-based venue integration
Status: open
Opened: 2026-04-07
## Target outcome
This turn proves that `unrip` can absorb a second venue with materially different execution semantics without breaking the shared truth pipeline.
The concrete target is one real CoW Protocol trader flow for one approved chain and pair:
- request a CoW `/quote`
- construct the exact order amounts that CoW expects after fee and slippage handling
- sign the order with the correct chain-specific EIP-712 domain
- submit the signed order to the CoW orderbook
- durably track the resulting order lifecycle and any associated trade or settlement state
- expose the resulting truth to operators without hand-assembled SQL, log scraping, or one-off scripts
## Why this is a meaningful architecture test
The current proven venue path is NEAR Intents, where the hot path is close to immediate quote-response execution.
CoW is different in ways that matter:
- `unrip` acts as a trader submitting intents, not as a solver
- submission returns an order UID, not an immediate final settlement
- orders can remain `Open`, become `Partially-filled`, `Filled`, `Expired`, or `Cancelled`
- the signed order depends on chain-specific domain separation and fee semantics from the CoW orderbook quote
If the repo can integrate this flow without bypassing Kafka, PostgreSQL, and the existing operator surfaces, the architecture is likely good enough for more venue work.
## Hypothesis
`unrip` becomes a more trustworthy multi-venue system if it can integrate CoW Protocol's intent flow as a first-class execution venue while keeping the same core rules:
- Kafka remains the event backbone
- PostgreSQL remains the durable truth store
- operator visibility comes from durable and live sources, not from ad hoc inspection
- venue-specific behavior lives behind explicit adapters instead of leaking through the whole system
The turn passes only if CoW order submission and lifecycle truth become real repository-owned behavior rather than docs, SDK experiments, or local throwaway scripts.
## Scope
- [I019] CoW Protocol intent-based venue integration: quote, sign, submit, and durably track CoW orders through the shared Kafka and PostgreSQL truth pipeline without widening live-funds risk beyond explicit approval.
- One approved CoW-supported chain for the first integration. Initial assumption: Gnosis Chain because the current treasury already reasons about EURe on chain `100`.
- One approved CoW-supported pair for the first integration: `EURe/WBTC` on Gnosis using `EURe` token `0x420CA0f9B9b604cE0fd9C18EF134C705e5Fa3430` and `WBTC` token `0x8e5bBbb09Ed1ebdE8674Cda39A0c169401db4252`.
- One supported signing path for the first pass. Initial assumption: EIP-712 EOA signing. `ERC-1271`, `PreSign`, hooks, and conditional orders are out of scope unless explicitly pulled in during the turn.
- One truthful operator surface for CoW order state, submission failures, and open-order status, implemented through the existing dashboard backend and WebSocket model.
## Assumptions
- CoW orderbook access is available over the documented REST API for the selected chain.
- The implementation will use the documented CoW amount and signing semantics, including chain-specific EIP-712 domain separation against the settlement contract.
- A live CoW quote for `EURe -> WBTC` on Gnosis was verified during planning on 2026-04-07, so pair quoteability is no longer only a planning assumption.
- A dedicated CoW trader identity can be provided during implementation if the user wants a fully real posted order. Without that identity and its approved inventory, the turn can make the quote, signing, persistence, and monitoring paths real but cannot claim a passed live-trading proof.
- Existing NEAR verifier and bridge credit remain the only spendable truth for the already-live BTC/EURe loop. CoW balances are separate and must not be silently merged into the current spendable inventory model.
## Turn-shaping rules
- This is a second-venue proof, not a broad multi-venue router project.
- Integrate CoW as a trader on the intent and orderbook side only. Do not take on solver, autopilot, CoW AMM, JIT order, or watch-tower work in this turn.
- The browser must still talk only to repo-owned backend services. No browser-direct CoW API usage.
- Durable truth must distinguish at least these stages:
- quote request or response
- signed order intent
- orderbook submission acknowledgement
- later order status transitions
- terminal outcome and any trade or settlement linkage
- No live-funds-moving CoW funding, approval, or replenishment path may be added without explicit user approval during implementation.
## Non-goals
- No CoW solver implementation or solver-competition participation.
- No conditional orders, TWAP, hooks, milkman, or other advanced CoW order types.
- No generalized smart order router across NEAR Intents and CoW.
- No automatic cross-chain treasury balancing between the existing NEAR inventory and a CoW wallet.
- No silent expansion of portfolio PnL to include CoW balances before a separate spendable-truth decision.
- No UI-only venue showcase without a real repository-owned quote, sign, submit, and lifecycle path underneath it.
## Required runtime behavior
### Canonical execution path
For one approved chain and pair, `unrip` must be able to:
- construct a real CoW `/quote` request from repo-owned command inputs
- capture the raw quote response durably
- transform the quote response into the exact order amounts that CoW expects for the selected order kind
- compute the correct CoW order digest using the chain-specific EIP-712 domain
- sign the order using the approved signing scheme
- submit the signed order to `POST /api/v1/orders`
- store the returned order UID durably and link it to the canonical command ID
### Lifecycle truth
After submission, the system must durably observe and expose later CoW order states from the orderbook or trade endpoints.
At minimum it must be able to represent and persist:
- `Open`
- `Partially-filled`
- `Filled`
- `Expired`
- `Cancelled`
- submission rejection or later monitoring failure with explicit reason text
It is not sufficient to log the UID and stop.
### Execution model upgrade
The system must stop assuming that every venue command produces one immediate terminal execution result.
This turn must introduce a truthful way to represent:
- submission-time acknowledgement
- non-terminal order states
- terminal order completion or cancellation
- settlement identifiers such as trade IDs or transaction hashes when available
### Inventory and risk boundary
CoW execution must use only explicitly configured CoW wallet state.
Required rules:
- current NEAR spendable inventory truth stays unchanged
- pre-credit observations still do not count as spendable
- CoW wallet balances must be treated as separate venue-local state
- if venue-local funds are not yet approved for live use, the system must say so plainly instead of implying they are active inventory
### Operator surface
Operators must be able to answer:
- is the CoW path configured for the expected chain and wallet
- what was the last CoW quote request and response
- what orders are currently open
- what was the last terminal CoW outcome
- whether the venue path is paused, healthy, or failing
- whether a cancellation was requested and what happened next
Any control shown for CoW must be real and wired, or absent.
## Definition of done
- The finished dashboard turn is archived and the live turn files govern the CoW turn.
- A real CoW venue adapter exists in the repo and uses the documented CoW quote, signing, and orderbook APIs.
- Kafka remains the backbone for CoW quote, order, and lifecycle fan-out.
- PostgreSQL durably stores CoW raw quote data plus order lifecycle truth.
- A canonical command can produce a CoW quote request, signed order, order submission, and durable linked order UID.
- The system observes at least one later order-state transition from the CoW orderbook after submission.
- Operators can inspect current CoW state from the dashboard or equivalent repo-owned backend surface.
- Safe control actions for the CoW path exist where needed, such as refresh or cancel, or are explicitly absent.
- The current NEAR live loop remains armed-state-safe and unchanged in spendable truth.
- Tests cover CoW amount construction, signing-domain selection, lifecycle reduction, and persistence mapping.
For this turn to close with status `passed`, one real CoW order must be submitted from an explicitly approved isolated trader identity and observed through at least one later status transition. If that approval or identity is not provided during implementation, the turn may end `paused` with the remaining blocker named plainly.
## Validation evidence required
- direct evidence of a successful CoW `/quote` response for the selected chain and pair
- automated test evidence that signed amounts match CoW quote semantics for both sell-side or buy-side paths used
- direct evidence that the repo computes the correct EIP-712 digest for the selected chain and settlement contract domain
- direct evidence of order submission acknowledgement and returned order UID
- direct evidence of later order status retrieval from CoW orderbook or trades APIs
- PostgreSQL evidence that the quote, order UID, and later lifecycle state were persisted
- operator-surface evidence that the CoW state is visible without manual one-off inspection
## Failure conditions
- CoW support exists only as SDK experimentation or scripts outside the main services.
- The system special-cases CoW by bypassing Kafka or PostgreSQL.
- The signed order ignores CoW fee semantics and signs the wrong amounts.
- The chain ID or settlement contract domain is wrong, making signatures invalid or unsafe.
- The repo stores only the initial order submission and not the later lifecycle.
- Open CoW exposure is invisible to operators.
- CoW funds are implied to be spendable without explicit wallet and approval boundaries.
- The implementation quietly widens live-funds risk by adding funding, approval, or treasury flows without user approval.
## Current real before this turn
- The BTC/EURe NEAR Intents loop is already proven and archived.
- Pre-credit BTC funding visibility, durable alerts, armed-state persistence, and a real operator dashboard are already proven and archived.
- Kafka and PostgreSQL already serve as the live and durable backbone for market, inventory, decision, and execution truth.
- The current execution model is still biased toward immediate terminal results and does not yet prove a stateful orderbook venue lifecycle.
## Deliberately not built by this proof
- CoW solver participation
- broad multi-venue routing logic
- treasury funding and approval UX for CoW wallets
- fee-complete realized PnL for CoW fills