Skip to content

Commit 0b91344

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 0b91344

1 file changed

Lines changed: 304 additions & 0 deletions

File tree

CONVENTIONS.md

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