@gvnrdao/dh-mcp 0.1.1 → 0.2.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.
Files changed (4) hide show
  1. package/README.md +67 -26
  2. package/dist/boundary.js +1507 -444
  3. package/dist/index.js +1687 -492
  4. package/package.json +2 -1
package/dist/boundary.js CHANGED
@@ -34,6 +34,261 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
34
  ));
35
35
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
36
 
37
+ // src/boundary/upstream/shared/tx-validator.ts
38
+ var tx_validator_exports = {};
39
+ __export(tx_validator_exports, {
40
+ TxValidationError: () => TxValidationError,
41
+ decodeSignable: () => decodeSignable,
42
+ describeUnsignedTx: () => describeUnsignedTx,
43
+ encodeSignable: () => encodeSignable,
44
+ validateUnsignedTx: () => validateUnsignedTx
45
+ });
46
+ function encodeSignable(fn, args) {
47
+ return IFACE.encodeFunctionData(fn, args);
48
+ }
49
+ function decodeSignable(data) {
50
+ return decode(data);
51
+ }
52
+ function eqAddr(a, b) {
53
+ if (!a || !b) return false;
54
+ try {
55
+ return import_ethers3.ethers.getAddress(a) === import_ethers3.ethers.getAddress(b);
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ function readToAddress(tx2) {
61
+ const to = tx2["to"];
62
+ if (typeof to !== "string") throw new TxValidationError(`unsignedTx.to is missing or not a string`);
63
+ return to;
64
+ }
65
+ function readData(tx2) {
66
+ const data = tx2["data"];
67
+ if (typeof data !== "string" || !data.startsWith("0x")) throw new TxValidationError(`unsignedTx.data missing or malformed`);
68
+ return data;
69
+ }
70
+ function readChainId(tx2) {
71
+ const c = tx2["chainId"];
72
+ if (c == null) return null;
73
+ if (typeof c === "number") return c;
74
+ if (typeof c === "string") return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
75
+ if (typeof c === "bigint") return Number(c);
76
+ return null;
77
+ }
78
+ function readValue(tx2) {
79
+ const v = tx2["value"];
80
+ if (v == null) return 0n;
81
+ if (typeof v === "string") return BigInt(v.startsWith("0x") ? v : v);
82
+ if (typeof v === "number") return BigInt(v);
83
+ if (typeof v === "bigint") return v;
84
+ if (typeof v?.toBigInt === "function") return v.toBigInt();
85
+ if (typeof v?.toString === "function") return BigInt(v.toString());
86
+ throw new TxValidationError(`unsignedTx.value has unrecognized type`);
87
+ }
88
+ function decode(data) {
89
+ try {
90
+ const parsed = IFACE.parseTransaction({ data });
91
+ if (!parsed) throw new TxValidationError(`unsignedTx.data does not decode against the signable-function whitelist`);
92
+ return { name: parsed.name, args: parsed.args };
93
+ } catch (e) {
94
+ if (e instanceof TxValidationError) throw e;
95
+ throw new TxValidationError(
96
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
97
+ );
98
+ }
99
+ }
100
+ function normalizePositionId(id) {
101
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
102
+ return import_ethers3.ethers.zeroPadValue(hex, 32).toLowerCase();
103
+ }
104
+ function validateUnsignedTx(unsignedTx, expected, vctx) {
105
+ const txChainId = readChainId(unsignedTx);
106
+ if (txChainId != null && txChainId !== vctx.chainId) {
107
+ throw new TxValidationError(`chainId mismatch \u2014 tx says ${txChainId}, expected ${vctx.chainId}`);
108
+ }
109
+ const value = readValue(unsignedTx);
110
+ if (value !== 0n) throw new TxValidationError(`unsignedTx.value is non-zero (${value})`);
111
+ const to = readToAddress(unsignedTx);
112
+ const data = readData(unsignedTx);
113
+ const { name, args } = decode(data);
114
+ const pm = vctx.contracts.PositionManager;
115
+ switch (expected.kind) {
116
+ case "mint": {
117
+ if (name !== "mintUCD") throw new TxValidationError(`expected mintUCD, server returned ${name}`);
118
+ if (!eqAddr(to, pm)) throw new TxValidationError(`mintUCD must target PositionManager (${pm}), got ${to}`);
119
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
120
+ throw new TxValidationError(`positionId mismatch`);
121
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
122
+ throw new TxValidationError(`mintAmount mismatch`);
123
+ if (BigInt(String(args[2])).toString() !== expected.mintFeeWei)
124
+ throw new TxValidationError(`mintFee mismatch`);
125
+ break;
126
+ }
127
+ case "repay": {
128
+ if (name !== "makePayment" && name !== "repayPosition")
129
+ throw new TxValidationError(`expected makePayment/repayPosition, server returned ${name}`);
130
+ if (!eqAddr(to, pm)) throw new TxValidationError(`${name} must target PositionManager`);
131
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
132
+ throw new TxValidationError(`positionId mismatch`);
133
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
134
+ throw new TxValidationError(`paymentAmount mismatch`);
135
+ break;
136
+ }
137
+ case "extend": {
138
+ if (name !== "extendPosition") throw new TxValidationError(`expected extendPosition, server returned ${name}`);
139
+ if (!eqAddr(to, pm)) throw new TxValidationError(`extendPosition must target PositionManager`);
140
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
141
+ throw new TxValidationError(`positionId mismatch`);
142
+ if (Number(args[1]) !== expected.selectedTerm) throw new TxValidationError(`selectedTerm mismatch`);
143
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
144
+ const txFee = BigInt(String(args[5]));
145
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
146
+ if (txFee > upper) throw new TxValidationError(`proRataRenewalFee=${txFee} exceeds upper bound=${upper}`);
147
+ }
148
+ break;
149
+ }
150
+ case "withdraw-btc": {
151
+ if (name !== "withdrawBTC") throw new TxValidationError(`expected withdrawBTC, server returned ${name}`);
152
+ if (!eqAddr(to, pm)) throw new TxValidationError(`withdrawBTC must target PositionManager`);
153
+ const paramsTuple = args[0];
154
+ if (String(paramsTuple[0]).toLowerCase() !== normalizePositionId(expected.positionId))
155
+ throw new TxValidationError(`positionId mismatch`);
156
+ if (String(paramsTuple[5]) !== expected.btcAddress) throw new TxValidationError(`btcAddress mismatch`);
157
+ if (expected.upperBoundTotalDeduction != null) {
158
+ const txDeduction = BigInt(String(paramsTuple[6]));
159
+ const upper = BigInt(expected.upperBoundTotalDeduction);
160
+ if (txDeduction > upper)
161
+ throw new TxValidationError(
162
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}`
163
+ );
164
+ }
165
+ break;
166
+ }
167
+ case "create-position": {
168
+ if (name !== "createPosition") throw new TxValidationError(`expected createPosition, decoded ${name}`);
169
+ if (!eqAddr(to, pm)) throw new TxValidationError(`createPosition must target PositionManager (${pm}), got ${to}`);
170
+ if (Number(args[4]) !== expected.selectedTerm)
171
+ throw new TxValidationError(`selectedTermMonths mismatch \u2014 tx says ${Number(args[4])}, user asked for ${expected.selectedTerm}`);
172
+ break;
173
+ }
174
+ case "bwar-add-address": {
175
+ if (name !== "addAddress") throw new TxValidationError(`expected addAddress, decoded ${name}`);
176
+ if (!eqAddr(to, expected.registryAddress))
177
+ throw new TxValidationError(`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`);
178
+ if (String(args[0]) !== expected.btcAddress)
179
+ throw new TxValidationError(`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`);
180
+ break;
181
+ }
182
+ case "ucd-approve": {
183
+ if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
184
+ const ucd = vctx.contracts.UCDToken;
185
+ if (!eqAddr(to, ucd)) throw new TxValidationError(`approve must target UCDToken`);
186
+ if (!expected.spenderCandidates.some((s) => eqAddr(String(args[0]), s)))
187
+ throw new TxValidationError(`approve spender not in expected set`);
188
+ const amt = BigInt(String(args[1]));
189
+ const min = BigInt(expected.minAmountWei);
190
+ if (amt < min) throw new TxValidationError(`approve amount ${amt} is less than required ${min}`);
191
+ if (amt > min * 1000n) throw new TxValidationError(`approve amount ${amt} exceeds sanity cap`);
192
+ break;
193
+ }
194
+ case "stablecoin-approve": {
195
+ if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
196
+ if (!eqAddr(to, expected.tokenAddress))
197
+ throw new TxValidationError(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
198
+ if (!eqAddr(String(args[0]), expected.spender))
199
+ throw new TxValidationError(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
200
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits)
201
+ throw new TxValidationError(
202
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
203
+ );
204
+ break;
205
+ }
206
+ case "ucd-approve-controller": {
207
+ if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
208
+ if (!eqAddr(to, expected.ucdTokenAddress))
209
+ throw new TxValidationError(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
210
+ if (!eqAddr(String(args[0]), expected.spender))
211
+ throw new TxValidationError(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
212
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
213
+ throw new TxValidationError(
214
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
215
+ );
216
+ break;
217
+ }
218
+ case "psm-swap": {
219
+ if (name !== "swap") throw new TxValidationError(`expected swap, server returned ${name}`);
220
+ if (!eqAddr(to, expected.psmAddress)) throw new TxValidationError(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
221
+ if (!eqAddr(String(args[0]), expected.stablecoin)) throw new TxValidationError(`swap stablecoin mismatch`);
222
+ if (BigInt(String(args[1])).toString() !== expected.amountIn) throw new TxValidationError(`swap amountIn mismatch`);
223
+ if (BigInt(String(args[2])).toString() !== expected.minOut) throw new TxValidationError(`swap minUcdOut mismatch`);
224
+ if (BigInt(expected.minOut) === 0n)
225
+ throw new TxValidationError(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
226
+ break;
227
+ }
228
+ case "psm-redeem": {
229
+ if (name !== "redeem") throw new TxValidationError(`expected redeem, server returned ${name}`);
230
+ if (!eqAddr(to, expected.psmAddress)) throw new TxValidationError(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
231
+ if (!eqAddr(String(args[0]), expected.stablecoin)) throw new TxValidationError(`redeem stablecoin mismatch`);
232
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei) throw new TxValidationError(`redeem ucdAmount mismatch`);
233
+ if (BigInt(String(args[2])).toString() !== expected.minOut) throw new TxValidationError(`redeem minStablecoinOut mismatch`);
234
+ if (BigInt(expected.minOut) === 0n)
235
+ throw new TxValidationError(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
236
+ break;
237
+ }
238
+ case "set-position-delegate": {
239
+ if (name !== "setPositionDelegate") throw new TxValidationError(`expected setPositionDelegate`);
240
+ if (!eqAddr(to, expected.registryAddress)) throw new TxValidationError(`setPositionDelegate wrong target`);
241
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
242
+ throw new TxValidationError(`positionId mismatch`);
243
+ if (!eqAddr(String(args[1]), expected.delegate)) throw new TxValidationError(`delegate mismatch`);
244
+ break;
245
+ }
246
+ }
247
+ }
248
+ function describeUnsignedTx(unsignedTx) {
249
+ const to = readToAddress(unsignedTx);
250
+ const data = readData(unsignedTx);
251
+ const chainId = readChainId(unsignedTx);
252
+ let fn = "<unparseable>";
253
+ try {
254
+ const parsed = IFACE.parseTransaction({ data });
255
+ if (parsed) fn = parsed.name;
256
+ } catch {
257
+ }
258
+ return { to, fn, chainId };
259
+ }
260
+ var import_ethers3, SIGNABLE_FUNCTIONS, IFACE, TxValidationError;
261
+ var init_tx_validator = __esm({
262
+ "src/boundary/upstream/shared/tx-validator.ts"() {
263
+ "use strict";
264
+ import_ethers3 = require("ethers");
265
+ SIGNABLE_FUNCTIONS = [
266
+ "function mintUCD(bytes32 positionId, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractHash, uint256 quantumTimestamp, bytes calldata mintValidatorSignature) external returns (bool)",
267
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
268
+ "function repayPosition(bytes32 positionId, uint256 repaymentAmount) external returns (bool)",
269
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
270
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
271
+ "function withdrawBTC((bytes32 positionId, bytes32 actionHash, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractBundleHash, string withdrawalAddress, uint256 totalDeduction, uint256 newCollateral, uint256 quantumTimestamp, uint256 btcPrice, string utxoTxid, uint32 utxoVout) params, bytes withdrawalValidatorSignature, bytes btcSpendAuthSignature) external returns (bool)",
272
+ "function approve(address spender, uint256 amount) external returns (bool)",
273
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
274
+ // SimplePSMV2 (plan 08 Part B Phase W1) — the PSM exchange pair, exact signatures.
275
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
276
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
277
+ // Plan 10 A1b — the SDK-originated borrower txs (external-wallet path). Signatures from
278
+ // contracts/src/core/PositionManager.sol:271 and registry/BitcoinWithdrawalAddressRegistry.sol:179.
279
+ "function createPosition(bytes32 pkpId, bytes validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes pkpPublicKey) external returns (bytes32)",
280
+ "function addAddress(string btcAddress) external"
281
+ ];
282
+ IFACE = new import_ethers3.ethers.Interface(SIGNABLE_FUNCTIONS);
283
+ TxValidationError = class extends Error {
284
+ constructor(msg) {
285
+ super(`Refusing to sign server-returned transaction: ${msg}`);
286
+ this.name = "TxValidationError";
287
+ }
288
+ };
289
+ }
290
+ });
291
+
37
292
  // ../sdk/node_modules/bech32/dist/index.js
38
293
  var require_dist = __commonJS({
39
294
  "../sdk/node_modules/bech32/dist/index.js"(exports2) {
@@ -10262,11 +10517,11 @@ var require_mime_types = __commonJS({
10262
10517
  }
10263
10518
  return exts[0];
10264
10519
  }
10265
- function lookup(path4) {
10266
- if (!path4 || typeof path4 !== "string") {
10520
+ function lookup(path5) {
10521
+ if (!path5 || typeof path5 !== "string") {
10267
10522
  return false;
10268
10523
  }
10269
- var extension2 = extname("x." + path4).toLowerCase().substr(1);
10524
+ var extension2 = extname("x." + path5).toLowerCase().substr(1);
10270
10525
  if (!extension2) {
10271
10526
  return false;
10272
10527
  }
@@ -11381,7 +11636,7 @@ var require_form_data = __commonJS({
11381
11636
  "use strict";
11382
11637
  var CombinedStream = require_combined_stream();
11383
11638
  var util3 = require("util");
11384
- var path4 = require("path");
11639
+ var path5 = require("path");
11385
11640
  var http4 = require("http");
11386
11641
  var https2 = require("https");
11387
11642
  var parseUrl2 = require("url").parse;
@@ -11509,11 +11764,11 @@ var require_form_data = __commonJS({
11509
11764
  FormData3.prototype._getContentDisposition = function(value, options) {
11510
11765
  var filename;
11511
11766
  if (typeof options.filepath === "string") {
11512
- filename = path4.normalize(options.filepath).replace(/\\/g, "/");
11767
+ filename = path5.normalize(options.filepath).replace(/\\/g, "/");
11513
11768
  } else if (options.filename || value && (value.name || value.path)) {
11514
- filename = path4.basename(options.filename || value && (value.name || value.path));
11769
+ filename = path5.basename(options.filename || value && (value.name || value.path));
11515
11770
  } else if (value && value.readable && hasOwn(value, "httpVersion")) {
11516
- filename = path4.basename(value.client._httpMessage.path || "");
11771
+ filename = path5.basename(value.client._httpMessage.path || "");
11517
11772
  }
11518
11773
  if (filename) {
11519
11774
  return 'filename="' + filename + '"';
@@ -12177,7 +12432,7 @@ var require_has_flag = __commonJS({
12177
12432
  var require_supports_color = __commonJS({
12178
12433
  "../sdk/node_modules/supports-color/index.js"(exports2, module2) {
12179
12434
  "use strict";
12180
- var os2 = require("os");
12435
+ var os3 = require("os");
12181
12436
  var tty = require("tty");
12182
12437
  var hasFlag = require_has_flag();
12183
12438
  var { env } = process;
@@ -12225,7 +12480,7 @@ var require_supports_color = __commonJS({
12225
12480
  return min;
12226
12481
  }
12227
12482
  if (process.platform === "win32") {
12228
- const osRelease = os2.release().split(".");
12483
+ const osRelease = os3.release().split(".");
12229
12484
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
12230
12485
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
12231
12486
  }
@@ -15155,7 +15410,7 @@ ${errorReport}`);
15155
15410
  }
15156
15411
  init_debug_logger();
15157
15412
  init_session_signature_cache();
15158
- var import_ethers35 = require("ethers");
15413
+ var import_ethers38 = require("ethers");
15159
15414
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15160
15415
  var GRACE_PERIOD_DAYS = 30;
15161
15416
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -17976,12 +18231,12 @@ ${auth.clientId}`;
17976
18231
  }
17977
18232
  async function executeVaultSnapshot(params) {
17978
18233
  global.ethers = {
17979
- ...import_ethers35.ethers,
18234
+ ...import_ethers38.ethers,
17980
18235
  providers: {
17981
- StaticJsonRpcProvider: import_ethers35.ethers.JsonRpcProvider
18236
+ StaticJsonRpcProvider: import_ethers38.ethers.JsonRpcProvider
17982
18237
  },
17983
- Contract: import_ethers35.ethers.Contract,
17984
- utils: import_ethers35.ethers
18238
+ Contract: import_ethers38.ethers.Contract,
18239
+ utils: import_ethers38.ethers
17985
18240
  // v6 moved utils to top level
17986
18241
  };
17987
18242
  global.Lit = {
@@ -27231,11 +27486,11 @@ var require_mime_types2 = __commonJS({
27231
27486
  }
27232
27487
  return exts[0];
27233
27488
  }
27234
- function lookup(path4) {
27235
- if (!path4 || typeof path4 !== "string") {
27489
+ function lookup(path5) {
27490
+ if (!path5 || typeof path5 !== "string") {
27236
27491
  return false;
27237
27492
  }
27238
- var extension2 = extname("x." + path4).toLowerCase().substr(1);
27493
+ var extension2 = extname("x." + path5).toLowerCase().substr(1);
27239
27494
  if (!extension2) {
27240
27495
  return false;
27241
27496
  }
@@ -28350,7 +28605,7 @@ var require_form_data2 = __commonJS({
28350
28605
  "use strict";
28351
28606
  var CombinedStream = require_combined_stream2();
28352
28607
  var util3 = require("util");
28353
- var path4 = require("path");
28608
+ var path5 = require("path");
28354
28609
  var http4 = require("http");
28355
28610
  var https2 = require("https");
28356
28611
  var parseUrl2 = require("url").parse;
@@ -28478,11 +28733,11 @@ var require_form_data2 = __commonJS({
28478
28733
  FormData3.prototype._getContentDisposition = function(value, options) {
28479
28734
  var filename;
28480
28735
  if (typeof options.filepath === "string") {
28481
- filename = path4.normalize(options.filepath).replace(/\\/g, "/");
28736
+ filename = path5.normalize(options.filepath).replace(/\\/g, "/");
28482
28737
  } else if (options.filename || value && (value.name || value.path)) {
28483
- filename = path4.basename(options.filename || value && (value.name || value.path));
28738
+ filename = path5.basename(options.filename || value && (value.name || value.path));
28484
28739
  } else if (value && value.readable && hasOwn(value, "httpVersion")) {
28485
- filename = path4.basename(value.client._httpMessage.path || "");
28740
+ filename = path5.basename(value.client._httpMessage.path || "");
28486
28741
  }
28487
28742
  if (filename) {
28488
28743
  return 'filename="' + filename + '"';
@@ -29146,7 +29401,7 @@ var require_has_flag2 = __commonJS({
29146
29401
  var require_supports_color2 = __commonJS({
29147
29402
  "../lit-ops/node_modules/supports-color/index.js"(exports2, module2) {
29148
29403
  "use strict";
29149
- var os2 = require("os");
29404
+ var os3 = require("os");
29150
29405
  var tty = require("tty");
29151
29406
  var hasFlag = require_has_flag2();
29152
29407
  var { env } = process;
@@ -29194,7 +29449,7 @@ var require_supports_color2 = __commonJS({
29194
29449
  return min;
29195
29450
  }
29196
29451
  if (process.platform === "win32") {
29197
- const osRelease = os2.release().split(".");
29452
+ const osRelease = os3.release().split(".");
29198
29453
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
29199
29454
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
29200
29455
  }
@@ -30426,7 +30681,7 @@ var require_axios = __commonJS({
30426
30681
  var https2 = require("https");
30427
30682
  var http22 = require("http2");
30428
30683
  var util3 = require("util");
30429
- var path4 = require("path");
30684
+ var path5 = require("path");
30430
30685
  var followRedirects2 = require_follow_redirects2();
30431
30686
  var zlib2 = require("zlib");
30432
30687
  var stream4 = require("stream");
@@ -31366,9 +31621,9 @@ var require_axios = __commonJS({
31366
31621
  function removeBrackets2(key) {
31367
31622
  return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
31368
31623
  }
31369
- function renderKey2(path5, key, dots) {
31370
- if (!path5) return key;
31371
- return path5.concat(key).map(function each(token, i) {
31624
+ function renderKey2(path6, key, dots) {
31625
+ if (!path6) return key;
31626
+ return path6.concat(key).map(function each(token, i) {
31372
31627
  token = removeBrackets2(token);
31373
31628
  return !dots && i ? "[" + token + "]" : token;
31374
31629
  }).join(dots ? "." : "");
@@ -31446,13 +31701,13 @@ var require_axios = __commonJS({
31446
31701
  return currentValue;
31447
31702
  });
31448
31703
  }
31449
- function defaultVisitor(value, key, path5) {
31704
+ function defaultVisitor(value, key, path6) {
31450
31705
  let arr = value;
31451
31706
  if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
31452
- formData.append(renderKey2(path5, key, dots), convertValue(value));
31707
+ formData.append(renderKey2(path6, key, dots), convertValue(value));
31453
31708
  return false;
31454
31709
  }
31455
- if (value && !path5 && typeof value === "object") {
31710
+ if (value && !path6 && typeof value === "object") {
31456
31711
  if (utils$1.endsWith(key, "{}")) {
31457
31712
  key = metaTokens ? key : key.slice(0, -2);
31458
31713
  value = stringifyWithDepthLimit(value, 1);
@@ -31471,7 +31726,7 @@ var require_axios = __commonJS({
31471
31726
  if (isVisitable2(value)) {
31472
31727
  return true;
31473
31728
  }
31474
- formData.append(renderKey2(path5, key, dots), convertValue(value));
31729
+ formData.append(renderKey2(path6, key, dots), convertValue(value));
31475
31730
  return false;
31476
31731
  }
31477
31732
  const exposedHelpers = Object.assign(predicates2, {
@@ -31479,17 +31734,17 @@ var require_axios = __commonJS({
31479
31734
  convertValue,
31480
31735
  isVisitable: isVisitable2
31481
31736
  });
31482
- function build(value, path5, depth = 0) {
31737
+ function build(value, path6, depth = 0) {
31483
31738
  if (utils$1.isUndefined(value)) return;
31484
31739
  throwIfMaxDepthExceeded(depth);
31485
31740
  if (stack.indexOf(value) !== -1) {
31486
- throw new Error("Circular reference detected in " + path5.join("."));
31741
+ throw new Error("Circular reference detected in " + path6.join("."));
31487
31742
  }
31488
31743
  stack.push(value);
31489
31744
  utils$1.forEach(value, function each(el, key) {
31490
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path5, exposedHelpers);
31745
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path6, exposedHelpers);
31491
31746
  if (result === true) {
31492
- build(el, path5 ? path5.concat(key) : [key], depth + 1);
31747
+ build(el, path6 ? path6.concat(key) : [key], depth + 1);
31493
31748
  }
31494
31749
  });
31495
31750
  stack.pop();
@@ -31678,7 +31933,7 @@ var require_axios = __commonJS({
31678
31933
  };
31679
31934
  function toURLEncodedForm2(data, options) {
31680
31935
  return toFormData3(data, new platform.classes.URLSearchParams(), {
31681
- visitor: function(value, key, path5, helpers) {
31936
+ visitor: function(value, key, path6, helpers) {
31682
31937
  if (platform.isNode && utils$1.isBuffer(value)) {
31683
31938
  this.append(key, value.toString("base64"));
31684
31939
  return false;
@@ -31695,14 +31950,14 @@ var require_axios = __commonJS({
31695
31950
  }
31696
31951
  }
31697
31952
  function parsePropPath2(name) {
31698
- const path5 = [];
31953
+ const path6 = [];
31699
31954
  const pattern = /\w+|\[(\w*)]/g;
31700
31955
  let match;
31701
31956
  while ((match = pattern.exec(name)) !== null) {
31702
- throwIfDepthExceeded(path5.length);
31703
- path5.push(match[0] === "[]" ? "" : match[1] || match[0]);
31957
+ throwIfDepthExceeded(path6.length);
31958
+ path6.push(match[0] === "[]" ? "" : match[1] || match[0]);
31704
31959
  }
31705
- return path5;
31960
+ return path6;
31706
31961
  }
31707
31962
  function arrayToObject2(arr) {
31708
31963
  const obj = {};
@@ -31717,12 +31972,12 @@ var require_axios = __commonJS({
31717
31972
  return obj;
31718
31973
  }
31719
31974
  function formDataToJSON2(formData) {
31720
- function buildPath(path5, value, target, index) {
31975
+ function buildPath(path6, value, target, index) {
31721
31976
  throwIfDepthExceeded(index);
31722
- let name = path5[index++];
31977
+ let name = path6[index++];
31723
31978
  if (name === "__proto__") return true;
31724
31979
  const isNumericKey = Number.isFinite(+name);
31725
- const isLast = index >= path5.length;
31980
+ const isLast = index >= path6.length;
31726
31981
  name = !name && utils$1.isArray(target) ? target.length : name;
31727
31982
  if (isLast) {
31728
31983
  if (utils$1.hasOwnProp(target, name)) {
@@ -31735,7 +31990,7 @@ var require_axios = __commonJS({
31735
31990
  if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
31736
31991
  target[name] = [];
31737
31992
  }
31738
- const result = buildPath(path5, value, target[name], index);
31993
+ const result = buildPath(path6, value, target[name], index);
31739
31994
  if (result && utils$1.isArray(target[name])) {
31740
31995
  target[name] = arrayToObject2(target[name]);
31741
31996
  }
@@ -33230,8 +33485,8 @@ var require_axios = __commonJS({
33230
33485
  const allowedSocketPaths = own3("allowedSocketPaths");
33231
33486
  if (allowedSocketPaths != null) {
33232
33487
  const allowed = Array.isArray(allowedSocketPaths) ? allowedSocketPaths : [allowedSocketPaths];
33233
- const resolvedSocket = path4.resolve(socketPath);
33234
- const isAllowed = allowed.some((entry) => typeof entry === "string" && path4.resolve(entry) === resolvedSocket);
33488
+ const resolvedSocket = path5.resolve(socketPath);
33489
+ const isAllowed = allowed.some((entry) => typeof entry === "string" && path5.resolve(entry) === resolvedSocket);
33235
33490
  if (!isAllowed) {
33236
33491
  return reject(new AxiosError3(`socketPath "${socketPath}" is not permitted by allowedSocketPaths`, AxiosError3.ERR_BAD_OPTION_VALUE, config));
33237
33492
  }
@@ -33530,14 +33785,14 @@ var require_axios = __commonJS({
33530
33785
  var cookies = platform.hasStandardBrowserEnv ? (
33531
33786
  // Standard browser envs support document.cookie
33532
33787
  {
33533
- write(name, value, expires, path5, domain, secure, sameSite) {
33788
+ write(name, value, expires, path6, domain, secure, sameSite) {
33534
33789
  if (typeof document === "undefined") return;
33535
33790
  const cookie = [`${name}=${encodeURIComponent(value)}`];
33536
33791
  if (utils$1.isNumber(expires)) {
33537
33792
  cookie.push(`expires=${new Date(expires).toUTCString()}`);
33538
33793
  }
33539
- if (utils$1.isString(path5)) {
33540
- cookie.push(`path=${path5}`);
33794
+ if (utils$1.isString(path6)) {
33795
+ cookie.push(`path=${path6}`);
33541
33796
  }
33542
33797
  if (utils$1.isString(domain)) {
33543
33798
  cookie.push(`domain=${domain}`);
@@ -33555,12 +33810,12 @@ var require_axios = __commonJS({
33555
33810
  const cookies2 = document.cookie.split(";");
33556
33811
  for (let i = 0; i < cookies2.length; i++) {
33557
33812
  const cookie = cookies2[i].replace(/^\s+/, "");
33558
- const eq2 = cookie.indexOf("=");
33559
- if (eq2 !== -1 && cookie.slice(0, eq2) === name) {
33813
+ const eq3 = cookie.indexOf("=");
33814
+ if (eq3 !== -1 && cookie.slice(0, eq3) === name) {
33560
33815
  try {
33561
- return decodeURIComponent(cookie.slice(eq2 + 1));
33816
+ return decodeURIComponent(cookie.slice(eq3 + 1));
33562
33817
  } catch (e) {
33563
- return cookie.slice(eq2 + 1);
33818
+ return cookie.slice(eq3 + 1);
33564
33819
  }
33565
33820
  }
33566
33821
  }
@@ -42547,7 +42802,7 @@ var require_bn = __commonJS({
42547
42802
  BN.prototype.eqn = function eqn(num) {
42548
42803
  return this.cmpn(num) === 0;
42549
42804
  };
42550
- BN.prototype.eq = function eq2(num) {
42805
+ BN.prototype.eq = function eq3(num) {
42551
42806
  return this.cmp(num) === 0;
42552
42807
  };
42553
42808
  BN.red = function red(num) {
@@ -45431,7 +45686,7 @@ var require_bn2 = __commonJS({
45431
45686
  BN.prototype.eqn = function eqn(num) {
45432
45687
  return this.cmpn(num) === 0;
45433
45688
  };
45434
- BN.prototype.eq = function eq2(num) {
45689
+ BN.prototype.eq = function eq3(num) {
45435
45690
  return this.cmp(num) === 0;
45436
45691
  };
45437
45692
  BN.red = function red(num) {
@@ -46377,7 +46632,7 @@ var require_base2 = __commonJS({
46377
46632
  this.precomputed = null;
46378
46633
  }
46379
46634
  BaseCurve.BasePoint = BasePoint;
46380
- BasePoint.prototype.eq = function eq2() {
46635
+ BasePoint.prototype.eq = function eq3() {
46381
46636
  throw new Error("Not implemented");
46382
46637
  };
46383
46638
  BasePoint.prototype.validate = function validate2() {
@@ -46882,7 +47137,7 @@ var require_short = __commonJS({
46882
47137
  else
46883
47138
  return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
46884
47139
  };
46885
- Point.prototype.eq = function eq2(p) {
47140
+ Point.prototype.eq = function eq3(p) {
46886
47141
  return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
46887
47142
  };
46888
47143
  Point.prototype.neg = function neg(_precompute) {
@@ -47182,7 +47437,7 @@ var require_short = __commonJS({
47182
47437
  k = new BN(k, kbase);
47183
47438
  return this.curve._wnafMul(this, k);
47184
47439
  };
47185
- JPoint.prototype.eq = function eq2(p) {
47440
+ JPoint.prototype.eq = function eq3(p) {
47186
47441
  if (p.type === "affine")
47187
47442
  return this.eq(p.toJ());
47188
47443
  if (this === p)
@@ -47335,7 +47590,7 @@ var require_mont = __commonJS({
47335
47590
  Point.prototype.jumlAdd = function jumlAdd() {
47336
47591
  throw new Error("Not supported on Montgomery curve");
47337
47592
  };
47338
- Point.prototype.eq = function eq2(other) {
47593
+ Point.prototype.eq = function eq3(other) {
47339
47594
  return this.getX().cmp(other.getX()) === 0;
47340
47595
  };
47341
47596
  Point.prototype.normalize = function normalize() {
@@ -47628,7 +47883,7 @@ var require_edwards = __commonJS({
47628
47883
  this.normalize();
47629
47884
  return this.y.fromRed();
47630
47885
  };
47631
- Point.prototype.eq = function eq2(other) {
47886
+ Point.prototype.eq = function eq3(other) {
47632
47887
  return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0;
47633
47888
  };
47634
47889
  Point.prototype.eqXToP = function eqXToP(x) {
@@ -51800,8 +52055,10 @@ __export(boundary_exports, {
51800
52055
  resolveBoundaryConfig: () => resolveBoundaryConfig
51801
52056
  });
51802
52057
  module.exports = __toCommonJS(boundary_exports);
51803
- var import_node_crypto6 = require("crypto");
52058
+ var import_node_crypto7 = require("crypto");
51804
52059
  var fs5 = __toESM(require("fs"));
52060
+ var os2 = __toESM(require("os"));
52061
+ var path4 = __toESM(require("path"));
51805
52062
 
51806
52063
  // src/boundary/envelope.ts
51807
52064
  function okEnvelope(data, source, warnings = []) {
@@ -52522,6 +52779,14 @@ var BoundaryCore = class {
52522
52779
  borrowerAddress: this.deps.borrowerAddress
52523
52780
  } : {},
52524
52781
  ...info.walletStance ? { walletStance: info.walletStance } : {},
52782
+ ...this.deps.capabilities ? {
52783
+ capabilities: {
52784
+ network: this.deps.network,
52785
+ chainId: this.deps.chainId,
52786
+ practiceWorld: this.deps.network !== "mainnet",
52787
+ ...this.deps.capabilities()
52788
+ }
52789
+ } : {},
52525
52790
  configFingerprint: this.deps.configFingerprint
52526
52791
  },
52527
52792
  source
@@ -54012,218 +54277,7 @@ var MockControl = class {
54012
54277
 
54013
54278
  // src/boundary/upstream/mock/tx-builder.ts
54014
54279
  var import_ethers4 = require("ethers");
54015
-
54016
- // src/boundary/upstream/shared/tx-validator.ts
54017
- var import_ethers3 = require("ethers");
54018
- var SIGNABLE_FUNCTIONS = [
54019
- "function mintUCD(bytes32 positionId, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractHash, uint256 quantumTimestamp, bytes calldata mintValidatorSignature) external returns (bool)",
54020
- "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
54021
- "function repayPosition(bytes32 positionId, uint256 repaymentAmount) external returns (bool)",
54022
- "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
54023
- "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
54024
- "function withdrawBTC((bytes32 positionId, bytes32 actionHash, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractBundleHash, string withdrawalAddress, uint256 totalDeduction, uint256 newCollateral, uint256 quantumTimestamp, uint256 btcPrice, string utxoTxid, uint32 utxoVout) params, bytes withdrawalValidatorSignature, bytes btcSpendAuthSignature) external returns (bool)",
54025
- "function approve(address spender, uint256 amount) external returns (bool)",
54026
- "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
54027
- // SimplePSMV2 (plan 08 Part B Phase W1) — the PSM exchange pair, exact signatures.
54028
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
54029
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)"
54030
- ];
54031
- var IFACE = new import_ethers3.ethers.Interface(SIGNABLE_FUNCTIONS);
54032
- function encodeSignable(fn, args) {
54033
- return IFACE.encodeFunctionData(fn, args);
54034
- }
54035
- function decodeSignable(data) {
54036
- return decode(data);
54037
- }
54038
- var TxValidationError = class extends Error {
54039
- constructor(msg) {
54040
- super(`Refusing to sign server-returned transaction: ${msg}`);
54041
- this.name = "TxValidationError";
54042
- }
54043
- };
54044
- function eqAddr(a, b) {
54045
- if (!a || !b) return false;
54046
- try {
54047
- return import_ethers3.ethers.getAddress(a) === import_ethers3.ethers.getAddress(b);
54048
- } catch {
54049
- return false;
54050
- }
54051
- }
54052
- function readToAddress(tx2) {
54053
- const to = tx2["to"];
54054
- if (typeof to !== "string") throw new TxValidationError(`unsignedTx.to is missing or not a string`);
54055
- return to;
54056
- }
54057
- function readData(tx2) {
54058
- const data = tx2["data"];
54059
- if (typeof data !== "string" || !data.startsWith("0x")) throw new TxValidationError(`unsignedTx.data missing or malformed`);
54060
- return data;
54061
- }
54062
- function readChainId(tx2) {
54063
- const c = tx2["chainId"];
54064
- if (c == null) return null;
54065
- if (typeof c === "number") return c;
54066
- if (typeof c === "string") return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
54067
- if (typeof c === "bigint") return Number(c);
54068
- return null;
54069
- }
54070
- function readValue(tx2) {
54071
- const v = tx2["value"];
54072
- if (v == null) return 0n;
54073
- if (typeof v === "string") return BigInt(v.startsWith("0x") ? v : v);
54074
- if (typeof v === "number") return BigInt(v);
54075
- if (typeof v === "bigint") return v;
54076
- if (typeof v?.toBigInt === "function") return v.toBigInt();
54077
- if (typeof v?.toString === "function") return BigInt(v.toString());
54078
- throw new TxValidationError(`unsignedTx.value has unrecognized type`);
54079
- }
54080
- function decode(data) {
54081
- try {
54082
- const parsed = IFACE.parseTransaction({ data });
54083
- if (!parsed) throw new TxValidationError(`unsignedTx.data does not decode against the signable-function whitelist`);
54084
- return { name: parsed.name, args: parsed.args };
54085
- } catch (e) {
54086
- if (e instanceof TxValidationError) throw e;
54087
- throw new TxValidationError(
54088
- `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
54089
- );
54090
- }
54091
- }
54092
- function normalizePositionId(id) {
54093
- const hex = id.startsWith("0x") ? id : `0x${id}`;
54094
- return import_ethers3.ethers.zeroPadValue(hex, 32).toLowerCase();
54095
- }
54096
- function validateUnsignedTx(unsignedTx, expected, vctx) {
54097
- const txChainId = readChainId(unsignedTx);
54098
- if (txChainId != null && txChainId !== vctx.chainId) {
54099
- throw new TxValidationError(`chainId mismatch \u2014 tx says ${txChainId}, expected ${vctx.chainId}`);
54100
- }
54101
- const value = readValue(unsignedTx);
54102
- if (value !== 0n) throw new TxValidationError(`unsignedTx.value is non-zero (${value})`);
54103
- const to = readToAddress(unsignedTx);
54104
- const data = readData(unsignedTx);
54105
- const { name, args } = decode(data);
54106
- const pm = vctx.contracts.PositionManager;
54107
- switch (expected.kind) {
54108
- case "mint": {
54109
- if (name !== "mintUCD") throw new TxValidationError(`expected mintUCD, server returned ${name}`);
54110
- if (!eqAddr(to, pm)) throw new TxValidationError(`mintUCD must target PositionManager (${pm}), got ${to}`);
54111
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54112
- throw new TxValidationError(`positionId mismatch`);
54113
- if (BigInt(String(args[1])).toString() !== expected.amountWei)
54114
- throw new TxValidationError(`mintAmount mismatch`);
54115
- if (BigInt(String(args[2])).toString() !== expected.mintFeeWei)
54116
- throw new TxValidationError(`mintFee mismatch`);
54117
- break;
54118
- }
54119
- case "repay": {
54120
- if (name !== "makePayment" && name !== "repayPosition")
54121
- throw new TxValidationError(`expected makePayment/repayPosition, server returned ${name}`);
54122
- if (!eqAddr(to, pm)) throw new TxValidationError(`${name} must target PositionManager`);
54123
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54124
- throw new TxValidationError(`positionId mismatch`);
54125
- if (BigInt(String(args[1])).toString() !== expected.amountWei)
54126
- throw new TxValidationError(`paymentAmount mismatch`);
54127
- break;
54128
- }
54129
- case "extend": {
54130
- if (name !== "extendPosition") throw new TxValidationError(`expected extendPosition, server returned ${name}`);
54131
- if (!eqAddr(to, pm)) throw new TxValidationError(`extendPosition must target PositionManager`);
54132
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54133
- throw new TxValidationError(`positionId mismatch`);
54134
- if (Number(args[1]) !== expected.selectedTerm) throw new TxValidationError(`selectedTerm mismatch`);
54135
- if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
54136
- const txFee = BigInt(String(args[5]));
54137
- const upper = BigInt(expected.upperBoundProRataFeeWei);
54138
- if (txFee > upper) throw new TxValidationError(`proRataRenewalFee=${txFee} exceeds upper bound=${upper}`);
54139
- }
54140
- break;
54141
- }
54142
- case "withdraw-btc": {
54143
- if (name !== "withdrawBTC") throw new TxValidationError(`expected withdrawBTC, server returned ${name}`);
54144
- if (!eqAddr(to, pm)) throw new TxValidationError(`withdrawBTC must target PositionManager`);
54145
- const paramsTuple = args[0];
54146
- if (String(paramsTuple[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54147
- throw new TxValidationError(`positionId mismatch`);
54148
- if (String(paramsTuple[5]) !== expected.btcAddress) throw new TxValidationError(`btcAddress mismatch`);
54149
- if (expected.upperBoundTotalDeduction != null) {
54150
- const txDeduction = BigInt(String(paramsTuple[6]));
54151
- const upper = BigInt(expected.upperBoundTotalDeduction);
54152
- if (txDeduction > upper)
54153
- throw new TxValidationError(
54154
- `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}`
54155
- );
54156
- }
54157
- break;
54158
- }
54159
- case "ucd-approve": {
54160
- if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
54161
- const ucd = vctx.contracts.UCDToken;
54162
- if (!eqAddr(to, ucd)) throw new TxValidationError(`approve must target UCDToken`);
54163
- if (!expected.spenderCandidates.some((s) => eqAddr(String(args[0]), s)))
54164
- throw new TxValidationError(`approve spender not in expected set`);
54165
- const amt = BigInt(String(args[1]));
54166
- const min = BigInt(expected.minAmountWei);
54167
- if (amt < min) throw new TxValidationError(`approve amount ${amt} is less than required ${min}`);
54168
- if (amt > min * 1000n) throw new TxValidationError(`approve amount ${amt} exceeds sanity cap`);
54169
- break;
54170
- }
54171
- case "stablecoin-approve": {
54172
- if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
54173
- if (!eqAddr(to, expected.tokenAddress))
54174
- throw new TxValidationError(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
54175
- if (!eqAddr(String(args[0]), expected.spender))
54176
- throw new TxValidationError(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
54177
- if (BigInt(String(args[1])).toString() !== expected.amountUnits)
54178
- throw new TxValidationError(
54179
- `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
54180
- );
54181
- break;
54182
- }
54183
- case "ucd-approve-controller": {
54184
- if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
54185
- if (!eqAddr(to, expected.ucdTokenAddress))
54186
- throw new TxValidationError(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
54187
- if (!eqAddr(String(args[0]), expected.spender))
54188
- throw new TxValidationError(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
54189
- if (BigInt(String(args[1])).toString() !== expected.amountWei)
54190
- throw new TxValidationError(
54191
- `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
54192
- );
54193
- break;
54194
- }
54195
- case "psm-swap": {
54196
- if (name !== "swap") throw new TxValidationError(`expected swap, server returned ${name}`);
54197
- if (!eqAddr(to, expected.psmAddress)) throw new TxValidationError(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
54198
- if (!eqAddr(String(args[0]), expected.stablecoin)) throw new TxValidationError(`swap stablecoin mismatch`);
54199
- if (BigInt(String(args[1])).toString() !== expected.amountIn) throw new TxValidationError(`swap amountIn mismatch`);
54200
- if (BigInt(String(args[2])).toString() !== expected.minOut) throw new TxValidationError(`swap minUcdOut mismatch`);
54201
- if (BigInt(expected.minOut) === 0n)
54202
- throw new TxValidationError(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
54203
- break;
54204
- }
54205
- case "psm-redeem": {
54206
- if (name !== "redeem") throw new TxValidationError(`expected redeem, server returned ${name}`);
54207
- if (!eqAddr(to, expected.psmAddress)) throw new TxValidationError(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
54208
- if (!eqAddr(String(args[0]), expected.stablecoin)) throw new TxValidationError(`redeem stablecoin mismatch`);
54209
- if (BigInt(String(args[1])).toString() !== expected.amountUcdWei) throw new TxValidationError(`redeem ucdAmount mismatch`);
54210
- if (BigInt(String(args[2])).toString() !== expected.minOut) throw new TxValidationError(`redeem minStablecoinOut mismatch`);
54211
- if (BigInt(expected.minOut) === 0n)
54212
- throw new TxValidationError(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
54213
- break;
54214
- }
54215
- case "set-position-delegate": {
54216
- if (name !== "setPositionDelegate") throw new TxValidationError(`expected setPositionDelegate`);
54217
- if (!eqAddr(to, expected.registryAddress)) throw new TxValidationError(`setPositionDelegate wrong target`);
54218
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54219
- throw new TxValidationError(`positionId mismatch`);
54220
- if (!eqAddr(String(args[1]), expected.delegate)) throw new TxValidationError(`delegate mismatch`);
54221
- break;
54222
- }
54223
- }
54224
- }
54225
-
54226
- // src/boundary/upstream/mock/tx-builder.ts
54280
+ init_tx_validator();
54227
54281
  var ZERO32 = import_ethers4.ethers.ZeroHash;
54228
54282
  var EMPTY_SIG = "0x" + "00".repeat(65);
54229
54283
  function tx(ctx, data) {
@@ -54426,6 +54480,12 @@ var KeystoreProvider = class {
54426
54480
  signer() {
54427
54481
  return this.wallet;
54428
54482
  }
54483
+ /** Adopt an ALREADY-DECRYPTED wallet (plan 10 OV-8: the real boot keeps its eager
54484
+ * decrypt with loud typed errors; the provider consumes the result instead of paying
54485
+ * scrypt twice). */
54486
+ adopt(wallet) {
54487
+ this.wallet = wallet;
54488
+ }
54429
54489
  /** Material exists (unlocked already, or the env pair is set) — `use keystore` succeeds. */
54430
54490
  materialConfigured() {
54431
54491
  return this.wallet !== null || Boolean(this.env.keystorePath && this.env.keystorePassword);
@@ -55300,6 +55360,7 @@ var import_ethers9 = require("ethers");
55300
55360
 
55301
55361
  // src/boundary/upstream/shared/external-bridge/card.ts
55302
55362
  var import_ethers7 = require("ethers");
55363
+ init_tx_validator();
55303
55364
  function formatUcd(wei) {
55304
55365
  const negative = wei < 0n;
55305
55366
  const abs = negative ? -wei : wei;
@@ -55340,6 +55401,23 @@ function cardForTx(tx2) {
55340
55401
  if (args.length >= 7) lines.push(ucdLine("Renewal fee, at most (ADDED TO YOUR DEBT \u2014 wallet not charged)", args[5]));
55341
55402
  return [...lines, ...head];
55342
55403
  }
55404
+ case "createPosition":
55405
+ return [
55406
+ "Operation: create a new borrowing position (your wallet is the borrower)",
55407
+ `Term: ${Number(args[4])} months`,
55408
+ `Position key (PKP id): ${String(args[0])}`,
55409
+ `BTC vault (mainnet form): ${String(args[2])}`,
55410
+ `BTC vault (regtest form): ${String(args[3])}`,
55411
+ `Validator generation: ${Number(args[5])}`,
55412
+ ...head
55413
+ ];
55414
+ case "addAddress":
55415
+ return [
55416
+ "Operation: allowlist a Bitcoin withdrawal destination for YOUR account",
55417
+ `BTC address to allowlist: ${String(args[0])}`,
55418
+ "Withdrawals to this address become possible only after the registry's on-chain delay",
55419
+ ...head
55420
+ ];
55343
55421
  case "approve":
55344
55422
  return [
55345
55423
  "Operation: token allowance approval (EXACT amount \u2014 never unlimited)",
@@ -55407,6 +55485,9 @@ function recoverOperationSigner(payload, signature) {
55407
55485
  );
55408
55486
  }
55409
55487
 
55488
+ // src/boundary/upstream/mock/external-ceremony.ts
55489
+ init_tx_validator();
55490
+
55410
55491
  // src/signer/keystore-signer.ts
55411
55492
  var import_ethers8 = require("ethers");
55412
55493
  var LOGIN_DOMAIN = (chainId) => ({ name: "Diamond Hands", version: "1", chainId });
@@ -55640,6 +55721,7 @@ function openInBrowser(url2) {
55640
55721
 
55641
55722
  // src/boundary/upstream/mock/keystore-ceremony.ts
55642
55723
  var import_ethers10 = require("ethers");
55724
+ init_tx_validator();
55643
55725
  var SOURCE2 = "keystore-signer";
55644
55726
  var KeystoreCeremony = class {
55645
55727
  constructor(deps) {
@@ -55715,6 +55797,7 @@ var KeystoreCeremony = class {
55715
55797
  // src/boundary/upstream/mock/safe-ceremony.ts
55716
55798
  var import_node_crypto4 = require("crypto");
55717
55799
  var import_ethers11 = require("ethers");
55800
+ init_tx_validator();
55718
55801
 
55719
55802
  // src/boundary/upstream/shared/quantum.ts
55720
55803
  var QUANTUM_WINDOW_SECONDS = 60;
@@ -55728,6 +55811,10 @@ function isAuthFresh(issuedAtSec, nowSec) {
55728
55811
  function isStrictCurrentQuantum(issuedAtSec, nowSec) {
55729
55812
  return issuedAtSec <= nowSec && Math.floor(issuedAtSec / QUANTUM_WINDOW_SECONDS) === Math.floor(nowSec / QUANTUM_WINDOW_SECONDS);
55730
55813
  }
55814
+ function nextQuantumTimestamp(nowMs) {
55815
+ const now = Math.floor(nowMs / 1e3);
55816
+ return Math.floor(now / QUANTUM_WINDOW_SECONDS) * QUANTUM_WINDOW_SECONDS + QUANTUM_WINDOW_SECONDS;
55817
+ }
55731
55818
 
55732
55819
  // src/boundary/upstream/mock/safe-ceremony.ts
55733
55820
  var SOURCE3 = "safe-ceremony";
@@ -56118,6 +56205,7 @@ var SafeCeremony = class {
56118
56205
 
56119
56206
  // src/boundary/upstream/mock/safe-module-ceremony.ts
56120
56207
  var import_ethers12 = require("ethers");
56208
+ init_tx_validator();
56121
56209
  var SOURCE4 = "safe-module";
56122
56210
  var SafeModuleCeremony = class {
56123
56211
  constructor(deps) {
@@ -56279,7 +56367,7 @@ var SafeModuleCeremony = class {
56279
56367
  };
56280
56368
 
56281
56369
  // src/boundary/upstream/real/plugin.ts
56282
- var import_ethers34 = require("ethers");
56370
+ var import_ethers37 = require("ethers");
56283
56371
 
56284
56372
  // ../sdk/dist/index.mjs
56285
56373
  var import_ethers13 = require("ethers");
@@ -57658,9 +57746,9 @@ function isVisitable(thing) {
57658
57746
  function removeBrackets(key) {
57659
57747
  return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
57660
57748
  }
57661
- function renderKey(path4, key, dots) {
57662
- if (!path4) return key;
57663
- return path4.concat(key).map(function each(token, i) {
57749
+ function renderKey(path5, key, dots) {
57750
+ if (!path5) return key;
57751
+ return path5.concat(key).map(function each(token, i) {
57664
57752
  token = removeBrackets(token);
57665
57753
  return !dots && i ? "[" + token + "]" : token;
57666
57754
  }).join(dots ? "." : "");
@@ -57714,13 +57802,13 @@ function toFormData(obj, formData, options) {
57714
57802
  }
57715
57803
  return value;
57716
57804
  }
57717
- function defaultVisitor(value, key, path4) {
57805
+ function defaultVisitor(value, key, path5) {
57718
57806
  let arr = value;
57719
57807
  if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) {
57720
- formData.append(renderKey(path4, key, dots), convertValue(value));
57808
+ formData.append(renderKey(path5, key, dots), convertValue(value));
57721
57809
  return false;
57722
57810
  }
57723
- if (value && !path4 && typeof value === "object") {
57811
+ if (value && !path5 && typeof value === "object") {
57724
57812
  if (utils_default.endsWith(key, "{}")) {
57725
57813
  key = metaTokens ? key : key.slice(0, -2);
57726
57814
  value = JSON.stringify(value);
@@ -57739,7 +57827,7 @@ function toFormData(obj, formData, options) {
57739
57827
  if (isVisitable(value)) {
57740
57828
  return true;
57741
57829
  }
57742
- formData.append(renderKey(path4, key, dots), convertValue(value));
57830
+ formData.append(renderKey(path5, key, dots), convertValue(value));
57743
57831
  return false;
57744
57832
  }
57745
57833
  const stack = [];
@@ -57748,7 +57836,7 @@ function toFormData(obj, formData, options) {
57748
57836
  convertValue,
57749
57837
  isVisitable
57750
57838
  });
57751
- function build(value, path4, depth = 0) {
57839
+ function build(value, path5, depth = 0) {
57752
57840
  if (utils_default.isUndefined(value)) return;
57753
57841
  if (depth > maxDepth) {
57754
57842
  throw new AxiosError_default(
@@ -57757,13 +57845,13 @@ function toFormData(obj, formData, options) {
57757
57845
  );
57758
57846
  }
57759
57847
  if (stack.indexOf(value) !== -1) {
57760
- throw Error("Circular reference detected in " + path4.join("."));
57848
+ throw Error("Circular reference detected in " + path5.join("."));
57761
57849
  }
57762
57850
  stack.push(value);
57763
57851
  utils_default.forEach(value, function each(el, key) {
57764
- const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path4, exposedHelpers);
57852
+ const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path5, exposedHelpers);
57765
57853
  if (result === true) {
57766
- build(el, path4 ? path4.concat(key) : [key], depth + 1);
57854
+ build(el, path5 ? path5.concat(key) : [key], depth + 1);
57767
57855
  }
57768
57856
  });
57769
57857
  stack.pop();
@@ -57974,7 +58062,7 @@ var platform_default = {
57974
58062
  // ../sdk/node_modules/axios/lib/helpers/toURLEncodedForm.js
57975
58063
  function toURLEncodedForm(data, options) {
57976
58064
  return toFormData_default(data, new platform_default.classes.URLSearchParams(), {
57977
- visitor: function(value, key, path4, helpers) {
58065
+ visitor: function(value, key, path5, helpers) {
57978
58066
  if (platform_default.isNode && utils_default.isBuffer(value)) {
57979
58067
  this.append(key, value.toString("base64"));
57980
58068
  return false;
@@ -58004,11 +58092,11 @@ function arrayToObject(arr) {
58004
58092
  return obj;
58005
58093
  }
58006
58094
  function formDataToJSON(formData) {
58007
- function buildPath(path4, value, target, index) {
58008
- let name = path4[index++];
58095
+ function buildPath(path5, value, target, index) {
58096
+ let name = path5[index++];
58009
58097
  if (name === "__proto__") return true;
58010
58098
  const isNumericKey = Number.isFinite(+name);
58011
- const isLast = index >= path4.length;
58099
+ const isLast = index >= path5.length;
58012
58100
  name = !name && utils_default.isArray(target) ? target.length : name;
58013
58101
  if (isLast) {
58014
58102
  if (utils_default.hasOwnProp(target, name)) {
@@ -58021,7 +58109,7 @@ function formDataToJSON(formData) {
58021
58109
  if (!utils_default.hasOwnProp(target, name) || !utils_default.isObject(target[name])) {
58022
58110
  target[name] = [];
58023
58111
  }
58024
- const result = buildPath(path4, value, target[name], index);
58112
+ const result = buildPath(path5, value, target[name], index);
58025
58113
  if (result && utils_default.isArray(target[name])) {
58026
58114
  target[name] = arrayToObject(target[name]);
58027
58115
  }
@@ -59477,9 +59565,9 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
59477
59565
  auth = urlUsername + ":" + urlPassword;
59478
59566
  }
59479
59567
  auth && headers.delete("authorization");
59480
- let path4;
59568
+ let path5;
59481
59569
  try {
59482
- path4 = buildURL(
59570
+ path5 = buildURL(
59483
59571
  parsed.pathname + parsed.search,
59484
59572
  config.params,
59485
59573
  config.paramsSerializer
@@ -59497,7 +59585,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
59497
59585
  false
59498
59586
  );
59499
59587
  const options = Object.assign(/* @__PURE__ */ Object.create(null), {
59500
- path: path4,
59588
+ path: path5,
59501
59589
  method,
59502
59590
  headers: toByteStringHeaderObject(headers),
59503
59591
  agents: { http: config.httpAgent, https: config.httpsAgent },
@@ -59840,14 +59928,14 @@ var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PUR
59840
59928
  var cookies_default = platform_default.hasStandardBrowserEnv ? (
59841
59929
  // Standard browser envs support document.cookie
59842
59930
  {
59843
- write(name, value, expires, path4, domain, secure, sameSite) {
59931
+ write(name, value, expires, path5, domain, secure, sameSite) {
59844
59932
  if (typeof document === "undefined") return;
59845
59933
  const cookie = [`${name}=${encodeURIComponent(value)}`];
59846
59934
  if (utils_default.isNumber(expires)) {
59847
59935
  cookie.push(`expires=${new Date(expires).toUTCString()}`);
59848
59936
  }
59849
- if (utils_default.isString(path4)) {
59850
- cookie.push(`path=${path4}`);
59937
+ if (utils_default.isString(path5)) {
59938
+ cookie.push(`path=${path5}`);
59851
59939
  }
59852
59940
  if (utils_default.isString(domain)) {
59853
59941
  cookie.push(`domain=${domain}`);
@@ -59865,9 +59953,9 @@ var cookies_default = platform_default.hasStandardBrowserEnv ? (
59865
59953
  const cookies = document.cookie.split(";");
59866
59954
  for (let i = 0; i < cookies.length; i++) {
59867
59955
  const cookie = cookies[i].replace(/^\s+/, "");
59868
- const eq2 = cookie.indexOf("=");
59869
- if (eq2 !== -1 && cookie.slice(0, eq2) === name) {
59870
- return decodeURIComponent(cookie.slice(eq2 + 1));
59956
+ const eq3 = cookie.indexOf("=");
59957
+ if (eq3 !== -1 && cookie.slice(0, eq3) === name) {
59958
+ return decodeURIComponent(cookie.slice(eq3 + 1));
59871
59959
  }
59872
59960
  }
59873
59961
  return null;
@@ -87123,6 +87211,12 @@ var LitOpsSession = class {
87123
87211
  address() {
87124
87212
  return this.wallet.address;
87125
87213
  }
87214
+ /** A JWT is cached and not about to expire — reads in external mode consult this
87215
+ * instead of `token()` so they NEVER summon the wallet (plan 10 A0.7). */
87216
+ hasValidToken() {
87217
+ const now = Math.floor(Date.now() / 1e3);
87218
+ return this.cached !== null && this.cached.expiresAtSec - REFRESH_LEEWAY_SEC > now;
87219
+ }
87126
87220
  /** A valid Bearer token, logging in (or re-logging) as needed. Throws with a legible
87127
87221
  * message on failure — the gateway maps it to the taxonomy. */
87128
87222
  async token() {
@@ -87180,9 +87274,240 @@ function decodeJwtExp(token) {
87180
87274
  }
87181
87275
 
87182
87276
  // src/boundary/upstream/real/write-ops.ts
87277
+ var import_ethers33 = require("ethers");
87278
+
87279
+ // src/signer/types.ts
87280
+ var OperationDeclined = class extends Error {
87281
+ };
87282
+
87283
+ // src/boundary/upstream/real/write-ops.ts
87284
+ init_tx_validator();
87285
+
87286
+ // src/boundary/upstream/shared/external-bridge/page-crypto.ts
87183
87287
  var import_ethers32 = require("ethers");
87288
+ var PERSONAL_SIGN_LAYOUTS = {
87289
+ "dh-op-envelope-v1": {
87290
+ types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87291
+ fieldOrder: ["positionId", "timestamp", "chainId", "amount", "action"],
87292
+ hashUtf8Fields: ["action"]
87293
+ }
87294
+ };
87295
+ function hashForLayout(layout, fields) {
87296
+ const def = PERSONAL_SIGN_LAYOUTS[layout];
87297
+ if (!def) throw new Error(`page-crypto: unknown layout "${layout}"`);
87298
+ const hashUtf8 = new Set(def.hashUtf8Fields);
87299
+ const values = def.fieldOrder.map((name) => {
87300
+ const raw = fields[name];
87301
+ if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
87302
+ return hashUtf8.has(name) ? import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(raw)) : raw;
87303
+ });
87304
+ return import_ethers32.ethers.solidityPackedKeccak256(def.types, values);
87305
+ }
87306
+ var PAGE_CRYPTO_JS = `"use strict";
87307
+ (function () {
87308
+ // keccak-f[1600] \u2014 25 lanes of 64-bit BigInt, state[x + 5*y]. Validated bit-for-bit
87309
+ // against ethers.keccak256 across empty/short/rate-boundary inputs (page-crypto.test.ts).
87310
+ var MASK64 = (1n << 64n) - 1n;
87311
+
87312
+ function rotl64(x, n) {
87313
+ x &= MASK64;
87314
+ var nn = BigInt(n % 64);
87315
+ if (nn === 0n) return x;
87316
+ return ((x << nn) | (x >> (64n - nn))) & MASK64;
87317
+ }
87318
+
87319
+ var RC = [
87320
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
87321
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
87322
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
87323
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
87324
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
87325
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n
87326
+ ];
87327
+
87328
+ // r[x][y] rotation offsets, flat index x + 5*y.
87329
+ var ROT = [
87330
+ 0, 1, 62, 28, 27,
87331
+ 36, 44, 6, 55, 20,
87332
+ 3, 10, 43, 25, 39,
87333
+ 41, 45, 15, 21, 8,
87334
+ 18, 2, 61, 56, 14
87335
+ ];
87336
+
87337
+ function keccakF1600(state) {
87338
+ for (var round = 0; round < 24; round++) {
87339
+ var C = new Array(5);
87340
+ for (var x = 0; x < 5; x++) {
87341
+ C[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20];
87342
+ }
87343
+ var D = new Array(5);
87344
+ for (var x2 = 0; x2 < 5; x2++) {
87345
+ D[x2] = C[(x2 + 4) % 5] ^ rotl64(C[(x2 + 1) % 5], 1);
87346
+ }
87347
+ for (var x3 = 0; x3 < 5; x3++) {
87348
+ for (var y = 0; y < 5; y++) {
87349
+ state[x3 + 5 * y] ^= D[x3];
87350
+ }
87351
+ }
87352
+ var B = new Array(25);
87353
+ for (var x4 = 0; x4 < 5; x4++) {
87354
+ for (var y2 = 0; y2 < 5; y2++) {
87355
+ var newX = y2;
87356
+ var newY = (2 * x4 + 3 * y2) % 5;
87357
+ B[newX + 5 * newY] = rotl64(state[x4 + 5 * y2], ROT[x4 + 5 * y2]);
87358
+ }
87359
+ }
87360
+ for (var x5 = 0; x5 < 5; x5++) {
87361
+ for (var y3 = 0; y3 < 5; y3++) {
87362
+ var idx = x5 + 5 * y3;
87363
+ state[idx] = (B[idx] ^ (~B[(x5 + 1) % 5 + 5 * y3] & B[(x5 + 2) % 5 + 5 * y3])) & MASK64;
87364
+ }
87365
+ }
87366
+ state[0] = (state[0] ^ RC[round]) & MASK64;
87367
+ }
87368
+ }
87369
+
87370
+ function keccak256Bytes(bytes) {
87371
+ var rateBytes = 136; // 1088-bit rate (keccak256: capacity 512 bits)
87372
+ var state = new Array(25).fill(0n);
87373
+
87374
+ // Original-Keccak multi-rate padding (pad10*1, domain byte 0x01 \u2014 NOT NIST SHA3's 0x06).
87375
+ var padLen = rateBytes - (bytes.length % rateBytes);
87376
+ var padded = new Uint8Array(bytes.length + padLen);
87377
+ padded.set(bytes);
87378
+ padded[bytes.length] ^= 0x01;
87379
+ padded[padded.length - 1] ^= 0x80;
87380
+
87381
+ for (var off = 0; off < padded.length; off += rateBytes) {
87382
+ for (var i = 0; i < rateBytes / 8; i++) {
87383
+ var lane = 0n;
87384
+ for (var b = 7; b >= 0; b--) {
87385
+ lane = (lane << 8n) | BigInt(padded[off + i * 8 + b]);
87386
+ }
87387
+ state[i] ^= lane;
87388
+ }
87389
+ keccakF1600(state);
87390
+ }
87391
+
87392
+ var out = new Uint8Array(32);
87393
+ for (var j = 0; j < 4; j++) {
87394
+ var laneOut = state[j];
87395
+ for (var b2 = 0; b2 < 8; b2++) {
87396
+ out[j * 8 + b2] = Number(laneOut & 0xffn);
87397
+ laneOut >>= 8n;
87398
+ }
87399
+ }
87400
+ return out;
87401
+ }
87402
+
87403
+ function bytesToHex(bytes) {
87404
+ var hex = "0x";
87405
+ for (var i = 0; i < bytes.length; i++) {
87406
+ hex += bytes[i].toString(16).padStart(2, "0");
87407
+ }
87408
+ return hex;
87409
+ }
87410
+
87411
+ function hexToBytes(hex) {
87412
+ if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) {
87413
+ throw new Error("dhPageCrypto: not a 0x-hex string: " + String(hex));
87414
+ }
87415
+ var clean = hex.slice(2);
87416
+ if (clean.length % 2 !== 0) {
87417
+ throw new Error("dhPageCrypto: odd-length hex string: " + hex);
87418
+ }
87419
+ var out = new Uint8Array(clean.length / 2);
87420
+ for (var i = 0; i < out.length; i++) {
87421
+ out[i] = parseInt(clean.substr(i * 2, 2), 16);
87422
+ }
87423
+ return out;
87424
+ }
87425
+
87426
+ function keccak256HexOfBytes(hexStr) {
87427
+ return bytesToHex(keccak256Bytes(hexToBytes(hexStr)));
87428
+ }
87429
+
87430
+ function keccak256Utf8(str) {
87431
+ return bytesToHex(keccak256Bytes(new TextEncoder().encode(String(str))));
87432
+ }
87433
+
87434
+ function uint256ToBytes32(decStr) {
87435
+ if (typeof decStr !== "string" || !/^[0-9]+$/.test(decStr)) {
87436
+ throw new Error("dhPageCrypto: not a decimal uint256 string: " + String(decStr));
87437
+ }
87438
+ var n = BigInt(decStr);
87439
+ if (n > (2n ** 256n) - 1n) {
87440
+ throw new Error("dhPageCrypto: uint256 out of range: " + decStr);
87441
+ }
87442
+ var bytes = new Uint8Array(32);
87443
+ for (var i = 31; i >= 0; i--) {
87444
+ bytes[i] = Number(n & 0xffn);
87445
+ n >>= 8n;
87446
+ }
87447
+ return bytes;
87448
+ }
87449
+
87450
+ function requireBytes32(hex, fieldName) {
87451
+ var bytes = hexToBytes(hex);
87452
+ if (bytes.length !== 32) {
87453
+ throw new Error("dhPageCrypto: field \\"" + fieldName + "\\" must be exactly 32 bytes, got " + bytes.length);
87454
+ }
87455
+ return bytes;
87456
+ }
87457
+
87458
+ // Embedded verbatim from PERSONAL_SIGN_LAYOUTS (page-crypto.ts) \u2014 see the anti-drift note
87459
+ // in that file's header comment. Do not hand-edit; this is generated at module load.
87460
+ var PERSONAL_SIGN_LAYOUTS = ${JSON.stringify(PERSONAL_SIGN_LAYOUTS)};
87461
+
87462
+ function packAndHash(layout, fields) {
87463
+ var def = PERSONAL_SIGN_LAYOUTS[layout];
87464
+ if (!def) {
87465
+ throw new Error("dhPageCrypto: unknown layout \\"" + layout + "\\"");
87466
+ }
87467
+ var hashUtf8 = {};
87468
+ for (var h = 0; h < def.hashUtf8Fields.length; h++) {
87469
+ hashUtf8[def.hashUtf8Fields[h]] = true;
87470
+ }
87471
+ var parts = [];
87472
+ var totalLen = 0;
87473
+ for (var i = 0; i < def.fieldOrder.length; i++) {
87474
+ var name = def.fieldOrder[i];
87475
+ var type = def.types[i];
87476
+ var raw = fields ? fields[name] : undefined;
87477
+ if (raw === undefined || raw === null) {
87478
+ throw new Error("dhPageCrypto: layout \\"" + layout + "\\" missing field \\"" + name + "\\"");
87479
+ }
87480
+ var valueHex = hashUtf8[name] ? keccak256Utf8(String(raw)) : raw;
87481
+ var part;
87482
+ if (type === "bytes32") {
87483
+ part = requireBytes32(valueHex, name);
87484
+ } else if (type === "uint256") {
87485
+ part = uint256ToBytes32(valueHex);
87486
+ } else {
87487
+ throw new Error("dhPageCrypto: unsupported packed type \\"" + type + "\\" in layout \\"" + layout + "\\"");
87488
+ }
87489
+ parts.push(part);
87490
+ totalLen += part.length;
87491
+ }
87492
+ var packed = new Uint8Array(totalLen);
87493
+ var offset = 0;
87494
+ for (var p = 0; p < parts.length; p++) {
87495
+ packed.set(parts[p], offset);
87496
+ offset += parts[p].length;
87497
+ }
87498
+ return keccak256HexOfBytes(bytesToHex(packed));
87499
+ }
87500
+
87501
+ globalThis.dhPageCrypto = {
87502
+ keccak256HexOfBytes: keccak256HexOfBytes,
87503
+ keccak256Utf8: keccak256Utf8,
87504
+ packAndHash: packAndHash
87505
+ };
87506
+ })();
87507
+ `;
87184
87508
 
87185
87509
  // src/boundary/upstream/real/validation-context.ts
87510
+ init_tx_validator();
87186
87511
  function buildValidationContext(network, chainId) {
87187
87512
  const sdkKey = chainId === 31337 ? "localhost" : chainId === 11155111 ? "sepolia" : network.toLowerCase();
87188
87513
  const contracts = getContractsByNetwork(sdkKey);
@@ -87202,14 +87527,10 @@ function psmMainnetWriteRefusal(network, chainId) {
87202
87527
  message: `psmSwap is refused (MAINNET_WRITES_DISABLED): PSM writes are enabled on sepolia ONLY, and this process is configured for network '${network}' (chainId ${chainId}) \u2014 the standing mainnet write block; mainnet PSM operations await their dedicated security review. No ceremony was started and no signer was touched. PSM reads (psm_quote, protocol://psm) remain available.`
87203
87528
  };
87204
87529
  }
87205
- var QUANTUM_SECONDS3 = 60;
87206
87530
  var SOURCE5 = "real-ops";
87207
- function nextQuantumTimestamp() {
87208
- const now = Math.floor(Date.now() / 1e3);
87209
- return Math.floor(now / QUANTUM_SECONDS3) * QUANTUM_SECONDS3 + QUANTUM_SECONDS3;
87210
- }
87531
+ var OP_LAYOUT = "dh-op-envelope-v1";
87211
87532
  function randomNonceHex() {
87212
- return "0x" + Buffer.from(import_ethers32.ethers.randomBytes(16)).toString("hex");
87533
+ return "0x" + Buffer.from(import_ethers33.ethers.randomBytes(16)).toString("hex");
87213
87534
  }
87214
87535
  async function postJson(url2, body, headers) {
87215
87536
  const res = await fetch(url2, {
@@ -87249,15 +87570,55 @@ function buildWriteOps(deps) {
87249
87570
  })
87250
87571
  );
87251
87572
  const failed = (op, e) => upFail({ kind: "unavailable", source: SOURCE5, message: `${op} failed to reach lit-ops`, raw: String(e) });
87573
+ const submitFailure = (leg, e) => e instanceof OperationDeclined ? upFail({ kind: "rejected", source: SOURCE5, message: `${leg} was refused: ${e.message}` }) : upFail({ kind: "unavailable", source: SOURCE5, message: `${leg} failed: ${e instanceof Error ? e.message : String(e)}`, raw: String(e) });
87574
+ function opAuthSpec(p) {
87575
+ return {
87576
+ action: p.action,
87577
+ layout: OP_LAYOUT,
87578
+ stamp: (quantumTs) => {
87579
+ const fields = {
87580
+ positionId: p.positionId,
87581
+ timestamp: String(quantumTs),
87582
+ chainId: String(chainId),
87583
+ amount: p.amount.toString(),
87584
+ action: p.action
87585
+ };
87586
+ return { fields, hashHex: hashForLayout(OP_LAYOUT, fields), card: p.card(fields) };
87587
+ }
87588
+ };
87589
+ }
87590
+ function toCardPayload(tx2) {
87591
+ return {
87592
+ to: String(tx2["to"] ?? ""),
87593
+ data: String(tx2["data"] ?? "0x"),
87594
+ value: tx2["value"] != null ? import_ethers33.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
87595
+ chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
87596
+ };
87597
+ }
87252
87598
  async function executeAndBroadcast(p) {
87253
- const userSignature = await dhSigner.signAuthMessage(p.messageHash);
87599
+ let authRes;
87600
+ try {
87601
+ authRes = await dhSigner.signAuthorization(p.spec);
87602
+ } catch (e) {
87603
+ return submitFailure(`${p.op} authorization`, e);
87604
+ }
87605
+ const digest = p.spec.stamp(authRes.quantumTs).hashHex;
87254
87606
  const borrowerAddress = await dhSigner.getBorrowerAddress();
87255
- const headers = await session.authHeader();
87607
+ let headers;
87608
+ try {
87609
+ headers = await session.authHeader();
87610
+ } catch (e) {
87611
+ return upFail({
87612
+ kind: "unavailable",
87613
+ source: SOURCE5,
87614
+ message: `${p.op} could not establish the lit-ops login session (broker unreachable, or throttling logins): ${e instanceof Error ? e.message : String(e)}`
87615
+ });
87616
+ }
87256
87617
  let execJson;
87257
87618
  try {
87258
87619
  execJson = await postJson(
87259
87620
  `${config.serviceEndpoint}/api/lit/${p.op}/execute`,
87260
- { authMessage: p.authMessage, userSignature, borrowerAddress },
87621
+ { authMessage: p.authMessage(authRes.quantumTs), userSignature: authRes.signature, borrowerAddress },
87261
87622
  headers
87262
87623
  );
87263
87624
  } catch (e) {
@@ -87281,12 +87642,13 @@ function buildWriteOps(deps) {
87281
87642
  } catch (e) {
87282
87643
  return upFail({ kind: "rejected", source: SOURCE5, message: `approve tx failed the M-9 whitelist: ${e.message}` });
87283
87644
  }
87284
- const signedApprove = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedApproveTx));
87285
87645
  try {
87286
- const approveJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx: signedApprove }, headers);
87287
- if (approveJson["success"] !== true) return declined(`${p.op} (UCD approve)`, approveJson["error"]);
87646
+ await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedApproveTx), {
87647
+ action: `${p.spec.action} (UCD approve)`,
87648
+ card: cardForTx(toCardPayload(unsignedApproveTx))
87649
+ });
87288
87650
  } catch (e) {
87289
- return failed(`${p.op} (UCD approve broadcast)`, e);
87651
+ return submitFailure(`${p.op} (UCD approve)`, e);
87290
87652
  }
87291
87653
  }
87292
87654
  }
@@ -87299,23 +87661,18 @@ function buildWriteOps(deps) {
87299
87661
  } catch (e) {
87300
87662
  return upFail({ kind: "rejected", source: SOURCE5, message: `unsigned tx failed the M-9 whitelist: ${e.message}` });
87301
87663
  }
87302
- const signedTx = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedTx));
87303
- let broadcastJson;
87664
+ let submitted;
87304
87665
  try {
87305
87666
  const meta = p.broadcastMeta(data);
87306
- broadcastJson = await postJson(
87307
- `${config.serviceEndpoint}/api/lit/broadcast`,
87308
- { signedTx, ...meta ? { [p.broadcastMetaKey]: meta } : {} },
87309
- headers
87310
- );
87667
+ submitted = await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedTx), {
87668
+ action: p.spec.action,
87669
+ card: cardForTx(toCardPayload(unsignedTx)),
87670
+ ...meta ? { broadcast: { key: p.broadcastMetaKey, meta } } : {}
87671
+ });
87311
87672
  } catch (e) {
87312
- return failed(`${p.op} broadcast`, e);
87673
+ return submitFailure(`${p.op} broadcast`, e);
87313
87674
  }
87314
- if (broadcastJson["success"] !== true) return declined(`${p.op} broadcast`, broadcastJson["error"]);
87315
- const bData = broadcastJson["data"] ?? {};
87316
- const txHash = String(bData["txHash"] ?? "");
87317
- if (!txHash) return upFail({ kind: "malformed", source: SOURCE5, message: `${p.op} broadcast returned no txHash` });
87318
- return upOk({ data, txHash, digest: p.messageHash }, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87675
+ return upOk({ data, txHash: submitted.txHash, digest }, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87319
87676
  }
87320
87677
  return {
87321
87678
  createPosition: async (p) => {
@@ -87357,15 +87714,21 @@ function buildWriteOps(deps) {
87357
87714
  mint: async (p) => {
87358
87715
  const amountWei = BigInt(p.amountUcdWei);
87359
87716
  const action = "mint-ucd";
87360
- const timestamp = nextQuantumTimestamp();
87361
- const messageHash = import_ethers32.ethers.solidityPackedKeccak256(
87362
- ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87363
- [p.positionId, timestamp, chainId, amountWei, import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(action))]
87364
- );
87365
87717
  const r = await executeAndBroadcast({
87366
87718
  op: "mint",
87367
- authMessage: { positionId: p.positionId, timestamp, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87368
- messageHash,
87719
+ spec: opAuthSpec({
87720
+ action,
87721
+ positionId: p.positionId,
87722
+ amount: amountWei,
87723
+ card: (f) => [
87724
+ "Authorize: mint UCD against your BTC collateral (this signature authorizes the operation; the transaction that executes it is approved separately)",
87725
+ `Position: ${p.positionId}`,
87726
+ `Amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
87727
+ `Chain id: ${chainId}`,
87728
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87729
+ ]
87730
+ }),
87731
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87369
87732
  validation: (data) => {
87370
87733
  const mintFee2 = data["mintFee"];
87371
87734
  if (typeof mintFee2 !== "string" || mintFee2.length === 0) {
@@ -87388,7 +87751,7 @@ function buildWriteOps(deps) {
87388
87751
  mintedUcdWei: minted,
87389
87752
  feeUcdWei: mintFee,
87390
87753
  echoedAmountUcdWei: minted,
87391
- authorization: auth(action, `mint ${import_ethers32.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87754
+ authorization: auth(action, `mint ${import_ethers33.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87392
87755
  },
87393
87756
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87394
87757
  );
@@ -87396,15 +87759,21 @@ function buildWriteOps(deps) {
87396
87759
  repay: async (p) => {
87397
87760
  const amountWei = BigInt(p.amountUcdWei);
87398
87761
  const action = "make-payment";
87399
- const timestamp = nextQuantumTimestamp();
87400
- const messageHash = import_ethers32.ethers.solidityPackedKeccak256(
87401
- ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87402
- [p.positionId, timestamp, chainId, amountWei, import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(action))]
87403
- );
87404
87762
  const r = await executeAndBroadcast({
87405
87763
  op: "repay",
87406
- authMessage: { positionId: p.positionId, timestamp, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87407
- messageHash,
87764
+ spec: opAuthSpec({
87765
+ action,
87766
+ positionId: p.positionId,
87767
+ amount: amountWei,
87768
+ card: (f) => [
87769
+ "Authorize: pay down UCD debt (this signature authorizes the operation; the transaction that executes it is approved separately)",
87770
+ `Position: ${p.positionId}`,
87771
+ `Payment amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
87772
+ `Chain id: ${chainId}`,
87773
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87774
+ ]
87775
+ }),
87776
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87408
87777
  validation: () => ({ kind: "repay", positionId: p.positionId, amountWei: amountWei.toString() }),
87409
87778
  approveValidation: () => {
87410
87779
  const vctx = buildValidationContext(config.network, chainId);
@@ -87423,22 +87792,28 @@ function buildWriteOps(deps) {
87423
87792
  txRef: { kind: "eth-tx", id: r.value.txHash },
87424
87793
  paidUcdWei: paid,
87425
87794
  echoedAmountUcdWei: paid,
87426
- authorization: auth(action, `repay ${import_ethers32.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
87795
+ authorization: auth(action, `repay ${import_ethers33.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
87427
87796
  },
87428
87797
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87429
87798
  );
87430
87799
  },
87431
87800
  extend: async (p) => {
87432
87801
  const action = "extend-position";
87433
- const timestamp = nextQuantumTimestamp();
87434
- const messageHash = import_ethers32.ethers.solidityPackedKeccak256(
87435
- ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87436
- [p.positionId, timestamp, chainId, p.selectedTerm, import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(action))]
87437
- );
87438
87802
  const r = await executeAndBroadcast({
87439
87803
  op: "renew",
87440
- authMessage: { positionId: p.positionId, timestamp, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() },
87441
- messageHash,
87804
+ spec: opAuthSpec({
87805
+ action,
87806
+ positionId: p.positionId,
87807
+ amount: BigInt(p.selectedTerm),
87808
+ card: (f) => [
87809
+ "Authorize: extend (renew) the position term (this signature authorizes the operation; the transaction that executes it is approved separately)",
87810
+ `Position: ${p.positionId}`,
87811
+ `New term: ${p.selectedTerm} months`,
87812
+ `Chain id: ${chainId}`,
87813
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87814
+ ]
87815
+ }),
87816
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() }),
87442
87817
  validation: () => ({ kind: "extend", positionId: p.positionId, selectedTerm: p.selectedTerm }),
87443
87818
  broadcastMetaKey: "renewMeta",
87444
87819
  broadcastMeta: () => ({ positionId: p.positionId, borrowerAddress: p.borrower, selectedTerm: p.selectedTerm, chainId })
@@ -87514,20 +87889,18 @@ function buildWriteOps(deps) {
87514
87889
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
87515
87890
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
87516
87891
  const tokenSymbol = isSwap ? "USDC" : "UCD";
87517
- const headers = await session.authHeader();
87518
87892
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
87519
87893
  if (!quoteR.ok) return upFail(quoteR.failure);
87520
- const broadcast = async (leg, tx2) => {
87894
+ const broadcast = async (leg, action, tx2) => {
87521
87895
  try {
87522
87896
  const populated = await dhSigner.getEthersSigner().populateTransaction(tx2);
87523
- const signed = await dhSigner.signTransaction(populated);
87524
- const j = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx: signed }, headers);
87525
- if (j["success"] !== true) return declined(leg, j["error"]);
87526
- const txHash = String((j["data"] ?? {})["txHash"] ?? "");
87527
- if (!txHash) return upFail({ kind: "malformed", source: SOURCE5, message: `${leg} broadcast returned no txHash` });
87528
- return upOk(txHash, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87897
+ const submitted = await dhSigner.submitValidatedTx(populated, {
87898
+ action,
87899
+ card: cardForTx(toCardPayload(tx2))
87900
+ });
87901
+ return upOk(submitted.txHash, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87529
87902
  } catch (e) {
87530
- return failed(leg, e);
87903
+ return submitFailure(leg, e);
87531
87904
  }
87532
87905
  };
87533
87906
  const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
@@ -87541,7 +87914,7 @@ function buildWriteOps(deps) {
87541
87914
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
87542
87915
  }
87543
87916
  const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
87544
- const approveHashR = await broadcast("psmSwap (approve)", approveTx);
87917
+ const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
87545
87918
  if (!approveHashR.ok) return approveHashR;
87546
87919
  const approveHash = approveHashR.value;
87547
87920
  const residualNote = `the approve ALREADY broadcast (tx ${approveHash}) \u2014 an exact-amount allowance of ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} stands; it authorizes only that amount and nothing else. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
@@ -87556,7 +87929,7 @@ function buildWriteOps(deps) {
87556
87929
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
87557
87930
  }
87558
87931
  const execCard = `${p.direction} ${p.amountIn} ${isSwap ? "USDC smallest units" : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
87559
- const execHashR = await broadcast(`psmSwap (${p.direction})`, execTx);
87932
+ const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
87560
87933
  if (!execHashR.ok) {
87561
87934
  const f = execHashR.failure;
87562
87935
  return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
@@ -87640,33 +88013,296 @@ function buildWriteOps(deps) {
87640
88013
  }
87641
88014
 
87642
88015
  // src/signer/eoa-dh.ts
87643
- var import_ethers33 = require("ethers");
88016
+ var import_ethers34 = require("ethers");
87644
88017
  var EoaDHSigner = class {
87645
- kind = "eoa-env";
87646
- wallet;
87647
- constructor(wallet) {
88018
+ constructor(wallet, broadcast, clock = Date.now) {
87648
88019
  this.wallet = wallet;
88020
+ this.broadcast = broadcast;
88021
+ this.clock = clock;
87649
88022
  }
88023
+ kind = "eoa-env";
87650
88024
  async getBorrowerAddress() {
87651
88025
  return this.wallet.getAddress();
87652
88026
  }
87653
88027
  async getAuthSignerAddress() {
87654
88028
  return this.wallet.getAddress();
87655
88029
  }
87656
- async signAuthMessage(messageHash) {
87657
- return this.wallet.signMessage(import_ethers33.ethers.getBytes(messageHash));
88030
+ async signAuthorization(spec) {
88031
+ const quantumTs = nextQuantumTimestamp(this.clock());
88032
+ const { fields, hashHex } = spec.stamp(quantumTs);
88033
+ const signature = await this.wallet.signMessage(import_ethers34.ethers.getBytes(hashHex));
88034
+ return { signature, quantumTs, fields };
87658
88035
  }
87659
88036
  async wrapInnerTx(innerTx) {
87660
88037
  return innerTx;
87661
88038
  }
87662
- async signTransaction(outerTx) {
87663
- return this.wallet.signTransaction(outerTx);
88039
+ async submitValidatedTx(outerTx, ctx) {
88040
+ const signed = await this.wallet.signTransaction(outerTx);
88041
+ const txHash = await this.broadcast(signed, ctx.broadcast ? { [ctx.broadcast.key]: ctx.broadcast.meta } : void 0);
88042
+ return { txHash, signer: await this.wallet.getAddress(), scheme: "eip712-eoa" };
87664
88043
  }
87665
88044
  getEthersSigner() {
87666
88045
  return this.wallet;
87667
88046
  }
87668
88047
  };
87669
88048
 
88049
+ // src/signer/external-eoa.ts
88050
+ var import_node_crypto5 = require("crypto");
88051
+ var import_ethers36 = require("ethers");
88052
+
88053
+ // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
88054
+ var import_ethers35 = require("ethers");
88055
+ function eq2(a, b) {
88056
+ return a.toLowerCase() === b.toLowerCase();
88057
+ }
88058
+ function compareLandedTx(landed, approved, borrower) {
88059
+ const mismatch = !eq2(landed.to, approved.to) ? `to (${landed.to} \u2260 ${approved.to})` : landed.data.toLowerCase() !== approved.data.toLowerCase() ? "calldata" : landed.value !== BigInt(approved.value) ? `value (${landed.value} \u2260 ${BigInt(approved.value)})` : landed.chainId !== BigInt(approved.chainId) ? `chainId (${landed.chainId} \u2260 ${approved.chainId})` : null;
88060
+ if (mismatch) {
88061
+ return {
88062
+ status: "mismatch",
88063
+ hash: landed.hash,
88064
+ reason: `the wallet broadcast tx ${landed.hash} but it does not match the approved operation (${mismatch}) \u2014 the transaction is already on-chain; do NOT retry, re-read position state`
88065
+ };
88066
+ }
88067
+ if (!eq2(landed.from, borrower)) {
88068
+ return {
88069
+ status: "mismatch",
88070
+ hash: landed.hash,
88071
+ reason: `tx ${landed.hash} was signed by ${landed.from}, not the borrower ${borrower} \u2014 already on-chain; do NOT retry, re-read state`
88072
+ };
88073
+ }
88074
+ return { status: "verified", from: landed.from, hash: landed.hash };
88075
+ }
88076
+ function verifyRawSignedTx(rawSignedTx, approved, borrower) {
88077
+ const parsed = import_ethers35.ethers.Transaction.from(rawSignedTx);
88078
+ if (!parsed.from || !parsed.to || !parsed.hash) {
88079
+ return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
88080
+ }
88081
+ return compareLandedTx(
88082
+ { from: parsed.from, to: parsed.to, data: parsed.data, value: parsed.value, chainId: parsed.chainId, hash: parsed.hash },
88083
+ approved,
88084
+ borrower
88085
+ );
88086
+ }
88087
+ async function verifyBroadcastTxByHash(provider, hash, approved, borrower, budget) {
88088
+ let tx2 = null;
88089
+ for (let i = 0; i < budget.attempts && tx2 === null; i++) {
88090
+ tx2 = await provider.getTransaction(hash);
88091
+ if (tx2 === null && i < budget.attempts - 1) await new Promise((r) => setTimeout(r, budget.delayMs));
88092
+ }
88093
+ if (tx2 === null || !tx2.from || !tx2.to) {
88094
+ return {
88095
+ status: "unknown",
88096
+ hash,
88097
+ reason: `the wallet reported broadcasting tx ${hash}, but the RPC has not served it within the wait budget \u2014 the transaction may still be propagating. Treat as UNKNOWN: re-read position state before retrying (a completed operation must not be repeated).`
88098
+ };
88099
+ }
88100
+ return compareLandedTx(
88101
+ { from: tx2.from, to: tx2.to, data: tx2.data, value: tx2.value, chainId: BigInt(tx2.chainId), hash: tx2.hash },
88102
+ approved,
88103
+ borrower
88104
+ );
88105
+ }
88106
+
88107
+ // src/signer/external-eoa.ts
88108
+ var DEFAULT_BUDGET = { attempts: 30, delayMs: 3e3 };
88109
+ var ExternalEoaDHSigner = class {
88110
+ constructor(deps) {
88111
+ this.deps = deps;
88112
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88113
+ }
88114
+ kind = "external-eoa";
88115
+ budget;
88116
+ async getBorrowerAddress() {
88117
+ return this.deps.borrower;
88118
+ }
88119
+ async getAuthSignerAddress() {
88120
+ return this.deps.borrower;
88121
+ }
88122
+ async signAuthorization(spec) {
88123
+ const initialTs = nextQuantumTimestamp(Date.now());
88124
+ const initial = spec.stamp(initialTs);
88125
+ let used = { quantumTs: initialTs, fields: initial.fields };
88126
+ const outcome = await this.deps.bridge.requestSignature(
88127
+ {
88128
+ id: (0, import_node_crypto5.randomUUID)(),
88129
+ kind: "personal-sign",
88130
+ action: spec.action,
88131
+ card: initial.card,
88132
+ expectedSigner: this.deps.borrower,
88133
+ chainId: this.deps.chainId,
88134
+ personalSign: { layout: spec.layout, fields: initial.fields, hashHex: initial.hashHex }
88135
+ },
88136
+ {
88137
+ finalize: async () => {
88138
+ const ts = nextQuantumTimestamp(Date.now());
88139
+ const s = spec.stamp(ts);
88140
+ used = { quantumTs: ts, fields: s.fields };
88141
+ return { personalSign: { layout: spec.layout, fields: s.fields, hashHex: s.hashHex }, card: s.card };
88142
+ }
88143
+ }
88144
+ );
88145
+ if (outcome.status !== "approved" || !outcome.signature) {
88146
+ throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
88147
+ }
88148
+ const finalHash = spec.stamp(used.quantumTs).hashHex;
88149
+ const recovered = import_ethers36.ethers.verifyMessage(import_ethers36.ethers.getBytes(finalHash), outcome.signature);
88150
+ if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
88151
+ throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
88152
+ }
88153
+ return { signature: outcome.signature, quantumTs: used.quantumTs, fields: used.fields };
88154
+ }
88155
+ async wrapInnerTx(innerTx) {
88156
+ return innerTx;
88157
+ }
88158
+ async submitValidatedTx(outerTx, ctx) {
88159
+ const approved = toApprovedTx(outerTx, this.deps.chainId);
88160
+ const outcome = await this.deps.bridge.requestSignature({
88161
+ id: (0, import_node_crypto5.randomUUID)(),
88162
+ kind: "transaction",
88163
+ action: ctx.action,
88164
+ card: ctx.card,
88165
+ expectedSigner: this.deps.borrower,
88166
+ chainId: this.deps.chainId,
88167
+ tx: approved
88168
+ });
88169
+ if (outcome.status !== "approved") {
88170
+ throw new OperationDeclined(`the ${ctx.action} transaction was not approved: ${describeOutcome(outcome)}`);
88171
+ }
88172
+ const verdict = await this.resolveLanded(outcome, approved);
88173
+ if (verdict.status !== "verified") {
88174
+ throw new Error(verdict.reason);
88175
+ }
88176
+ return { txHash: verdict.hash, signer: verdict.from, scheme: "external-wallet" };
88177
+ }
88178
+ async resolveLanded(outcome, approved) {
88179
+ if (outcome.rawSignedTx) {
88180
+ const verdict = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88181
+ if (verdict.status === "verified") await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88182
+ return verdict;
88183
+ }
88184
+ if (!outcome.txHash) {
88185
+ return { status: "unknown", hash: "0x", reason: "the wallet approved but returned neither a tx hash nor a signed transaction" };
88186
+ }
88187
+ return verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88188
+ }
88189
+ getEthersSigner() {
88190
+ return new BridgeEthersSigner(this.deps);
88191
+ }
88192
+ };
88193
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers36.ethers.AbstractSigner {
88194
+ constructor(deps) {
88195
+ super(deps.provider);
88196
+ this.deps = deps;
88197
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88198
+ }
88199
+ budget;
88200
+ async getAddress() {
88201
+ return this.deps.borrower;
88202
+ }
88203
+ async signMessage(_message) {
88204
+ throw new Error(
88205
+ "external-wallet mode cannot sign this operation yet: it needs a raw message signature whose fields are built inside the SDK (BTC withdrawal). That is the plan-10 Phase A-2 signing-context seam \u2014 use the keystore signer for this operation until it lands."
88206
+ );
88207
+ }
88208
+ async signTypedData(domain, types, value) {
88209
+ const typedData = {
88210
+ domain,
88211
+ types,
88212
+ primaryType: Object.keys(types)[0] ?? "EIP712",
88213
+ message: value
88214
+ };
88215
+ const outcome = await this.deps.bridge.requestSignature({
88216
+ id: (0, import_node_crypto5.randomUUID)(),
88217
+ kind: "typed-data",
88218
+ action: "login",
88219
+ card: cardForTypedData("login", typedData),
88220
+ expectedSigner: this.deps.borrower,
88221
+ chainId: this.deps.chainId,
88222
+ typedData
88223
+ });
88224
+ if (outcome.status !== "approved" || !outcome.signature) {
88225
+ throw new OperationDeclined(`the login signature was not approved: ${describeOutcome(outcome)}`);
88226
+ }
88227
+ return outcome.signature;
88228
+ }
88229
+ async sendTransaction(tx2) {
88230
+ if (!tx2.to || typeof tx2.data !== "string") {
88231
+ throw new Error("BridgeEthersSigner.sendTransaction: tx.to and hex tx.data are required");
88232
+ }
88233
+ const approved = {
88234
+ to: tx2.to,
88235
+ data: tx2.data,
88236
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88237
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
88238
+ };
88239
+ const card = cardForTx(approved);
88240
+ const outcome = await this.deps.bridge.requestSignature({
88241
+ id: (0, import_node_crypto5.randomUUID)(),
88242
+ kind: "transaction",
88243
+ action: describeFn(approved.data),
88244
+ card,
88245
+ expectedSigner: this.deps.borrower,
88246
+ chainId: approved.chainId,
88247
+ tx: { ...approved, ...tx2.gasLimit != null ? { gas: import_ethers36.ethers.toBeHex(BigInt(String(tx2.gasLimit))) } : {}, txType: 2 }
88248
+ });
88249
+ if (outcome.status !== "approved") {
88250
+ throw new OperationDeclined(`the transaction was not approved: ${describeOutcome(outcome)}`);
88251
+ }
88252
+ let hash;
88253
+ if (outcome.rawSignedTx) {
88254
+ const v = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88255
+ if (v.status !== "verified") throw new Error(v.reason);
88256
+ await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88257
+ hash = v.hash;
88258
+ } else if (outcome.txHash) {
88259
+ const v = await verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88260
+ if (v.status !== "verified") throw new Error(v.reason);
88261
+ hash = v.hash;
88262
+ } else {
88263
+ throw new Error("the wallet approved but returned neither a tx hash nor a signed transaction");
88264
+ }
88265
+ const resp = await this.provider.getTransaction(hash);
88266
+ if (!resp) throw new Error(`tx ${hash} verified but the provider no longer returns it`);
88267
+ return resp;
88268
+ }
88269
+ async signTransaction(_tx) {
88270
+ throw new Error("BridgeEthersSigner: browser wallets cannot raw-sign a transaction \u2014 use sendTransaction (self-broadcast).");
88271
+ }
88272
+ connect(provider) {
88273
+ return new _BridgeEthersSigner({ ...this.deps, provider });
88274
+ }
88275
+ };
88276
+ function toApprovedTx(tx2, fallbackChainId) {
88277
+ if (!tx2.to || typeof tx2.data !== "string") throw new Error("submitValidatedTx: tx.to and hex tx.data are required");
88278
+ return {
88279
+ to: tx2.to,
88280
+ data: tx2.data,
88281
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88282
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
88283
+ };
88284
+ }
88285
+ function describeFn(data) {
88286
+ try {
88287
+ const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
88288
+ return decodeSignable2(data).name;
88289
+ } catch {
88290
+ return "operation";
88291
+ }
88292
+ }
88293
+ function describeOutcome(outcome) {
88294
+ switch (outcome.status) {
88295
+ case "rejected":
88296
+ return outcome.reason;
88297
+ case "expired":
88298
+ return "the approval request expired without a wallet decision \u2014 reopen the approval page and retry";
88299
+ case "invalidated":
88300
+ return outcome.reason;
88301
+ default:
88302
+ return outcome.status;
88303
+ }
88304
+ }
88305
+
87670
88306
  // src/boundary/upstream/real/plugin.ts
87671
88307
  var STATUS_BY_INDEX = [
87672
88308
  "PENDING_DEPOSIT",
@@ -87684,10 +88320,11 @@ var POSITION_DETAILS_ABI = [
87684
88320
  var PAUSABLE_ABI = ["function paused() view returns (bool)"];
87685
88321
  var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
87686
88322
  var RealUpstreamPlugin = class {
87687
- constructor(config, wallet) {
88323
+ constructor(config, wallet, runtime) {
87688
88324
  this.config = config;
87689
- this.provider = new import_ethers34.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
88325
+ this.provider = new import_ethers37.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
87690
88326
  this.wallet = wallet ?? null;
88327
+ this.runtime = runtime ?? null;
87691
88328
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
87692
88329
  this.contracts = getContractsByNetwork(config.network) ?? {};
87693
88330
  this.indexer = {
@@ -87811,7 +88448,7 @@ var RealUpstreamPlugin = class {
87811
88448
  })
87812
88449
  )
87813
88450
  };
87814
- const writeRefusalReason = this.config.network !== "sepolia" ? `writes are enabled on sepolia ONLY, and this process is configured for network '${this.config.network}' (chainId ${this.config.chainId}) \u2014 the standing mainnet write block; mainnet writes await their dedicated security review. Reads remain available.` : !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014 writes need the keystore env pair (DH_KEYSTORE_PATH + DH_KEYSTORE_PASSWORD_FILE), or run signer_setup.` : `the lit-ops login session is unavailable \u2014 the keystore is configured but EIP-712 login did not complete; check the broker endpoint and retry.`;
88451
+ const writeRefusalReason = this.config.network !== "sepolia" ? `writes are enabled on sepolia ONLY, and this process is configured for network '${this.config.network}' (chainId ${this.config.chainId}) \u2014 the standing mainnet write block; mainnet writes await their dedicated security review. Reads remain available.` : !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014 writes need the keystore env pair (DH_KEYSTORE_PATH + DH_KEYSTORE_PASSWORD), or run signer_setup.` : `the lit-ops login session is unavailable \u2014 the keystore is configured but EIP-712 login did not complete; check the broker endpoint and retry.`;
87815
88452
  const readOnly = (op) => Promise.resolve(
87816
88453
  upFail({
87817
88454
  kind: "unavailable",
@@ -87820,16 +88457,10 @@ var RealUpstreamPlugin = class {
87820
88457
  })
87821
88458
  );
87822
88459
  const writesArmed = this.config.network === "sepolia" || this.config.network === "mainnet" && this.config.mainnetWritesAck === true;
87823
- if (writesArmed && this.wallet && this.session) {
87824
- this.ops = buildWriteOps({
87825
- config: this.config,
87826
- chainId: this.config.chainId,
87827
- dhSigner: new EoaDHSigner(this.wallet.connect(this.provider)),
87828
- session: this.session,
87829
- getWriteSdk: () => this.writeSdk,
87830
- readDetails: (id) => this.readPositionDetails(id),
87831
- psm: () => this.psmCalls()
87832
- });
88460
+ if (writesArmed && this.runtime) {
88461
+ this.ops = this.resolvingOps();
88462
+ } else if (writesArmed && this.wallet && this.session) {
88463
+ this.ops = this.keystoreGateway(this.wallet.connect(this.provider), this.session);
87833
88464
  } else {
87834
88465
  this.ops = {
87835
88466
  createPosition: () => readOnly("createPosition"),
@@ -87862,10 +88493,17 @@ var RealUpstreamPlugin = class {
87862
88493
  provider;
87863
88494
  session;
87864
88495
  contracts;
87865
- /** Signer-bearing SDK for the WRITE gateways (sepolia, or armed mainnet). Null until
87866
- * initWriteSdk. */
87867
- writeSdk = null;
87868
- /** Build the signer-bearing WRITE SDK (sepolia only; a no-op otherwise).
88496
+ runtime;
88497
+ /** Per-identity caches (plan 10 A3): keys are `<mode>:<address lowercased>` — a mode
88498
+ * switch resolves a different key, so stale constructions are never reused. */
88499
+ sdkCache = /* @__PURE__ */ new Map();
88500
+ sdkInFlight = /* @__PURE__ */ new Map();
88501
+ sessionCache = /* @__PURE__ */ new Map();
88502
+ opsGatewayCache = /* @__PURE__ */ new Map();
88503
+ externalSigners = /* @__PURE__ */ new Map();
88504
+ /** Pre-warm the KEYSTORE write SDK at boot (0.1.1 parity: the common keystore boot pays
88505
+ * the create cost up front, not on the first write). External-mode SDKs build lazily on
88506
+ * the first write after the mode binds (plan 10 A3 latency honesty).
87869
88507
  *
87870
88508
  * INDEPENDENT of any graph/indexer discovery (plan 08 A4, M8B-4): indexer reads ride
87871
88509
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
@@ -87875,29 +88513,277 @@ var RealUpstreamPlugin = class {
87875
88513
  * (createPosition/withdraw report the uninitialized SDK). */
87876
88514
  async initWriteSdk() {
87877
88515
  const writesArmed = this.config.network === "sepolia" || this.config.network === "mainnet" && this.config.mainnetWritesAck === true;
87878
- if (!this.wallet || !writesArmed) return;
87879
- try {
87880
- const signer = this.wallet.connect(this.provider);
87881
- const v = this.config.validatorVersion;
87882
- const builtWrite = await DiamondHandsSDK.create({
87883
- mode: "service",
87884
- serviceEndpoint: this.config.serviceEndpoint,
87885
- contractSigner: signer,
87886
- authSigner: signer,
87887
- provider: this.provider,
87888
- ethRpcUrl: this.config.rpcUrl,
87889
- chainId: this.config.chainId,
87890
- litNetwork: this.config.litNetwork,
87891
- // No `subgraphs`: in service mode the SDK queries THROUGH the lit-ops proxy and
87892
- // ignores any provided URL — the old `/v1/init`-discovered value was dead weight
87893
- // nesting writes under indexer discovery (the M8B-4 coupling this removes).
87894
- ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
88516
+ if (!writesArmed) return;
88517
+ if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
88518
+ const wallet = this.wallet ?? this.runtime?.keystore.signer() ?? null;
88519
+ if (!wallet) return;
88520
+ await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
88521
+ }
88522
+ /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
88523
+ * the write gateways report the uninitialized SDK honestly, never fake readiness. */
88524
+ async ensureSdk(key, signer) {
88525
+ if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
88526
+ const inFlight = this.sdkInFlight.get(key);
88527
+ if (inFlight) return inFlight;
88528
+ const build = (async () => {
88529
+ try {
88530
+ const v = this.config.validatorVersion;
88531
+ const builtWrite = await DiamondHandsSDK.create({
88532
+ mode: "service",
88533
+ serviceEndpoint: this.config.serviceEndpoint,
88534
+ contractSigner: signer,
88535
+ authSigner: signer,
88536
+ provider: this.provider,
88537
+ ethRpcUrl: this.config.rpcUrl,
88538
+ chainId: this.config.chainId,
88539
+ litNetwork: this.config.litNetwork,
88540
+ // No `subgraphs`: in service mode the SDK queries THROUGH the lit-ops proxy and
88541
+ // ignores any provided URL — the old `/v1/init`-discovered value was dead weight
88542
+ // nesting writes under indexer discovery (the M8B-4 coupling this removes).
88543
+ ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
88544
+ });
88545
+ return isSuccess(builtWrite) ? builtWrite.value : null;
88546
+ } catch {
88547
+ return null;
88548
+ }
88549
+ })();
88550
+ this.sdkInFlight.set(key, build);
88551
+ const built = await build;
88552
+ this.sdkInFlight.delete(key);
88553
+ this.sdkCache.set(key, built);
88554
+ return built;
88555
+ }
88556
+ wallet;
88557
+ // ---- per-call signer resolution (plan 10 A3) ----
88558
+ /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
88559
+ * carries the service endpoint and the authenticated session header. It throws
88560
+ * `OperationDeclined` when lit-ops REFUSES the signed tx (a decision), a plain Error on
88561
+ * transport/shape trouble; write-ops maps the two to distinct failure kinds. */
88562
+ litOpsBroadcast(session) {
88563
+ return async (signedTx, extra) => {
88564
+ const res = await fetch(`${this.config.serviceEndpoint}/api/lit/broadcast`, {
88565
+ method: "POST",
88566
+ headers: { "Content-Type": "application/json", ...await session.authHeader() },
88567
+ body: JSON.stringify({ signedTx, ...extra ?? {} })
87895
88568
  });
87896
- if (isSuccess(builtWrite)) this.writeSdk = builtWrite.value;
87897
- } catch {
88569
+ const text = await res.text();
88570
+ let json;
88571
+ try {
88572
+ json = JSON.parse(text);
88573
+ } catch {
88574
+ throw new Error(`lit-ops broadcast returned non-JSON (HTTP ${res.status}): ${text.slice(0, 200)}`);
88575
+ }
88576
+ if (!res.ok && json["error"] === void 0) {
88577
+ throw new Error(`lit-ops broadcast HTTP ${res.status}: ${text.slice(0, 200)}`);
88578
+ }
88579
+ if (json["success"] !== true) {
88580
+ const reason = json["error"];
88581
+ throw new OperationDeclined(`lit-ops declined the signed transaction: ${typeof reason === "string" ? reason : "no reason given"}`);
88582
+ }
88583
+ const txHash = String((json["data"] ?? {})["txHash"] ?? "");
88584
+ if (!txHash) throw new Error("lit-ops broadcast returned no txHash");
88585
+ return txHash;
88586
+ };
88587
+ }
88588
+ keystoreGateway(wallet, session) {
88589
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88590
+ return buildWriteOps({
88591
+ config: this.config,
88592
+ chainId: this.config.chainId,
88593
+ dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
88594
+ session,
88595
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88596
+ readDetails: (id) => this.readPositionDetails(id),
88597
+ psm: () => this.psmCalls()
88598
+ });
88599
+ }
88600
+ sessionFor(key, signer) {
88601
+ let s = this.sessionCache.get(key);
88602
+ if (!s) {
88603
+ s = new LitOpsSession(signer, this.config.serviceEndpoint, this.config.chainId);
88604
+ this.sessionCache.set(key, s);
88605
+ }
88606
+ return s;
88607
+ }
88608
+ /** Verify-by-hash budget for external self-broadcast (A0.3): mainnet Chipotle
88609
+ * roundtrips exceed 60s, so the write-path budget is 300s there (F-MAIN-4). */
88610
+ verifyBudget() {
88611
+ return this.config.network === "mainnet" ? { attempts: 100, delayMs: 3e3 } : void 0;
88612
+ }
88613
+ /** The armed-boot ops surface: every method resolves the CURRENT signer mode first, so
88614
+ * the refusal-truth matrix is decided at call time, never frozen at boot. */
88615
+ resolvingOps() {
88616
+ const call = (k) => (async (p) => {
88617
+ const r = await this.resolveOpsGateway();
88618
+ if (!r.ok) return upFail(r.failure);
88619
+ return r.gateway[k](p);
88620
+ });
88621
+ return {
88622
+ createPosition: call("createPosition"),
88623
+ mint: call("mint"),
88624
+ repay: call("repay"),
88625
+ extend: call("extend"),
88626
+ withdraw: call("withdraw"),
88627
+ allowlistWithdrawalAddress: call("allowlistWithdrawalAddress"),
88628
+ psmSwap: call("psmSwap"),
88629
+ delegationSetup: call("delegationSetup"),
88630
+ delegationGrant: call("delegationGrant"),
88631
+ recoverStaleSpend: call("recoverStaleSpend")
88632
+ };
88633
+ }
88634
+ async resolveOpsGateway() {
88635
+ const rt = this.runtime;
88636
+ const mode = rt.manager.mode();
88637
+ if (mode === "none") {
88638
+ return {
88639
+ ok: false,
88640
+ failure: {
88641
+ kind: "signer-missing",
88642
+ source: "real-ops",
88643
+ message: "no authorization mode is chosen (SIGNER_UNAVAILABLE) \u2014 pick one via signer_setup ('external' = approve in your own wallet, 'keystore' = automatic signing), or set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD in the server environment."
88644
+ }
88645
+ };
87898
88646
  }
88647
+ if (mode === "keystore") {
88648
+ const ready = await rt.keystore.ensureReady();
88649
+ const wallet = rt.keystore.signer();
88650
+ if (!ready.ok || !wallet) {
88651
+ return {
88652
+ ok: false,
88653
+ failure: {
88654
+ kind: "signer-missing",
88655
+ source: "real-ops",
88656
+ message: `the keystore signer is not ready (SIGNER_UNAVAILABLE): ${ready.ok ? "no keystore material" : ready.reason}`
88657
+ }
88658
+ };
88659
+ }
88660
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88661
+ let gateway = this.opsGatewayCache.get(key);
88662
+ if (!gateway) {
88663
+ const connected = wallet.connect(this.provider);
88664
+ gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
88665
+ this.opsGatewayCache.set(key, gateway);
88666
+ }
88667
+ await this.ensureSdk(key, wallet.connect(this.provider));
88668
+ return { ok: true, gateway };
88669
+ }
88670
+ if (mode === "external") {
88671
+ const borrower = await rt.manager.resolveBorrowerForWrite();
88672
+ if (!borrower) {
88673
+ return {
88674
+ ok: false,
88675
+ failure: {
88676
+ kind: "signer-missing",
88677
+ source: "real-ops",
88678
+ message: "external-wallet mode: no wallet is connected yet (SIGNER_UNAVAILABLE) \u2014 call signer_setup with action 'status' for the approval-page link and connect your wallet there."
88679
+ }
88680
+ };
88681
+ }
88682
+ const key = `external:${borrower.toLowerCase()}`;
88683
+ let gateway = this.opsGatewayCache.get(key);
88684
+ if (!gateway) {
88685
+ const budget = this.verifyBudget();
88686
+ const deps = {
88687
+ bridge: rt.bridge,
88688
+ provider: this.provider,
88689
+ chainId: this.config.chainId,
88690
+ borrower,
88691
+ ...budget ? { verifyBudget: budget } : {}
88692
+ };
88693
+ const bridgeSigner = new BridgeEthersSigner(deps);
88694
+ this.externalSigners.set(key, bridgeSigner);
88695
+ const session = this.sessionFor(key, {
88696
+ address: borrower,
88697
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88698
+ });
88699
+ gateway = buildWriteOps({
88700
+ config: this.config,
88701
+ chainId: this.config.chainId,
88702
+ dhSigner: new ExternalEoaDHSigner(deps),
88703
+ session,
88704
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88705
+ readDetails: (id) => this.readPositionDetails(id),
88706
+ psm: () => this.psmCalls()
88707
+ });
88708
+ this.opsGatewayCache.set(key, gateway);
88709
+ }
88710
+ await this.ensureSdk(key, this.externalSigners.get(key));
88711
+ return { ok: true, gateway };
88712
+ }
88713
+ return {
88714
+ ok: false,
88715
+ failure: {
88716
+ kind: "signer-missing",
88717
+ source: "real-ops",
88718
+ message: `signer mode '${mode}' is not available on the real adapter \u2014 use 'external' or 'keystore' (signer_setup).`
88719
+ }
88720
+ };
88721
+ }
88722
+ /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
88723
+ * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
88724
+ * the first verified ceremony fixes the identity. */
88725
+ async connectExternal() {
88726
+ if (!this.runtime) return { ok: false, reason: "this construction has no signer runtime" };
88727
+ const { manager } = this.runtime;
88728
+ if (manager.mode() !== "external") {
88729
+ return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
88730
+ }
88731
+ const borrower = manager.borrowerForWrite();
88732
+ if (!borrower) {
88733
+ return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
88734
+ }
88735
+ const key = `external:${borrower.toLowerCase()}`;
88736
+ const budget = this.verifyBudget();
88737
+ const bridgeSigner = this.externalSigners.get(key) ?? new BridgeEthersSigner({
88738
+ bridge: this.runtime.bridge,
88739
+ provider: this.provider,
88740
+ chainId: this.config.chainId,
88741
+ borrower,
88742
+ ...budget ? { verifyBudget: budget } : {}
88743
+ });
88744
+ this.externalSigners.set(key, bridgeSigner);
88745
+ const session = this.sessionFor(key, {
88746
+ address: borrower,
88747
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88748
+ });
88749
+ await session.token();
88750
+ manager.bind(borrower);
88751
+ return { ok: true, address: borrower };
88752
+ }
88753
+ /** The authenticated-read session for the CURRENT mode. Reads NEVER summon the wallet
88754
+ * (A0.7): external mode without a live JWT refuses, naming the explicit connect action. */
88755
+ resolveReadSession() {
88756
+ if (!this.runtime) {
88757
+ return this.session ? { ok: true, session: this.session } : { ok: false, reason: "no signer configured \u2014 set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it." };
88758
+ }
88759
+ const mode = this.runtime.manager.mode();
88760
+ if (mode === "keystore") {
88761
+ const wallet = this.runtime.keystore.signer();
88762
+ if (!wallet) {
88763
+ return { ok: false, reason: "the keystore is configured but locked \u2014 say 'use keystore' (signer_setup) to unlock it, or check DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD." };
88764
+ }
88765
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88766
+ return { ok: true, session: this.sessionFor(key, wallet.connect(this.provider)) };
88767
+ }
88768
+ if (mode === "external") {
88769
+ const borrower = this.runtime.manager.borrowerForWrite();
88770
+ const session = borrower ? this.sessionCache.get(`external:${borrower.toLowerCase()}`) : void 0;
88771
+ if (session && session.hasValidToken()) return { ok: true, session };
88772
+ return {
88773
+ ok: false,
88774
+ reason: "external-wallet mode: there is no live lit-ops login session, and reads never open wallet popups on their own \u2014 run signer_setup action 'connect' to log in once with your wallet."
88775
+ };
88776
+ }
88777
+ return {
88778
+ ok: false,
88779
+ reason: "no signer is active \u2014 authenticated reads need a lit-ops login identity. Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD, or pick a mode via signer_setup."
88780
+ };
88781
+ }
88782
+ /** Capability truth for boundary://info (plan 10 B3): can authenticated reads run RIGHT
88783
+ * NOW without summoning a wallet? */
88784
+ authenticatedReadsAvailable() {
88785
+ return this.resolveReadSession().ok;
87899
88786
  }
87900
- wallet;
87901
88787
  describe() {
87902
88788
  return {
87903
88789
  adapter: "real",
@@ -87905,7 +88791,8 @@ var RealUpstreamPlugin = class {
87905
88791
  };
87906
88792
  }
87907
88793
  dispose() {
87908
- this.writeSdk?.dispose();
88794
+ for (const sdk of this.sdkCache.values()) sdk?.dispose();
88795
+ this.sdkCache.clear();
87909
88796
  this.provider.destroy();
87910
88797
  }
87911
88798
  // ---- helpers ----
@@ -87965,19 +88852,20 @@ var RealUpstreamPlugin = class {
87965
88852
  * present, else `_meta` from the document result (this is reading one response, not a
87966
88853
  * fallback path). Null when the document selects no `_meta` (e.g. PositionById). */
87967
88854
  async graphProxy(document2, variables) {
87968
- if (!this.session) {
88855
+ const sessionR = this.resolveReadSession();
88856
+ if (!sessionR.ok) {
87969
88857
  return upFail({
87970
88858
  kind: "signer-missing",
87971
88859
  // → SIGNER_UNAVAILABLE (same contract as the other authenticated reads)
87972
88860
  source: "subgraph",
87973
- message: "no signer configured \u2014 indexer reads go through the lit-ops graph proxy, which is authenticated (lit-ops login). Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable them. Chain-sourced reads (position status, protocol, price) still work."
88861
+ message: `indexer reads go through the lit-ops graph proxy, which is authenticated (lit-ops login): ${sessionR.reason} Chain-sourced reads (position status, protocol, price) still work.`
87974
88862
  });
87975
88863
  }
87976
88864
  let res;
87977
88865
  try {
87978
88866
  res = await fetch(`${this.config.serviceEndpoint}/api/lit/graph/query?chainId=${this.config.chainId}`, {
87979
88867
  method: "POST",
87980
- headers: { "Content-Type": "application/json", ...await this.session.authHeader() },
88868
+ headers: { "Content-Type": "application/json", ...await sessionR.session.authHeader() },
87981
88869
  body: JSON.stringify({ query: document2, variables })
87982
88870
  });
87983
88871
  } catch (e) {
@@ -88042,9 +88930,9 @@ var RealUpstreamPlugin = class {
88042
88930
  };
88043
88931
  }
88044
88932
  /** Public (unauthenticated) lit-ops GET. */
88045
- async publicRead(path4, map) {
88933
+ async publicRead(path5, map) {
88046
88934
  try {
88047
- const res = await fetch(`${this.config.serviceEndpoint}${path4}`);
88935
+ const res = await fetch(`${this.config.serviceEndpoint}${path5}`);
88048
88936
  const text = await res.text();
88049
88937
  if (!res.ok) {
88050
88938
  return upFail({
@@ -88061,18 +88949,19 @@ var RealUpstreamPlugin = class {
88061
88949
  }
88062
88950
  }
88063
88951
  /** Authenticated lit-ops GET → mapped value. Never throws; maps failures to the taxonomy. */
88064
- async opsRead(path4, map) {
88065
- if (!this.session) {
88952
+ async opsRead(path5, map) {
88953
+ const sessionR = this.resolveReadSession();
88954
+ if (!sessionR.ok) {
88066
88955
  return upFail({
88067
88956
  kind: "signer-missing",
88068
88957
  // → SIGNER_UNAVAILABLE (documented contract, pinned by REAL-08)
88069
88958
  source: "lit-ops",
88070
- message: "no signer configured \u2014 this read is authenticated (lit-ops login). Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
88959
+ message: `this read is authenticated (lit-ops login): ${sessionR.reason}`
88071
88960
  });
88072
88961
  }
88073
88962
  let res;
88074
88963
  try {
88075
- res = await fetch(`${this.config.serviceEndpoint}${path4}`, { headers: await this.session.authHeader() });
88964
+ res = await fetch(`${this.config.serviceEndpoint}${path5}`, { headers: await sessionR.session.authHeader() });
88076
88965
  } catch (e) {
88077
88966
  return upFail({ kind: "unavailable", source: "lit-ops", message: `lit-ops is unreachable`, raw: String(e) });
88078
88967
  }
@@ -88121,7 +89010,7 @@ var RealUpstreamPlugin = class {
88121
89010
  const pm = this.contracts["PositionManager"];
88122
89011
  if (!pm) return false;
88123
89012
  try {
88124
- const c = new import_ethers34.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
89013
+ const c = new import_ethers37.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
88125
89014
  return Boolean(await c["paused"]());
88126
89015
  } catch {
88127
89016
  return false;
@@ -88130,16 +89019,16 @@ var RealUpstreamPlugin = class {
88130
89019
  async readPositionDetails(id) {
88131
89020
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
88132
89021
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
88133
- const c = new import_ethers34.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
89022
+ const c = new import_ethers37.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
88134
89023
  let d;
88135
89024
  try {
88136
- d = await c["getPositionDetails"](import_ethers34.ethers.zeroPadValue(id, 32));
89025
+ d = await c["getPositionDetails"](import_ethers37.ethers.zeroPadValue(id, 32));
88137
89026
  } catch (e) {
88138
89027
  if (e.code === "CALL_EXCEPTION") return null;
88139
89028
  throw e;
88140
89029
  }
88141
89030
  const borrower = String(d["borrower"]);
88142
- if (borrower === import_ethers34.ethers.ZeroAddress) return null;
89031
+ if (borrower === import_ethers37.ethers.ZeroAddress) return null;
88143
89032
  return {
88144
89033
  positionId: String(d["positionId"]),
88145
89034
  pkpId: String(d["pkpId"]),
@@ -88163,7 +89052,7 @@ var RealUpstreamPlugin = class {
88163
89052
  // src/boundary/upstream/shared/external-bridge/bridge.ts
88164
89053
  var fs4 = __toESM(require("fs"));
88165
89054
  var http3 = __toESM(require("http"));
88166
- var import_node_crypto5 = require("crypto");
89055
+ var import_node_crypto6 = require("crypto");
88167
89056
 
88168
89057
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
88169
89058
  function renderApprovalPage(sessionId) {
@@ -88210,12 +89099,16 @@ function renderApprovalPage(sessionId) {
88210
89099
  <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
88211
89100
  Use a mobile wallet instead (WalletConnect)
88212
89101
  </button>
89102
+ <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
88213
89103
  <div id="wc-uri" class="card hidden" style="user-select:all; word-break:break-all; font-size:12px;"></div>
88214
- <div id="wc-hint" class="status hidden">Open your wallet app \u2192 WalletConnect \u2192 paste this pairing code. Approvals then happen on your phone.</div>
89104
+ <div id="wc-hint" class="status hidden">Scan the QR with your wallet app (or open the app \u2192 WalletConnect \u2192 paste the pairing code). Approvals then happen on your phone.</div>
88215
89105
  </div>
88216
89106
  </div>
88217
89107
  </main>
88218
89108
  <script>
89109
+ ${PAGE_CRYPTO_JS}
89110
+ </script>
89111
+ <script>
88219
89112
  "use strict";
88220
89113
  const SESSION = ${JSON.stringify(sessionId)};
88221
89114
  // One-time token leaves the address bar (and history) immediately.
@@ -88331,11 +89224,33 @@ document.getElementById("approve").onclick = async () => {
88331
89224
  const req = current;
88332
89225
  try {
88333
89226
  if (req.kind === "transaction") {
89227
+ const params = { from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value };
89228
+ if (req.tx.gas) params.gas = req.tx.gas; // hint only \u2014 the wallet may re-estimate
88334
89229
  const txHash = await window.ethereum.request({
88335
89230
  method: "eth_sendTransaction",
88336
- params: [{ from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value }],
89231
+ params: [params],
88337
89232
  });
88338
89233
  await post("/result", { requestId: req.id, approved: true, account: account, txHash: txHash });
89234
+ } else if (req.kind === "personal-sign") {
89235
+ // A0.9 sign-at-presence: fetch the FRESHLY quantum-stamped payload at the click\u2026
89236
+ const fr = await post("/finalize", { requestId: req.id });
89237
+ const fbody = await fr.json();
89238
+ if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
89239
+ const fresh = fbody.request;
89240
+ // \u2026re-render what will actually sign\u2026
89241
+ current = fresh; renderRequest();
89242
+ // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
89243
+ const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
89244
+ if (recomputed.toLowerCase() !== fresh.personalSign.hashHex.toLowerCase()) {
89245
+ await post("/result", { requestId: req.id, approved: false, reason: "page recompute mismatch \u2014 the requested hash does not derive from the displayed fields; refusing to sign" });
89246
+ clearRequest("REFUSED: the signature request did not match its own displayed fields. Nothing was signed.");
89247
+ return;
89248
+ }
89249
+ const signature = await window.ethereum.request({
89250
+ method: "personal_sign",
89251
+ params: [fresh.personalSign.hashHex, account],
89252
+ });
89253
+ await post("/result", { requestId: req.id, approved: true, account: account, signature: signature });
88339
89254
  } else {
88340
89255
  // MetaMask's v4 schema REQUIRES an EIP712Domain entry in "types" (ethers' signer
88341
89256
  // API forbids the same entry) \u2014 derive it here from the domain's present fields.
@@ -88368,8 +89283,13 @@ document.getElementById("wc-connect").onclick = async () => {
88368
89283
  const uriEl = document.getElementById("wc-uri");
88369
89284
  uriEl.textContent = body.uri;
88370
89285
  uriEl.classList.remove("hidden");
89286
+ if (body.qrSvg) {
89287
+ const qrEl = document.getElementById("wc-qr");
89288
+ qrEl.innerHTML = body.qrSvg; // server-generated SVG from OUR loopback process
89289
+ qrEl.classList.remove("hidden");
89290
+ }
88371
89291
  document.getElementById("wc-hint").classList.remove("hidden");
88372
- showStatus("Pair your mobile wallet with the code below \u2014 it becomes the signing wallet.");
89292
+ showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
88373
89293
  };
88374
89294
 
88375
89295
  connect();
@@ -88456,7 +89376,7 @@ var SignatureBridge = class {
88456
89376
  expiryMs;
88457
89377
  server = null;
88458
89378
  port = 0;
88459
- token = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89379
+ token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88460
89380
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
88461
89381
  * each open mints its own session. The link is NOT signing authority: only recovered
88462
89382
  * OWNER signatures count (M6-9); the token still gates drive-by loopback scans. */
@@ -88488,7 +89408,7 @@ var SignatureBridge = class {
88488
89408
  unlockUrl() {
88489
89409
  if (!this.server) throw new Error("bridge is not started");
88490
89410
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
88491
- this.unlockToken = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89411
+ this.unlockToken = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88492
89412
  return `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
88493
89413
  }
88494
89414
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2). */
@@ -88543,7 +89463,7 @@ var SignatureBridge = class {
88543
89463
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
88544
89464
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
88545
89465
  */
88546
- requestSignature(request) {
89466
+ requestSignature(request, handlers) {
88547
89467
  if (!this.server) return Promise.resolve({ status: "invalidated", reason: "bridge is not started" });
88548
89468
  if (this.wallet && this.wallet.chainId !== request.chainId) {
88549
89469
  return Promise.resolve({
@@ -88556,7 +89476,8 @@ var SignatureBridge = class {
88556
89476
  request,
88557
89477
  deadlineMs: this.clock() + this.expiryMs,
88558
89478
  resolve,
88559
- settled: false
89479
+ settled: false,
89480
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {}
88560
89481
  };
88561
89482
  this.pending.set(request.id, entry);
88562
89483
  if (this.wcActive) {
@@ -88624,9 +89545,18 @@ var SignatureBridge = class {
88624
89545
  if (req.kind === "transaction") {
88625
89546
  const tx2 = req.tx;
88626
89547
  const txHash = await transport.request("eth_sendTransaction", [
88627
- { from: account, to: tx2.to, data: tx2.data, value: tx2.value }
89548
+ { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
88628
89549
  ]);
88629
89550
  if (!entry.settled) this.settle(entry, { status: "approved", account, txHash });
89551
+ } else if (req.kind === "personal-sign") {
89552
+ if (entry.finalize) {
89553
+ const fresh = await entry.finalize();
89554
+ req.personalSign = fresh.personalSign;
89555
+ req.card = fresh.card;
89556
+ }
89557
+ const ps = req.personalSign;
89558
+ const signature = await transport.request("personal_sign", [ps.hashHex, account]);
89559
+ if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
88630
89560
  } else {
88631
89561
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
88632
89562
  const payload = withEip712DomainType2(req.typedData);
@@ -88678,6 +89608,8 @@ var SignatureBridge = class {
88678
89608
  if (req.method === "POST" && url2.pathname === "/wallet-event")
88679
89609
  return void this.readJson(req, res, (b) => this.onWalletEvent(b, res));
88680
89610
  if (req.method === "POST" && url2.pathname === "/result") return void this.readJson(req, res, (b) => this.onResult(b, res));
89611
+ if (req.method === "POST" && url2.pathname === "/finalize")
89612
+ return void this.readJson(req, res, (b) => void this.onFinalize(b, res));
88681
89613
  this.deny(res, 404, "not found");
88682
89614
  }
88683
89615
  /** Loopback discipline: Host must be this loopback bind; Origin (when a browser sends
@@ -88707,7 +89639,7 @@ var SignatureBridge = class {
88707
89639
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
88708
89640
  return;
88709
89641
  }
88710
- const sessionId = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89642
+ const sessionId = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88711
89643
  this.sessions.set(sessionId, { wallet: null, sse: null });
88712
89644
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88713
89645
  res.end(renderApprovalPage(sessionId));
@@ -88743,8 +89675,13 @@ var SignatureBridge = class {
88743
89675
  });
88744
89676
  }
88745
89677
  const { uri } = await this.wcTransport.createPairing();
89678
+ const { default: qrcode } = await import("qrcode-generator");
89679
+ const qr = qrcode(0, "M");
89680
+ qr.addData(uri);
89681
+ qr.make();
89682
+ const qrSvg = qr.createSvgTag({ cellSize: 4, margin: 8, scalable: true });
88746
89683
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
88747
- res.end(JSON.stringify({ uri }));
89684
+ res.end(JSON.stringify({ uri, qrSvg }));
88748
89685
  } catch (e) {
88749
89686
  this.deny(res, 502, `WalletConnect pairing failed: ${e.message}`);
88750
89687
  }
@@ -88762,7 +89699,7 @@ var SignatureBridge = class {
88762
89699
  return;
88763
89700
  }
88764
89701
  this.unlockToken = null;
88765
- this.unlockSession = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89702
+ this.unlockSession = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88766
89703
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88767
89704
  res.end(renderUnlockPage(this.unlockSession));
88768
89705
  }
@@ -88850,6 +89787,37 @@ var SignatureBridge = class {
88850
89787
  }
88851
89788
  this.ok(res);
88852
89789
  }
89790
+ /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
89791
+ * request. Idempotent for requests without a finalize handler (payload as enqueued). */
89792
+ async onFinalize(body, res) {
89793
+ if (!this.sessionOf(body["sessionId"], res)) return;
89794
+ const entry = this.pending.get(String(body["requestId"] ?? ""));
89795
+ if (!entry || entry.settled) {
89796
+ this.deny(res, 404, "unknown or already-settled requestId");
89797
+ return;
89798
+ }
89799
+ if (entry.request.kind !== "personal-sign") {
89800
+ this.deny(res, 400, "finalize applies only to personal-sign requests");
89801
+ return;
89802
+ }
89803
+ if (entry.finalize) {
89804
+ let fresh;
89805
+ try {
89806
+ fresh = await entry.finalize();
89807
+ } catch (e) {
89808
+ this.deny(res, 502, `finalize failed: ${e.message}`);
89809
+ return;
89810
+ }
89811
+ if (entry.settled) {
89812
+ this.deny(res, 404, "request settled while finalizing");
89813
+ return;
89814
+ }
89815
+ entry.request.personalSign = fresh.personalSign;
89816
+ entry.request.card = fresh.card;
89817
+ }
89818
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
89819
+ res.end(JSON.stringify({ request: entry.request }));
89820
+ }
88853
89821
  onResult(body, res) {
88854
89822
  if (!this.sessionOf(body["sessionId"], res)) return;
88855
89823
  const entry = this.pending.get(String(body["requestId"] ?? ""));
@@ -88874,8 +89842,8 @@ var SignatureBridge = class {
88874
89842
  this.deny(res, 400, "transaction approval requires txHash or rawSignedTx");
88875
89843
  return;
88876
89844
  }
88877
- if (entry.request.kind === "typed-data" && !signature) {
88878
- this.deny(res, 400, "typed-data approval requires signature");
89845
+ if ((entry.request.kind === "typed-data" || entry.request.kind === "personal-sign") && !signature) {
89846
+ this.deny(res, 400, `${entry.request.kind} approval requires signature`);
88879
89847
  return;
88880
89848
  }
88881
89849
  if (entry.collect) {
@@ -89079,9 +90047,13 @@ function resolveRealConfig(env) {
89079
90047
  const missing = [];
89080
90048
  const signer = env["DH_SIGNER"];
89081
90049
  if (signer !== void 0 && signer !== "") {
89082
- problems.push(
89083
- `DH_SIGNER='${signer}' is not wired for the real adapter in this build (plan 04 D1 is mock-pipeline; the sepolia slice is a separate gated delivery). Unset DH_SIGNER or use DH_ADAPTER=mock.`
89084
- );
90050
+ if (signer === "mock-simulated") {
90051
+ problems.push(
90052
+ "DH_SIGNER='mock-simulated' is the test-world stand-in ceremony and cannot authorize real-protocol operations. On the real adapter use 'external' (your own wallet) or 'keystore', or DH_ADAPTER=mock."
90053
+ );
90054
+ } else if (signer !== "external" && signer !== "keystore") {
90055
+ problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
90056
+ }
89085
90057
  }
89086
90058
  const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "sepolia" : env["DH_NETWORK"];
89087
90059
  if (NETWORKS[network] === void 0) {
@@ -89099,6 +90071,21 @@ function resolveRealConfig(env) {
89099
90071
  if (keystorePath && !keystorePassword || !keystorePath && keystorePassword) {
89100
90072
  problems.push("DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD must be set together (or neither).");
89101
90073
  }
90074
+ const stateDir = env["DH_STATE_DIR"];
90075
+ const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
90076
+ const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
90077
+ const wcProjectId = env["DH_WC_PROJECT_ID"];
90078
+ if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
90079
+ problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
90080
+ }
90081
+ let bridgeOpenBrowser;
90082
+ if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
90083
+ if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
90084
+ problems.push(`DH_BRIDGE_OPEN='${bridgeOpenRaw}' must be 0 or 1.`);
90085
+ } else {
90086
+ bridgeOpenBrowser = bridgeOpenRaw === "1";
90087
+ }
90088
+ }
89102
90089
  const ACK_PHRASE = "I-UNDERSTAND-REAL-FUNDS";
89103
90090
  const ackRaw = env["DH_MAINNET_WRITES_ACK"];
89104
90091
  let mainnetWritesAck;
@@ -89142,6 +90129,11 @@ function resolveRealConfig(env) {
89142
90129
  serviceEndpoint,
89143
90130
  litNetwork,
89144
90131
  ...keystorePath && keystorePassword ? { keystorePath, keystorePassword } : {},
90132
+ ...signer === "external" || signer === "keystore" ? { signer } : {},
90133
+ ...stateDir ? { stateDir } : {},
90134
+ ...bridgeUrlFile ? { bridgeUrlFile } : {},
90135
+ ...bridgeOpenBrowser !== void 0 ? { bridgeOpenBrowser } : {},
90136
+ ...wcProjectId ? { wcProjectId } : {},
89145
90137
  ...validatorVersion !== void 0 ? { validatorVersion } : {},
89146
90138
  ...mainnetWritesAck === true ? { mainnetWritesAck: true } : {}
89147
90139
  }
@@ -89149,14 +90141,15 @@ function resolveRealConfig(env) {
89149
90141
  }
89150
90142
 
89151
90143
  // src/boundary/index.ts
89152
- function fileSignerPersistence(path4) {
90144
+ function fileSignerPersistence(filePath) {
89153
90145
  return {
89154
90146
  load() {
89155
- if (!fs5.existsSync(path4)) return null;
89156
- return JSON.parse(fs5.readFileSync(path4, "utf8"));
90147
+ if (!fs5.existsSync(filePath)) return null;
90148
+ return JSON.parse(fs5.readFileSync(filePath, "utf8"));
89157
90149
  },
89158
90150
  save(state) {
89159
- fs5.writeFileSync(path4, JSON.stringify(state));
90151
+ fs5.mkdirSync(path4.dirname(filePath), { recursive: true });
90152
+ fs5.writeFileSync(filePath, JSON.stringify(state));
89160
90153
  }
89161
90154
  };
89162
90155
  }
@@ -89166,7 +90159,7 @@ function createBoundary(config, opts) {
89166
90159
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
89167
90160
  );
89168
90161
  }
89169
- const configFingerprint = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
90162
+ const configFingerprint = (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
89170
90163
  if (opts?.ceremony) {
89171
90164
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
89172
90165
  const boundary2 = new BoundaryCore({
@@ -89175,6 +90168,11 @@ function createBoundary(config, opts) {
89175
90168
  network: "mock",
89176
90169
  chainId: config.chainId ?? 1337,
89177
90170
  ...config.borrower ? { borrowerAddress: config.borrower } : {},
90171
+ capabilities: () => ({
90172
+ reads: { public: true, authenticated: "available" },
90173
+ writes: { enabled: true, signerModes: ["external"], activeMode: "external" },
90174
+ signerSetupTool: false
90175
+ }),
89178
90176
  configFingerprint
89179
90177
  });
89180
90178
  return { boundary: boundary2, mockControl: plugin2.control, dispose: () => plugin2.dispose() };
@@ -89252,6 +90250,16 @@ function createBoundary(config, opts) {
89252
90250
  chainId,
89253
90251
  ...config.borrower ? { borrowerAddress: config.borrower } : {},
89254
90252
  signer: manager,
90253
+ // B3: the mock sandbox runs every ceremony class; reads have no login gate.
90254
+ capabilities: () => ({
90255
+ reads: { public: true, authenticated: "available" },
90256
+ writes: {
90257
+ enabled: true,
90258
+ signerModes: ["external", "keystore", "mock-simulated", "safe", "safe-module"],
90259
+ activeMode: manager.mode()
90260
+ },
90261
+ signerSetupTool: true
90262
+ }),
89255
90263
  configFingerprint
89256
90264
  });
89257
90265
  return {
@@ -89265,18 +90273,73 @@ function createBoundary(config, opts) {
89265
90273
  };
89266
90274
  }
89267
90275
  async function createRealBoundary(config, wallet) {
89268
- const plugin = new RealUpstreamPlugin(config, wallet);
90276
+ const keystore = new KeystoreProvider({
90277
+ ...config.keystorePath ? { keystorePath: config.keystorePath } : {},
90278
+ ...config.keystorePassword ? { keystorePassword: config.keystorePassword } : {}
90279
+ });
90280
+ if (wallet) keystore.adopt(wallet);
90281
+ const stateDir = config.stateDir ?? path4.join(os2.homedir(), ".dh-mcp");
90282
+ const stateFile = path4.join(stateDir, `${config.network}.signer.json`);
90283
+ const chainName = config.network === "mainnet" ? "Ethereum Mainnet" : "Sepolia";
90284
+ const bridge = new SignatureBridge({
90285
+ ...config.bridgeUrlFile ? { urlFile: config.bridgeUrlFile } : {},
90286
+ network: { chainId: config.chainId, chainName, rpcUrl: config.rpcUrl },
90287
+ ...config.wcProjectId ? { wc: { projectId: config.wcProjectId, chainId: config.chainId } } : {},
90288
+ keystoreUnlock: {
90289
+ unlock: (json, password) => keystore.unlock(json, password),
90290
+ unlockConfigured: (password) => keystore.unlockConfigured(password),
90291
+ generate: (password) => keystore.generateAndSave(password, path4.join(stateDir, `${config.network}.keystore.json`))
90292
+ }
90293
+ });
90294
+ const initialMode = config.signer ?? (keystore.materialConfigured() ? "keystore" : "none");
90295
+ const manager = new SignerManager({
90296
+ persistence: fileSignerPersistence(stateFile),
90297
+ initialMode,
90298
+ candidate: () => bridge.walletState()?.account ?? null,
90299
+ pendingCeremonies: () => bridge.pendingCount(),
90300
+ keystore
90301
+ // No safeInfo: the Safe planes are mock-only pending their own plans — manager.use
90302
+ // refuses 'safe'/'safe-module' with the missing-discovery reason, truthfully.
90303
+ });
90304
+ if (initialMode === "external" || manager.mode() === "external") {
90305
+ void bridge.start();
90306
+ }
90307
+ const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
89269
90308
  await plugin.initWriteSdk();
89270
- const configFingerprint = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
90309
+ const configFingerprint = (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
90310
+ const writesArmed = config.network === "sepolia" || config.network === "mainnet" && config.mainnetWritesAck === true;
90311
+ const capabilities = () => ({
90312
+ reads: {
90313
+ public: true,
90314
+ authenticated: plugin.authenticatedReadsAvailable() ? "available" : "needs-signer"
90315
+ },
90316
+ writes: writesArmed ? { enabled: true, signerModes: ["external", "keystore"], activeMode: manager.mode() } : {
90317
+ enabled: false,
90318
+ reason: "writes are operator-gated on mainnet \u2014 the standing mainnet write block; mainnet writes await their dedicated security review. Reads remain available.",
90319
+ signerModes: [],
90320
+ activeMode: manager.mode()
90321
+ },
90322
+ signerSetupTool: true
90323
+ });
89271
90324
  const boundary = new BoundaryCore({
89272
90325
  plugin,
89273
90326
  adapter: "real",
89274
90327
  network: config.network,
89275
90328
  chainId: config.chainId,
89276
- ...wallet ? { borrowerAddress: wallet.address } : {},
90329
+ // M10-5: the manager IS the identity surface — boundary://info signerKind/borrower
90330
+ // stay live across mode switches instead of freezing a boot-time address.
90331
+ signer: manager,
90332
+ capabilities,
89277
90333
  configFingerprint
89278
90334
  });
89279
- return { boundary, dispose: () => plugin.dispose() };
90335
+ return {
90336
+ boundary,
90337
+ signer: { manager, bridge, keystore, connect: () => plugin.connectExternal() },
90338
+ dispose: () => {
90339
+ plugin.dispose();
90340
+ bridge.close();
90341
+ }
90342
+ };
89280
90343
  }
89281
90344
  // Annotate the CommonJS export names for ESM import in node:
89282
90345
  0 && (module.exports = {