Skip to content

feat: add bitflow-limit-order (BFF Skills Comp Day 18 winner by @ClankOS)#329

Merged
biwasxyz merged 2 commits intoaibtcdev:mainfrom
diegomey:bff-comp/bitflow-limit-order
Apr 21, 2026
Merged

feat: add bitflow-limit-order (BFF Skills Comp Day 18 winner by @ClankOS)#329
biwasxyz merged 2 commits intoaibtcdev:mainfrom
diegomey:bff-comp/bitflow-limit-order

Conversation

@diegomey
Copy link
Copy Markdown
Contributor

bitflow-limit-order

Author: @ClankOS (Grim Seraph)
Competition PR: BitflowFinance/bff-skills#277
PR Title: [AIBTC Skills Comp Day 19] bitflow-limit-order — Agent-Powered Limit Orders on Bitflow


This skill was submitted to the AIBTC x Bitflow Skills Pay the Bills competition, reviewed by judging agents and the human panel, and approved as a Day 18 winner.

Frontmatter has been converted to the aibtcdev/skills metadata: convention. Command paths updated to match this repo root-level skill layout.

Files

  • bitflow-limit-order/SKILL.md — Skill definition with AIBTC-format frontmatter
  • bitflow-limit-order/AGENT.md — Agent behavior rules and guardrails
  • bitflow-limit-order/bitflow-limit-order.ts — TypeScript implementation

Attribution

Original author: @ClankOS. The metadata.author field in SKILL.md preserves their attribution permanently.


Automated by BFF Skills Bot on merge of PR #277.

Copy link
Copy Markdown
Contributor

@arc0btc arc0btc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed as Arc (arc0.btc) — operational context from running Bitflow integrations 24/7.

Verdict: Approve

The agent-as-order-engine pattern is the right approach for a DEX with no native limit orders. HODLMM active bin as oracle is clever — on-chain, no external feed dependency.

What's good:

  • Anti-wick guard (--confirm-ticks N) — essential on thin L2 liquidity. Prevents getting filled on a 1-block spike at 3am
  • --confirm required for all writes — correct safety gate
  • Hardcoded spend caps (2000 STX / 0.005 sBTC, max 10 active orders) — good floor
  • Event log at events.jsonl with rotation — strong auditability
  • JSONL output in watch mode (one valid JSON object per line) — parseable by downstream tools

[suggestion] No file locking on orders.json:
If run is called by two processes simultaneously (heartbeat overlap), both read the same stale file and one's write will overwrite the other's fill. Standard atomic write pattern:

const tmpPath = ordersPath + ".tmp";
writeFileSync(tmpPath, JSON.stringify(orders, null, 2));
renameSync(tmpPath, ordersPath); // atomic on POSIX

Bun's Bun.write() doesn't do atomic rename — renameSync from "fs" is needed here. Low probability of concurrent invocation in most agent setups, but worth hardening.

[nit] Balance check on sBTC orders:
The requires-funds tag is correct. Docs mention "verify STX-for-fee on sBTC orders" — make sure the balance check accounts for the STX fee reserve when validating sBTC sell orders (not just sBTC balance).

No blocking issues.

@biwasxyz biwasxyz force-pushed the bff-comp/bitflow-limit-order branch from 7123fe5 to ffa9bc7 Compare April 21, 2026 16:31
Copy link
Copy Markdown
Contributor

@biwasxyz biwasxyz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed and ready to merge.

Changes:

  • Adds bitflow-limit-order skill (BFF Skills Comp Day 18 winner by @ClankOS) — agent-powered limit orders with set/list/cancel/run subcommands and --watch mode
  • Fixes pre-existing main CI failures

Review highlights:

  • ✅ Orders persisted at ~/.aibtc/limit-orders/orders.json with JSONL audit log (auto-rotates at 10MB); survives process restart
  • ✅ Hard safety limits: MAX_ORDER_STX=2000, MAX_SBTC=0.005, MAX_ACTIVE=10, MAX_SLIPPAGE=5%, expires 1m–7d
  • --confirm required for on-chain execution; --confirm-ticks N anti-wick guard (default 2)
  • ✅ Watch loop handles SIGINT/SIGTERM cleanly with chunked sleep
  • ✅ Uses AIBTC keystore (scrypt + AES-256-GCM) or STACKS_PRIVATE_KEY env — no hardcoded secrets
  • ✅ On-chain price oracle (Bitflow active-bin API) — no external oracle dependency
  • Nits (non-blocking): no file-locking on orders.json (low risk, heartbeat-driven); anti-wick counter is per-process (documented in AGENT.md)

Verdict: MERGE-READY

@biwasxyz biwasxyz force-pushed the bff-comp/bitflow-limit-order branch from ffa9bc7 to a2a37b3 Compare April 21, 2026 16:53
ClankOS and others added 2 commits April 21, 2026 22:39
Submitted by @ClankOS (Grim Seraph) via the AIBTC x Bitflow Skills Pay the Bills competition.

Competition PR: BitflowFinance/bff-skills#277
- contract-preflight: replace invalid tags with controlled vocabulary, drop unknown "network" dependency
- stacking-delegation: user-invocable false, add missing AGENT.md frontmatter
- regenerate skills.json

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@biwasxyz biwasxyz force-pushed the bff-comp/bitflow-limit-order branch from a2a37b3 to 2c737a7 Compare April 21, 2026 16:54
@biwasxyz biwasxyz merged commit 8aa5d3f into aibtcdev:main Apr 21, 2026
2 checks passed
@macbotmini-eng
Copy link
Copy Markdown

Note

Thread map — posted 2026-04-22. Skill-specific follow-up for aibtcdev/skills#329. Sits alongside the parallel upstream follow-ups on aibtcdev/skills#326 (hodlmm-arb-executor), aibtcdev/skills#328 (hodlmm-flow — your Day-19 sibling), and aibtcdev/skills#339 (stacks-alpha-engine). Release-pipeline context for all four Day-winners in the skills-v0.41.0 window is consolidated in the aibtcdev/skills#345 release-please advisory. Staging-origin trophy on BitflowFinance/bff-skills#277. Follow-up patch PR lands upstream via a direct PR against aibtcdev/skills:main — matches the established pattern on Day 8 zest-auto-repay (aibtcdev/skills#287→#320), Day 12 hodlmm-range-keeper (aibtcdev/skills#307→#308), and Day 14 hodlmm-move-liquidity (aibtcdev/skills#317).

Hi @ClankOS — thanks for the bitflow-limit-order submission and for the under-4-hour turnaround on the staging-round review cycle at bff-skills#277 where all 4 @arc0btc review items landed in commit 2eed33d4 plus 3 unrequested upgrades (watch loop, anti-wick guard, JSONL event log). That pattern matters here — this follow-up has more findings than the staging round did, but your responsiveness baseline is already demonstrated.

cc @TheBigMacBTC @diegomey @biwasxyz @arc0btc @aibtcdev @macbotmini-eng — on-thread for decision-chain visibility.


Post-merge status

This PR was merged on 2026-04-21 by @biwasxyz. The merge-time CI-fix commit 2c737a74 touched only skills.json (+29/-1) plus metadata on unrelated skills (contract-preflight, stacking-delegation); bitflow-limit-order.ts on aibtcdev/skills:main matches your submission byte-for-byte.

Second-pass review carries forward the three upstream review items raised pre-merge (not yet addressed on main) and surfaces additional post-merge audit findings. A single follow-up patch PR closes all of them.

Corrections (please land these before payment)

  • (a) bitflow-limit-order/SKILL.md line 35 — factually inaccurate market claim. The line reads "Zero limit order support exists on Bitflow — no native UI, no Keeper contracts, no competing skills." Three parts are contradicted in the same registry: the bitflow skill ships get-keeper-contract, create-order, get-order, cancel-order, and get-keeper-user at bitflow.ts lines 1034-1247; the dca skill ships scheduled direct-swap execution; and a live Bitflow Keeper contract has executed 18,716+ mainnet transactions at sender SP3R9DNHRSBPT42JX98J92ZJHASWSBXT5ZW8X4XCK. Please rewrite the scope framing so it aligns with the existing registry + protocol surface.

  • (b) HODLMM trigger→swap atomic claim vs actual execution path. SKILL.md line 20 frames the skill as executing HODLMM trigger → HODLMM-atomic swap, but the code only reads HODLMM active-bin state for the trigger and emits XYK via the SDK router. executeSwap at lines 366-427 drops order.poolId at lines 917-921, passes only token symbols to sdk.getQuoteForRoute at lines 378-380, and hands opaque swapParams to makeContractCall at lines 409-420. A grep for bin-swap | dlmm-pool-v | dlmm-liquidity-router in the execution path returns zero matches. The single submitted demo transaction 0x6fbd3b23… routed xyk-swap-helper-v-1-3.swap-helper-a (XYK path). The SDK router returns XYK, Stableswap, or cross-DEX routes — not DLMM routes. The registered wallet SP1KVZTZCTCN9TNA1H5MHQ3H0225JGN1RJHY4HA9W has no DLMM/HODLMM/Keeper contract sender transactions in its 85-tx on-chain record. Please either (i) re-document the trigger-vs-execution relationship so the "atomic" claim matches the emission path, or (ii) route execution through SP1PFR4V08H1RAZXREBGFFQ59WB739XM8VVGTFSEA.dlmm-core-v-1-1's swap-x-for-y / swap-y-for-x entrypoints with explicit bin-id if atomic HODLMM is the intended behavior.

  • (c) bitflow-limit-order.ts line 44 — hardcoded const TX_FEE_ESTIMATE = 5000; // microSTX, used at line 419 fee: BigInt(TX_FEE_ESTIMATE) passed into makeContractCall. The observed Bitflow prod-keeper wallet SP3R9DN…4XCK uses fee_rate: "100000" μSTX uniformly across a sampled window of mainnet transactions — 20× above the skill's hardcoded floor. Under fee-pressure conditions, orders broadcast at 5,000 μSTX will queue or stall. Suggested: replace with live-resolved fee via resolveFee (the canonical bitflow skill uses this pattern via src/lib/utils/fee.js), or at minimum raise the floor to match observed keeper baseline.

  • (d) Balance-check silent bypass for non-STX/non-sBTC tokenIn. SKILL.md line 161 states "Balance check: Always enforced", but in the code path isStxToken(tokenIn) and isSbtcToken(tokenIn) use substring matching and the try/catch balance-check block is structurally guarded by if (isStxToken) ... else if (isSbtcToken) .... Any tokenIn that is neither STX nor sBTC falls through both branches — no throw, no skip, no error — and the swap broadcasts with no balance guard. Claim-vs-behavior mismatch. Either throw on unsupported tokens or extend the balance-check branch to cover the full tokenIn catalog documented in MAX_ORDER_* caps.

  • (e) Non-atomic saveOrderBook + silent reset on parse error. [@arc0btc surfaced this on #329 at 2026-04-16T01:15:50Z](https://github.com/aibtcdev/skills/pull/329#issuecomment-4241267135) with a 5-line atomic-write proposal; 5 days 15 hours elapsed between the comment and merge with zero commits to bitflow-limit-order.ts on this path. Independently verified in the second-pass audit: a crash mid-write silently zeroes all active orders on next read (loadOrderBook` returns an empty book on parse error with only a stderr warning). Please apply @arc0btc's proposed atomic-write pattern.

  • (f) Pair-string asymmetry between findPool and runCycle. findPool accepts STX_sBTC / whitespace-separated forms; runCycle.split("-") requires literal -. Orders created against the accepted forms silently fail at execute with an unrecoverable error state. Normalize the pair-string handling across both call sites so accepted shapes at creation match the shapes parsed at execution.

Already-noted follow-ups from @arc0btc + @biwasxyz upstream review (carrying forward)

  • (g) @arc0btc R6 on aibtcdev/skills#329 — sBTC fee-handling nuance on the STX-fee path for sBTC-side orders.
  • (h) @biwasxyz merge-body review nits — items explicitly labeled "non-blocking follow-ups" at merge time that didn't have a pre-merge window to land. Please enumerate from the aibtcdev/skills#329 merge review and address in the same patch PR.
  • (i) Error-class bucketing in executeSwap. Post-condition-deny (slippage protection firing AS DESIGNED) flips orders to terminal error state identically to nonce race and broadcast-500. Slippage-triggered aborts should be retryable, not terminal.

Important

Payment remains on hold until items (a) through (f) land. Items (g), (h), and (i) are welcome in the same follow-up patch PR but not payment-blocking.

@ClankOS — open a follow-up patch PR from your fork directly against aibtcdev/skills:main carrying (a)-(f), optionally (g)-(i). A mirror patch against the BitflowFinance/bff-skills main branch brings the staging copy under skills/bitflow-limit-order/ into alignment and can land separately. Your staging-round commit 2eed33d4 addressing 4 items + 3 bonus upgrades in one pass is exactly the shape this follows.

@arc0btc — please validate or invalidate [the six corrections above (a)-(f) and the three carry-forward items (g)-(i)] + [TheBigMac's decision to hold payment pending (a)-(f)]. Thank you.

@TheBigMacBTC
Copy link
Copy Markdown

TheBigMacBTC commented Apr 23, 2026

@ClankOS — friendly bump on bitflow-limit-order.

Our HOLD advisory at #issuecomment-4293393204 (2026-04-22T03:54Z) flagged 9 payment-blocking items across the merged code. It's been ~58 hours with no fix-up PR opened against aibtcdev/skills:main. Day 18 prize remains on hold per feedback_payment_gates_on_all_fixes_merged — payment releases when the fix-up merges with the items addressed.

Staging mirror at BitflowFinance/bff-skills#277 still carries Winner-Pending-Fixes label consistent with the hold posture.

No pressure on timing; closing the loop on visibility. Your sibling skill hodlmm-flow#328 has a parallel bump going out — both are queued on your side, we assume. When ready to iterate, the 9-item action list + evidence is all at the advisory above.

Companion release PR aibtcdev/skills#345 is bundling four Day-winners into v0.41.0; #329 shipping with its current main state would tag 9 known findings live. We'd prefer to ship with fixes landed. The official release-blocker tracking issue aibtcdev/skills#348 from @whoabuddy explicitly aggregates all 4 bundled skills; #329 is on that list. (amended 2026-04-23T17:10Z — #348 ref added)

Ping here or open the fix-up PR when ready.

cc @diegomey @biwasxyz @arc0btc @macbotmini-eng — for visibility.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants