@crewhaus/wallet-engine 0.1.4 → 0.1.5
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/dist/index.d.ts +199 -0
- package/dist/index.js +266 -0
- package/package.json +11 -8
- package/src/index.test.ts +0 -369
- package/src/index.ts +0 -489
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { type BoundaryResult } 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
|
+
export declare class WalletEngineError extends CrewhausError {
|
|
31
|
+
readonly name = "WalletEngineError";
|
|
32
|
+
readonly walletId: string;
|
|
33
|
+
constructor(walletId: string, message: string, cause?: unknown);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Static configuration for a wallet binding, lowered from IR. The
|
|
37
|
+
* runtime constructs one of these per `IrWalletBinding` at boot.
|
|
38
|
+
*/
|
|
39
|
+
export type WalletConfig = {
|
|
40
|
+
readonly id: string;
|
|
41
|
+
readonly chainId: string;
|
|
42
|
+
readonly custody: "user-controlled" | "kms" | "hsm" | "local";
|
|
43
|
+
readonly signingPolicy: "explicit-user-approval" | "policy-gated" | "automated";
|
|
44
|
+
/**
|
|
45
|
+
* Optional secret reference. Required for `kms` / `hsm` / `local`
|
|
46
|
+
* custody (the key id / handle / path); omitted for
|
|
47
|
+
* `user-controlled` (WalletConnect, MetaMask, etc.) where signing
|
|
48
|
+
* happens externally.
|
|
49
|
+
*/
|
|
50
|
+
readonly keyRef?: string;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Mirrors `IrTransactionPolicy`. Carried alongside the wallet because
|
|
54
|
+
* a single bundle may declare one policy that applies to every wallet.
|
|
55
|
+
* The IR pass (slice 1 `transactionPolicyEnforcement`) validates that
|
|
56
|
+
* `allowedContracts` references declared contracts; the wallet-engine
|
|
57
|
+
* enforces it again at runtime as a defense-in-depth check.
|
|
58
|
+
*/
|
|
59
|
+
export type TransactionPolicy = {
|
|
60
|
+
readonly defaultWriteApproval: "required" | "policy" | "none";
|
|
61
|
+
readonly maxValueUsd?: number;
|
|
62
|
+
/**
|
|
63
|
+
* Native-token value ceiling in wei (decimal or 0x-hex). Oracle-free and
|
|
64
|
+
* enforced pre-broadcast (#152).
|
|
65
|
+
*/
|
|
66
|
+
readonly maxValueWei?: string;
|
|
67
|
+
readonly allowedContracts: readonly string[];
|
|
68
|
+
/**
|
|
69
|
+
* Resolved `contractId` → address map. When present, `tx.to` is bound to the
|
|
70
|
+
* address registered for `tx.contractId`, so a whitelisted id cannot be used
|
|
71
|
+
* to send to an arbitrary address (#151). The runtime should populate this
|
|
72
|
+
* from the spec's `contracts[]`; the stronger long-term fix is to drop `to`
|
|
73
|
+
* from the tool input entirely and resolve it from `contractId` here.
|
|
74
|
+
*/
|
|
75
|
+
readonly contractAddresses?: Readonly<Record<string, string>>;
|
|
76
|
+
readonly simulationRequired: boolean;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* The unsigned-transaction shape the wallet-engine accepts. Generic
|
|
80
|
+
* over EVM today; the `chainId` field steers the right adapter.
|
|
81
|
+
*
|
|
82
|
+
* `contractId` is the spec-level binding id (from `contracts[]`),
|
|
83
|
+
* resolved into `to` (address) by the caller. Carrying both lets the
|
|
84
|
+
* policy engine compare against `allowedContracts` symbolically rather
|
|
85
|
+
* than by raw address (less brittle when contracts get redeployed).
|
|
86
|
+
*/
|
|
87
|
+
export type UnsignedTx = {
|
|
88
|
+
readonly chainId: string;
|
|
89
|
+
readonly walletId: string;
|
|
90
|
+
readonly contractId?: string;
|
|
91
|
+
readonly to: string;
|
|
92
|
+
/** Hex-encoded calldata, 0x-prefixed. */
|
|
93
|
+
readonly data: string;
|
|
94
|
+
/** Hex-encoded native-token value (wei), 0x-prefixed. Defaults to "0x0". */
|
|
95
|
+
readonly value?: string;
|
|
96
|
+
/** Optional gas limit (hex). Adapter estimates if omitted. */
|
|
97
|
+
readonly gasLimit?: string;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Simulation result. Conservatively typed — real adapters surface
|
|
101
|
+
* decoded balance deltas, permission deltas, etc. Slice 1 carries
|
|
102
|
+
* the minimum payload the approval prompt needs.
|
|
103
|
+
*/
|
|
104
|
+
export type SimulationResult = {
|
|
105
|
+
readonly success: boolean;
|
|
106
|
+
readonly gasUsed: string;
|
|
107
|
+
readonly returnData?: string;
|
|
108
|
+
/** Adapter-decoded error string when `success === false`. */
|
|
109
|
+
readonly revertReason?: string;
|
|
110
|
+
/**
|
|
111
|
+
* Boundary verdict on the simulator's raw response. Always present.
|
|
112
|
+
* Callers that promote sim output into the model context use this
|
|
113
|
+
* to decide whether to redact.
|
|
114
|
+
*/
|
|
115
|
+
readonly boundary: BoundaryResult;
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* Receipt of a broadcast transaction. Same Pillar 3 boundary wrap.
|
|
119
|
+
*/
|
|
120
|
+
export type BroadcastReceipt = {
|
|
121
|
+
readonly txHash: string;
|
|
122
|
+
/**
|
|
123
|
+
* Block number the transaction landed in. `null` while pending; the
|
|
124
|
+
* caller polls with `EvmGetTransactionReceipt` to wait for finality.
|
|
125
|
+
*/
|
|
126
|
+
readonly blockNumber: string | null;
|
|
127
|
+
readonly status: "0x0" | "0x1" | null;
|
|
128
|
+
readonly boundary: BoundaryResult;
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* The approval gate. Slice 1 ships an in-process resolver that the
|
|
132
|
+
* runtime wires to the §7 permission engine (or the CLI HITL prompt
|
|
133
|
+
* for `default` mode). Tests provide a deterministic resolver.
|
|
134
|
+
*/
|
|
135
|
+
export type ApprovalDecision = "allow" | "deny";
|
|
136
|
+
export type ApprovalRequest = {
|
|
137
|
+
readonly walletId: string;
|
|
138
|
+
readonly chainId: string;
|
|
139
|
+
readonly tx: UnsignedTx;
|
|
140
|
+
readonly simulation?: SimulationResult;
|
|
141
|
+
readonly reason: string;
|
|
142
|
+
};
|
|
143
|
+
export type ApprovalResolver = (req: ApprovalRequest) => Promise<ApprovalDecision>;
|
|
144
|
+
/**
|
|
145
|
+
* Custody adapter — abstracts the signing primitive across user-
|
|
146
|
+
* controlled wallets, KMS, HSM, and local-key custody. Slice 1 ships
|
|
147
|
+
* the interface plus a `LocalSignerStub` for tests; real KMS / HSM
|
|
148
|
+
* integrations are follow-up packages.
|
|
149
|
+
*/
|
|
150
|
+
export interface CustodyProvider {
|
|
151
|
+
readonly custody: WalletConfig["custody"];
|
|
152
|
+
/**
|
|
153
|
+
* Sign + broadcast. The provider is responsible for whatever
|
|
154
|
+
* external loop the custody type requires (WalletConnect QR scan,
|
|
155
|
+
* KMS signRequest, HSM PKCS#11 call, local-key signing). Returns
|
|
156
|
+
* the raw tx hash; the wallet-engine wraps it in a `BroadcastReceipt`.
|
|
157
|
+
*/
|
|
158
|
+
signAndBroadcast(args: {
|
|
159
|
+
readonly tx: UnsignedTx;
|
|
160
|
+
readonly walletConfig: WalletConfig;
|
|
161
|
+
readonly adapter: ChainAdapter;
|
|
162
|
+
}): Promise<string>;
|
|
163
|
+
/**
|
|
164
|
+
* Optional: the wallet's on-chain address, used as `from` in pre-broadcast
|
|
165
|
+
* simulation so msg.sender-dependent / access-controlled calls (onlyOwner,
|
|
166
|
+
* etc.) are modeled as the REAL signer rather than address(0). When a
|
|
167
|
+
* provider can't (or won't) expose the address ahead of signing, simulation
|
|
168
|
+
* falls back to no `from` — accurate for stateless calls, best-effort
|
|
169
|
+
* otherwise.
|
|
170
|
+
*/
|
|
171
|
+
getAddress?(walletConfig: WalletConfig): Promise<string | undefined>;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The slice-1 wallet engine. Construct one per bundle; register one
|
|
175
|
+
* custody provider per custody kind in use; resolve adapters from the
|
|
176
|
+
* `chains[]` block via the supplied resolver.
|
|
177
|
+
*/
|
|
178
|
+
export type WalletEngine = {
|
|
179
|
+
readonly registerCustody: (provider: CustodyProvider) => void;
|
|
180
|
+
readonly requestSignAndBroadcast: (args: {
|
|
181
|
+
readonly tx: UnsignedTx;
|
|
182
|
+
readonly policy: TransactionPolicy;
|
|
183
|
+
readonly wallet: WalletConfig;
|
|
184
|
+
}) => Promise<BroadcastReceipt>;
|
|
185
|
+
readonly simulate: (args: {
|
|
186
|
+
readonly tx: UnsignedTx;
|
|
187
|
+
}) => Promise<SimulationResult>;
|
|
188
|
+
};
|
|
189
|
+
export type WalletEngineOptions = {
|
|
190
|
+
readonly resolveAdapter: (chainId: string) => ChainAdapter | undefined;
|
|
191
|
+
readonly approve: ApprovalResolver;
|
|
192
|
+
};
|
|
193
|
+
export declare function createWalletEngine(opts: WalletEngineOptions): WalletEngine;
|
|
194
|
+
/**
|
|
195
|
+
* Test-only custody stub. Implements the `local` custody kind with a
|
|
196
|
+
* deterministic tx-hash mint. Real implementations live in follow-up
|
|
197
|
+
* packages (`wallet-custody-kms`, `wallet-custody-wc`, etc.).
|
|
198
|
+
*/
|
|
199
|
+
export declare function createLocalSignerStub(): CustodyProvider;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { classifyBoundary } from "@crewhaus/boundary-classifier";
|
|
2
|
+
/**
|
|
3
|
+
* Section 47 — `wallet-engine`.
|
|
4
|
+
*
|
|
5
|
+
* Custody and sign-request orchestration. Every destructive transaction
|
|
6
|
+
* routes through `requestSignAndBroadcast()`, which:
|
|
7
|
+
*
|
|
8
|
+
* 1. Routes the unsigned transaction through `simulate()` when the
|
|
9
|
+
* transaction-policy block requires it (default: yes).
|
|
10
|
+
* 2. Enforces the static-checkable pieces of the policy (allowed
|
|
11
|
+
* contracts, max-value, simulationRequired). Mismatches throw
|
|
12
|
+
* before any approval prompt or key access.
|
|
13
|
+
* 3. Hands the signing request to a `CustodyProvider` keyed by the
|
|
14
|
+
* wallet's `custody` value (user-controlled / kms / hsm / local).
|
|
15
|
+
* 4. Broadcasts the signed transaction through the chain adapter and
|
|
16
|
+
* classifies the receipt with `origin: "chain"` before returning.
|
|
17
|
+
*
|
|
18
|
+
* Catalog layer: R8 (permission / policy / safety) — adjacent to
|
|
19
|
+
* `permission-engine`. Slice 1 surface; non-EVM custody adapters are
|
|
20
|
+
* deferred.
|
|
21
|
+
*
|
|
22
|
+
* Pillar 3 contract: every `simulate()` result, every receipt, and any
|
|
23
|
+
* peer-signed attestation forwarded by an external signer SHALL pass
|
|
24
|
+
* through `classifyBoundary({ origin: "chain" })` before reaching the
|
|
25
|
+
* model context. The wallet-engine implements this on every read path;
|
|
26
|
+
* custody adapters that read peer signatures must call it themselves.
|
|
27
|
+
*/
|
|
28
|
+
import { CrewhausError } from "@crewhaus/errors";
|
|
29
|
+
export class WalletEngineError extends CrewhausError {
|
|
30
|
+
name = "WalletEngineError";
|
|
31
|
+
walletId;
|
|
32
|
+
constructor(walletId, message, cause) {
|
|
33
|
+
super("config", `[wallet ${walletId}] ${message}`, cause);
|
|
34
|
+
this.walletId = walletId;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Parse a wei amount expressed as a decimal or 0x-hex string. Throws a
|
|
39
|
+
* WalletEngineError (fail-closed) on a malformed value.
|
|
40
|
+
*/
|
|
41
|
+
function parseWei(walletId, label, v) {
|
|
42
|
+
try {
|
|
43
|
+
return BigInt(v.trim());
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
throw new WalletEngineError(walletId, `invalid ${label} "${v}" (expected wei as a decimal or 0x-hex string)`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function createWalletEngine(opts) {
|
|
50
|
+
const custodies = new Map();
|
|
51
|
+
function requireAdapter(chainId, walletId) {
|
|
52
|
+
const a = opts.resolveAdapter(chainId);
|
|
53
|
+
if (a === undefined) {
|
|
54
|
+
throw new WalletEngineError(walletId, `no chain adapter registered for chainId "${chainId}". Declare it in spec.chains[].`);
|
|
55
|
+
}
|
|
56
|
+
return a;
|
|
57
|
+
}
|
|
58
|
+
async function simulate(args) {
|
|
59
|
+
const adapter = requireAdapter(args.tx.chainId, args.tx.walletId);
|
|
60
|
+
const callParams = {
|
|
61
|
+
to: args.tx.to,
|
|
62
|
+
data: args.tx.data,
|
|
63
|
+
};
|
|
64
|
+
// Run the eth_call AS the signing wallet (not address(0)) so onlyOwner /
|
|
65
|
+
// msg.sender-dependent logic is modeled faithfully — otherwise a
|
|
66
|
+
// simulationRequired pre-flight gives false assurance.
|
|
67
|
+
if (args.from !== undefined)
|
|
68
|
+
callParams["from"] = args.from;
|
|
69
|
+
if (args.tx.value !== undefined)
|
|
70
|
+
callParams["value"] = args.tx.value;
|
|
71
|
+
// Prefer eth_call for state-read; fall back to estimateGas for revert detection.
|
|
72
|
+
let returnData;
|
|
73
|
+
let success = true;
|
|
74
|
+
let revertReason;
|
|
75
|
+
let raw = "";
|
|
76
|
+
try {
|
|
77
|
+
const callResult = await adapter.rpcRead("eth_call", [callParams, "latest"]);
|
|
78
|
+
returnData = typeof callResult === "string" ? callResult : undefined;
|
|
79
|
+
raw = JSON.stringify({ kind: "call", result: callResult });
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
success = false;
|
|
83
|
+
revertReason = err.message;
|
|
84
|
+
raw = JSON.stringify({ kind: "revert", message: revertReason });
|
|
85
|
+
}
|
|
86
|
+
let gasUsed = "0x0";
|
|
87
|
+
if (success) {
|
|
88
|
+
try {
|
|
89
|
+
const est = await adapter.rpcRead("eth_estimateGas", [callParams]);
|
|
90
|
+
if (typeof est === "string")
|
|
91
|
+
gasUsed = est;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
/* tolerate — gasUsed stays 0x0 */
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const boundary = await classifyBoundary(raw, { origin: "chain" });
|
|
98
|
+
return {
|
|
99
|
+
success,
|
|
100
|
+
gasUsed,
|
|
101
|
+
...(returnData !== undefined ? { returnData } : {}),
|
|
102
|
+
...(revertReason !== undefined ? { revertReason } : {}),
|
|
103
|
+
boundary,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function enforceStaticPolicy(tx, policy) {
|
|
107
|
+
// Fail CLOSED on an empty `allowedContracts`. Previously empty meant "allow
|
|
108
|
+
// every contract", so an onchain agent on the default policy (allowedContracts
|
|
109
|
+
// defaults to []) let a prompt-injected model send arbitrary calldata/value
|
|
110
|
+
// to ANY address — a wallet-drain primitive. Operators must now declare the
|
|
111
|
+
// callable contract ids in transaction_policy.allowedContracts to permit sends.
|
|
112
|
+
if (policy.allowedContracts.length === 0) {
|
|
113
|
+
throw new WalletEngineError(tx.walletId, "transaction_policy.allowedContracts is empty — sends are denied (fail-closed). Declare the callable contract ids in transaction_policy.allowedContracts (bound to addresses via contracts[]).");
|
|
114
|
+
}
|
|
115
|
+
// Non-empty: contractId must be present and whitelisted. Raw-address calls
|
|
116
|
+
// (no contractId) are rejected — the spec author must declare every callable
|
|
117
|
+
// contract symbolically.
|
|
118
|
+
if (tx.contractId === undefined) {
|
|
119
|
+
throw new WalletEngineError(tx.walletId, `transaction_policy.allowedContracts is non-empty; raw-address calls forbidden (to=${tx.to}). Declare a contracts[] entry and pass its id.`);
|
|
120
|
+
}
|
|
121
|
+
if (!policy.allowedContracts.includes(tx.contractId)) {
|
|
122
|
+
throw new WalletEngineError(tx.walletId, `contract id "${tx.contractId}" not in transaction_policy.allowedContracts ${JSON.stringify(policy.allowedContracts)}`);
|
|
123
|
+
}
|
|
124
|
+
// #151 — bind `to` to the claimed contractId. `allowedContracts` alone is a
|
|
125
|
+
// symbolic gate; without this an attacker can claim a whitelisted id and
|
|
126
|
+
// still send to an arbitrary address. When the resolved address map is
|
|
127
|
+
// present, `tx.to` MUST equal the address registered for `tx.contractId`.
|
|
128
|
+
if (tx.contractId !== undefined && policy.contractAddresses !== undefined) {
|
|
129
|
+
const expected = policy.contractAddresses[tx.contractId];
|
|
130
|
+
if (expected === undefined) {
|
|
131
|
+
throw new WalletEngineError(tx.walletId, `contract id "${tx.contractId}" has no resolved address in transaction_policy.contractAddresses`);
|
|
132
|
+
}
|
|
133
|
+
if (tx.to.toLowerCase() !== expected.toLowerCase()) {
|
|
134
|
+
throw new WalletEngineError(tx.walletId, `tx.to "${tx.to}" does not match the address ${expected} bound to contract id "${tx.contractId}"`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// #152 — value caps. maxValueWei is an oracle-free native ceiling enforced
|
|
138
|
+
// here. maxValueUsd cannot be enforced without a price oracle (none is
|
|
139
|
+
// wired in this build), so fail closed rather than give false assurance.
|
|
140
|
+
if (policy.maxValueWei !== undefined) {
|
|
141
|
+
const cap = parseWei(tx.walletId, "transaction_policy.maxValueWei", policy.maxValueWei);
|
|
142
|
+
const val = parseWei(tx.walletId, "tx.value", tx.value ?? "0x0");
|
|
143
|
+
if (val > cap) {
|
|
144
|
+
throw new WalletEngineError(tx.walletId, `tx value ${val} wei exceeds transaction_policy.maxValueWei (${cap} wei)`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (policy.maxValueUsd !== undefined) {
|
|
148
|
+
throw new WalletEngineError(tx.walletId, `transaction_policy.maxValueUsd (${policy.maxValueUsd}) cannot be enforced: USD value caps require a price oracle, which is not wired in this build. Use transaction_policy.maxValueWei for a native-token ceiling.`);
|
|
149
|
+
}
|
|
150
|
+
// `none` (defaultWriteApproval) is only valid under `automated` custody —
|
|
151
|
+
// documented invariant. The runtime layers that allow this combo perform
|
|
152
|
+
// a stronger check at boot; this layer just rejects the obvious misuse.
|
|
153
|
+
if (policy.defaultWriteApproval === "none") {
|
|
154
|
+
// We can't read wallet custody from here without the wallet arg; the
|
|
155
|
+
// caller passes the wallet — see requestSignAndBroadcast below.
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async function requestSignAndBroadcast(args) {
|
|
159
|
+
if (args.tx.walletId !== args.wallet.id) {
|
|
160
|
+
throw new WalletEngineError(args.wallet.id, `tx.walletId "${args.tx.walletId}" does not match wallet.id "${args.wallet.id}"`);
|
|
161
|
+
}
|
|
162
|
+
if (args.tx.chainId !== args.wallet.chainId) {
|
|
163
|
+
throw new WalletEngineError(args.wallet.id, `tx.chainId "${args.tx.chainId}" does not match wallet.chainId "${args.wallet.chainId}"`);
|
|
164
|
+
}
|
|
165
|
+
enforceStaticPolicy(args.tx, args.policy);
|
|
166
|
+
if (args.policy.defaultWriteApproval === "none" && args.wallet.signingPolicy !== "automated") {
|
|
167
|
+
throw new WalletEngineError(args.wallet.id, `transaction_policy.defaultWriteApproval="none" requires signingPolicy="automated" (got "${args.wallet.signingPolicy}")`);
|
|
168
|
+
}
|
|
169
|
+
const adapter = requireAdapter(args.tx.chainId, args.wallet.id);
|
|
170
|
+
let sim;
|
|
171
|
+
if (args.policy.simulationRequired) {
|
|
172
|
+
// Resolve the signer address (best-effort) so simulation runs as the
|
|
173
|
+
// real wallet, not address(0).
|
|
174
|
+
let fromAddress;
|
|
175
|
+
const custody = custodies.get(args.wallet.custody);
|
|
176
|
+
if (custody?.getAddress !== undefined) {
|
|
177
|
+
try {
|
|
178
|
+
fromAddress = await custody.getAddress(args.wallet);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
fromAddress = undefined;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
sim = await simulate({
|
|
185
|
+
tx: args.tx,
|
|
186
|
+
...(fromAddress !== undefined ? { from: fromAddress } : {}),
|
|
187
|
+
});
|
|
188
|
+
if (!sim.success) {
|
|
189
|
+
throw new WalletEngineError(args.wallet.id, `simulation failed: ${sim.revertReason ?? "(no revert reason)"}; transaction_policy.simulationRequired=true and simulation must succeed before approval`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Approval gate. `policy-gated` defers to the resolver's own
|
|
193
|
+
// adjudication; `explicit-user-approval` always prompts;
|
|
194
|
+
// `automated` skips the resolver entirely.
|
|
195
|
+
const needApproval = args.wallet.signingPolicy !== "automated" || args.policy.defaultWriteApproval === "required";
|
|
196
|
+
if (needApproval) {
|
|
197
|
+
const decision = await opts.approve({
|
|
198
|
+
walletId: args.wallet.id,
|
|
199
|
+
chainId: args.tx.chainId,
|
|
200
|
+
tx: args.tx,
|
|
201
|
+
...(sim !== undefined ? { simulation: sim } : {}),
|
|
202
|
+
reason: `sign ${args.tx.data.length > 10 ? `${args.tx.data.slice(0, 10)}…` : args.tx.data} to ${args.tx.to} on ${args.tx.chainId}`,
|
|
203
|
+
});
|
|
204
|
+
if (decision !== "allow") {
|
|
205
|
+
throw new WalletEngineError(args.wallet.id, "approval denied; transaction not broadcast");
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const provider = custodies.get(args.wallet.custody);
|
|
209
|
+
if (provider === undefined) {
|
|
210
|
+
throw new WalletEngineError(args.wallet.id, `no CustodyProvider registered for custody="${args.wallet.custody}". Call registerCustody() at boot.`);
|
|
211
|
+
}
|
|
212
|
+
const txHash = await provider.signAndBroadcast({
|
|
213
|
+
tx: args.tx,
|
|
214
|
+
walletConfig: args.wallet,
|
|
215
|
+
adapter,
|
|
216
|
+
});
|
|
217
|
+
// Fetch the receipt for the caller. Receipts may be null when the
|
|
218
|
+
// tx is still pending; the receipt-poll loop is the caller's concern.
|
|
219
|
+
let receiptRaw;
|
|
220
|
+
try {
|
|
221
|
+
receiptRaw = await adapter.rpcRead("eth_getTransactionReceipt", [txHash]);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
receiptRaw = null;
|
|
225
|
+
}
|
|
226
|
+
const boundary = await classifyBoundary(JSON.stringify(receiptRaw ?? null), {
|
|
227
|
+
origin: "chain",
|
|
228
|
+
});
|
|
229
|
+
if (receiptRaw === null || typeof receiptRaw !== "object") {
|
|
230
|
+
return { txHash, blockNumber: null, status: null, boundary };
|
|
231
|
+
}
|
|
232
|
+
const r = receiptRaw;
|
|
233
|
+
const blockNumber = typeof r["blockNumber"] === "string" ? r["blockNumber"] : null;
|
|
234
|
+
const statusRaw = r["status"];
|
|
235
|
+
const status = statusRaw === "0x0" || statusRaw === "0x1" ? statusRaw : null;
|
|
236
|
+
return { txHash, blockNumber, status, boundary };
|
|
237
|
+
}
|
|
238
|
+
return {
|
|
239
|
+
registerCustody(provider) {
|
|
240
|
+
custodies.set(provider.custody, provider);
|
|
241
|
+
},
|
|
242
|
+
requestSignAndBroadcast,
|
|
243
|
+
simulate,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Test-only custody stub. Implements the `local` custody kind with a
|
|
248
|
+
* deterministic tx-hash mint. Real implementations live in follow-up
|
|
249
|
+
* packages (`wallet-custody-kms`, `wallet-custody-wc`, etc.).
|
|
250
|
+
*/
|
|
251
|
+
export function createLocalSignerStub() {
|
|
252
|
+
let nonce = 0;
|
|
253
|
+
return {
|
|
254
|
+
custody: "local",
|
|
255
|
+
async signAndBroadcast({ tx }) {
|
|
256
|
+
nonce += 1;
|
|
257
|
+
// Deterministic hash for tests: hex of walletId|chainId|nonce.
|
|
258
|
+
const seed = `${tx.walletId}:${tx.chainId}:${nonce}`;
|
|
259
|
+
const bytes = new TextEncoder().encode(seed);
|
|
260
|
+
let acc = 0n;
|
|
261
|
+
for (const b of bytes)
|
|
262
|
+
acc = (acc * 31n + BigInt(b)) & ((1n << 256n) - 1n);
|
|
263
|
+
return `0x${acc.toString(16).padStart(64, "0")}`;
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
package/package.json
CHANGED
|
@@ -1,20 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/wallet-engine",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Wallet custody + sign-request flow. Routes every transaction through simulation, transaction-policy enforcement, approval gate, then broadcast. §47 slice 1.",
|
|
6
|
-
"main": "
|
|
7
|
-
"types": "
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
-
".":
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
10
13
|
},
|
|
11
14
|
"scripts": {
|
|
12
15
|
"test": "bun test src"
|
|
13
16
|
},
|
|
14
17
|
"dependencies": {
|
|
15
|
-
"@crewhaus/boundary-classifier": "0.1.
|
|
16
|
-
"@crewhaus/chain-adapter-base": "0.1.
|
|
17
|
-
"@crewhaus/errors": "0.1.
|
|
18
|
+
"@crewhaus/boundary-classifier": "0.1.5",
|
|
19
|
+
"@crewhaus/chain-adapter-base": "0.1.5",
|
|
20
|
+
"@crewhaus/errors": "0.1.5"
|
|
18
21
|
},
|
|
19
22
|
"license": "Apache-2.0",
|
|
20
23
|
"author": {
|
|
@@ -34,5 +37,5 @@
|
|
|
34
37
|
"publishConfig": {
|
|
35
38
|
"access": "public"
|
|
36
39
|
},
|
|
37
|
-
"files": ["
|
|
40
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
38
41
|
}
|
package/src/index.test.ts
DELETED
|
@@ -1,369 +0,0 @@
|
|
|
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
|
-
// SECURITY: simulationRequired must model the REAL signer, not address(0),
|
|
89
|
-
// or onlyOwner / msg.sender-dependent calls give false assurance (#415).
|
|
90
|
-
describe("createWalletEngine — simulation from-address", () => {
|
|
91
|
-
test("passes the wallet address as eth_call `from` when custody exposes getAddress", async () => {
|
|
92
|
-
let seenFrom: unknown = "UNSET";
|
|
93
|
-
const we = createWalletEngine({
|
|
94
|
-
resolveAdapter: () =>
|
|
95
|
-
fakeAdapter((method, params) => {
|
|
96
|
-
if (method === "eth_call") {
|
|
97
|
-
seenFrom = (params[0] as Record<string, unknown>)["from"];
|
|
98
|
-
return "0x";
|
|
99
|
-
}
|
|
100
|
-
if (method === "eth_estimateGas") return "0x5208";
|
|
101
|
-
if (method === "eth_getTransactionReceipt") return { blockNumber: "0x1", status: "0x1" };
|
|
102
|
-
return null;
|
|
103
|
-
}),
|
|
104
|
-
approve: async () => "allow",
|
|
105
|
-
});
|
|
106
|
-
we.registerCustody({
|
|
107
|
-
custody: "local",
|
|
108
|
-
async signAndBroadcast() {
|
|
109
|
-
return "0xhash";
|
|
110
|
-
},
|
|
111
|
-
async getAddress() {
|
|
112
|
-
return "0xWALLETADDR";
|
|
113
|
-
},
|
|
114
|
-
});
|
|
115
|
-
await we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET });
|
|
116
|
-
expect(seenFrom).toBe("0xWALLETADDR");
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
test("omits `from` (back-compat) when custody does not expose getAddress", async () => {
|
|
120
|
-
let sawFromKey = true;
|
|
121
|
-
const we = createWalletEngine({
|
|
122
|
-
resolveAdapter: () =>
|
|
123
|
-
fakeAdapter((method, params) => {
|
|
124
|
-
if (method === "eth_call") {
|
|
125
|
-
sawFromKey = "from" in (params[0] as Record<string, unknown>);
|
|
126
|
-
return "0x";
|
|
127
|
-
}
|
|
128
|
-
if (method === "eth_estimateGas") return "0x5208";
|
|
129
|
-
if (method === "eth_getTransactionReceipt") return { blockNumber: "0x1", status: "0x1" };
|
|
130
|
-
return null;
|
|
131
|
-
}),
|
|
132
|
-
approve: async () => "allow",
|
|
133
|
-
});
|
|
134
|
-
we.registerCustody(createLocalSignerStub()); // no getAddress
|
|
135
|
-
await we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET });
|
|
136
|
-
expect(sawFromKey).toBe(false);
|
|
137
|
-
});
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
describe("createWalletEngine — policy enforcement", () => {
|
|
141
|
-
test("rejects when contractId is missing and allowedContracts is non-empty", async () => {
|
|
142
|
-
const we = createWalletEngine({
|
|
143
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
144
|
-
approve: async () => "allow",
|
|
145
|
-
});
|
|
146
|
-
we.registerCustody(createLocalSignerStub());
|
|
147
|
-
const tx: UnsignedTx = { chainId: "test-chain", walletId: "treasury", to: "0xraw", data: "0x" };
|
|
148
|
-
await expect(
|
|
149
|
-
we.requestSignAndBroadcast({ tx, policy: POLICY, wallet: WALLET }),
|
|
150
|
-
).rejects.toThrow(WalletEngineError);
|
|
151
|
-
});
|
|
152
|
-
|
|
153
|
-
test("rejects when contractId is not in allowedContracts", async () => {
|
|
154
|
-
const we = createWalletEngine({
|
|
155
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
156
|
-
approve: async () => "allow",
|
|
157
|
-
});
|
|
158
|
-
we.registerCustody(createLocalSignerStub());
|
|
159
|
-
const tx: UnsignedTx = { ...TX_OK, contractId: "uniswap-router" };
|
|
160
|
-
await expect(
|
|
161
|
-
we.requestSignAndBroadcast({ tx, policy: POLICY, wallet: WALLET }),
|
|
162
|
-
).rejects.toThrow(/uniswap-router/);
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
// SECURITY: empty allowedContracts is now FAIL-CLOSED (was allow-all). The
|
|
166
|
-
// default onchain policy must not let a prompt-injected model send arbitrary
|
|
167
|
-
// calldata/value to any address.
|
|
168
|
-
test("fails closed when allowedContracts is empty (default policy)", async () => {
|
|
169
|
-
const we = createWalletEngine({
|
|
170
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
171
|
-
approve: async () => "allow",
|
|
172
|
-
});
|
|
173
|
-
we.registerCustody(createLocalSignerStub());
|
|
174
|
-
const emptyPolicy: TransactionPolicy = { ...POLICY, allowedContracts: [] };
|
|
175
|
-
await expect(
|
|
176
|
-
we.requestSignAndBroadcast({ tx: TX_OK, policy: emptyPolicy, wallet: WALLET }),
|
|
177
|
-
).rejects.toThrow(/allowedContracts is empty/);
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
test("rejects when tx.to does not match the bound contract address (#151)", async () => {
|
|
181
|
-
const we = createWalletEngine({
|
|
182
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
183
|
-
approve: async () => "allow",
|
|
184
|
-
});
|
|
185
|
-
we.registerCustody(createLocalSignerStub());
|
|
186
|
-
const policy: TransactionPolicy = { ...POLICY, contractAddresses: { usdc: "0xusdc" } };
|
|
187
|
-
const tx: UnsignedTx = { ...TX_OK, to: "0xattacker" };
|
|
188
|
-
await expect(we.requestSignAndBroadcast({ tx, policy, wallet: WALLET })).rejects.toThrow(
|
|
189
|
-
/does not match the address/,
|
|
190
|
-
);
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
test("rejects when tx value exceeds maxValueWei (#152)", async () => {
|
|
194
|
-
const we = createWalletEngine({
|
|
195
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
196
|
-
approve: async () => "allow",
|
|
197
|
-
});
|
|
198
|
-
we.registerCustody(createLocalSignerStub());
|
|
199
|
-
const policy: TransactionPolicy = { ...POLICY, maxValueWei: "0x10" };
|
|
200
|
-
const tx: UnsignedTx = { ...TX_OK, value: "0x20" };
|
|
201
|
-
await expect(we.requestSignAndBroadcast({ tx, policy, wallet: WALLET })).rejects.toThrow(
|
|
202
|
-
/exceeds transaction_policy\.maxValueWei/,
|
|
203
|
-
);
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
test("fails closed when maxValueUsd is set without a price oracle (#152)", async () => {
|
|
207
|
-
const we = createWalletEngine({
|
|
208
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
209
|
-
approve: async () => "allow",
|
|
210
|
-
});
|
|
211
|
-
we.registerCustody(createLocalSignerStub());
|
|
212
|
-
const policy: TransactionPolicy = { ...POLICY, maxValueUsd: 100 };
|
|
213
|
-
await expect(we.requestSignAndBroadcast({ tx: TX_OK, policy, wallet: WALLET })).rejects.toThrow(
|
|
214
|
-
/price oracle/,
|
|
215
|
-
);
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
test("allows a case-insensitive address match with value under maxValueWei (#151, #152)", async () => {
|
|
219
|
-
const we = createWalletEngine({
|
|
220
|
-
resolveAdapter: () =>
|
|
221
|
-
fakeAdapter((method) => {
|
|
222
|
-
if (method === "eth_call") return "0x";
|
|
223
|
-
if (method === "eth_estimateGas") return "0x5208";
|
|
224
|
-
if (method === "eth_getTransactionReceipt")
|
|
225
|
-
return { blockNumber: "0x100", status: "0x1" };
|
|
226
|
-
return null;
|
|
227
|
-
}),
|
|
228
|
-
approve: async () => "allow",
|
|
229
|
-
});
|
|
230
|
-
we.registerCustody(createLocalSignerStub());
|
|
231
|
-
const policy: TransactionPolicy = {
|
|
232
|
-
...POLICY,
|
|
233
|
-
contractAddresses: { usdc: "0xUSDC" }, // checksum/case differs from TX_OK.to "0xusdc"
|
|
234
|
-
maxValueWei: "0x100",
|
|
235
|
-
};
|
|
236
|
-
const tx: UnsignedTx = { ...TX_OK, value: "0x10" };
|
|
237
|
-
const receipt = await we.requestSignAndBroadcast({ tx, policy, wallet: WALLET });
|
|
238
|
-
expect(receipt.status).toBe("0x1");
|
|
239
|
-
});
|
|
240
|
-
|
|
241
|
-
test("rejects approval='none' with non-automated wallet", async () => {
|
|
242
|
-
const we = createWalletEngine({
|
|
243
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
244
|
-
approve: async () => "allow",
|
|
245
|
-
});
|
|
246
|
-
we.registerCustody(createLocalSignerStub());
|
|
247
|
-
await expect(
|
|
248
|
-
we.requestSignAndBroadcast({
|
|
249
|
-
tx: TX_OK,
|
|
250
|
-
policy: { ...POLICY, defaultWriteApproval: "none", simulationRequired: false },
|
|
251
|
-
wallet: WALLET,
|
|
252
|
-
}),
|
|
253
|
-
).rejects.toThrow(/automated/);
|
|
254
|
-
});
|
|
255
|
-
});
|
|
256
|
-
|
|
257
|
-
describe("createWalletEngine — simulation gate", () => {
|
|
258
|
-
test("aborts on failed simulation when simulationRequired", async () => {
|
|
259
|
-
const we = createWalletEngine({
|
|
260
|
-
resolveAdapter: () =>
|
|
261
|
-
fakeAdapter((method) => {
|
|
262
|
-
if (method === "eth_call") throw new Error("execution reverted: insufficient balance");
|
|
263
|
-
return "0x";
|
|
264
|
-
}),
|
|
265
|
-
approve: async () => "allow",
|
|
266
|
-
});
|
|
267
|
-
we.registerCustody(createLocalSignerStub());
|
|
268
|
-
await expect(
|
|
269
|
-
we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET }),
|
|
270
|
-
).rejects.toThrow(/simulation failed/);
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
test("skips simulation when simulationRequired is false", async () => {
|
|
274
|
-
const simCalls: string[] = [];
|
|
275
|
-
const we = createWalletEngine({
|
|
276
|
-
resolveAdapter: () =>
|
|
277
|
-
fakeAdapter((method) => {
|
|
278
|
-
simCalls.push(method);
|
|
279
|
-
if (method === "eth_getTransactionReceipt")
|
|
280
|
-
return { blockNumber: "0x100", status: "0x1" };
|
|
281
|
-
return "0x";
|
|
282
|
-
}),
|
|
283
|
-
approve: async () => "allow",
|
|
284
|
-
});
|
|
285
|
-
we.registerCustody(createLocalSignerStub());
|
|
286
|
-
await we.requestSignAndBroadcast({
|
|
287
|
-
tx: TX_OK,
|
|
288
|
-
policy: { ...POLICY, simulationRequired: false },
|
|
289
|
-
wallet: WALLET,
|
|
290
|
-
});
|
|
291
|
-
expect(simCalls.includes("eth_call")).toBe(false);
|
|
292
|
-
expect(simCalls.includes("eth_estimateGas")).toBe(false);
|
|
293
|
-
expect(simCalls.includes("eth_getTransactionReceipt")).toBe(true);
|
|
294
|
-
});
|
|
295
|
-
});
|
|
296
|
-
|
|
297
|
-
describe("createWalletEngine — approval gate", () => {
|
|
298
|
-
test("denied approval blocks broadcast", async () => {
|
|
299
|
-
let signedCalls = 0;
|
|
300
|
-
const we = createWalletEngine({
|
|
301
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
302
|
-
approve: async () => "deny",
|
|
303
|
-
});
|
|
304
|
-
we.registerCustody({
|
|
305
|
-
custody: "local",
|
|
306
|
-
async signAndBroadcast() {
|
|
307
|
-
signedCalls += 1;
|
|
308
|
-
return "0xfake";
|
|
309
|
-
},
|
|
310
|
-
});
|
|
311
|
-
await expect(
|
|
312
|
-
we.requestSignAndBroadcast({
|
|
313
|
-
tx: TX_OK,
|
|
314
|
-
policy: { ...POLICY, simulationRequired: false },
|
|
315
|
-
wallet: WALLET,
|
|
316
|
-
}),
|
|
317
|
-
).rejects.toThrow(/approval denied/);
|
|
318
|
-
expect(signedCalls).toBe(0);
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
test("automated signing skips the approval resolver", async () => {
|
|
322
|
-
let approvalCalls = 0;
|
|
323
|
-
const we = createWalletEngine({
|
|
324
|
-
resolveAdapter: () =>
|
|
325
|
-
fakeAdapter((method) =>
|
|
326
|
-
method === "eth_getTransactionReceipt" ? { blockNumber: "0x100", status: "0x1" } : "0x",
|
|
327
|
-
),
|
|
328
|
-
approve: async () => {
|
|
329
|
-
approvalCalls += 1;
|
|
330
|
-
return "allow";
|
|
331
|
-
},
|
|
332
|
-
});
|
|
333
|
-
we.registerCustody(createLocalSignerStub());
|
|
334
|
-
await we.requestSignAndBroadcast({
|
|
335
|
-
tx: TX_OK,
|
|
336
|
-
policy: { ...POLICY, defaultWriteApproval: "policy", simulationRequired: false },
|
|
337
|
-
wallet: { ...WALLET, signingPolicy: "automated" },
|
|
338
|
-
});
|
|
339
|
-
expect(approvalCalls).toBe(0);
|
|
340
|
-
});
|
|
341
|
-
});
|
|
342
|
-
|
|
343
|
-
describe("createWalletEngine — missing wiring", () => {
|
|
344
|
-
test("throws when no adapter for chainId", async () => {
|
|
345
|
-
const we = createWalletEngine({
|
|
346
|
-
resolveAdapter: () => undefined,
|
|
347
|
-
approve: async () => "allow",
|
|
348
|
-
});
|
|
349
|
-
we.registerCustody(createLocalSignerStub());
|
|
350
|
-
await expect(
|
|
351
|
-
we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET }),
|
|
352
|
-
).rejects.toThrow(/no chain adapter registered/);
|
|
353
|
-
});
|
|
354
|
-
|
|
355
|
-
test("throws when no custody provider for wallet.custody", async () => {
|
|
356
|
-
const we = createWalletEngine({
|
|
357
|
-
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
358
|
-
approve: async () => "allow",
|
|
359
|
-
});
|
|
360
|
-
// Note: no registerCustody() call.
|
|
361
|
-
await expect(
|
|
362
|
-
we.requestSignAndBroadcast({
|
|
363
|
-
tx: TX_OK,
|
|
364
|
-
policy: { ...POLICY, simulationRequired: false },
|
|
365
|
-
wallet: WALLET,
|
|
366
|
-
}),
|
|
367
|
-
).rejects.toThrow(/no CustodyProvider registered/);
|
|
368
|
-
});
|
|
369
|
-
});
|
package/src/index.ts
DELETED
|
@@ -1,489 +0,0 @@
|
|
|
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
|
-
/**
|
|
70
|
-
* Native-token value ceiling in wei (decimal or 0x-hex). Oracle-free and
|
|
71
|
-
* enforced pre-broadcast (#152).
|
|
72
|
-
*/
|
|
73
|
-
readonly maxValueWei?: string;
|
|
74
|
-
readonly allowedContracts: readonly string[];
|
|
75
|
-
/**
|
|
76
|
-
* Resolved `contractId` → address map. When present, `tx.to` is bound to the
|
|
77
|
-
* address registered for `tx.contractId`, so a whitelisted id cannot be used
|
|
78
|
-
* to send to an arbitrary address (#151). The runtime should populate this
|
|
79
|
-
* from the spec's `contracts[]`; the stronger long-term fix is to drop `to`
|
|
80
|
-
* from the tool input entirely and resolve it from `contractId` here.
|
|
81
|
-
*/
|
|
82
|
-
readonly contractAddresses?: Readonly<Record<string, string>>;
|
|
83
|
-
readonly simulationRequired: boolean;
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* The unsigned-transaction shape the wallet-engine accepts. Generic
|
|
88
|
-
* over EVM today; the `chainId` field steers the right adapter.
|
|
89
|
-
*
|
|
90
|
-
* `contractId` is the spec-level binding id (from `contracts[]`),
|
|
91
|
-
* resolved into `to` (address) by the caller. Carrying both lets the
|
|
92
|
-
* policy engine compare against `allowedContracts` symbolically rather
|
|
93
|
-
* than by raw address (less brittle when contracts get redeployed).
|
|
94
|
-
*/
|
|
95
|
-
export type UnsignedTx = {
|
|
96
|
-
readonly chainId: string;
|
|
97
|
-
readonly walletId: string;
|
|
98
|
-
readonly contractId?: string;
|
|
99
|
-
readonly to: string;
|
|
100
|
-
/** Hex-encoded calldata, 0x-prefixed. */
|
|
101
|
-
readonly data: string;
|
|
102
|
-
/** Hex-encoded native-token value (wei), 0x-prefixed. Defaults to "0x0". */
|
|
103
|
-
readonly value?: string;
|
|
104
|
-
/** Optional gas limit (hex). Adapter estimates if omitted. */
|
|
105
|
-
readonly gasLimit?: string;
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Parse a wei amount expressed as a decimal or 0x-hex string. Throws a
|
|
110
|
-
* WalletEngineError (fail-closed) on a malformed value.
|
|
111
|
-
*/
|
|
112
|
-
function parseWei(walletId: string, label: string, v: string): bigint {
|
|
113
|
-
try {
|
|
114
|
-
return BigInt(v.trim());
|
|
115
|
-
} catch {
|
|
116
|
-
throw new WalletEngineError(
|
|
117
|
-
walletId,
|
|
118
|
-
`invalid ${label} "${v}" (expected wei as a decimal or 0x-hex string)`,
|
|
119
|
-
);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Simulation result. Conservatively typed — real adapters surface
|
|
125
|
-
* decoded balance deltas, permission deltas, etc. Slice 1 carries
|
|
126
|
-
* the minimum payload the approval prompt needs.
|
|
127
|
-
*/
|
|
128
|
-
export type SimulationResult = {
|
|
129
|
-
readonly success: boolean;
|
|
130
|
-
readonly gasUsed: string;
|
|
131
|
-
readonly returnData?: string;
|
|
132
|
-
/** Adapter-decoded error string when `success === false`. */
|
|
133
|
-
readonly revertReason?: string;
|
|
134
|
-
/**
|
|
135
|
-
* Boundary verdict on the simulator's raw response. Always present.
|
|
136
|
-
* Callers that promote sim output into the model context use this
|
|
137
|
-
* to decide whether to redact.
|
|
138
|
-
*/
|
|
139
|
-
readonly boundary: BoundaryResult;
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Receipt of a broadcast transaction. Same Pillar 3 boundary wrap.
|
|
144
|
-
*/
|
|
145
|
-
export type BroadcastReceipt = {
|
|
146
|
-
readonly txHash: string;
|
|
147
|
-
/**
|
|
148
|
-
* Block number the transaction landed in. `null` while pending; the
|
|
149
|
-
* caller polls with `EvmGetTransactionReceipt` to wait for finality.
|
|
150
|
-
*/
|
|
151
|
-
readonly blockNumber: string | null;
|
|
152
|
-
readonly status: "0x0" | "0x1" | null;
|
|
153
|
-
readonly boundary: BoundaryResult;
|
|
154
|
-
};
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* The approval gate. Slice 1 ships an in-process resolver that the
|
|
158
|
-
* runtime wires to the §7 permission engine (or the CLI HITL prompt
|
|
159
|
-
* for `default` mode). Tests provide a deterministic resolver.
|
|
160
|
-
*/
|
|
161
|
-
export type ApprovalDecision = "allow" | "deny";
|
|
162
|
-
export type ApprovalRequest = {
|
|
163
|
-
readonly walletId: string;
|
|
164
|
-
readonly chainId: string;
|
|
165
|
-
readonly tx: UnsignedTx;
|
|
166
|
-
readonly simulation?: SimulationResult;
|
|
167
|
-
readonly reason: string;
|
|
168
|
-
};
|
|
169
|
-
export type ApprovalResolver = (req: ApprovalRequest) => Promise<ApprovalDecision>;
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Custody adapter — abstracts the signing primitive across user-
|
|
173
|
-
* controlled wallets, KMS, HSM, and local-key custody. Slice 1 ships
|
|
174
|
-
* the interface plus a `LocalSignerStub` for tests; real KMS / HSM
|
|
175
|
-
* integrations are follow-up packages.
|
|
176
|
-
*/
|
|
177
|
-
export interface CustodyProvider {
|
|
178
|
-
readonly custody: WalletConfig["custody"];
|
|
179
|
-
/**
|
|
180
|
-
* Sign + broadcast. The provider is responsible for whatever
|
|
181
|
-
* external loop the custody type requires (WalletConnect QR scan,
|
|
182
|
-
* KMS signRequest, HSM PKCS#11 call, local-key signing). Returns
|
|
183
|
-
* the raw tx hash; the wallet-engine wraps it in a `BroadcastReceipt`.
|
|
184
|
-
*/
|
|
185
|
-
signAndBroadcast(args: {
|
|
186
|
-
readonly tx: UnsignedTx;
|
|
187
|
-
readonly walletConfig: WalletConfig;
|
|
188
|
-
readonly adapter: ChainAdapter;
|
|
189
|
-
}): Promise<string>;
|
|
190
|
-
/**
|
|
191
|
-
* Optional: the wallet's on-chain address, used as `from` in pre-broadcast
|
|
192
|
-
* simulation so msg.sender-dependent / access-controlled calls (onlyOwner,
|
|
193
|
-
* etc.) are modeled as the REAL signer rather than address(0). When a
|
|
194
|
-
* provider can't (or won't) expose the address ahead of signing, simulation
|
|
195
|
-
* falls back to no `from` — accurate for stateless calls, best-effort
|
|
196
|
-
* otherwise.
|
|
197
|
-
*/
|
|
198
|
-
getAddress?(walletConfig: WalletConfig): Promise<string | undefined>;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* The slice-1 wallet engine. Construct one per bundle; register one
|
|
203
|
-
* custody provider per custody kind in use; resolve adapters from the
|
|
204
|
-
* `chains[]` block via the supplied resolver.
|
|
205
|
-
*/
|
|
206
|
-
export type WalletEngine = {
|
|
207
|
-
readonly registerCustody: (provider: CustodyProvider) => void;
|
|
208
|
-
readonly requestSignAndBroadcast: (args: {
|
|
209
|
-
readonly tx: UnsignedTx;
|
|
210
|
-
readonly policy: TransactionPolicy;
|
|
211
|
-
readonly wallet: WalletConfig;
|
|
212
|
-
}) => Promise<BroadcastReceipt>;
|
|
213
|
-
readonly simulate: (args: {
|
|
214
|
-
readonly tx: UnsignedTx;
|
|
215
|
-
}) => Promise<SimulationResult>;
|
|
216
|
-
};
|
|
217
|
-
|
|
218
|
-
export type WalletEngineOptions = {
|
|
219
|
-
readonly resolveAdapter: (chainId: string) => ChainAdapter | undefined;
|
|
220
|
-
readonly approve: ApprovalResolver;
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
export function createWalletEngine(opts: WalletEngineOptions): WalletEngine {
|
|
224
|
-
const custodies = new Map<WalletConfig["custody"], CustodyProvider>();
|
|
225
|
-
|
|
226
|
-
function requireAdapter(chainId: string, walletId: string): ChainAdapter {
|
|
227
|
-
const a = opts.resolveAdapter(chainId);
|
|
228
|
-
if (a === undefined) {
|
|
229
|
-
throw new WalletEngineError(
|
|
230
|
-
walletId,
|
|
231
|
-
`no chain adapter registered for chainId "${chainId}". Declare it in spec.chains[].`,
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
return a;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
async function simulate(args: { tx: UnsignedTx; from?: string }): Promise<SimulationResult> {
|
|
238
|
-
const adapter = requireAdapter(args.tx.chainId, args.tx.walletId);
|
|
239
|
-
const callParams: Record<string, unknown> = {
|
|
240
|
-
to: args.tx.to,
|
|
241
|
-
data: args.tx.data,
|
|
242
|
-
};
|
|
243
|
-
// Run the eth_call AS the signing wallet (not address(0)) so onlyOwner /
|
|
244
|
-
// msg.sender-dependent logic is modeled faithfully — otherwise a
|
|
245
|
-
// simulationRequired pre-flight gives false assurance.
|
|
246
|
-
if (args.from !== undefined) callParams["from"] = args.from;
|
|
247
|
-
if (args.tx.value !== undefined) callParams["value"] = args.tx.value;
|
|
248
|
-
// Prefer eth_call for state-read; fall back to estimateGas for revert detection.
|
|
249
|
-
let returnData: string | undefined;
|
|
250
|
-
let success = true;
|
|
251
|
-
let revertReason: string | undefined;
|
|
252
|
-
let raw = "";
|
|
253
|
-
try {
|
|
254
|
-
const callResult = await adapter.rpcRead("eth_call", [callParams, "latest"]);
|
|
255
|
-
returnData = typeof callResult === "string" ? callResult : undefined;
|
|
256
|
-
raw = JSON.stringify({ kind: "call", result: callResult });
|
|
257
|
-
} catch (err) {
|
|
258
|
-
success = false;
|
|
259
|
-
revertReason = (err as Error).message;
|
|
260
|
-
raw = JSON.stringify({ kind: "revert", message: revertReason });
|
|
261
|
-
}
|
|
262
|
-
let gasUsed = "0x0";
|
|
263
|
-
if (success) {
|
|
264
|
-
try {
|
|
265
|
-
const est = await adapter.rpcRead("eth_estimateGas", [callParams]);
|
|
266
|
-
if (typeof est === "string") gasUsed = est;
|
|
267
|
-
} catch {
|
|
268
|
-
/* tolerate — gasUsed stays 0x0 */
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
const boundary = await classifyBoundary(raw, { origin: "chain" });
|
|
272
|
-
return {
|
|
273
|
-
success,
|
|
274
|
-
gasUsed,
|
|
275
|
-
...(returnData !== undefined ? { returnData } : {}),
|
|
276
|
-
...(revertReason !== undefined ? { revertReason } : {}),
|
|
277
|
-
boundary,
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function enforceStaticPolicy(tx: UnsignedTx, policy: TransactionPolicy): void {
|
|
282
|
-
// Fail CLOSED on an empty `allowedContracts`. Previously empty meant "allow
|
|
283
|
-
// every contract", so an onchain agent on the default policy (allowedContracts
|
|
284
|
-
// defaults to []) let a prompt-injected model send arbitrary calldata/value
|
|
285
|
-
// to ANY address — a wallet-drain primitive. Operators must now declare the
|
|
286
|
-
// callable contract ids in transaction_policy.allowedContracts to permit sends.
|
|
287
|
-
if (policy.allowedContracts.length === 0) {
|
|
288
|
-
throw new WalletEngineError(
|
|
289
|
-
tx.walletId,
|
|
290
|
-
"transaction_policy.allowedContracts is empty — sends are denied (fail-closed). Declare the callable contract ids in transaction_policy.allowedContracts (bound to addresses via contracts[]).",
|
|
291
|
-
);
|
|
292
|
-
}
|
|
293
|
-
// Non-empty: contractId must be present and whitelisted. Raw-address calls
|
|
294
|
-
// (no contractId) are rejected — the spec author must declare every callable
|
|
295
|
-
// contract symbolically.
|
|
296
|
-
if (tx.contractId === undefined) {
|
|
297
|
-
throw new WalletEngineError(
|
|
298
|
-
tx.walletId,
|
|
299
|
-
`transaction_policy.allowedContracts is non-empty; raw-address calls forbidden (to=${tx.to}). Declare a contracts[] entry and pass its id.`,
|
|
300
|
-
);
|
|
301
|
-
}
|
|
302
|
-
if (!policy.allowedContracts.includes(tx.contractId)) {
|
|
303
|
-
throw new WalletEngineError(
|
|
304
|
-
tx.walletId,
|
|
305
|
-
`contract id "${tx.contractId}" not in transaction_policy.allowedContracts ${JSON.stringify(policy.allowedContracts)}`,
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// #151 — bind `to` to the claimed contractId. `allowedContracts` alone is a
|
|
310
|
-
// symbolic gate; without this an attacker can claim a whitelisted id and
|
|
311
|
-
// still send to an arbitrary address. When the resolved address map is
|
|
312
|
-
// present, `tx.to` MUST equal the address registered for `tx.contractId`.
|
|
313
|
-
if (tx.contractId !== undefined && policy.contractAddresses !== undefined) {
|
|
314
|
-
const expected = policy.contractAddresses[tx.contractId];
|
|
315
|
-
if (expected === undefined) {
|
|
316
|
-
throw new WalletEngineError(
|
|
317
|
-
tx.walletId,
|
|
318
|
-
`contract id "${tx.contractId}" has no resolved address in transaction_policy.contractAddresses`,
|
|
319
|
-
);
|
|
320
|
-
}
|
|
321
|
-
if (tx.to.toLowerCase() !== expected.toLowerCase()) {
|
|
322
|
-
throw new WalletEngineError(
|
|
323
|
-
tx.walletId,
|
|
324
|
-
`tx.to "${tx.to}" does not match the address ${expected} bound to contract id "${tx.contractId}"`,
|
|
325
|
-
);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// #152 — value caps. maxValueWei is an oracle-free native ceiling enforced
|
|
330
|
-
// here. maxValueUsd cannot be enforced without a price oracle (none is
|
|
331
|
-
// wired in this build), so fail closed rather than give false assurance.
|
|
332
|
-
if (policy.maxValueWei !== undefined) {
|
|
333
|
-
const cap = parseWei(tx.walletId, "transaction_policy.maxValueWei", policy.maxValueWei);
|
|
334
|
-
const val = parseWei(tx.walletId, "tx.value", tx.value ?? "0x0");
|
|
335
|
-
if (val > cap) {
|
|
336
|
-
throw new WalletEngineError(
|
|
337
|
-
tx.walletId,
|
|
338
|
-
`tx value ${val} wei exceeds transaction_policy.maxValueWei (${cap} wei)`,
|
|
339
|
-
);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
if (policy.maxValueUsd !== undefined) {
|
|
343
|
-
throw new WalletEngineError(
|
|
344
|
-
tx.walletId,
|
|
345
|
-
`transaction_policy.maxValueUsd (${policy.maxValueUsd}) cannot be enforced: USD value caps require a price oracle, which is not wired in this build. Use transaction_policy.maxValueWei for a native-token ceiling.`,
|
|
346
|
-
);
|
|
347
|
-
}
|
|
348
|
-
// `none` (defaultWriteApproval) is only valid under `automated` custody —
|
|
349
|
-
// documented invariant. The runtime layers that allow this combo perform
|
|
350
|
-
// a stronger check at boot; this layer just rejects the obvious misuse.
|
|
351
|
-
if (policy.defaultWriteApproval === "none") {
|
|
352
|
-
// We can't read wallet custody from here without the wallet arg; the
|
|
353
|
-
// caller passes the wallet — see requestSignAndBroadcast below.
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
async function requestSignAndBroadcast(args: {
|
|
358
|
-
tx: UnsignedTx;
|
|
359
|
-
policy: TransactionPolicy;
|
|
360
|
-
wallet: WalletConfig;
|
|
361
|
-
}): Promise<BroadcastReceipt> {
|
|
362
|
-
if (args.tx.walletId !== args.wallet.id) {
|
|
363
|
-
throw new WalletEngineError(
|
|
364
|
-
args.wallet.id,
|
|
365
|
-
`tx.walletId "${args.tx.walletId}" does not match wallet.id "${args.wallet.id}"`,
|
|
366
|
-
);
|
|
367
|
-
}
|
|
368
|
-
if (args.tx.chainId !== args.wallet.chainId) {
|
|
369
|
-
throw new WalletEngineError(
|
|
370
|
-
args.wallet.id,
|
|
371
|
-
`tx.chainId "${args.tx.chainId}" does not match wallet.chainId "${args.wallet.chainId}"`,
|
|
372
|
-
);
|
|
373
|
-
}
|
|
374
|
-
enforceStaticPolicy(args.tx, args.policy);
|
|
375
|
-
if (args.policy.defaultWriteApproval === "none" && args.wallet.signingPolicy !== "automated") {
|
|
376
|
-
throw new WalletEngineError(
|
|
377
|
-
args.wallet.id,
|
|
378
|
-
`transaction_policy.defaultWriteApproval="none" requires signingPolicy="automated" (got "${args.wallet.signingPolicy}")`,
|
|
379
|
-
);
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
const adapter = requireAdapter(args.tx.chainId, args.wallet.id);
|
|
383
|
-
|
|
384
|
-
let sim: SimulationResult | undefined;
|
|
385
|
-
if (args.policy.simulationRequired) {
|
|
386
|
-
// Resolve the signer address (best-effort) so simulation runs as the
|
|
387
|
-
// real wallet, not address(0).
|
|
388
|
-
let fromAddress: string | undefined;
|
|
389
|
-
const custody = custodies.get(args.wallet.custody);
|
|
390
|
-
if (custody?.getAddress !== undefined) {
|
|
391
|
-
try {
|
|
392
|
-
fromAddress = await custody.getAddress(args.wallet);
|
|
393
|
-
} catch {
|
|
394
|
-
fromAddress = undefined;
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
sim = await simulate({
|
|
398
|
-
tx: args.tx,
|
|
399
|
-
...(fromAddress !== undefined ? { from: fromAddress } : {}),
|
|
400
|
-
});
|
|
401
|
-
if (!sim.success) {
|
|
402
|
-
throw new WalletEngineError(
|
|
403
|
-
args.wallet.id,
|
|
404
|
-
`simulation failed: ${sim.revertReason ?? "(no revert reason)"}; transaction_policy.simulationRequired=true and simulation must succeed before approval`,
|
|
405
|
-
);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
// Approval gate. `policy-gated` defers to the resolver's own
|
|
410
|
-
// adjudication; `explicit-user-approval` always prompts;
|
|
411
|
-
// `automated` skips the resolver entirely.
|
|
412
|
-
const needApproval =
|
|
413
|
-
args.wallet.signingPolicy !== "automated" || args.policy.defaultWriteApproval === "required";
|
|
414
|
-
if (needApproval) {
|
|
415
|
-
const decision = await opts.approve({
|
|
416
|
-
walletId: args.wallet.id,
|
|
417
|
-
chainId: args.tx.chainId,
|
|
418
|
-
tx: args.tx,
|
|
419
|
-
...(sim !== undefined ? { simulation: sim } : {}),
|
|
420
|
-
reason: `sign ${args.tx.data.length > 10 ? `${args.tx.data.slice(0, 10)}…` : args.tx.data} to ${args.tx.to} on ${args.tx.chainId}`,
|
|
421
|
-
});
|
|
422
|
-
if (decision !== "allow") {
|
|
423
|
-
throw new WalletEngineError(args.wallet.id, "approval denied; transaction not broadcast");
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
const provider = custodies.get(args.wallet.custody);
|
|
428
|
-
if (provider === undefined) {
|
|
429
|
-
throw new WalletEngineError(
|
|
430
|
-
args.wallet.id,
|
|
431
|
-
`no CustodyProvider registered for custody="${args.wallet.custody}". Call registerCustody() at boot.`,
|
|
432
|
-
);
|
|
433
|
-
}
|
|
434
|
-
const txHash = await provider.signAndBroadcast({
|
|
435
|
-
tx: args.tx,
|
|
436
|
-
walletConfig: args.wallet,
|
|
437
|
-
adapter,
|
|
438
|
-
});
|
|
439
|
-
|
|
440
|
-
// Fetch the receipt for the caller. Receipts may be null when the
|
|
441
|
-
// tx is still pending; the receipt-poll loop is the caller's concern.
|
|
442
|
-
let receiptRaw: unknown;
|
|
443
|
-
try {
|
|
444
|
-
receiptRaw = await adapter.rpcRead("eth_getTransactionReceipt", [txHash]);
|
|
445
|
-
} catch {
|
|
446
|
-
receiptRaw = null;
|
|
447
|
-
}
|
|
448
|
-
const boundary = await classifyBoundary(JSON.stringify(receiptRaw ?? null), {
|
|
449
|
-
origin: "chain",
|
|
450
|
-
});
|
|
451
|
-
if (receiptRaw === null || typeof receiptRaw !== "object") {
|
|
452
|
-
return { txHash, blockNumber: null, status: null, boundary };
|
|
453
|
-
}
|
|
454
|
-
const r = receiptRaw as Record<string, unknown>;
|
|
455
|
-
const blockNumber = typeof r["blockNumber"] === "string" ? (r["blockNumber"] as string) : null;
|
|
456
|
-
const statusRaw = r["status"];
|
|
457
|
-
const status = statusRaw === "0x0" || statusRaw === "0x1" ? (statusRaw as "0x0" | "0x1") : null;
|
|
458
|
-
return { txHash, blockNumber, status, boundary };
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
return {
|
|
462
|
-
registerCustody(provider) {
|
|
463
|
-
custodies.set(provider.custody, provider);
|
|
464
|
-
},
|
|
465
|
-
requestSignAndBroadcast,
|
|
466
|
-
simulate,
|
|
467
|
-
};
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
/**
|
|
471
|
-
* Test-only custody stub. Implements the `local` custody kind with a
|
|
472
|
-
* deterministic tx-hash mint. Real implementations live in follow-up
|
|
473
|
-
* packages (`wallet-custody-kms`, `wallet-custody-wc`, etc.).
|
|
474
|
-
*/
|
|
475
|
-
export function createLocalSignerStub(): CustodyProvider {
|
|
476
|
-
let nonce = 0;
|
|
477
|
-
return {
|
|
478
|
-
custody: "local",
|
|
479
|
-
async signAndBroadcast({ tx }) {
|
|
480
|
-
nonce += 1;
|
|
481
|
-
// Deterministic hash for tests: hex of walletId|chainId|nonce.
|
|
482
|
-
const seed = `${tx.walletId}:${tx.chainId}:${nonce}`;
|
|
483
|
-
const bytes = new TextEncoder().encode(seed);
|
|
484
|
-
let acc = 0n;
|
|
485
|
-
for (const b of bytes) acc = (acc * 31n + BigInt(b)) & ((1n << 256n) - 1n);
|
|
486
|
-
return `0x${acc.toString(16).padStart(64, "0")}`;
|
|
487
|
-
},
|
|
488
|
-
};
|
|
489
|
-
}
|