Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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.)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
43 changes: 40 additions & 3 deletions lib/core/address.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
81 changes: 77 additions & 4 deletions lib/core/address.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
58 changes: 58 additions & 0 deletions lib/core/assets.ts
Original file line number Diff line number Diff line change
@@ -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<TargetKey, TargetAsset> = {
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);
}
29 changes: 25 additions & 4 deletions lib/core/cost.test.ts
Original file line number Diff line number Diff line change
@@ -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" });
});
});
35 changes: 30 additions & 5 deletions lib/core/cost.ts
Original file line number Diff line number Diff line change
@@ -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<QuoteSummary, "amountInUsd" | "amountOutUsd">): 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<QuoteSummary, "amountInUsd" | "amountOutUsd">, 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 };
}
5 changes: 5 additions & 0 deletions lib/core/index.ts
Original file line number Diff line number Diff line change
@@ -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";
38 changes: 35 additions & 3 deletions lib/core/money.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
Loading
Loading