---
name: cross-chain-twap-execution
description: Use when TWAPing token buys or sells across chains.
created_by: agent
---

> Oracle native tools: `oracle_cli` (read/prepare), `vault_status`, `signer_status`, `signer_execute` (needs human confirmationNonce), `skill_load`. No generic shell. No fleet SSH.


# Cross-chain TWAP execution

Use when DEMI asks to TWAP buy, TWAP sell, ladder in/out, or chunk an order across one or more chains.

## Core rule

"TWAP anything across chains" means **any supported fungible asset with a live quoteable + executable route inside a bounded owner-approved order envelope**. It does **not** mean blind arbitrary-token authority or reusable scanner-wide trading permission.

## Required order envelope

Before live execution, require the exact:

- side: `buy` / `sell`
- token(s): contract + chain, or a precise portfolio slice
- source wallet / signer lane
- total size: raw amount, notional, or % balance
- allowed source/destination chains
- duration and interval/chunk count
- max slippage cap and max price impact
- max gas / bridge fee budget
- min receive / limit-price guard
- deadline
- kill switch / cancel path

`paper` and `prepare` can run without live authority. Live chunks require DEMI confirmation of this exact envelope.

## Per-chunk loop

Each chunk must repeat the full protection stack; do not reuse stale quote data from an earlier chunk.

1. Resolve token + chain identity.
2. Check balance, allowance, native gas, and venue support tier.
3. Quote best route ranked **net of gas and fees**, not gross amount out.
4. Split smaller or skip if price impact/liquidity is outside bounds.
5. Re-quote immediately before prepare.
6. Prepare exact artifact and simulate it when the path supports simulation.
7. Execute only if quote age, min receive, slippage, gas, chain, destination, spender, and deadline still match the envelope.
8. Record tx/order id, receipt status, balance delta, chunk price, cumulative average price, and remaining notional.
9. Stop or pause on drift, failed simulation, missing allowance, missing gas, provider failure, bridge ambiguity, or DEMI cancel.

## Cross-chain chunking

- If funds must bridge before a swap, prove **every leg** quotes executable before firing leg 1.
- Bridge destination native gas when the destination leg needs gas; token-only bridges can leave the executor unable to continue.
- Track pending bridge state. Origin confirmation is not destination arrival.
- Never double-send a pending bridge leg because the next chunk timer fired.
- Multi-hop is allowed only when every hop has fresh quote/prepare support and a bounded failure plan.

## Sell path

Selling is stricter than buying because unsupported exits strand risk.

- Run sellability / sell-sim first for illiquid, honeypot-prone, custom-router, or custom-pool tokens.
- Unsupported exits are `blocked`, not guessed or routed through an unverified contract.
- Custom pools may need a separate raw-pair or venue-native adapter; do not pretend a generic aggregator failure is a working sell route.

## Asset boundaries

This skill covers fungible token swaps/bridges. Do not reuse the same engine unchanged for:

- NFTs / marketplace laddering
- Bitcoin UTXOs, inscriptions, runes, rare sats
- Solana/Jupiter transactions
- Hyperliquid orders

Those lanes can share the chunking concept but need their own signer, settlement, receipt, and asset-safety rules.

## Reporting

For every run or prepared schedule, report:

- mode: `paper`, `prepare`, or `live`
- envelope summary
- chunks completed / pending / skipped / failed
- realized average price and cumulative balance delta
- hashes / order ids for completed chunks
- current blocker or next scheduled chunk
- confidence: high / moderate / low / unknown

## Pitfalls

- Treating a broad phrase like "anything" as reusable authority. It is a routing universe, not a signing grant.
- Computing a TWAP schedule once and reusing stale quotes for every chunk.
- Firing bridge leg 1 before proving leg 2 is executable.
- Forgetting destination native gas after a token bridge.
- Letting a timer continue after a failed chunk without checking why it failed.
- Reporting a prepared chunk as executed. Prepared != signed != broadcast != filled.
- Applying EVM fungible assumptions to NFTs, BTC inscriptions/runes, Solana, or venue orderbooks.

## Related skills

- `oracle-best-execution` — route ranking net of gas and fees. **Same-chain over-time swaps use Li.Fi directly** (`https://li.quest/v1/quote`, keyless, returns `transactionRequest` with calldata), not the public server's risk pipeline (which requires on-chain data probes — sellability/approval/liquidity — unsuitable for aggregator quotes). Cross-chain still uses `/public/convert`.
- `multichain-exec-desk` — Oracle desk execution surfaces and provider guardrails.
- `trade-loop-circuit-breaker` — live-money loop halts, caps, and deploy discipline.
- `oracle-action-semantics` — watch / prepare / arm / sign / send vocabulary.

## Oracle App over-time (primary surface)

The live implementation ships in `~/projects/oracle-app/` with a full engine, durable store, background worker, and API routes. See `references/oracle-app-over-time.md` for architecture, endpoints, env vars, and desk API contract.

Quick dev loop:
```bash
# Terminal 1: desk server (required for live quotes)
cd ~/projects/multiagent-desk && node bin/oracle-public-server.mjs

# Terminal 2: Oracle app dev server
cd ~/projects/oracle-app && ORACLE_DESK_URL=http://127.0.0.1:8799 npm run dev

# Test paper mode end-to-end:
curl -X POST http://localhost:3000/api/oracle/over-time \
  -H 'Content-Type: application/json' \
  -d '{"side":"buy","mode":"paper","ownerAddress":"0x1111111111111111111111111111111111111111","chainId":"base","sellSymbol":"USDC","buySymbol":"ETH","totalAmount":"100","durationMs":120000,"chunkCount":4}'

# Check activity + receipts:
curl http://localhost:3000/api/oracle/over-time/activity?owner=0x1111111111111111111111111111111111111111
```
