From 3bff103d058174b28fa928acff97d715daf534d0 Mon Sep 17 00:00:00 2001 From: Luis Covarrubias Date: Mon, 23 Feb 2026 15:48:02 -0800 Subject: [PATCH] docs: add BitGoWasm API design conventions document 7 architectural patterns enforced in code reviews: - prefer Uint8Array, avoid unnecessary base conversions - bigint for monetary amounts (conversions are caller's responsibility) - as const arrays for union types, not magic strings - builders return Transaction objects, not bytes - parsing separate from Transaction (standalone parseTransaction) - use wrapper classes over raw WASM bindings - consistent wrapper API (fromBytes, toBytes, getId, get wasm()) distilled from recurring review comments across wasm-utxo, wasm-solana, and wasm-dot. ref: PR #145 discussion. --- CONVENTIONS.md | 264 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 CONVENTIONS.md diff --git a/CONVENTIONS.md b/CONVENTIONS.md new file mode 100644 index 0000000..b83e9ab --- /dev/null +++ b/CONVENTIONS.md @@ -0,0 +1,264 @@ +# BitGoWasm Code Conventions + +This file documents API design and architecture patterns from code reviews. Following these conventions prevents review churn and keeps the codebase consistent across wasm-utxo, wasm-solana, wasm-mps, and future packages. + +These are hard rules, not suggestions. If you're unsure about a pattern, check the existing implementations in wasm-utxo. +--- + +## 1. Prefer Uint8Array, avoid unnecessary base conversions + +**What:** Generally, binary formats like transactions should use `Uint8Array` . Avoid base conversions in the wasm interface. + +**Why:** Type safety at the boundary. If a method accepts or returns transaction bytes, it's always `Uint8Array`. String encodings (hex, base64) belong in serialization/API layers, not in the core transaction model. This prevents API bloat where we have to add encoding and decoding variants for various base conversion formats, as well as inefficiencies due to round-tripping binary data through two base conversions. + +Exceptions are allowed for instances where a hex encoded representations are conventional (Ethereum addresses for instance) + +**Good:** +```typescript +class Transaction { + static fromBytes(bytes: Uint8Array): Transaction { ... } + toBytes(): Uint8Array { ... } + signablePayload(): Uint8Array { ... } +} + +// Encoding happens at the boundary +const txBytes = Buffer.from(txHex, 'hex'); +const tx = Transaction.fromBytes(txBytes); +``` + +**Bad:** +```typescript +// ❌ Don't accept/return hex strings on Transaction +class Transaction { + static fromHex(hex: string): Transaction { ... } + toHex(): string { ... } +} + +// ❌ Don't mix encodings +static fromBytes(bytes: Uint8Array | string): Transaction { ... } +``` + +**See:** `packages/wasm-solana/js/transaction.ts`, `packages/wasm-utxo/js/transaction.ts` + +--- + +## 2. bigint for amounts, never string + +**What:** All monetary amounts, lamports, satoshis, token quantities, fees — use `bigint`. Never `number` or `string`. + +**Why:** +- `number` loses precision above 2^53 (unsafe for large amounts) +- `string` delays type errors to runtime (no compile-time safety) +- `bigint` is exact, type-safe, and enforces correctness at compile time + +Conversions between external representations (API strings, JSON numbers) and `bigint` are the caller's responsibility, outside the `wasm-*` package boundary. The wasm package API accepts and returns `bigint` only — no `string` or `number` overloads for amounts. + +**Good:** +```typescript +export interface ExplainedOutput { + address: string; + amount: bigint; // ✅ +} + +const fee = 5000n; +const total = amount + fee; // Type-safe bigint arithmetic +``` + +**Bad:** +```typescript +export interface ExplainedOutput { + address: string; + amount: string; // ❌ Runtime errors, no type safety +} + +const fee = "5000"; // ❌ Can't do arithmetic +const total = parseInt(amount) + parseInt(fee); // ❌ Loses precision +``` + +**See:** `packages/wasm-solana/js/explain.ts` (lines 40-43), `CLAUDE.md` + +--- + +## 3. Const arrays for union types, not magic strings + +**What:** Use `as const` arrays to define finite sets of known values. Never use bare string literals for types, opcodes, instruction names, etc. + +**Why:** +- Compile-time checking (typos caught at build time) +- IDE autocomplete +- Exhaustiveness checking in switch statements +- Less repetitive than `enum` (no `Key = "Key"` duplication) + +**Good:** +```typescript +export const TransactionType = ["Send", "StakingActivate", "StakingDeactivate"] as const; +export type TransactionType = typeof TransactionType[number]; + +function handleTx(type: TransactionType) { + switch (type) { + case "Send": + // ... + case "StakingActivate": + // ... + // TypeScript warns if you miss a case + } +} +``` + +**Bad:** +```typescript +// ❌ No type safety, typos not caught +function handleTx(type: string) { + if (type === "send") { // Oops, wrong case + // ... + } +} + +// ❌ Magic strings scattered everywhere +const txType = "Send"; +``` + +**See:** `packages/wasm-solana/js/explain.ts` (lines 19-28) + +--- + +## 4. Return Transaction objects, not bytes (builders) + +**What:** Builder functions and transaction constructors return `Transaction` objects, not raw `Uint8Array`. The caller serializes when they need bytes. + +**Why:** Transaction objects can be inspected and further modified (`.addSignature()`, `.signWithKeypair()`). Returning bytes forces the caller to re-parse if they need to inspect or modify. + +**Good:** +```typescript +export function buildFromIntent(params: BuildParams): Transaction { + const wasm = BuilderNamespace.build_from_intent(...); + return Transaction.fromWasm(wasm); +} + +// Caller has full control +const tx = buildFromIntent(intent); +console.log(tx.feePayer); // Inspect +tx.addSignature(pubkey, sig); // Modify +const bytes = tx.toBytes(); // Serialize when ready +``` + +**Bad:** +```typescript +// ❌ Forces caller to re-parse for inspection +export function buildFromIntent(params: BuildParams): Uint8Array { + const wasm = BuilderNamespace.build_from_intent(...); + return wasm.to_bytes(); +} + +const bytes = buildFromIntent(intent); +const tx = Transaction.fromBytes(bytes); // Unnecessary round-trip +``` + +**See:** `packages/wasm-solana/js/intentBuilder.ts`, `packages/wasm-solana/js/builder.ts` + +--- + +## 5. Parsing separate from Transaction + +**What:** Transaction deserialization (for signing) and transaction parsing (decoding instructions) are separate operations with separate entry points. `Transaction.fromBytes()` deserializes for signing. `parseTransaction()` is a standalone function that decodes instructions into structured data. + +**Why:** +- Separation of concerns: decoding is a protocol-level concept, parsing is a BitGo-level concept + +**Good:** +```typescript +// For signing — deserialize only +const tx = Transaction.fromBytes(txBytes); +tx.addSignature(pubkey, signature); +const signedBytes = tx.toBytes(); + +// For parsing — standalone function, takes bytes as argument +const parsed = parseTransaction(txBytes, context); +for (const instr of parsed.instructionsData) { + if (instr.type === 'Transfer') { + console.log(`${instr.amount} to ${instr.toAddress}`); + } +} +``` + +**Bad:** +```typescript +// ❌ Transaction no longer has .parse() method +const tx = Transaction.fromBytes(txBytes); +const parsed = tx.parse(); // Doesn't exist + +// ❌ Don't use parseTransaction result for signing +const parsed = parseTransaction(txBytes); +parsed.addSignature(pubkey, sig); // Wrong object type +``` + +**See:** `packages/wasm-solana/js/parser.ts` (parseTransaction function), `packages/wasm-solana/js/transaction.ts` (Transaction.fromBytes), `packages/wasm-dot/js/parser.ts` + +--- + +## 6. Use wrapper classes + +**What:** Wrap WASM-generated types in TypeScript classes that provide better type signatures, `camelCase` naming, and encapsulation. Don't expose raw WASM bindings to consumers. + +**Why:** `wasm-bindgen` emits loose types (`any`, `string | null`) and `snake_case` naming. Wrapper classes provide precise TypeScript types, idiomatic JS naming, and hide WASM implementation details. Two patterns exist: namespace wrappers for stateless utilities, class wrappers for stateful objects. + +**See:** [`packages/wasm-utxo/js/README.md`](https://github.com/BitGo/BitGoWASM/blob/master/packages/wasm-utxo/js/README.md#purpose) for the full rationale and examples of both patterns. + +--- + +## 7. Follow wasm-utxo conventions (get wasm(), fromBytes, toBytes, getId) + +**What:** All wrapper classes follow the same API pattern: +- `static fromBytes(bytes: Uint8Array)` — deserialize +- `toBytes(): Uint8Array` — serialize +- `getId(): string` — transaction ID / hash +- `get wasm(): WasmType` (internal) — access underlying WASM instance + +**Why:** +- Consistency across packages (wasm-utxo, wasm-solana, wasm-mps all work the same way) +- Predictable API for consumers +- `get wasm()` allows package-internal code to access WASM without exposing it publicly + +**Good:** +```typescript +export class Transaction { + private constructor(private _wasm: WasmTransaction) {} + + static fromBytes(bytes: Uint8Array): Transaction { + return new Transaction(WasmTransaction.from_bytes(bytes)); + } + + toBytes(): Uint8Array { + return this._wasm.to_bytes(); + } + + getId(): string { + return this._wasm.id; + } + + /** @internal */ + get wasm(): WasmTransaction { + return this._wasm; + } +} +``` + +**Bad:** +```typescript +// ❌ Inconsistent naming +export class Transaction { + static parse(bytes: Uint8Array): Transaction { ... } // Should be fromBytes + serialize(): Uint8Array { ... } // Should be toBytes + getTransactionId(): string { ... } // Should be getId +} +``` + +**See:** `packages/wasm-utxo/js/transaction.ts`, `packages/wasm-solana/js/transaction.ts` + +--- + +## Summary + +These 7 conventions define how BitGoWasm packages structure their APIs. They're architectural patterns enforced in code reviews — not general software practices or build requirements. + +When in doubt, look at wasm-solana and wasm-utxo — they're the reference implementations. Following these patterns from the start prevents review churn and keeps all packages consistent.