Skip to content

Commit 9786387

Browse files
committed
docs: add BitGoWasm API design conventions
Document 7 core architectural patterns enforced in code reviews: - Uint8Array for binary data (no hex on Transaction) - bigint for monetary amounts - Enums over magic strings - Builders return Transaction objects - Parsing separate from Transaction - Consistent wrapper API (fromBytes, toBytes, get wasm) - Typed wrappers over string-encoded data These conventions prevent review churn by defining how WASM wrapper APIs should be structured. Distilled from recurring patterns in wasm-utxo, wasm-solana, and wasm-dot reviews.
1 parent f0a75ac commit 9786387

1 file changed

Lines changed: 307 additions & 0 deletions

File tree

CONVENTIONS.md

Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
# BitGoWasm Code Conventions
2+
3+
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.
4+
5+
These are hard rules, not suggestions. If you're unsure about a pattern, check the existing implementations in wasm-utxo and wasm-solana.
6+
7+
For general best practices (bigint usage, enum usage), see `CLAUDE.md`. For build requirements (ESM setup), see package READMEs.
8+
9+
---
10+
11+
## 1. Uint8Array everywhere, no hex/base64 on Transaction
12+
13+
**What:** Transaction objects work exclusively with `Uint8Array` for binary data. No hex strings, no base64 strings.
14+
15+
**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 silent bugs where someone passes hex to a function expecting raw bytes.
16+
17+
**Good:**
18+
```typescript
19+
class Transaction {
20+
static fromBytes(bytes: Uint8Array): Transaction { ... }
21+
toBytes(): Uint8Array { ... }
22+
signablePayload(): Uint8Array { ... }
23+
}
24+
25+
// Encoding happens at the boundary
26+
const txBytes = Buffer.from(txHex, 'hex');
27+
const tx = Transaction.fromBytes(txBytes);
28+
```
29+
30+
**Bad:**
31+
```typescript
32+
// ❌ Don't accept/return hex strings on Transaction
33+
class Transaction {
34+
static fromHex(hex: string): Transaction { ... }
35+
toHex(): string { ... }
36+
}
37+
38+
// ❌ Don't mix encodings
39+
static fromBytes(bytes: Uint8Array | string): Transaction { ... }
40+
```
41+
42+
**See:** `packages/wasm-solana/js/transaction.ts`, `packages/wasm-utxo/js/transaction.ts`
43+
44+
---
45+
46+
## 2. bigint for amounts, never string
47+
48+
**What:** All monetary amounts, lamports, satoshis, token quantities, fees — use `bigint`. Never `number` or `string`.
49+
50+
**Why:**
51+
- `number` loses precision above 2^53 (unsafe for large amounts)
52+
- `string` delays type errors to runtime (no compile-time safety)
53+
- `bigint` is exact, type-safe, and enforces correctness at compile time
54+
55+
Use `BigInt()` constructor when converting from external inputs. Use `String()` only at serialization boundaries (JSON responses, API output).
56+
57+
**Good:**
58+
```typescript
59+
export interface ExplainedOutput {
60+
address: string;
61+
amount: bigint; //
62+
}
63+
64+
const fee = 5000n;
65+
const total = amount + fee; // Type-safe bigint arithmetic
66+
```
67+
68+
**Bad:**
69+
```typescript
70+
export interface ExplainedOutput {
71+
address: string;
72+
amount: string; // ❌ Runtime errors, no type safety
73+
}
74+
75+
const fee = "5000"; // ❌ Can't do arithmetic
76+
const total = parseInt(amount) + parseInt(fee); // ❌ Loses precision
77+
```
78+
79+
**See:** `packages/wasm-solana/js/explain.ts` (lines 40-43), `CLAUDE.md`
80+
81+
---
82+
83+
## 3. Enums, not magic strings
84+
85+
**What:** Use TypeScript `enum` (string enums) for finite sets of known values. Never use bare string literals for types, opcodes, instruction names, etc.
86+
87+
**Why:**
88+
- Compile-time checking (typos caught at build time)
89+
- IDE autocomplete
90+
- Exhaustiveness checking in switch statements
91+
- Self-documenting code
92+
93+
**Good:**
94+
```typescript
95+
export enum TransactionType {
96+
Send = "Send",
97+
StakingActivate = "StakingActivate",
98+
StakingDeactivate = "StakingDeactivate",
99+
}
100+
101+
function handleTx(type: TransactionType) {
102+
switch (type) {
103+
case TransactionType.Send:
104+
// ...
105+
case TransactionType.StakingActivate:
106+
// ...
107+
// TypeScript warns if you miss a case
108+
}
109+
}
110+
```
111+
112+
**Bad:**
113+
```typescript
114+
// ❌ No type safety, typos not caught
115+
function handleTx(type: string) {
116+
if (type === "send") { // Oops, wrong case
117+
// ...
118+
}
119+
}
120+
121+
// ❌ Magic strings scattered everywhere
122+
const txType = "Send";
123+
```
124+
125+
**See:** `packages/wasm-solana/js/explain.ts` (lines 19-28)
126+
127+
---
128+
129+
## 4. Return Transaction objects, not bytes (builders)
130+
131+
**What:** Builder functions and transaction constructors return `Transaction` objects, not raw `Uint8Array`. The caller serializes when they need bytes.
132+
133+
**Why:**
134+
- Transaction objects can be inspected (`.instructions`, `.feePayer`, `.recentBlockhash`)
135+
- Transaction objects can be further modified (`.addSignature()`, `.signWithKeypair()`)
136+
- Returning bytes forces the caller to re-parse if they need to inspect
137+
- Consistent with wasm-utxo pattern (builders return `BitGoPsbt`, not bytes)
138+
139+
**Good:**
140+
```typescript
141+
export function buildFromIntent(params: BuildParams): Transaction {
142+
const wasm = BuilderNamespace.build_from_intent(...);
143+
return Transaction.fromWasm(wasm);
144+
}
145+
146+
// Caller has full control
147+
const tx = buildFromIntent(intent);
148+
console.log(tx.feePayer); // Inspect
149+
tx.addSignature(pubkey, sig); // Modify
150+
const bytes = tx.toBytes(); // Serialize when ready
151+
```
152+
153+
**Bad:**
154+
```typescript
155+
// ❌ Forces caller to re-parse for inspection
156+
export function buildFromIntent(params: BuildParams): Uint8Array {
157+
const wasm = BuilderNamespace.build_from_intent(...);
158+
return wasm.to_bytes();
159+
}
160+
161+
const bytes = buildFromIntent(intent);
162+
const tx = Transaction.fromBytes(bytes); // Unnecessary round-trip
163+
```
164+
165+
**See:** `packages/wasm-solana/js/intentBuilder.ts`, `packages/wasm-solana/js/builder.ts`
166+
167+
---
168+
169+
## 5. Parsing separate from Transaction
170+
171+
**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.
172+
173+
**Why:**
174+
- Not all use cases need full parsing (e.g., just signing)
175+
- Parsing can be expensive (especially for complex instruction decoding)
176+
- Separation of concerns — Transaction is for signing/serialization, parseTransaction is for decoding
177+
- Matches wasm-utxo pattern (BitGoPsbt doesn't parse on construction)
178+
179+
**Good:**
180+
```typescript
181+
// For signing — deserialize only
182+
const tx = Transaction.fromBytes(txBytes);
183+
tx.addSignature(pubkey, signature);
184+
const signedBytes = tx.toBytes();
185+
186+
// For parsing — decode instructions
187+
const parsed = parseTransaction(txBytes, context);
188+
for (const instr of parsed.instructionsData) {
189+
if (instr.type === 'Transfer') {
190+
console.log(`${instr.amount} to ${instr.toAddress}`);
191+
}
192+
}
193+
194+
// For high-level explanation — business logic
195+
const explained = explainTransaction(txBytes, options);
196+
console.log(explained.type); // "Send", "StakingActivate", etc.
197+
```
198+
199+
**Bad:**
200+
```typescript
201+
// ❌ Transaction no longer has .parse() method
202+
const tx = Transaction.fromBytes(txBytes);
203+
const parsed = tx.parse(); // Doesn't exist
204+
205+
// ❌ Don't use parseTransaction result for signing
206+
const parsed = parseTransaction(txBytes);
207+
parsed.addSignature(pubkey, sig); // Wrong object type
208+
```
209+
210+
**See:** `packages/wasm-solana/js/parser.ts` (parseTransaction function), `packages/wasm-solana/js/transaction.ts` (Transaction.fromBytes), `packages/wasm-dot/js/parser.ts`
211+
212+
---
213+
214+
## 6. Follow wasm-utxo conventions (get wasm(), fromBytes, toBytes, getId)
215+
216+
**What:** All wrapper classes follow the same API pattern:
217+
- `static fromBytes(bytes: Uint8Array)` — deserialize
218+
- `toBytes(): Uint8Array` — serialize
219+
- `getId(): string` — transaction ID / hash
220+
- `get wasm(): WasmType` (internal) — access underlying WASM instance
221+
222+
**Why:**
223+
- Consistency across packages (wasm-utxo, wasm-solana, wasm-mps all work the same way)
224+
- Predictable API for consumers
225+
- `get wasm()` allows package-internal code to access WASM without exposing it publicly
226+
227+
**Good:**
228+
```typescript
229+
export class Transaction {
230+
private constructor(private _wasm: WasmTransaction) {}
231+
232+
static fromBytes(bytes: Uint8Array): Transaction {
233+
return new Transaction(WasmTransaction.from_bytes(bytes));
234+
}
235+
236+
toBytes(): Uint8Array {
237+
return this._wasm.to_bytes();
238+
}
239+
240+
getId(): string {
241+
return this._wasm.id;
242+
}
243+
244+
/** @internal */
245+
get wasm(): WasmTransaction {
246+
return this._wasm;
247+
}
248+
}
249+
```
250+
251+
**Bad:**
252+
```typescript
253+
// ❌ Inconsistent naming
254+
export class Transaction {
255+
static parse(bytes: Uint8Array): Transaction { ... } // Should be fromBytes
256+
serialize(): Uint8Array { ... } // Should be toBytes
257+
getTransactionId(): string { ... } // Should be getId
258+
}
259+
```
260+
261+
**See:** `packages/wasm-utxo/js/transaction.ts`, `packages/wasm-solana/js/transaction.ts`
262+
263+
---
264+
265+
## 7. Use typed wrappers (e.g., Keypair) not string-encoded keys
266+
267+
**What:** Wrap WASM types in TypeScript classes (Keypair, Pubkey, Transaction). Don't pass around hex/base58 strings where a typed object should be used.
268+
269+
**Why:**
270+
- Type safety (can't mix up a pubkey string with a signature string)
271+
- Encapsulation (implementation details hidden)
272+
- Consistent API (methods, not free functions on strings)
273+
- Prevents passing the wrong encoding (hex vs base58 vs raw bytes)
274+
275+
**Good:**
276+
```typescript
277+
export class Keypair {
278+
private constructor(private _wasm: WasmKeypair) {}
279+
280+
static fromSecretKey(secretKey: Uint8Array): Keypair { ... }
281+
getAddress(): string { ... }
282+
sign(message: Uint8Array): Uint8Array { ... }
283+
}
284+
285+
// Usage
286+
const keypair = Keypair.fromSecretKey(secretKeyBytes);
287+
tx.signWithKeypair(keypair); // Type-safe
288+
```
289+
290+
**Bad:**
291+
```typescript
292+
// ❌ Stringly-typed API
293+
function signTransaction(tx: Transaction, secretKeyHex: string) {
294+
// Is this hex? base58? 32 bytes or 64 bytes?
295+
// Caller has to know implementation details
296+
}
297+
```
298+
299+
**See:** `packages/wasm-solana/js/keypair.ts`, `packages/wasm-solana/js/pubkey.ts`
300+
301+
---
302+
303+
## Summary
304+
305+
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.
306+
307+
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.

0 commit comments

Comments
 (0)