2026-12-06 ~8 min read Node 20 · Bittensor SCALE · OAW MVP 0.3 · WebMCP RSS

Decoding Bittensor L1 SCALE Without SDKs and Shipping a Zero-Backend Open Agentic CostGuard

Inside two zero-dependency Node 20 systems: a byte-exact Subtensor Finney SCALE & dTAO inference cost observatory and a browser-callable Open Agentic Website (MVP 0.3, WebMCP & Streamable HTTP MCP).

Whenever you connect an autonomous coding or research agent to external compute and peer tools, two operational risks surface immediately. On the supply side, decentralized inference networks advertise steep discounts over frontier APIs, yet per-token rate cards rarely reveal whether the underlying subnet has deep AMM reserves or thin-pool slippage. On the caller side, as static websites expose cross-origin agent actions, an unguarded loop or untrusted tool result can breach a monthly API ceiling or leak private session state across origins.

Because binary wire specs, public archive RPCs, and emerging agentic web standards are all open, technical barriers are lower than ever — making it practical to build small, zero-dependency tools at the right moment instead of wrapping megabytes of SDK middleware.

Alongside shipping xgbtxy/ap v2.100.0 (776 GitHub release binary downloads) and crossing 93 merged upstream open-source PRs (TensorBlock/awesome-mcp-servers#8171, gimli-rs/object#1039, valkey-io/valkey-go#236), I built two MIT-licensed, zero-npm-dependency Node 20+ systems on $0/month static + loopback hosting:

  1. xgbtxy/bittensor-subnet-cost-observatory (c4f5532, live terminal, snapshot.json, daily-brief.md) — a 310-line Substrate SCALE decoder for Opentensor's Subtensor Finney Mainnet L1 RPC, dTAO AMM slippage and operator-cluster auditor, live SN64 Chutes (including hardware TEE) vs. centralized LLM cost comparator, and Streamable HTTP MCP server.
  2. xgbtxy/open-agentic-costguard (5223009, live workbench, agentic-manifest.json, agent-manifest.json) — a client-side Open Agentic Website (Worldwide Agentic Web MVP Profile 0.3, W3C WebMCP navigator.modelContext, NANDA /.well-known/agent.json, cross-origin MessageChannel bridge, and Streamable HTTP MCP) passing cognizant-ai-labs/agentic-web's check_partner.mjs validator with 0 errors and 0 warnings across all 7/7 CORS endpoints.

Below are the wire-format details, routing and micropayment equations, cross-origin capability checks, and design trade-offs from building both.

1. Side-by-Side Architecture: Zero Transitive Dependencies, Isomorphic ESM

One repository decodes binary Substrate RPC buffers from a Layer-1 blockchain; the other coordinates browser-to-browser MessageChannel calls. Both use an isomorphic ES module layout so the exact same pure functions execute in Node CLI scripts, CI tests, loopback MCP servers, and static GitHub Pages tabs without a bundler:

Dimension bittensor-subnet-cost-observatory (c4f5532) open-agentic-costguard (5223009)
Runtime & Deps Node >=20.0.0 ESM · 0 npm dependencies Browser ESM + Node >=20.0.0 (20 & 22 CI) · 0 npm dependencies
Core Wire / Schema Layer 310-line Substrate SCALE reader (src/lib/scale-subtensor.mjs) on Finney L1 RPC Unified 4-tool JSON Schema registry (docs/lib/tools-registry.mjs, additionalProperties: false)
Agent Protocols Streamable HTTP MCP (POST /mcp, protocol 2025-03-26, 3 tools) + ?embed= iframes OAW MVP 0.3 (nsdeploy-actions-v1 bridge), WebMCP (navigator.modelContext), NANDA, Streamable HTTP MCP (2025-03-26, 4 tools)
Hosting & Refresh GitHub Pages + 6h GitHub Actions cron (17 */6 * * *) 100% client-side GitHub Pages ($0 host inference; optional visitor BYOK via Mozilla Otari / OpenRouter)
Verification 17/17 node:test checks (SCALE rao conservation, Gini/HHI, SVG NaN guard, live MCP) 20/20 node:test checks + upstream check_partner.mjs (7/7 HTTP 200 + CORS, 0 errors / 0 warnings)

Pulling a full blockchain SDK or schema validation library introduces hundreds of megabytes of transitive dependencies and forces a build step that breaks direct <script type="module"> execution on static hosts. Sticking to standard primitives (Uint8Array, BigInt, fetch, MessageChannel, node:http, and node:test) keeps cold starts under 50ms and every byte boundary auditable.

2. Inside bittensor-subnet-cost-observatory: Decoding Subtensor Finney SCALE Without an SDK

Three wire-format traps in raw Subtensor RPC responses

Most Bittensor analytics tools rely on paid indexer keys or heavy Python/TypeScript SDKs (bittensor, @polkadot/api). Yet Opentensor's public Finney Mainnet endpoint (https://entrypoint-finney.opentensor.ai) exposes the complete Dynamic TAO (dTAO) state across three runtime RPC calls: subnetInfo_getAllDynamicInfo, subnetInfo_getSubnetsInfo_v2, and swap_simSwapTaoForAlpha.

Those runtime methods return raw Substrate SCALE byte arrays rather than JSON. Writing src/lib/scale-subtensor.mjs (310 lines) directly against Subtensor's Rust struct definitions (pallets/subtensor/src/rpc_info/dynamic_info.rs and subnet_info.rs) surfaced three binary layout quirks that break naive parsers:

  1. Vec<Compact<u8>> vs. standard Vec<u8> strings: In SubnetIdentityV3, fields like github_repo and subnet_url are standard length-prefixed UTF-8 slices (readString()). Inside DynamicInfo, however, subnet_name and token_symbol are typed as Vec<Compact<u8>> — wrapping each byte as its own SCALE compact integer (0–63 uses 1-byte mode 0b00; 64–16,383 uses 2-byte little-endian mode 0b01). Because u8 maxes out at 255, every byte >= 64 (0x40, including all ASCII letters A–Z / a–z and UTF-8 continuation bytes like Greek α) encodes as ((byte << 2) | 0b01) across two wire bytes. Reading subnet_name as a plain Vec<u8> shifts every downstream emission and pool reserve field.
  2. Signed I96F32 fixed-point EMA prices: Subtensor stores each subnet's exponential moving price (moving_price) as Substrate I96F32 (96 integer bits + 32 fractional bits) inside a 128-bit little-endian two's-complement word (sign at bit 127), decoded via Number(reader.readI128Big()) / 2^32 (4,294,967,296).
  3. Fail-closed trailing-byte assertions + PII scrubbing: Without fetching chain metadata at runtime, an upstream struct addition must never silently shift field offsets. Both decodeAllDynamicInfo and decodeAllSubnetsInfoV2 assert reader.remaining === 0 after decoding the Vec<Option<...>> buffer, throwing immediately on a single unconsumed byte. Meanwhile, decodeSubnetIdentityV3 reads past subnet_contact and discards it (void _subnetContact) so personal operator emails never enter docs/data/snapshot.json (enforced by test #17).
readCompactByteVecUtf8() {
  const len = this.readCompactNum();
  const raw = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    raw[i] = this.readCompactNum(); // Vec<Compact<u8>>: byte >= 0x40 uses 2-byte ((b << 2) | 0b01) LE mode
  }
  return Buffer.from(raw).toString('utf8');
}

// Signed I96F32 (96-bit signed int + 32-bit frac in LE i128) + trailing-byte check:
const movingPrice = Number(reader.readI128Big()) / 4294967296; // 2^32
// ...
const items = reader.readVec(() => reader.readOption(() => decodeDynamicInfoItem(reader)));
if (reader.remaining !== 0) {
  throw new Error(`DynamicInfo trailing bytes: ${reader.remaining}`);
}

Verifying real 100-TAO AMM slippage and operator clusters at Finney Block #9,661,977

In Bittensor's dTAO model, each subnet operates an automated market maker (tao_in vs. alpha_in). Ranking subnets solely by daily emission share hides liquidity fragility: a subnet can capture a large slice of daily TAO emissions while sitting over a shallow pool where a 100 TAO order suffers double-digit price impact.

In scripts/collect.mjs and docs/lib/economics-core.mjs, the collector pairs full-network SCALE decoding with batched swap_simSwapTaoForAlpha(netuid, 100_000_000_000) runtime calls (100 TAO in rao across 22 priority high-emission and inference subnets, 6 concurrent RPC calls per batch, with constant-product fallback for smaller pools). In the committed Finney Block #9,661,977 snapshot (2026-12-06T09:05:42Z, TAO at $148.15 cross-checked across CoinGecko and Coinbase, subnet lock cost 295.52 TAO / $43,781):

  • Macro dispersion vs. pool skew: Across 134 active dTAO subnets locking 1,887,114 TAO ($559.2M bilateral pool depth) and emitting 1,424.96 TAO/day ($211,108/day), network-wide emission HHI is 338.6 (Distributed / Competitive, Top-5 emission share 30.49%). At the same time, Emission Gini is 0.758 and Liquidity Gini is 0.6798, with the top 5 pools holding 35.82% of all locked TAO — led by SN64 Chutes (188,477 TAO reserve, 0.10% 100-TAO slippage), SN51 lium.io (182,839 TAO, 0.11% slippage), and SN4 Targon (136,047 TAO).
  • 11 critical thin-pool & burn-wall redlines (25 watch): evaluateSubnetHealth measures Pool Coverage Days (tao_in / daily_tao_emission). SN35 TTedu captured 9.10% of total Finney emission (129.62 TAO/day, $19,203/day) backed by 853 TAO in pool reserve (6.6 days coverage, 10.53% 100-TAO price impact -> THIN_ALPHA_LIQUIDITY + HIGH_AMM_SLIPPAGE + EMISSION_WHALE_SHARE), while SN113 Elo recorded 15.85% 100-TAO slippage on a 532.3 TAO reserve (daily-brief.md #4) alongside a 100%-full neuron table (256/256 UIDs, 1.000 TAO registration burn -> MINER_BURN_WALL).
  • Multi-subnet entity clustering: Joining 8-hex L1 owner coldkey tags (ck-...) with verified on-chain SubnetIdentityV3 GitHub organizations (extractOperatorKey) maps multi-subnet operators directly from chain state — including gh:datura-ai (SN51 lium.io, SN22 Desearch — 7.286% combined emission, 189,908 TAO), gh:macrocosm-os (SN9, SN1, SN13 — 3 subnets, 90,372 TAO), and gh:taostat (SN28, SN19 — 52,590 TAO).

Live SN64 TEE vs. centralized frontier 80/20 inference TCO

To tie subnet depth directly to LLM routing budgets, collect.mjs queries live token rates from Bittensor SN64 Chutes (https://llm.chutes.ai/v1/models, 29 live models including hardware-attested Confidential Compute TEE endpoints) alongside 464 models in OpenRouter's public catalog. On a 500M tokens/month workload (70% input / 30% output):

  • SN64 primary (80%): Hardware-attested Qwen/Qwen3.8-27B-TEE ($0.039/1M input, $1.25/1M output -> $0.4023/1M blended, 0.002716 TAO/1M at $148.15/TAO, $201.15/mo at 100%).
  • Centralized fallback (20%): google/gemini-2.5-pro-preview ($1.25/1M input, $10.00/1M output -> $3.875/1M blended, $1,937.50/mo at 100%).
  • 80/20 hybrid bill: 0.80 × $201.15 + 0.20 × $1,937.50 = $160.92 + $387.50 = $548.42/month vs. $1,937.50/month pure centralized — saving $1,389.08/month (71.7%, $16,668.96/year), exposed to IDE agents via POST /mcp (get_bittensor_subnet_snapshot, compare_tao_vs_centralized_llm, audit_subnet_concentration).

3. Inside open-agentic-costguard: Four Agentic Surfaces from One Static Codebase

Wiring one pure-ESM tool registry across OAW MVP 0.3, WebMCP, NANDA, and HTTP MCP

Building on an earlier Unicode scanner experiment (open-agentic-guard), open-agentic-costguard (5223009) packages one static GitHub Pages bundle simultaneously as an interactive FinOps workbench, a verified Open Agentic Web (MVP Profile 0.3) peer node, an in-tab W3C WebMCP provider, and a local Streamable HTTP MCP server (2025-03-26 HTTP transport replacing legacy HTTP+SSE) at $0 host inference cost.

docs/lib/tools-registry.mjs defines one frozen MANIFEST_TOOLS table (estimate_llm_cost, optimize_hybrid_route, audit_prompt_safety_redline, inspect_x402_pricing) with additionalProperties: false JSON Schemas across four thin adapters:

  1. Open Agentic Web MVP 0.3 & Portable Neuro SAN Graph (docs/agent-manifest.json + open_agentic_costguard.network.json): Declares a 3-agent graph (costguard_architect at max_steps: 12 -> hybrid_route_optimizer and policy_budget_auditor at max_steps: 8), peer_policy.mode: "closed", sly_data deny-by-default, and visitor BYOK via Mozilla Otari or OpenRouter. Running cognizant-ai-labs/agentic-web's check_partner.mjs passes all 7/7 CORS endpoints (agent-manifest.json, open_agentic_costguard.network.json, links.json, bridge/action-bridge.html, bridge/bridge.js, bridge/agent-manifest.json, and bridge/bridge-actions.js) with 0 errors and 0 warnings.
  2. Replay-guarded nsdeploy-actions-v1 MessageChannel Action Bridge (docs/bridge/bridge.js): When a peer site loads bridge/action-bridge.html in a hidden iframe and transfers a MessageChannel port, the bridge rejects "null" origins, restricts cross-origin calls to entry.effect === "read", serializes calls behind a busy flag, and tracks seenRequestIds to reject replayed execute messages:
if (entry.effect !== "read") {
  throw new Error("Bridge permits read-only capabilities only.");
}
if (
  typeof req.requestId !== "string" ||
  !req.requestId ||
  req.requestId.length > 200 ||
  seenRequestIds.has(req.requestId)
) {
  throw new Error("Invalid or replayed requestId.");
}
const valid = validateToolArgs(entry.inputSchema, req.args || {});
if (!valid.ok) throw new Error(valid.error);
  1. In-page WebMCP (navigator.modelContext) & NANDA discovery: docs/lib/webmcp-shim.mjs mounts all four tools on navigator.modelContext (listTools(), callTool()) alongside /.well-known/agent.json, <link rel="agent-manifest">, and JSON-LD so browser agents call structured functions instead of scraping DOM nodes.
  2. Loopback Streamable HTTP MCP (src/mcp-server.mjs): node src/mcp-server.mjs --serve-docs serves JSON-RPC 2.0 POST /mcp (protocolVersion: "2025-03-26", batch array support, 1 MiB 413 body limit) on 127.0.0.1:8788.

Reverse-inferring workloads from an invoice + x402 vs. Stripe unit economics

Teams rarely track exact monthly token counts offhand, though they always know last month's dollar bill. In docs/lib/cost-engine.mjs, inferRequestsFromMonthlyBill works backward from a monthly invoice across 12 official APIs (Claude Opus 4.6, Claude Sonnet 4.6, GPT-4.1, Gemini 2.5 Pro, OpenAI o4-mini, Claude 3.5 Haiku, GPT-4.1 mini, Gemini 2.5 Flash, DeepSeek V3.2, Llama 4 Maverick, Qwen 3.8 Flash, and GPT-4.1 nano).

Given "Cut our $1,200/mo Claude Sonnet bill by 60% with 80/20 routing and enforce a $400 redline", planAndExecuteIntent runs a deterministic 3-step trace:

  • Step 1 (estimate_llm_cost): Using Claude Sonnet 4.6 rates ($3.00 uncached input / $0.30 cached input / $15.00 output per 1M tokens) at 1,800 avg input tokens, 650 output tokens, and a 25% cache hit ratio ($0.013935/call), a $1,200.00/mo bill infers 86,114 requests/month (155.01M input + 55.97M output tokens).
  • Step 2 (optimize_hybrid_route): On that same token volume, DeepSeek V3.2 ($0.27 uncached / $0.07 cached / $1.10 output per 1M) costs $34.10 input + $61.57 output = $95.68/mo at 100%. Pairing 80% DeepSeek V3.2 + 20% Claude Sonnet 4.6 yields 0.80 × $95.68 + 0.20 × $1,200.00 = $316.54/month — saving $883.46/month (73.6%), retaining 94.9% blended quality (90.2 vs. 95), cutting latency from 980ms to 692ms, and leaving $83.46 headroom under the $400/mo ceiling. Test #17 verifies zero label collisions (verifyZeroLabelOverlap) across all 13 pure-SVG bars.

For paid agent endpoints, inspect_x402_pricing quantifies why per-call machine APIs break on legacy card rails. Charging $0.005/call across 180,000 calls/month yields $900.00 gross revenue, backed by $73.87/mo of alibaba/qwen3.8-flash (1,200 input tokens at 30% cache hit on $0.15/$0.04 + 450 output tokens on $0.60 per 1M):

  • Legacy card rail (Stripe 2.9% + $0.30): $0.30 + ($0.005 × 0.029) = $0.300145 fee per swipe -> $54,026.10 in processing fees (60.03× gross revenue; Stripe's $0.30 fixed floor eats >20% of revenue anywhere below $1.50/call).
  • x402 USDC on Base (eip155:8453, EIP-3009, $0.00025 fixed): $45.00 in network fees (5.0% of gross), leaving $781.13/mo net operating income (86.8% net margin) after $73.87 inference.
  • x402 USDC on Solana (SPL, $0.00015 fixed): $27.00 in network fees (3.0% of gross), leaving $799.13/mo net operating income (88.8% net margin).

Deterministic 10-rule OAW policy gate (OAW-*)

Step 3 terminates in audit_prompt_safety_redline (docs/lib/safety-engine.mjs), checking 10 rules mapped to MVP Profile 0.3: direct role/system-tag overrides (OAW-INJ-001), indirect tool-result comments, markdown image-query exfiltration, and Unicode BiDi controls U+202A..U+202E / U+2066..U+2069 (OAW-INJ-002), live credential redaction (OAW-SEC-001, masking matches as sk-proj-...[REDACTED:31c]), sly_data cross-boundary forwarding (OAW-SEC-002), unconfirmed irreversible tool calls (OAW-ESC-001), unapproved allowed_peers origins (OAW-ESC-002), partner-bound PII (OAW-PII-001), the 85%–100% budget warning band vs. >100% hard block (OAW-FIN-001..002), and single-call x402 / max_steps <= 24 runaway caps (OAW-FIN-003) — returning a synchronous 64-bit dual-FNV-1a receipt (rcpt_oaw_<16-hex>).

4. Engineering Boundaries: Where Zero-SDK and Client-Side Designs Stop

  1. Hand-rolled SCALE codecs trade schema agility for zero-dependency speed. Because ScaleReader decodes Subtensor's DynamicInfo and SubnetInfov2 structs directly rather than downloading a 3 MB runtime metadata registry via @polkadot/api, an upstream Subtensor pallet upgrade that inserts a struct field will break binary alignment. Asserting reader.remaining === 0 plus 17 CI invariant checks ensures any wire-format change fails closed in GitHub Actions rather than publishing shifted numbers.
  2. Selective L1 simSwap batching (22 pools) vs. full-network AMM approximation. Firing 134 swap_simSwapTaoForAlpha runtime calls every 6 hours would add unnecessary load to public Finney nodes. Probing the 22 highest-emission and flagship inference/compute pools on L1 while using constant-product math (100 / (taoIn + 100)) on small long-tail pools captures exact protocol fees where liquidity concentrates without abusing shared RPC endpoints.
  3. Client-side policy receipts (rcpt_oaw_*) and pattern rules are pre-flight guardrails, not server-enforced billing locks or semantic firewalls. deterministicPolicyDigest uses synchronous dual-FNV-1a hashing so browser tabs and Node tests compute identical trace IDs in microseconds without key management; it is a reproducibility fingerprint, not a cryptographic signature. Likewise, OAW-INJ-001..002 catch delimiter spoofing, BiDi obfuscation, and markdown query-string exfiltration, while plain-language social engineering still depends on capability boundaries: keeping cross-origin bridges strictly effect: "read", sly_data deny-by-default, and peer_policy closed until visitor consent.

Both artifacts — Finney Block #9,661,977 in snapshot.json and the 7/7 check_partner.mjs-verified endpoints on open-agentic-costguard — run without servers or paid indexers, hhh. If you are routing agent workloads across decentralized GPU/inference subnets or wiring WebMCP and cross-origin manifests into static sites, how are you handling slippage redlines and untrusted peer context in your stack?

Links

我觉得技术没有壁垒,在合适的时间做合适的事情就好,hhh