@crewhaus/wallet-engine 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +43 -0
- package/src/index.test.ts +241 -0
- package/src/index.ts +386 -0
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@crewhaus/wallet-engine",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Wallet custody + sign-request flow. Routes every transaction through simulation, transaction-policy enforcement, approval gate, then broadcast. §47 slice 1.",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.ts"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "bun test src"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@crewhaus/boundary-classifier": "0.0.0",
|
|
16
|
+
"@crewhaus/chain-adapter-base": "0.0.0",
|
|
17
|
+
"@crewhaus/errors": "0.0.0"
|
|
18
|
+
},
|
|
19
|
+
"license": "Apache-2.0",
|
|
20
|
+
"author": {
|
|
21
|
+
"name": "Max Meier",
|
|
22
|
+
"email": "max@studiomax.io",
|
|
23
|
+
"url": "https://studiomax.io"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/crewhaus/factory.git",
|
|
28
|
+
"directory": "packages/wallet-engine"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://github.com/crewhaus/factory/tree/main/packages/wallet-engine#readme",
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/crewhaus/factory/issues"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "restricted"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"src",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE",
|
|
41
|
+
"NOTICE"
|
|
42
|
+
]
|
|
43
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import { clearBoundaryCache } from "@crewhaus/boundary-classifier";
|
|
3
|
+
import type { ChainAdapter } from "@crewhaus/chain-adapter-base";
|
|
4
|
+
import {
|
|
5
|
+
type TransactionPolicy,
|
|
6
|
+
type UnsignedTx,
|
|
7
|
+
type WalletConfig,
|
|
8
|
+
WalletEngineError,
|
|
9
|
+
createLocalSignerStub,
|
|
10
|
+
createWalletEngine,
|
|
11
|
+
} from "./index";
|
|
12
|
+
|
|
13
|
+
afterEach(() => clearBoundaryCache());
|
|
14
|
+
|
|
15
|
+
function fakeAdapter(
|
|
16
|
+
handler: (method: string, params: ReadonlyArray<unknown>) => unknown,
|
|
17
|
+
): ChainAdapter {
|
|
18
|
+
return {
|
|
19
|
+
chainId: "test-chain",
|
|
20
|
+
config: {
|
|
21
|
+
chainId: "test-chain",
|
|
22
|
+
rpcUrls: ["https://stub.test"],
|
|
23
|
+
rpcPolicy: "single",
|
|
24
|
+
finality: { kind: "finalized" },
|
|
25
|
+
reorgTolerant: true,
|
|
26
|
+
},
|
|
27
|
+
async rpcRead(method, params) {
|
|
28
|
+
return handler(method, params);
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const WALLET: WalletConfig = {
|
|
34
|
+
id: "treasury",
|
|
35
|
+
chainId: "test-chain",
|
|
36
|
+
custody: "local",
|
|
37
|
+
signingPolicy: "explicit-user-approval",
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const POLICY: TransactionPolicy = {
|
|
41
|
+
defaultWriteApproval: "required",
|
|
42
|
+
allowedContracts: ["usdc"],
|
|
43
|
+
simulationRequired: true,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const TX_OK: UnsignedTx = {
|
|
47
|
+
chainId: "test-chain",
|
|
48
|
+
walletId: "treasury",
|
|
49
|
+
contractId: "usdc",
|
|
50
|
+
to: "0xusdc",
|
|
51
|
+
data: "0xa9059cbb000000",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
describe("createWalletEngine — happy path", () => {
|
|
55
|
+
test("simulates, prompts approval, signs, fetches receipt", async () => {
|
|
56
|
+
let approvalCalls = 0;
|
|
57
|
+
const we = createWalletEngine({
|
|
58
|
+
resolveAdapter: () =>
|
|
59
|
+
fakeAdapter((method) => {
|
|
60
|
+
if (method === "eth_call") return "0x";
|
|
61
|
+
if (method === "eth_estimateGas") return "0x5208";
|
|
62
|
+
if (method === "eth_getTransactionReceipt") {
|
|
63
|
+
return { blockNumber: "0x100", status: "0x1" };
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}),
|
|
67
|
+
approve: async () => {
|
|
68
|
+
approvalCalls += 1;
|
|
69
|
+
return "allow";
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
we.registerCustody(createLocalSignerStub());
|
|
73
|
+
|
|
74
|
+
const receipt = await we.requestSignAndBroadcast({
|
|
75
|
+
tx: TX_OK,
|
|
76
|
+
policy: POLICY,
|
|
77
|
+
wallet: WALLET,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
expect(approvalCalls).toBe(1);
|
|
81
|
+
expect(receipt.status).toBe("0x1");
|
|
82
|
+
expect(receipt.blockNumber).toBe("0x100");
|
|
83
|
+
expect(receipt.txHash.startsWith("0x")).toBe(true);
|
|
84
|
+
expect(receipt.boundary.origin).toBe("chain");
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe("createWalletEngine — policy enforcement", () => {
|
|
89
|
+
test("rejects when contractId is missing and allowedContracts is non-empty", async () => {
|
|
90
|
+
const we = createWalletEngine({
|
|
91
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
92
|
+
approve: async () => "allow",
|
|
93
|
+
});
|
|
94
|
+
we.registerCustody(createLocalSignerStub());
|
|
95
|
+
const tx: UnsignedTx = { chainId: "test-chain", walletId: "treasury", to: "0xraw", data: "0x" };
|
|
96
|
+
await expect(
|
|
97
|
+
we.requestSignAndBroadcast({ tx, policy: POLICY, wallet: WALLET }),
|
|
98
|
+
).rejects.toThrow(WalletEngineError);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("rejects when contractId is not in allowedContracts", async () => {
|
|
102
|
+
const we = createWalletEngine({
|
|
103
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
104
|
+
approve: async () => "allow",
|
|
105
|
+
});
|
|
106
|
+
we.registerCustody(createLocalSignerStub());
|
|
107
|
+
const tx: UnsignedTx = { ...TX_OK, contractId: "uniswap-router" };
|
|
108
|
+
await expect(
|
|
109
|
+
we.requestSignAndBroadcast({ tx, policy: POLICY, wallet: WALLET }),
|
|
110
|
+
).rejects.toThrow(/uniswap-router/);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("rejects approval='none' with non-automated wallet", async () => {
|
|
114
|
+
const we = createWalletEngine({
|
|
115
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
116
|
+
approve: async () => "allow",
|
|
117
|
+
});
|
|
118
|
+
we.registerCustody(createLocalSignerStub());
|
|
119
|
+
await expect(
|
|
120
|
+
we.requestSignAndBroadcast({
|
|
121
|
+
tx: TX_OK,
|
|
122
|
+
policy: { ...POLICY, defaultWriteApproval: "none", simulationRequired: false },
|
|
123
|
+
wallet: WALLET,
|
|
124
|
+
}),
|
|
125
|
+
).rejects.toThrow(/automated/);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
describe("createWalletEngine — simulation gate", () => {
|
|
130
|
+
test("aborts on failed simulation when simulationRequired", async () => {
|
|
131
|
+
const we = createWalletEngine({
|
|
132
|
+
resolveAdapter: () =>
|
|
133
|
+
fakeAdapter((method) => {
|
|
134
|
+
if (method === "eth_call") throw new Error("execution reverted: insufficient balance");
|
|
135
|
+
return "0x";
|
|
136
|
+
}),
|
|
137
|
+
approve: async () => "allow",
|
|
138
|
+
});
|
|
139
|
+
we.registerCustody(createLocalSignerStub());
|
|
140
|
+
await expect(
|
|
141
|
+
we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET }),
|
|
142
|
+
).rejects.toThrow(/simulation failed/);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("skips simulation when simulationRequired is false", async () => {
|
|
146
|
+
const simCalls: string[] = [];
|
|
147
|
+
const we = createWalletEngine({
|
|
148
|
+
resolveAdapter: () =>
|
|
149
|
+
fakeAdapter((method) => {
|
|
150
|
+
simCalls.push(method);
|
|
151
|
+
if (method === "eth_getTransactionReceipt")
|
|
152
|
+
return { blockNumber: "0x100", status: "0x1" };
|
|
153
|
+
return "0x";
|
|
154
|
+
}),
|
|
155
|
+
approve: async () => "allow",
|
|
156
|
+
});
|
|
157
|
+
we.registerCustody(createLocalSignerStub());
|
|
158
|
+
await we.requestSignAndBroadcast({
|
|
159
|
+
tx: TX_OK,
|
|
160
|
+
policy: { ...POLICY, simulationRequired: false },
|
|
161
|
+
wallet: WALLET,
|
|
162
|
+
});
|
|
163
|
+
expect(simCalls.includes("eth_call")).toBe(false);
|
|
164
|
+
expect(simCalls.includes("eth_estimateGas")).toBe(false);
|
|
165
|
+
expect(simCalls.includes("eth_getTransactionReceipt")).toBe(true);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
describe("createWalletEngine — approval gate", () => {
|
|
170
|
+
test("denied approval blocks broadcast", async () => {
|
|
171
|
+
let signedCalls = 0;
|
|
172
|
+
const we = createWalletEngine({
|
|
173
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
174
|
+
approve: async () => "deny",
|
|
175
|
+
});
|
|
176
|
+
we.registerCustody({
|
|
177
|
+
custody: "local",
|
|
178
|
+
async signAndBroadcast() {
|
|
179
|
+
signedCalls += 1;
|
|
180
|
+
return "0xfake";
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
await expect(
|
|
184
|
+
we.requestSignAndBroadcast({
|
|
185
|
+
tx: TX_OK,
|
|
186
|
+
policy: { ...POLICY, simulationRequired: false },
|
|
187
|
+
wallet: WALLET,
|
|
188
|
+
}),
|
|
189
|
+
).rejects.toThrow(/approval denied/);
|
|
190
|
+
expect(signedCalls).toBe(0);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("automated signing skips the approval resolver", async () => {
|
|
194
|
+
let approvalCalls = 0;
|
|
195
|
+
const we = createWalletEngine({
|
|
196
|
+
resolveAdapter: () =>
|
|
197
|
+
fakeAdapter((method) =>
|
|
198
|
+
method === "eth_getTransactionReceipt" ? { blockNumber: "0x100", status: "0x1" } : "0x",
|
|
199
|
+
),
|
|
200
|
+
approve: async () => {
|
|
201
|
+
approvalCalls += 1;
|
|
202
|
+
return "allow";
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
we.registerCustody(createLocalSignerStub());
|
|
206
|
+
await we.requestSignAndBroadcast({
|
|
207
|
+
tx: TX_OK,
|
|
208
|
+
policy: { ...POLICY, defaultWriteApproval: "policy", simulationRequired: false },
|
|
209
|
+
wallet: { ...WALLET, signingPolicy: "automated" },
|
|
210
|
+
});
|
|
211
|
+
expect(approvalCalls).toBe(0);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
describe("createWalletEngine — missing wiring", () => {
|
|
216
|
+
test("throws when no adapter for chainId", async () => {
|
|
217
|
+
const we = createWalletEngine({
|
|
218
|
+
resolveAdapter: () => undefined,
|
|
219
|
+
approve: async () => "allow",
|
|
220
|
+
});
|
|
221
|
+
we.registerCustody(createLocalSignerStub());
|
|
222
|
+
await expect(
|
|
223
|
+
we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET }),
|
|
224
|
+
).rejects.toThrow(/no chain adapter registered/);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test("throws when no custody provider for wallet.custody", async () => {
|
|
228
|
+
const we = createWalletEngine({
|
|
229
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
230
|
+
approve: async () => "allow",
|
|
231
|
+
});
|
|
232
|
+
// Note: no registerCustody() call.
|
|
233
|
+
await expect(
|
|
234
|
+
we.requestSignAndBroadcast({
|
|
235
|
+
tx: TX_OK,
|
|
236
|
+
policy: { ...POLICY, simulationRequired: false },
|
|
237
|
+
wallet: WALLET,
|
|
238
|
+
}),
|
|
239
|
+
).rejects.toThrow(/no CustodyProvider registered/);
|
|
240
|
+
});
|
|
241
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { type BoundaryResult, classifyBoundary } from "@crewhaus/boundary-classifier";
|
|
2
|
+
import type { ChainAdapter } from "@crewhaus/chain-adapter-base";
|
|
3
|
+
/**
|
|
4
|
+
* Section 47 — `wallet-engine`.
|
|
5
|
+
*
|
|
6
|
+
* Custody and sign-request orchestration. Every destructive transaction
|
|
7
|
+
* routes through `requestSignAndBroadcast()`, which:
|
|
8
|
+
*
|
|
9
|
+
* 1. Routes the unsigned transaction through `simulate()` when the
|
|
10
|
+
* transaction-policy block requires it (default: yes).
|
|
11
|
+
* 2. Enforces the static-checkable pieces of the policy (allowed
|
|
12
|
+
* contracts, max-value, simulationRequired). Mismatches throw
|
|
13
|
+
* before any approval prompt or key access.
|
|
14
|
+
* 3. Hands the signing request to a `CustodyProvider` keyed by the
|
|
15
|
+
* wallet's `custody` value (user-controlled / kms / hsm / local).
|
|
16
|
+
* 4. Broadcasts the signed transaction through the chain adapter and
|
|
17
|
+
* classifies the receipt with `origin: "chain"` before returning.
|
|
18
|
+
*
|
|
19
|
+
* Catalog layer: R8 (permission / policy / safety) — adjacent to
|
|
20
|
+
* `permission-engine`. Slice 1 surface; non-EVM custody adapters are
|
|
21
|
+
* deferred.
|
|
22
|
+
*
|
|
23
|
+
* Pillar 3 contract: every `simulate()` result, every receipt, and any
|
|
24
|
+
* peer-signed attestation forwarded by an external signer SHALL pass
|
|
25
|
+
* through `classifyBoundary({ origin: "chain" })` before reaching the
|
|
26
|
+
* model context. The wallet-engine implements this on every read path;
|
|
27
|
+
* custody adapters that read peer signatures must call it themselves.
|
|
28
|
+
*/
|
|
29
|
+
import { CrewhausError } from "@crewhaus/errors";
|
|
30
|
+
|
|
31
|
+
export class WalletEngineError extends CrewhausError {
|
|
32
|
+
override readonly name = "WalletEngineError";
|
|
33
|
+
readonly walletId: string;
|
|
34
|
+
|
|
35
|
+
constructor(walletId: string, message: string, cause?: unknown) {
|
|
36
|
+
super("config", `[wallet ${walletId}] ${message}`, cause);
|
|
37
|
+
this.walletId = walletId;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Static configuration for a wallet binding, lowered from IR. The
|
|
43
|
+
* runtime constructs one of these per `IrWalletBinding` at boot.
|
|
44
|
+
*/
|
|
45
|
+
export type WalletConfig = {
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly chainId: string;
|
|
48
|
+
readonly custody: "user-controlled" | "kms" | "hsm" | "local";
|
|
49
|
+
readonly signingPolicy: "explicit-user-approval" | "policy-gated" | "automated";
|
|
50
|
+
/**
|
|
51
|
+
* Optional secret reference. Required for `kms` / `hsm` / `local`
|
|
52
|
+
* custody (the key id / handle / path); omitted for
|
|
53
|
+
* `user-controlled` (WalletConnect, MetaMask, etc.) where signing
|
|
54
|
+
* happens externally.
|
|
55
|
+
*/
|
|
56
|
+
readonly keyRef?: string;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Mirrors `IrTransactionPolicy`. Carried alongside the wallet because
|
|
61
|
+
* a single bundle may declare one policy that applies to every wallet.
|
|
62
|
+
* The IR pass (slice 1 `transactionPolicyEnforcement`) validates that
|
|
63
|
+
* `allowedContracts` references declared contracts; the wallet-engine
|
|
64
|
+
* enforces it again at runtime as a defense-in-depth check.
|
|
65
|
+
*/
|
|
66
|
+
export type TransactionPolicy = {
|
|
67
|
+
readonly defaultWriteApproval: "required" | "policy" | "none";
|
|
68
|
+
readonly maxValueUsd?: number;
|
|
69
|
+
readonly allowedContracts: readonly string[];
|
|
70
|
+
readonly simulationRequired: boolean;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The unsigned-transaction shape the wallet-engine accepts. Generic
|
|
75
|
+
* over EVM today; the `chainId` field steers the right adapter.
|
|
76
|
+
*
|
|
77
|
+
* `contractId` is the spec-level binding id (from `contracts[]`),
|
|
78
|
+
* resolved into `to` (address) by the caller. Carrying both lets the
|
|
79
|
+
* policy engine compare against `allowedContracts` symbolically rather
|
|
80
|
+
* than by raw address (less brittle when contracts get redeployed).
|
|
81
|
+
*/
|
|
82
|
+
export type UnsignedTx = {
|
|
83
|
+
readonly chainId: string;
|
|
84
|
+
readonly walletId: string;
|
|
85
|
+
readonly contractId?: string;
|
|
86
|
+
readonly to: string;
|
|
87
|
+
/** Hex-encoded calldata, 0x-prefixed. */
|
|
88
|
+
readonly data: string;
|
|
89
|
+
/** Hex-encoded native-token value (wei), 0x-prefixed. Defaults to "0x0". */
|
|
90
|
+
readonly value?: string;
|
|
91
|
+
/** Optional gas limit (hex). Adapter estimates if omitted. */
|
|
92
|
+
readonly gasLimit?: string;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Simulation result. Conservatively typed — real adapters surface
|
|
97
|
+
* decoded balance deltas, permission deltas, etc. Slice 1 carries
|
|
98
|
+
* the minimum payload the approval prompt needs.
|
|
99
|
+
*/
|
|
100
|
+
export type SimulationResult = {
|
|
101
|
+
readonly success: boolean;
|
|
102
|
+
readonly gasUsed: string;
|
|
103
|
+
readonly returnData?: string;
|
|
104
|
+
/** Adapter-decoded error string when `success === false`. */
|
|
105
|
+
readonly revertReason?: string;
|
|
106
|
+
/**
|
|
107
|
+
* Boundary verdict on the simulator's raw response. Always present.
|
|
108
|
+
* Callers that promote sim output into the model context use this
|
|
109
|
+
* to decide whether to redact.
|
|
110
|
+
*/
|
|
111
|
+
readonly boundary: BoundaryResult;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Receipt of a broadcast transaction. Same Pillar 3 boundary wrap.
|
|
116
|
+
*/
|
|
117
|
+
export type BroadcastReceipt = {
|
|
118
|
+
readonly txHash: string;
|
|
119
|
+
/**
|
|
120
|
+
* Block number the transaction landed in. `null` while pending; the
|
|
121
|
+
* caller polls with `EvmGetTransactionReceipt` to wait for finality.
|
|
122
|
+
*/
|
|
123
|
+
readonly blockNumber: string | null;
|
|
124
|
+
readonly status: "0x0" | "0x1" | null;
|
|
125
|
+
readonly boundary: BoundaryResult;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The approval gate. Slice 1 ships an in-process resolver that the
|
|
130
|
+
* runtime wires to the §7 permission engine (or the CLI HITL prompt
|
|
131
|
+
* for `default` mode). Tests provide a deterministic resolver.
|
|
132
|
+
*/
|
|
133
|
+
export type ApprovalDecision = "allow" | "deny";
|
|
134
|
+
export type ApprovalRequest = {
|
|
135
|
+
readonly walletId: string;
|
|
136
|
+
readonly chainId: string;
|
|
137
|
+
readonly tx: UnsignedTx;
|
|
138
|
+
readonly simulation?: SimulationResult;
|
|
139
|
+
readonly reason: string;
|
|
140
|
+
};
|
|
141
|
+
export type ApprovalResolver = (req: ApprovalRequest) => Promise<ApprovalDecision>;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Custody adapter — abstracts the signing primitive across user-
|
|
145
|
+
* controlled wallets, KMS, HSM, and local-key custody. Slice 1 ships
|
|
146
|
+
* the interface plus a `LocalSignerStub` for tests; real KMS / HSM
|
|
147
|
+
* integrations are follow-up packages.
|
|
148
|
+
*/
|
|
149
|
+
export interface CustodyProvider {
|
|
150
|
+
readonly custody: WalletConfig["custody"];
|
|
151
|
+
/**
|
|
152
|
+
* Sign + broadcast. The provider is responsible for whatever
|
|
153
|
+
* external loop the custody type requires (WalletConnect QR scan,
|
|
154
|
+
* KMS signRequest, HSM PKCS#11 call, local-key signing). Returns
|
|
155
|
+
* the raw tx hash; the wallet-engine wraps it in a `BroadcastReceipt`.
|
|
156
|
+
*/
|
|
157
|
+
signAndBroadcast(args: {
|
|
158
|
+
readonly tx: UnsignedTx;
|
|
159
|
+
readonly walletConfig: WalletConfig;
|
|
160
|
+
readonly adapter: ChainAdapter;
|
|
161
|
+
}): Promise<string>;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The slice-1 wallet engine. Construct one per bundle; register one
|
|
166
|
+
* custody provider per custody kind in use; resolve adapters from the
|
|
167
|
+
* `chains[]` block via the supplied resolver.
|
|
168
|
+
*/
|
|
169
|
+
export type WalletEngine = {
|
|
170
|
+
readonly registerCustody: (provider: CustodyProvider) => void;
|
|
171
|
+
readonly requestSignAndBroadcast: (args: {
|
|
172
|
+
readonly tx: UnsignedTx;
|
|
173
|
+
readonly policy: TransactionPolicy;
|
|
174
|
+
readonly wallet: WalletConfig;
|
|
175
|
+
}) => Promise<BroadcastReceipt>;
|
|
176
|
+
readonly simulate: (args: {
|
|
177
|
+
readonly tx: UnsignedTx;
|
|
178
|
+
}) => Promise<SimulationResult>;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export type WalletEngineOptions = {
|
|
182
|
+
readonly resolveAdapter: (chainId: string) => ChainAdapter | undefined;
|
|
183
|
+
readonly approve: ApprovalResolver;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export function createWalletEngine(opts: WalletEngineOptions): WalletEngine {
|
|
187
|
+
const custodies = new Map<WalletConfig["custody"], CustodyProvider>();
|
|
188
|
+
|
|
189
|
+
function requireAdapter(chainId: string, walletId: string): ChainAdapter {
|
|
190
|
+
const a = opts.resolveAdapter(chainId);
|
|
191
|
+
if (a === undefined) {
|
|
192
|
+
throw new WalletEngineError(
|
|
193
|
+
walletId,
|
|
194
|
+
`no chain adapter registered for chainId "${chainId}". Declare it in spec.chains[].`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return a;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function simulate(args: { tx: UnsignedTx }): Promise<SimulationResult> {
|
|
201
|
+
const adapter = requireAdapter(args.tx.chainId, args.tx.walletId);
|
|
202
|
+
const callParams: Record<string, unknown> = {
|
|
203
|
+
to: args.tx.to,
|
|
204
|
+
data: args.tx.data,
|
|
205
|
+
};
|
|
206
|
+
if (args.tx.value !== undefined) callParams["value"] = args.tx.value;
|
|
207
|
+
// Prefer eth_call for state-read; fall back to estimateGas for revert detection.
|
|
208
|
+
let returnData: string | undefined;
|
|
209
|
+
let success = true;
|
|
210
|
+
let revertReason: string | undefined;
|
|
211
|
+
let raw = "";
|
|
212
|
+
try {
|
|
213
|
+
const callResult = await adapter.rpcRead("eth_call", [callParams, "latest"]);
|
|
214
|
+
returnData = typeof callResult === "string" ? callResult : undefined;
|
|
215
|
+
raw = JSON.stringify({ kind: "call", result: callResult });
|
|
216
|
+
} catch (err) {
|
|
217
|
+
success = false;
|
|
218
|
+
revertReason = (err as Error).message;
|
|
219
|
+
raw = JSON.stringify({ kind: "revert", message: revertReason });
|
|
220
|
+
}
|
|
221
|
+
let gasUsed = "0x0";
|
|
222
|
+
if (success) {
|
|
223
|
+
try {
|
|
224
|
+
const est = await adapter.rpcRead("eth_estimateGas", [callParams]);
|
|
225
|
+
if (typeof est === "string") gasUsed = est;
|
|
226
|
+
} catch {
|
|
227
|
+
/* tolerate — gasUsed stays 0x0 */
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const boundary = await classifyBoundary(raw, { origin: "chain" });
|
|
231
|
+
return {
|
|
232
|
+
success,
|
|
233
|
+
gasUsed,
|
|
234
|
+
...(returnData !== undefined ? { returnData } : {}),
|
|
235
|
+
...(revertReason !== undefined ? { revertReason } : {}),
|
|
236
|
+
boundary,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function enforceStaticPolicy(tx: UnsignedTx, policy: TransactionPolicy): void {
|
|
241
|
+
// `allowedContracts` empty == every declared contract permitted; non-empty
|
|
242
|
+
// means contractId must be in the list. Raw-address calls (no contractId)
|
|
243
|
+
// are always rejected when the list is non-empty: the spec author must
|
|
244
|
+
// declare every callable contract symbolically.
|
|
245
|
+
if (policy.allowedContracts.length > 0) {
|
|
246
|
+
if (tx.contractId === undefined) {
|
|
247
|
+
throw new WalletEngineError(
|
|
248
|
+
tx.walletId,
|
|
249
|
+
`transaction_policy.allowedContracts is non-empty; raw-address calls forbidden (to=${tx.to}). Declare a contracts[] entry and pass its id.`,
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
if (!policy.allowedContracts.includes(tx.contractId)) {
|
|
253
|
+
throw new WalletEngineError(
|
|
254
|
+
tx.walletId,
|
|
255
|
+
`contract id "${tx.contractId}" not in transaction_policy.allowedContracts ${JSON.stringify(policy.allowedContracts)}`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
// `none` (defaultWriteApproval) is only valid under `automated` custody —
|
|
260
|
+
// documented invariant. The runtime layers that allow this combo perform
|
|
261
|
+
// a stronger check at boot; this layer just rejects the obvious misuse.
|
|
262
|
+
if (policy.defaultWriteApproval === "none") {
|
|
263
|
+
// We can't read wallet custody from here without the wallet arg; the
|
|
264
|
+
// caller passes the wallet — see requestSignAndBroadcast below.
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function requestSignAndBroadcast(args: {
|
|
269
|
+
tx: UnsignedTx;
|
|
270
|
+
policy: TransactionPolicy;
|
|
271
|
+
wallet: WalletConfig;
|
|
272
|
+
}): Promise<BroadcastReceipt> {
|
|
273
|
+
if (args.tx.walletId !== args.wallet.id) {
|
|
274
|
+
throw new WalletEngineError(
|
|
275
|
+
args.wallet.id,
|
|
276
|
+
`tx.walletId "${args.tx.walletId}" does not match wallet.id "${args.wallet.id}"`,
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
if (args.tx.chainId !== args.wallet.chainId) {
|
|
280
|
+
throw new WalletEngineError(
|
|
281
|
+
args.wallet.id,
|
|
282
|
+
`tx.chainId "${args.tx.chainId}" does not match wallet.chainId "${args.wallet.chainId}"`,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
enforceStaticPolicy(args.tx, args.policy);
|
|
286
|
+
if (args.policy.defaultWriteApproval === "none" && args.wallet.signingPolicy !== "automated") {
|
|
287
|
+
throw new WalletEngineError(
|
|
288
|
+
args.wallet.id,
|
|
289
|
+
`transaction_policy.defaultWriteApproval="none" requires signingPolicy="automated" (got "${args.wallet.signingPolicy}")`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const adapter = requireAdapter(args.tx.chainId, args.wallet.id);
|
|
294
|
+
|
|
295
|
+
let sim: SimulationResult | undefined;
|
|
296
|
+
if (args.policy.simulationRequired) {
|
|
297
|
+
sim = await simulate({ tx: args.tx });
|
|
298
|
+
if (!sim.success) {
|
|
299
|
+
throw new WalletEngineError(
|
|
300
|
+
args.wallet.id,
|
|
301
|
+
`simulation failed: ${sim.revertReason ?? "(no revert reason)"}; transaction_policy.simulationRequired=true and simulation must succeed before approval`,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Approval gate. `policy-gated` defers to the resolver's own
|
|
307
|
+
// adjudication; `explicit-user-approval` always prompts;
|
|
308
|
+
// `automated` skips the resolver entirely.
|
|
309
|
+
const needApproval =
|
|
310
|
+
args.wallet.signingPolicy !== "automated" || args.policy.defaultWriteApproval === "required";
|
|
311
|
+
if (needApproval) {
|
|
312
|
+
const decision = await opts.approve({
|
|
313
|
+
walletId: args.wallet.id,
|
|
314
|
+
chainId: args.tx.chainId,
|
|
315
|
+
tx: args.tx,
|
|
316
|
+
...(sim !== undefined ? { simulation: sim } : {}),
|
|
317
|
+
reason: `sign ${args.tx.data.length > 10 ? `${args.tx.data.slice(0, 10)}…` : args.tx.data} to ${args.tx.to} on ${args.tx.chainId}`,
|
|
318
|
+
});
|
|
319
|
+
if (decision !== "allow") {
|
|
320
|
+
throw new WalletEngineError(args.wallet.id, "approval denied; transaction not broadcast");
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const provider = custodies.get(args.wallet.custody);
|
|
325
|
+
if (provider === undefined) {
|
|
326
|
+
throw new WalletEngineError(
|
|
327
|
+
args.wallet.id,
|
|
328
|
+
`no CustodyProvider registered for custody="${args.wallet.custody}". Call registerCustody() at boot.`,
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
const txHash = await provider.signAndBroadcast({
|
|
332
|
+
tx: args.tx,
|
|
333
|
+
walletConfig: args.wallet,
|
|
334
|
+
adapter,
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
// Fetch the receipt for the caller. Receipts may be null when the
|
|
338
|
+
// tx is still pending; the receipt-poll loop is the caller's concern.
|
|
339
|
+
let receiptRaw: unknown;
|
|
340
|
+
try {
|
|
341
|
+
receiptRaw = await adapter.rpcRead("eth_getTransactionReceipt", [txHash]);
|
|
342
|
+
} catch {
|
|
343
|
+
receiptRaw = null;
|
|
344
|
+
}
|
|
345
|
+
const boundary = await classifyBoundary(JSON.stringify(receiptRaw ?? null), {
|
|
346
|
+
origin: "chain",
|
|
347
|
+
});
|
|
348
|
+
if (receiptRaw === null || typeof receiptRaw !== "object") {
|
|
349
|
+
return { txHash, blockNumber: null, status: null, boundary };
|
|
350
|
+
}
|
|
351
|
+
const r = receiptRaw as Record<string, unknown>;
|
|
352
|
+
const blockNumber = typeof r["blockNumber"] === "string" ? (r["blockNumber"] as string) : null;
|
|
353
|
+
const statusRaw = r["status"];
|
|
354
|
+
const status = statusRaw === "0x0" || statusRaw === "0x1" ? (statusRaw as "0x0" | "0x1") : null;
|
|
355
|
+
return { txHash, blockNumber, status, boundary };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return {
|
|
359
|
+
registerCustody(provider) {
|
|
360
|
+
custodies.set(provider.custody, provider);
|
|
361
|
+
},
|
|
362
|
+
requestSignAndBroadcast,
|
|
363
|
+
simulate,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Test-only custody stub. Implements the `local` custody kind with a
|
|
369
|
+
* deterministic tx-hash mint. Real implementations live in follow-up
|
|
370
|
+
* packages (`wallet-custody-kms`, `wallet-custody-wc`, etc.).
|
|
371
|
+
*/
|
|
372
|
+
export function createLocalSignerStub(): CustodyProvider {
|
|
373
|
+
let nonce = 0;
|
|
374
|
+
return {
|
|
375
|
+
custody: "local",
|
|
376
|
+
async signAndBroadcast({ tx }) {
|
|
377
|
+
nonce += 1;
|
|
378
|
+
// Deterministic hash for tests: hex of walletId|chainId|nonce.
|
|
379
|
+
const seed = `${tx.walletId}:${tx.chainId}:${nonce}`;
|
|
380
|
+
const bytes = new TextEncoder().encode(seed);
|
|
381
|
+
let acc = 0n;
|
|
382
|
+
for (const b of bytes) acc = (acc * 31n + BigInt(b)) & ((1n << 256n) - 1n);
|
|
383
|
+
return `0x${acc.toString(16).padStart(64, "0")}`;
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
}
|