diff --git a/ROADMAP.md b/ROADMAP.md index 74277d0..0c8b9e9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,7 +16,7 @@ | D. Design & docs | Nov 4 | 100% | ✅ done | | 0. Setup & verification | Nov 4–5 | 80% | in progress (K0.9 blocked on K0.8; K0.8, K0.14 👤) | | 1. Contracts | Nov 5–7 | 92% | in progress (K1.13 deploy is 👤) | -| 2. Core logic (`lib/core`) | Nov 6–7 | 0% | in progress (drafted) | +| 2. Core logic (`lib/core`) | Nov 6–7 | 100% | ✅ done | | 3. Integrations (1Click, NEAR, DB) | Nov 7–8 | 0% | in progress (schema drafted) | | 4. API routes | Nov 8–9 | 0% | not started | | 5. Worker (scheduler) | Nov 9–10 | 0% | not started | @@ -27,7 +27,7 @@ | 10. README & public repo | Nov 12–13 | 14% | in progress | | 11. Launch: video, post, submission | Nov 13–14 | 0% | not started | | 12. After submission | Nov 14–25 | 0% | not started | -| **Overall (MVP)** | | **~20%** | | +| **Overall (MVP)** | | **~27%** | | Phase % = done tasks ÷ non-dropped tasks in that phase. Overall = average of all 14 rows (D + phases 0–12). (Earlier entries over-estimated the overall %; recalculated 2026-11-04.) @@ -101,12 +101,12 @@ Format: `- [task id] what blocks it · who can unblock · since date` ## Phase 2 — Core logic `lib/core` (Nov 6–7) -- [ ] **K2.1** [#33](https://github.com/MFrancis-dev/stack/issues/33) `money.ts` · tests -- [ ] **K2.2** [#34](https://github.com/MFrancis-dev/stack/issues/34) `cost.ts`: `cost_bps` from quote USD values · tests -- [ ] **K2.3** [#35](https://github.com/MFrancis-dev/stack/issues/35) `planMatch.ts`: quote recipient/asset/amount vs `get_state()` · tests incl. mismatches -- [~] **K2.4** [#36](https://github.com/MFrancis-dev/stack/issues/36) (2026-11-04: unions + both mappings written) `status.ts`: funding + buy unions and mapping · tests for every status -- [ ] **K2.5** [#37](https://github.com/MFrancis-dev/stack/issues/37) `address.ts`: validators for BTC, ETH (per chain), NEAR · tests -- [~] **K2.6** [#38](https://github.com/MFrancis-dev/stack/issues/38) (2026-11-04: interfaces + schemas drafted) `adapters.ts` interfaces (`QuoteProvider`, `StatusProvider`, `VaultClient`), `schemas.ts` +- [x] **K2.1** [#33](https://github.com/MFrancis-dev/stack/issues/33) `money.ts` · tests · 2026-11-04: bigint `toBaseUnits`/`formatAmount`/`parseScaled`, tests incl. 0, 1 unit, > 2^64 +- [x] **K2.2** [#34](https://github.com/MFrancis-dev/stack/issues/34) `cost.ts`: `cost_bps` from quote USD values · tests · 2026-11-04: `costBps` (rounded up, null when unknown) + `checkCost`, tested with real quote numbers +- [x] **K2.3** [#35](https://github.com/MFrancis-dev/stack/issues/35) `planMatch.ts`: quote recipient/asset/amount vs `get_state()` · tests incl. mismatches · 2026-11-04: `quoteMatchesPlan` checks paused/plan, dry, deposit address, origin USDC, asset, recipient, refundTo = vault, amount ≤ per-run +- [x] **K2.4** [#36](https://github.com/MFrancis-dev/stack/issues/36) (2026-11-04: unions + both mappings written) `status.ts`: funding + buy unions and mapping · tests for every status · 2026-11-04: unions + both mappings, tested against the 7-value SDK enum +- [x] **K2.5** [#37](https://github.com/MFrancis-dev/stack/issues/37) `address.ts`: validators for BTC, ETH (per chain), NEAR · tests · 2026-11-04: checksummed: BTC bech32/bech32m + base58check, EVM EIP-55, NEAR named/implicit (BIP-173/350, EIP-55 vectors); adds `@noble/hashes` 2.2.0 + `@scure/base` 2.4.0 +- [x] **K2.6** [#38](https://github.com/MFrancis-dev/stack/issues/38) (2026-11-04: interfaces + schemas drafted) `adapters.ts` interfaces (`QuoteProvider`, `StatusProvider`, `VaultClient`), `schemas.ts` · 2026-11-04: adapters (QuoteSummary echoes originAsset/refundTo), schemas (plan form: address twice + checksum + on-chain limits), `assets.ts` with KD-6 ids ## Phase 3 — Integrations (Nov 7–8) @@ -214,6 +214,7 @@ Format: `- [task id] what blocks it · who can unblock · since date` ## Update log One line per contribution, newest first: `YYYY-MM-DD · who/agent · what changed · tasks` +- 2026-11-04 · agent · Phase 2 core logic: money, cost, planMatch, address (checksums), assets, schemas; 33 TS tests · K2.1–K2.6 - 2026-11-04 · agent · Rewrote `main` history (approved force-push) to drop tool attribution lines from commit messages; every commit's files unchanged · — - 2026-11-04 · agent · Phase 1 contracts: vault + factory implemented, mock-ft crate, 49 contract tests passing (unit + near-workspaces sandbox); wasm vault 137 KB / factory 146 KB · K1.1–K1.10, K1.12 - 2026-11-04 · agent · Decisions accepted by the human: KD-5 no upgrades, KD-6 BTC/ETH/NEAR, KD-7 name Stack, KD-8 regular deploy; K1.11 dropped; update-log actor made neutral · K0.1, K0.10, K1.11 diff --git a/lib/core/address.test.ts b/lib/core/address.test.ts index a36253d..40c8a1a 100644 --- a/lib/core/address.test.ts +++ b/lib/core/address.test.ts @@ -1,6 +1,43 @@ -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { isValidAddress, isValidBtcAddress, isValidEvmAddress, isValidNearAccount } from "./address"; -// Roadmap: K2.5 +// Roadmap: K2.5 · vectors from BIP-173, BIP-350 and EIP-55 describe("address", () => { - it.todo("validates BTC, ETH and NEAR addresses"); + it("accepts valid BTC addresses", () => { + expect(isValidBtcAddress("BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4")).toBe(true); + expect(isValidBtcAddress("bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3")).toBe(true); + expect(isValidBtcAddress("bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0")).toBe(true); + expect(isValidBtcAddress("bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq")).toBe(true); + expect(isValidBtcAddress("1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2")).toBe(true); + expect(isValidBtcAddress("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy")).toBe(true); + }); + + it("rejects BTC typos and wrong encodings", () => { + expect(isValidBtcAddress("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5")).toBe(false); // bad checksum + expect(isValidBtcAddress("bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqh2y7hd")).toBe(false); // v1 with bech32 + expect(isValidBtcAddress("1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN3")).toBe(false); + expect(isValidBtcAddress("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx")).toBe(false); // other network prefix + expect(isValidBtcAddress("bc1QW508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4")).toBe(false); // mixed case + }); + + it("checks EIP-55 only when the address is mixed-case", () => { + expect(isValidEvmAddress("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed")).toBe(true); + expect(isValidEvmAddress("0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed")).toBe(true); + expect(isValidEvmAddress("0x5aAeb6053f3E94C9b9A09f33669435E7Ef1BeAed")).toBe(false); + expect(isValidEvmAddress("0x5aaeb6053f3e94c9b9a09f33669435e7ef1bea")).toBe(false); + }); + + it("validates NEAR accounts", () => { + expect(isValidNearAccount("alice.near")).toBe(true); + expect(isValidNearAccount("a1-b_2.stack.near")).toBe(true); + expect(isValidNearAccount("0".repeat(63) + "a")).toBe(true); + expect(isValidNearAccount("Alice.near")).toBe(false); + expect(isValidNearAccount("alice..near")).toBe(false); + expect(isValidNearAccount("a")).toBe(false); + }); + + it("dispatches by chain", () => { + expect(isValidAddress("btc", "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2")).toBe(true); + expect(isValidAddress("eth", "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2")).toBe(false); + }); }); diff --git a/lib/core/address.ts b/lib/core/address.ts index 1ee34b0..5f05a6e 100644 --- a/lib/core/address.ts +++ b/lib/core/address.ts @@ -1,7 +1,80 @@ /** - * Address validation for BTC, ETH (per chain) and NEAR destinations. - * Roadmap: K2.5 · Spec: ARCHITECTURE.md §11 - * Status: scaffold — not implemented yet. + * Address validation with real checksums, so a typo can't send savings to the wrong place (K-E10). + * BTC: bech32 (v0) / bech32m (v1+) and base58check (P2PKH, P2SH). EVM: EIP-55 when mixed-case. + * NEAR: named and implicit accounts. Roadmap: K2.5 */ -export {}; +import { sha256 } from "@noble/hashes/sha2.js"; +import { keccak_256 } from "@noble/hashes/sha3.js"; +import { bech32, bech32m, createBase58check } from "@scure/base"; + +export type AddressChain = "btc" | "eth" | "near"; + +const base58check = createBase58check(sha256); + +export function isValidBtcAddress(address: string): boolean { + const a = address.trim(); + if (/^bc1/i.test(a)) { + if (a !== a.toLowerCase() && a !== a.toUpperCase()) return false; + const lower = a.toLowerCase(); + for (const coder of [bech32, bech32m]) { + try { + const { prefix, words } = coder.decode(lower as `${string}1${string}`); + if (prefix !== "bc" || words.length === 0) continue; + const version = words[0]!; + const program = coder.fromWords(words.slice(1)); + // BIP-350: v0 uses bech32, v1+ uses bech32m. + if (version === 0 && coder === bech32 && (program.length === 20 || program.length === 32)) return true; + if (version >= 1 && version <= 16 && coder === bech32m && program.length >= 2 && program.length <= 40) return true; + } catch { + /* try the other encoding */ + } + } + return false; + } + if (/^[13]/.test(a)) { + try { + const payload = base58check.decode(a); + return payload.length === 21 && (payload[0] === 0x00 || payload[0] === 0x05); + } catch { + return false; + } + } + return false; +} + +export function isValidEvmAddress(address: string): boolean { + const a = address.trim(); + if (!/^0x[0-9a-fA-F]{40}$/.test(a)) return false; + const hex = a.slice(2); + if (hex === hex.toLowerCase() || hex === hex.toUpperCase()) return true; + const hash = keccak_256(new TextEncoder().encode(hex.toLowerCase())); + for (let i = 0; i < 40; i++) { + const nibble = (hash[i >> 1]! >> (i % 2 === 0 ? 4 : 0)) & 0xf; + const ch = hex[i]!; + if (/[a-f]/.test(ch) && nibble >= 8) return false; + if (/[A-F]/.test(ch) && nibble < 8) return false; + } + return true; +} + +const NEAR_NAMED = /^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/; + +export function isValidNearAccount(account: string): boolean { + const a = account.trim(); + if (a.length < 2 || a.length > 64) return false; + if (/^[0-9a-f]{64}$/.test(a)) return true; // implicit + if (/^0x[0-9a-f]{40}$/.test(a)) return true; // eth-implicit + return NEAR_NAMED.test(a); +} + +export function isValidAddress(chain: AddressChain, address: string): boolean { + switch (chain) { + case "btc": + return isValidBtcAddress(address); + case "eth": + return isValidEvmAddress(address); + case "near": + return isValidNearAccount(address); + } +} diff --git a/lib/core/assets.ts b/lib/core/assets.ts new file mode 100644 index 0000000..cb164ea --- /dev/null +++ b/lib/core/assets.ts @@ -0,0 +1,58 @@ +/** + * Assets Stack works with (decision KD-6). Ids verified against live /v0/tokens on 2026-11-04 + * (ARCHITECTURE.md §12). Always match on assetId — symbols repeat across chains. + * Roadmap: K2.x + */ + +import type { AssetId } from "./types"; + +export const USDC_ON_NEAR: AssetId = "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1"; +export const USDC_DECIMALS = 6; + +export type TargetKey = "btc" | "eth" | "near"; + +export interface TargetAsset { + key: TargetKey; + assetId: AssetId; + symbol: string; + /** Chain the asset is delivered on; selects the address validator. */ + chain: "btc" | "eth" | "near"; + chainName: string; + decimals: number; + /** Below this, fees dominate (BTC $10 ≈ 15% cost). Used as a UI suggestion, not a rule. */ + suggestedMinPerRunUsd: number; +} + +export const TARGET_ASSETS: Record = { + btc: { + key: "btc", + assetId: "nep141:btc.omft.near", + symbol: "BTC", + chain: "btc", + chainName: "Bitcoin", + decimals: 8, + suggestedMinPerRunUsd: 100, + }, + eth: { + key: "eth", + assetId: "nep141:eth.omft.near", + symbol: "ETH", + chain: "eth", + chainName: "Ethereum", + decimals: 18, + suggestedMinPerRunUsd: 20, + }, + near: { + key: "near", + assetId: "nep141:wrap.near", + symbol: "NEAR", + chain: "near", + chainName: "NEAR", + decimals: 24, + suggestedMinPerRunUsd: 10, + }, +}; + +export function targetByAssetId(assetId: AssetId): TargetAsset | undefined { + return Object.values(TARGET_ASSETS).find((t) => t.assetId === assetId); +} diff --git a/lib/core/cost.test.ts b/lib/core/cost.test.ts index 9457faf..648eb5a 100644 --- a/lib/core/cost.test.ts +++ b/lib/core/cost.test.ts @@ -1,7 +1,28 @@ -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { checkCost, costBps } from "./cost"; -// Roadmap: K2.2 +// Roadmap: K2.2 · numbers from real dry quotes on 2026-11-04 (ARCHITECTURE §12) describe("cost", () => { - it.todo("computes bps from USD values"); - it.todo("treats missing USD values as unknown, not zero"); + it("computes bps from USD values, rounding up", () => { + // $100 USDC → BTC + expect(costBps({ amountInUsd: "99.962900000000", amountOutUsd: "98.358361500000" })).toBe(161); + // $10 USDC → BTC is mostly fees + expect(costBps({ amountInUsd: "9.996", amountOutUsd: "8.454" })).toBe(1543); + }); + + it("treats missing or broken USD values as unknown, not zero", () => { + expect(costBps({ amountInUsd: null, amountOutUsd: "1" })).toBeNull(); + expect(costBps({ amountInUsd: "0", amountOutUsd: "0" })).toBeNull(); + expect(costBps({ amountInUsd: "abc", amountOutUsd: "1" })).toBeNull(); + }); + + it("never reports negative cost", () => { + expect(costBps({ amountInUsd: "10", amountOutUsd: "10.5" })).toBe(0); + }); + + it("checks against the plan limit", () => { + expect(checkCost({ amountInUsd: "100", amountOutUsd: "99" }, 300)).toEqual({ ok: true, costBps: 100 }); + expect(checkCost({ amountInUsd: "10", amountOutUsd: "8.454" }, 300)).toEqual({ ok: false, costBps: 1546, reason: "over_limit" }); + expect(checkCost({ amountInUsd: null, amountOutUsd: null }, 300)).toEqual({ ok: false, costBps: null, reason: "unknown_cost" }); + }); }); diff --git a/lib/core/cost.ts b/lib/core/cost.ts index ebdd161..c81f95a 100644 --- a/lib/core/cost.ts +++ b/lib/core/cost.ts @@ -1,11 +1,36 @@ /** - * cost_bps = (1 − outUsd/inUsd) × 10_000 from a quote's own USD values. - * Roadmap: K2.2 · Spec: ARCHITECTURE.md §4.2 - * Status: scaffold — not implemented yet. + * Cost of a quote in basis points: (1 − outUsd/inUsd) × 10_000, from the quote's own USD values. + * Covers slippage, solver spread and payout network fees (ARCHITECTURE.md §4.2). + * Roadmap: K2.2 */ +import { parseScaled } from "./money"; import type { QuoteSummary } from "./types"; -export function costBps(_quote: QuoteSummary): number { - throw new Error("Not implemented (K2.2)"); +const SCALE = 12; + +/** Rounded up (conservative). null when the quote has no usable USD values — treat as unknown, never as free. */ +export function costBps(quote: Pick): number | null { + if (!quote.amountInUsd || !quote.amountOutUsd) return null; + let inUsd: bigint; + let outUsd: bigint; + try { + inUsd = parseScaled(quote.amountInUsd, SCALE); + outUsd = parseScaled(quote.amountOutUsd, SCALE); + } catch { + return null; + } + if (inUsd <= 0n) return null; + if (outUsd >= inUsd) return 0; + const lost = (inUsd - outUsd) * 10_000n; + return Number((lost + inUsd - 1n) / inUsd); +} + +export type CostVerdict = { ok: true; costBps: number } | { ok: false; costBps: number | null; reason: "unknown_cost" | "over_limit" }; + +export function checkCost(quote: Pick, maxCostBps: number): CostVerdict { + const bps = costBps(quote); + if (bps === null) return { ok: false, costBps: null, reason: "unknown_cost" }; + if (bps > maxCostBps) return { ok: false, costBps: bps, reason: "over_limit" }; + return { ok: true, costBps: bps }; } diff --git a/lib/core/index.ts b/lib/core/index.ts index d65e145..3bd0c9c 100644 --- a/lib/core/index.ts +++ b/lib/core/index.ts @@ -1,3 +1,8 @@ export * from "./types"; export * from "./status"; export * from "./adapters"; +export * from "./assets"; +export * from "./money"; +export * from "./cost"; +export * from "./planMatch"; +export * from "./address"; diff --git a/lib/core/money.test.ts b/lib/core/money.test.ts index 5493a01..eb27da1 100644 --- a/lib/core/money.test.ts +++ b/lib/core/money.test.ts @@ -1,7 +1,39 @@ -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { asBaseUnits, formatAmount, minUnits, parseScaled, toBaseUnits } from "./money"; // Roadmap: K2.1 describe("money", () => { - it.todo("converts display amounts for 6 and 18 decimals"); - it.todo("handles 0 and 1 base unit"); + it("converts display amounts to base units for 6 and 24 decimals", () => { + expect(toBaseUnits("12.5", 6)).toBe("12500000"); + expect(toBaseUnits("0.000001", 6)).toBe("1"); + expect(toBaseUnits("100", 6)).toBe("100000000"); + expect(toBaseUnits("1", 24)).toBe("1000000000000000000000000"); + }); + + it("rejects too many decimals, negatives and junk", () => { + expect(() => toBaseUnits("1.0000001", 6)).toThrow(); + expect(() => toBaseUnits("-1", 6)).toThrow(); + expect(() => toBaseUnits("1e6", 6)).toThrow(); + expect(() => asBaseUnits("1.5")).toThrow(); + }); + + it("formats base units without float error", () => { + expect(formatAmount("12500000", 6)).toBe("12.5"); + expect(formatAmount("1", 24)).toBe("0.000000000000000000000001"); + expect(formatAmount("100000000", 6)).toBe("100"); + expect(formatAmount("123456789", 6, 2)).toBe("123.45"); + }); + + it("handles 0 and values beyond 2^64", () => { + expect(formatAmount("0", 6)).toBe("0"); + const big = (2n ** 128n).toString(); + expect(asBaseUnits(big)).toBe(big); + expect(toBaseUnits(formatAmount(big, 6), 6)).toBe(big); + }); + + it("parses scaled decimals and picks the smaller amount", () => { + expect(parseScaled("99.9629", 4)).toBe(999629n); + expect(parseScaled("1.123456789", 3)).toBe(1123n); + expect(minUnits(asBaseUnits("5"), asBaseUnits("7"))).toBe("5"); + }); }); diff --git a/lib/core/money.ts b/lib/core/money.ts index 89a65ba..6104e45 100644 --- a/lib/core/money.ts +++ b/lib/core/money.ts @@ -1,15 +1,48 @@ /** - * Base-unit conversion and formatting. bigint only — never floats. + * Base-unit conversion, formatting and decimal parsing. bigint only — never floats. * Roadmap: K2.1 · Spec: AGENTS.md §6 - * Status: scaffold — not implemented yet. */ import type { BaseUnits } from "./types"; -export function toBaseUnits(_display: string, _decimals: number): BaseUnits { - throw new Error("Not implemented (K2.1)"); +const DIGITS = /^\d+$/; +const DECIMAL = /^(\d+)(?:\.(\d+))?$/; + +/** Validates and brands an integer string (or bigint) as base units. */ +export function asBaseUnits(value: string | bigint): BaseUnits { + const s = typeof value === "bigint" ? value.toString() : value; + if (!DIGITS.test(s)) throw new Error(`Not a non-negative integer amount: "${s}"`); + return BigInt(s).toString() as BaseUnits; +} + +/** "12.5" with 6 decimals → "12500000". Rejects more fraction digits than the asset has. */ +export function toBaseUnits(display: string, decimals: number): BaseUnits { + const m = DECIMAL.exec(display.trim()); + if (!m) throw new Error(`Not a decimal amount: "${display}"`); + const whole = m[1] ?? "0"; + const frac = m[2] ?? ""; + if (frac.length > decimals) throw new Error(`At most ${decimals} decimal places`); + return asBaseUnits(BigInt(whole + frac.padEnd(decimals, "0"))); +} + +/** "12500000" with 6 decimals → "12.5" (trailing zeros trimmed, optional cap on shown digits). */ +export function formatAmount(amount: BaseUnits | string, decimals: number, maxFractionDigits = decimals): string { + const v = BigInt(asBaseUnits(amount)); + const base = 10n ** BigInt(decimals); + const whole = v / base; + let frac = (v % base).toString().padStart(decimals, "0").slice(0, maxFractionDigits); + frac = frac.replace(/0+$/, ""); + return frac ? `${whole}.${frac}` : whole.toString(); +} + +/** Parses a decimal string (e.g. a USD value from 1Click) into a bigint scaled by 10^scale, truncating. */ +export function parseScaled(decimal: string, scale: number): bigint { + const m = DECIMAL.exec(decimal.trim()); + if (!m) throw new Error(`Not a decimal: "${decimal}"`); + const frac = (m[2] ?? "").slice(0, scale).padEnd(scale, "0"); + return BigInt((m[1] ?? "0") + frac); } -export function formatAmount(_amount: BaseUnits, _decimals: number): string { - throw new Error("Not implemented (K2.1)"); +export function minUnits(a: BaseUnits, b: BaseUnits): BaseUnits { + return BigInt(a) <= BigInt(b) ? a : b; } diff --git a/lib/core/planMatch.test.ts b/lib/core/planMatch.test.ts index 1f5c09a..d0b4e96 100644 --- a/lib/core/planMatch.test.ts +++ b/lib/core/planMatch.test.ts @@ -1,9 +1,63 @@ -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { USDC_ON_NEAR } from "./assets"; +import { asBaseUnits } from "./money"; +import { quoteMatchesPlan } from "./planMatch"; +import type { QuoteSummary, VaultState } from "./types"; // Roadmap: K2.3 +const VAULT_ID = "v0123456789abcdef.factory.stack.near"; + +const vault: VaultState = { + owner: "alice.near", + keeper: "keeper.stack.near", + usdc: "17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1", + targetAsset: "nep141:btc.omft.near", + destinationAddress: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", + amountPerRun: asBaseUnits("100000000"), + intervalS: 86_400, + maxCostBps: 300, + paused: false, + lastRunAtS: 0, + nextRunAtS: 86_400, +}; + +const quote: QuoteSummary = { + dry: false, + originAsset: USDC_ON_NEAR, + refundTo: VAULT_ID, + depositAddress: "0000000000000000000000000000000000000000000000000000000000000abc", + amountIn: asBaseUnits("100000000"), + amountOut: asBaseUnits("121000"), + minAmountOut: asBaseUnits("119000"), + timeEstimateS: 465, + amountInUsd: "99.96", + amountOutUsd: "98.35", + recipient: vault.destinationAddress!, + destinationAsset: vault.targetAsset!, + deadline: "2026-11-04T19:00:00.000Z", + signature: "ed25519:sig", + raw: {}, +}; + describe("planMatch", () => { - it.todo("accepts a matching quote"); - it.todo("rejects wrong recipient"); - it.todo("rejects wrong asset"); - it.todo("rejects amount above amount_per_run"); + it("accepts a matching quote", () => { + expect(quoteMatchesPlan(quote, vault, VAULT_ID)).toEqual({ ok: true }); + }); + + it.each([ + ["wrong recipient", { recipient: "bc1qattacker" }, "recipient differs from plan"], + ["wrong asset", { destinationAsset: "nep141:eth.omft.near" }, "destination asset differs from plan"], + ["amount above amount_per_run", { amountIn: asBaseUnits("100000001") }, "amount above amount_per_run"], + ["refund not to the vault", { refundTo: "attacker.near" }, "refunds must go back to the vault"], + ["wrong origin", { originAsset: "nep141:usdt.tether-token.near" }, "origin asset is not USDC on NEAR"], + ["dry quote", { dry: true }, "dry quote cannot be executed"], + ["no deposit address", { depositAddress: null }, "quote has no deposit address"], + ])("rejects %s", (_name, patch, reason) => { + expect(quoteMatchesPlan({ ...quote, ...(patch as Partial) }, vault, VAULT_ID)).toEqual({ ok: false, reason }); + }); + + it("rejects when the vault is paused or has no plan", () => { + expect(quoteMatchesPlan(quote, { ...vault, paused: true }, VAULT_ID)).toEqual({ ok: false, reason: "vault is paused" }); + expect(quoteMatchesPlan(quote, { ...vault, targetAsset: null }, VAULT_ID)).toEqual({ ok: false, reason: "vault has no plan" }); + }); }); diff --git a/lib/core/planMatch.ts b/lib/core/planMatch.ts index 47f5fad..316c8ac 100644 --- a/lib/core/planMatch.ts +++ b/lib/core/planMatch.ts @@ -1,11 +1,25 @@ /** - * Rejects a buy quote whose recipient/asset/amount don't match the on-chain plan. - * Roadmap: K2.3 · Spec: ARCHITECTURE.md §3.6 - * Status: scaffold — not implemented yet. + * The last off-chain guard before `execute_buy`: a buy quote must match the vault's on-chain plan. + * The contract bounds amount and timing; this check protects the recipient and asset (ARCHITECTURE §3.6). + * Roadmap: K2.3 */ +import { USDC_ON_NEAR } from "./assets"; import type { QuoteSummary, VaultState } from "./types"; -export function quoteMatchesPlan(_quote: QuoteSummary, _vault: VaultState): { ok: true } | { ok: false; reason: string } { - throw new Error("Not implemented (K2.3)"); +export type PlanMatch = { ok: true } | { ok: false; reason: string }; + +export function quoteMatchesPlan(quote: QuoteSummary, vault: VaultState, vaultAccountId: string): PlanMatch { + if (vault.paused) return { ok: false, reason: "vault is paused" }; + if (!vault.targetAsset || !vault.destinationAddress) return { ok: false, reason: "vault has no plan" }; + if (quote.dry) return { ok: false, reason: "dry quote cannot be executed" }; + if (!quote.depositAddress) return { ok: false, reason: "quote has no deposit address" }; + if (quote.originAsset !== USDC_ON_NEAR) return { ok: false, reason: "origin asset is not USDC on NEAR" }; + if (quote.destinationAsset !== vault.targetAsset) return { ok: false, reason: "destination asset differs from plan" }; + if (quote.recipient !== vault.destinationAddress) return { ok: false, reason: "recipient differs from plan" }; + if (quote.refundTo !== vaultAccountId) return { ok: false, reason: "refunds must go back to the vault" }; + const amount = BigInt(quote.amountIn); + if (amount <= 0n) return { ok: false, reason: "amount must be positive" }; + if (amount > BigInt(vault.amountPerRun)) return { ok: false, reason: "amount above amount_per_run" }; + return { ok: true }; } diff --git a/lib/core/schemas.test.ts b/lib/core/schemas.test.ts new file mode 100644 index 0000000..6019c68 --- /dev/null +++ b/lib/core/schemas.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { fundQuoteInput, planInput } from "./schemas"; + +// Roadmap: K2.6 +const plan = { + target: "btc", + destinationAddress: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", + destinationAddressConfirm: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", + amountPerRun: "100000000", + intervalS: 86_400, + maxCostBps: 300, +}; + +describe("schemas", () => { + it("accepts a valid plan", () => { + expect(planInput.safeParse(plan).success).toBe(true); + }); + + it("requires the address typed twice", () => { + const r = planInput.safeParse({ ...plan, destinationAddressConfirm: "bc1qsomethingelse" }); + expect(r.success).toBe(false); + }); + + it("rejects an address with a bad checksum for the chosen chain", () => { + const bad = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdr"; + expect(planInput.safeParse({ ...plan, destinationAddress: bad, destinationAddressConfirm: bad }).success).toBe(false); + }); + + it("rejects an ETH address for a BTC plan", () => { + const eth = "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"; + expect(planInput.safeParse({ ...plan, destinationAddress: eth, destinationAddressConfirm: eth }).success).toBe(false); + }); + + it("enforces the on-chain limits", () => { + expect(planInput.safeParse({ ...plan, intervalS: 59 }).success).toBe(false); + expect(planInput.safeParse({ ...plan, maxCostBps: 5_001 }).success).toBe(false); + expect(planInput.safeParse({ ...plan, amountPerRun: "0" }).success).toBe(false); + }); + + it("validates funding quote bodies", () => { + expect(fundQuoteInput.safeParse({ originAsset: "nep141:sol.omft.near", amountIn: "1000", refundTo: "x", dry: true }).success).toBe(true); + expect(fundQuoteInput.safeParse({ originAsset: "x", amountIn: "1.5", refundTo: "x", dry: true }).success).toBe(false); + }); +}); diff --git a/lib/core/schemas.ts b/lib/core/schemas.ts index cf215b3..9189db4 100644 --- a/lib/core/schemas.ts +++ b/lib/core/schemas.ts @@ -1,19 +1,59 @@ /** - * zod schemas for API request bodies. + * zod schemas for API request bodies. Amounts are base-unit integer strings. * Roadmap: K2.6 · Spec: ARCHITECTURE.md §4.1 - * Status: scaffold — not implemented yet. */ import { z } from "zod"; +import { TARGET_ASSETS } from "./assets"; +import { isValidAddress } from "./address"; + +// zod runs refinements even after the regex fails, so guard before calling BigInt. +const baseUnits = z + .string() + .regex(/^\d+$/, "Amount must be an integer in base units") + .refine((v) => /^\d+$/.test(v) && BigInt(v) > 0n, "Amount must be positive"); export const fundQuoteInput = z.object({ - originAsset: z.string().min(1), - amountIn: z.string().regex(/^\d+$/), - refundTo: z.string().min(1), + originAsset: z.string().min(1).max(200), + amountIn: baseUnits, + refundTo: z.string().min(1).max(200), dry: z.boolean(), }); +export type FundQuoteInput = z.infer; + +const targetKey = z.enum(["btc", "eth", "near"]); export const planPreviewInput = z.object({ - targetAsset: z.string().min(1), - amountPerRun: z.string().regex(/^\d+$/), + target: targetKey, + amountPerRun: baseUnits, +}); +export type PlanPreviewInput = z.infer; + +/** The plan form; validated again on-chain. The address is checked with the target chain's checksum rules. */ +export const planInput = z + .object({ + target: targetKey, + destinationAddress: z.string().trim().min(1).max(128), + destinationAddressConfirm: z.string().trim().min(1).max(128), + amountPerRun: baseUnits, + intervalS: z.number().int().min(60), + maxCostBps: z.number().int().min(1).max(5_000), + }) + .refine((p) => p.destinationAddress === p.destinationAddressConfirm, { + message: "Addresses don't match", + path: ["destinationAddressConfirm"], + }) + .refine((p) => isValidAddress(TARGET_ASSETS[p.target].chain, p.destinationAddress), { + message: "Not a valid address for this chain", + path: ["destinationAddress"], + }); +export type PlanInputForm = z.infer; + +export const sessionInput = z.object({ + accountId: z.string().min(2).max(64), + publicKey: z.string().min(1), + signature: z.string().min(1), + message: z.string().min(1), + nonce: z.string().min(1), }); +export type SessionInput = z.infer; diff --git a/lib/core/status.test.ts b/lib/core/status.test.ts index 2f276ae..f2785c4 100644 --- a/lib/core/status.test.ts +++ b/lib/core/status.test.ts @@ -1,7 +1,27 @@ -import { describe, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { ONECLICK_STATUSES, buyStatusFromOneClick, fundingStatusFromOneClick } from "./status"; -// Roadmap: K2.4 +// Roadmap: K2.4 · enum verified against SDK 0.1.26 (ARCHITECTURE §12) describe("status", () => { - it.todo("maps every 1Click status for funding"); - it.todo("maps every 1Click status for buys"); + it("covers exactly the 7 1Click statuses", () => { + expect([...ONECLICK_STATUSES].sort()).toEqual( + ["FAILED", "INCOMPLETE_DEPOSIT", "KNOWN_DEPOSIT_TX", "PENDING_DEPOSIT", "PROCESSING", "REFUNDED", "SUCCESS"], + ); + }); + + it("maps every 1Click status for funding", () => { + expect(ONECLICK_STATUSES.map(fundingStatusFromOneClick)).toEqual([ + "awaiting_deposit", + "detected", + "processing", + "credited", + "underpaid", + "refunded", + "failed", + ]); + }); + + it("maps every 1Click status for buys", () => { + expect(ONECLICK_STATUSES.map(buyStatusFromOneClick)).toEqual(["sent", "sent", "processing", "success", "failed", "refunded", "failed"]); + }); }); diff --git a/lib/core/types.ts b/lib/core/types.ts index 13daf13..85f473a 100644 --- a/lib/core/types.ts +++ b/lib/core/types.ts @@ -1,7 +1,6 @@ /** * Domain types shared by server, worker and UI. Pure — no I/O. * Roadmap: K2.x · Spec: ARCHITECTURE.md §3–5 - * Status: scaffold — not implemented yet. */ /** Amount in an asset's smallest unit, as a decimal string. Never a float. */ @@ -40,12 +39,16 @@ export interface PlanInput { maxCostBps: number; } -/** What we keep from a verified 1Click quote. */ +/** What we keep from a verified 1Click quote (request fields echoed so plan checks can compare them). */ export interface QuoteSummary { dry: boolean; + originAsset: AssetId; + refundTo: string; depositAddress: string | null; amountIn: BaseUnits; amountOut: BaseUnits; + minAmountOut: BaseUnits | null; + timeEstimateS: number | null; amountInUsd: string | null; amountOutUsd: string | null; recipient: string; diff --git a/package.json b/package.json index 48f9e50..40a61ce 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,8 @@ "@defuse-protocol/one-click-sdk-typescript": "0.1.26", "@electric-sql/pglite": "0.2.17", "@hot-labs/near-connect": "0.12.0", + "@noble/hashes": "2.2.0", + "@scure/base": "2.4.0", "@tanstack/react-query": "5.105.3", "drizzle-orm": "0.36.4", "nanoid": "5.1.16", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7e969fe..2648c43 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,12 @@ importers: '@hot-labs/near-connect': specifier: 0.12.0 version: 0.12.0 + '@noble/hashes': + specifier: 2.2.0 + version: 2.2.0 + '@scure/base': + specifier: 2.4.0 + version: 2.4.0 '@tanstack/react-query': specifier: 5.105.3 version: 5.105.3(@types/react@19.3.0)(react@19.3.1) diff --git a/project_structure.md b/project_structure.md index 538f9e4..1ae9663 100644 --- a/project_structure.md +++ b/project_structure.md @@ -90,7 +90,7 @@ components/ ## 5. `lib/` ``` lib/ -├─ core/ # pure: money.ts, status.ts, cost.ts (cost_bps), planMatch.ts, address.ts, adapters.ts, schemas.ts +├─ core/ # pure: assets.ts (KD-6 ids), money.ts, status.ts, cost.ts (cost_bps), planMatch.ts, address.ts (checksums), adapters.ts, schemas.ts ├─ oneclick/ # client.ts, tokens.ts, quote.ts (funding + buy, verify), status.ts, demo.ts, __fixtures__/ ├─ near/ # rpc.ts, nep413.ts, vault.ts (bindings), factory.ts, keeper.ts (server only), events.ts, demo.ts ├─ db/ # schema.ts, client.ts (PGlite/Postgres), queries/, seed-demo.ts