@gvnrdao/dh-mcp 0.1.1 → 0.2.1

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 +101 -38
  2. package/dist/boundary.js +1617 -485
  3. package/dist/index.js +1814 -534
  4. package/package.json +11 -4
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;
@@ -61673,7 +61761,7 @@ var init_deployment_addresses = __esm2({
61673
61761
  LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9",
61674
61762
  CircuitBreakerModule: "0xF7b545d3a4Ee056D06909AB367E2F7bFFE3cB1BC",
61675
61763
  AdminModule: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
61676
- PositionManagerViews: "0x9225647a30bbACA4Acc0491B786869036914242e",
61764
+ PositionManagerViews: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
61677
61765
  PositionManager: "0x12A1836e56139ccaD8722B89519d84233efc224B",
61678
61766
  OperationAuthorizationRegistry: "0xD4505645b724754f5170a2027804a4265e860d44",
61679
61767
  ContractVersionRegistry: "0x5e18f77d01940dA5B1D986D373D9A6ad0767008d",
@@ -61751,13 +61839,13 @@ var init_deployment_addresses = __esm2({
61751
61839
  block: 25472957
61752
61840
  },
61753
61841
  PositionManager: {
61754
- previousImplementation: "0x9f52BaBB40FbFC5863e45B1A4014cB433950c684",
61755
- newImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
61756
- upgradedAt: "2026-07-06T08:42:47.000Z",
61757
- upgradedBy: "AdminModule/Safe audit-batch upgradeToAndCall; executed by 0x2002827d34A781883Ec4c83c36ECC140c3911F2B in tx 0xa1fbe31cb71736514a868e681573dff22c9fab91d69cec157a24a30e29eadbe6 (block 25472368)",
61758
- reason: "Reconciled from chain \u2014 mainnet audit rollout batch (cross-ref onchain-auth/.safe-batches/mainnet-audit-execute.json)",
61759
- executeTx: "0xa1fbe31cb71736514a868e681573dff22c9fab91d69cec157a24a30e29eadbe6",
61760
- block: 25472368
61842
+ previousImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
61843
+ newImplementation: "0x2e7170d6Fb15A876dB726732e72e63109bcB916d",
61844
+ upgradedAt: "2026-08-03T08:34:23.000Z",
61845
+ upgradedBy: "AdminModule generic-op 0x69b79a906ed2 (3-of-3 signatures, 24h timelock; proposed by 0xEba7BfAeB35ee18408b424Ee0BB45AdDf776589f, executed in the release batch onchain-auth/.safe-batches/mainnet-release-execute-B.json, submitted by EOA 0x2002827d34A781883Ec4c83c36ECC140c3911F2B, tx 0xf1f8d5fc13f45d7a3f932bf1a2d6e29381fdd41cd31298ad785bf7688df07fe6, block 25673200)",
61846
+ reason: "2026-08 agent-stack release, Execute B: agent-delegation digest rebind. makePayment/mintUCD/extendPosition now bind their EIP-712 digest to the STORED borrower rather than msg.sender, so a scoped AgentDelegationRegistry grant can submit; withdrawBTC still binds msg.sender and stays non-delegable. Also adds setViews(address), which the same batch used to repoint PM at the replacement PositionManagerViews. NOTE: VERSION reads 1.5.4 on BOTH sides of this upgrade \u2014 verify by implementation ADDRESS, never by VERSION(). NOTE: not the July audit rollout batch \u2014 reconcile-deployment-record.ts --write templates every row with that text; this hand-authored provenance is the accurate one, restore it if --write flattens it again.",
61847
+ executeTx: "0xf1f8d5fc13f45d7a3f932bf1a2d6e29381fdd41cd31298ad785bf7688df07fe6",
61848
+ block: 25673200
61761
61849
  },
61762
61850
  LoanOperationsManagerModule: {
61763
61851
  previousImplementation: "0x56671D671e492Dae625413d463D47605Cf54edf6",
@@ -61801,6 +61889,16 @@ var init_deployment_addresses = __esm2({
61801
61889
  reason: "2026-08 agent-stack release: PositionDelegateRegistry VERSION 1.1.0 -> 2.0.0 via upgradeToAndCall + initializeV2(AdminModule, registrar 0x5D54E0BE\u2026, pauser 0xC205Ae99\u2026) \u2014 kill-switch, deny-only registrar, permanent delegate burn. NOTE: not the July audit rollout batch \u2014 reconcile-deployment-record.ts --write templates every row with that text; this hand-authored provenance is the accurate one, restore it if --write flattens it again.",
61802
61890
  executeTx: "0xf0f237f6c4e958c37de556571908283c59c3fba6ebf9fa3cefb956f37e315a10",
61803
61891
  block: 25669024
61892
+ },
61893
+ PositionManagerViews: {
61894
+ previousImplementation: "0x9225647a30bbACA4Acc0491B786869036914242e",
61895
+ newImplementation: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
61896
+ proxy: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
61897
+ upgradedAt: "2026-08-03T08:34:23.000Z",
61898
+ upgradedBy: "REPLACED, not upgraded. Fresh ERC1967Proxy (atomically initialized) + AdminModule generic-op 0x848a97186f0d PositionManager.setViews(proxy) \u2014 3-of-3, 24h timelock, executed in onchain-auth/.safe-batches/mainnet-release-execute-B.json",
61899
+ reason: "2026-08 agent-stack release. The mainnet PositionManagerViews at 0x9225647a was deployed as a BARE implementation (EIP-1967 slot 0x00), so upgradeToAndCall reverts UUPSUnauthorizedCallContext \u2014 it could never be upgraded. PositionManager.setViews (added in the same Execute B batch) removed the repoint blocker, so Views was replaced behind a new proxy rather than upgraded. This makes the Pashov F3 renewal debt-ceiling check REACHABLE for the first time: ExceedsMaxLoan (0x499e7985) is present in 0xE68DC096 and absent from 0x9225647a. Views holds no protocol state (8 wiring slots + roles + pause), which is what made replacement safe. The old contract is ABANDONED, not decommissioned \u2014 it stays live and callable as the rollback target for setViews. NOTE: VERSION reads 1.1.1 on both sides; verify by address.",
61900
+ executeTx: "0xf1f8d5fc13f45d7a3f932bf1a2d6e29381fdd41cd31298ad785bf7688df07fe6",
61901
+ block: 25673200
61804
61902
  }
61805
61903
  },
61806
61904
  latestEnv: {
@@ -61834,10 +61932,10 @@ var init_deployment_addresses = __esm2({
61834
61932
  ADMIN_MODULE_IMPL: "0xb4C5C7E051A1e672F014B25CB5D55B225Aa0D512",
61835
61933
  BTC_SPEND_AUTHORIZER: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
61836
61934
  BTC_SPEND_AUTHORIZER_IMPL: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
61837
- POSITION_MANAGER_VIEWS: "0x9225647a30bbACA4Acc0491B786869036914242e",
61838
- POSITION_MANAGER_VIEWS_IMPL: "0x9225647a30bbACA4Acc0491B786869036914242e",
61935
+ POSITION_MANAGER_VIEWS: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
61936
+ POSITION_MANAGER_VIEWS_IMPL: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
61839
61937
  POSITION_MANAGER: "0x12A1836e56139ccaD8722B89519d84233efc224B",
61840
- POSITION_MANAGER_IMPL: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
61938
+ POSITION_MANAGER_IMPL: "0x2e7170d6Fb15A876dB726732e72e63109bcB916d",
61841
61939
  LOAN_OPERATIONS_MANAGER_MODULE: "0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",
61842
61940
  LOAN_OPERATIONS_MANAGER_MODULE_IMPL: "0x7d90aAB4466f59BA9aC9C7a9BF14dC53734336e7",
61843
61941
  UPGRADE_VALIDATOR: "0xC46Ae71F22e3741A6CF46E399aE914C4868fEbed",
@@ -61863,7 +61961,7 @@ var init_deployment_addresses = __esm2({
61863
61961
  LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9",
61864
61962
  CircuitBreakerModule: "0xF7b545d3a4Ee056D06909AB367E2F7bFFE3cB1BC",
61865
61963
  AdminModule: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
61866
- PositionManagerViews: "0x9225647a30bbACA4Acc0491B786869036914242e",
61964
+ PositionManagerViews: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
61867
61965
  PositionManager: "0x12A1836e56139ccaD8722B89519d84233efc224B",
61868
61966
  OperationAuthorizationRegistry: "0xD4505645b724754f5170a2027804a4265e860d44",
61869
61967
  ContractVersionRegistry: "0x5e18f77d01940dA5B1D986D373D9A6ad0767008d",
@@ -67687,6 +67785,7 @@ function sessionStoreKey(address, chainId, endpoint) {
67687
67785
  return STORE_PREFIX + `${address.trim().toLowerCase()}:${chainId}:${endpoint.replace(/\/+$/, "")}`;
67688
67786
  }
67689
67787
  var PENDING_ENVELOPE_TTL_SECONDS = 8 * 60;
67788
+ var EOA_PENDING_ENVELOPE_TTL_SECONDS = 60;
67690
67789
  function pendingEnvelopeKey(sessionKey) {
67691
67790
  return sessionKey + ":pending";
67692
67791
  }
@@ -67734,7 +67833,7 @@ var LocalStorageSessionStore = class {
67734
67833
  } catch {
67735
67834
  }
67736
67835
  }
67737
- loadPending(key) {
67836
+ loadPending(key, maxAgeSeconds = PENDING_ENVELOPE_TTL_SECONDS) {
67738
67837
  let raw;
67739
67838
  try {
67740
67839
  raw = window.localStorage.getItem(pendingEnvelopeKey(key));
@@ -67751,7 +67850,7 @@ var LocalStorageSessionStore = class {
67751
67850
  return null;
67752
67851
  }
67753
67852
  const nowSec = Math.floor(Date.now() / 1e3);
67754
- if (!isPendingEnvelopeShape(parsed) || nowSec >= parsed.issuedAt + PENDING_ENVELOPE_TTL_SECONDS) {
67853
+ if (!isPendingEnvelopeShape(parsed) || nowSec >= parsed.issuedAt + maxAgeSeconds) {
67755
67854
  this.clearPending(key);
67756
67855
  return null;
67757
67856
  }
@@ -67785,12 +67884,12 @@ var MemorySessionStore = class {
67785
67884
  clear(key) {
67786
67885
  this.entries.delete(key);
67787
67886
  }
67788
- loadPending(key) {
67887
+ loadPending(key, maxAgeSeconds = PENDING_ENVELOPE_TTL_SECONDS) {
67789
67888
  const envelope = this.pending.get(key);
67790
67889
  if (!envelope)
67791
67890
  return null;
67792
67891
  const nowSec = Math.floor(Date.now() / 1e3);
67793
- if (nowSec >= envelope.issuedAt + PENDING_ENVELOPE_TTL_SECONDS) {
67892
+ if (nowSec >= envelope.issuedAt + maxAgeSeconds) {
67794
67893
  this.pending.delete(key);
67795
67894
  return null;
67796
67895
  }
@@ -67822,15 +67921,23 @@ var REFRESH_LEEWAY_SECONDS = 30;
67822
67921
  var LOGIN_RETRY_BASE_MS = 3e4;
67823
67922
  var LOGIN_RETRY_MAX_MS = 5 * 6e4;
67824
67923
  var ServerLoginError = class extends Error {
67825
- constructor(message, status) {
67924
+ constructor(message, status, reason) {
67826
67925
  super(message);
67827
67926
  this.status = status;
67927
+ this.reason = reason;
67828
67928
  this.name = "ServerLoginError";
67829
67929
  }
67830
67930
  };
67831
67931
  function isLoginRejection(error) {
67832
67932
  return error instanceof ServerLoginError && error.status >= 400 && error.status < 500 && error.status !== 429;
67833
67933
  }
67934
+ var SPENT_ENVELOPE_REASONS = /* @__PURE__ */ new Set(["replayed_nonce", "expired_issuedAt"]);
67935
+ function isSpentEnvelope(error) {
67936
+ if (!isLoginRejection(error))
67937
+ return false;
67938
+ const { reason, status } = error;
67939
+ return reason ? SPENT_ENVELOPE_REASONS.has(reason) : status === 409;
67940
+ }
67834
67941
  var ServerSession = class {
67835
67942
  signer;
67836
67943
  serviceEndpoint;
@@ -67861,6 +67968,12 @@ var ServerSession = class {
67861
67968
  * `clear()` can drop the persisted token without an async address lookup.
67862
67969
  */
67863
67970
  lastStoreKey = null;
67971
+ /**
67972
+ * Whether the signer is a smart-contract wallet, memoized after the first
67973
+ * `eth_getCode`. Decides which of the server's two first-use windows bounds
67974
+ * envelope reuse; a signer cannot change kind for the life of the session.
67975
+ */
67976
+ contractSigner = null;
67864
67977
  constructor(opts) {
67865
67978
  assertSafeServiceEndpoint(opts.serviceEndpoint);
67866
67979
  this.signer = opts.signer;
@@ -68059,6 +68172,34 @@ var ServerSession = class {
68059
68172
  return null;
68060
68173
  }
68061
68174
  }
68175
+ /**
68176
+ * How long a pending envelope for THIS signer may be reused, in seconds.
68177
+ *
68178
+ * The server grants an EOA 120s to make an envelope's first use and a contract
68179
+ * wallet 600s, so one local TTL is necessarily wrong for one of them. Deployed
68180
+ * code has bytecode; an EOA does not — one `eth_getCode`, memoized, settles it.
68181
+ *
68182
+ * Reports the CONTRACT window when it cannot tell, which is the behavior that
68183
+ * shipped before the split. The asymmetry is intended: guessing "EOA" for a
68184
+ * Safe hands it a new message and orphans the owner signatures already
68185
+ * collected, while guessing "contract" for an EOA now costs one rejected
68186
+ * attempt, because a rejection clears the envelope.
68187
+ */
68188
+ async pendingEnvelopeTtl() {
68189
+ if (this.contractSigner === null) {
68190
+ try {
68191
+ const provider = this.signer.provider;
68192
+ if (!provider)
68193
+ return PENDING_ENVELOPE_TTL_SECONDS;
68194
+ const address = await this.signer.getAddress();
68195
+ const code = await provider.getCode(address);
68196
+ this.contractSigner = typeof code === "string" && code !== "0x";
68197
+ } catch {
68198
+ return PENDING_ENVELOPE_TTL_SECONDS;
68199
+ }
68200
+ }
68201
+ return this.contractSigner ? PENDING_ENVELOPE_TTL_SECONDS : EOA_PENDING_ENVELOPE_TTL_SECONDS;
68202
+ }
68062
68203
  async getOrRefresh() {
68063
68204
  const nowSec = this.now();
68064
68205
  if (this.cached && this.cached.expiresAt - REFRESH_LEEWAY_SECONDS > nowSec) {
@@ -68080,10 +68221,10 @@ var ServerSession = class {
68080
68221
  }
68081
68222
  this.onSignaturePrompt?.();
68082
68223
  let session;
68224
+ const store = this.store;
68225
+ const storeKey = store ? this.lastStoreKey : null;
68083
68226
  try {
68084
- const store = this.store;
68085
- const storeKey = store ? this.lastStoreKey : null;
68086
- const reuse = storeKey ? store.loadPending?.(storeKey) ?? void 0 : void 0;
68227
+ const reuse = storeKey ? store.loadPending?.(storeKey, await this.pendingEnvelopeTtl()) ?? void 0 : void 0;
68087
68228
  const payload = await buildSignedLoginPayload(
68088
68229
  this.signer,
68089
68230
  this.chainId,
@@ -68106,6 +68247,9 @@ var ServerSession = class {
68106
68247
  this.onSignatureResolved?.(true);
68107
68248
  } catch (error) {
68108
68249
  this.onSignatureResolved?.(false);
68250
+ if (storeKey && isSpentEnvelope(error)) {
68251
+ store.clearPending?.(storeKey);
68252
+ }
68109
68253
  const failures = (this.promptBackoff?.failures ?? 0) + 1;
68110
68254
  this.promptBackoff = {
68111
68255
  failures,
@@ -68134,9 +68278,17 @@ var ServerSession = class {
68134
68278
  });
68135
68279
  if (!res.ok) {
68136
68280
  const detail = await res.text().catch(() => "");
68281
+ let reason;
68282
+ try {
68283
+ const parsed = JSON.parse(detail);
68284
+ if (typeof parsed?.reason === "string")
68285
+ reason = parsed.reason;
68286
+ } catch {
68287
+ }
68137
68288
  throw new ServerLoginError(
68138
68289
  `lit-ops-server login failed: HTTP ${res.status} ${detail.slice(0, 200)}`,
68139
- res.status
68290
+ res.status,
68291
+ reason
68140
68292
  );
68141
68293
  }
68142
68294
  const body = await res.json();
@@ -73710,7 +73862,7 @@ var DiamondHandsGraph = class {
73710
73862
  async getPSMConfiguration() {
73711
73863
  const query = `
73712
73864
  query GetPSMConfiguration {
73713
- psmConfiguration(id: "psm") {
73865
+ psmConfiguration: psmconfiguration(id: "psm") {
73714
73866
  id
73715
73867
  version
73716
73868
  redeemEnabled
@@ -73832,7 +73984,7 @@ var DiamondHandsGraph = class {
73832
73984
  const whereClause = whereConditions.length > 0 ? `where: { ${whereConditions.join(", ")} }` : "";
73833
73985
  const query = `
73834
73986
  query GetPSMTransactions($first: Int!, $skip: Int!) {
73835
- psmTransactions(${whereClause}, first: $first, skip: $skip, orderBy: timestamp, orderDirection: desc) {
73987
+ psmTransactions: psmtransactions(${whereClause}, first: $first, skip: $skip, orderBy: timestamp, orderDirection: desc) {
73836
73988
  id
73837
73989
  type
73838
73990
  user
@@ -73867,7 +74019,7 @@ var DiamondHandsGraph = class {
73867
74019
  const whereClause = whereConditions.length > 0 ? `where: { ${whereConditions.join(", ")} }` : "";
73868
74020
  const query = `
73869
74021
  query GetPSMDailyMetrics($first: Int!) {
73870
- psmDailyMetrics(${whereClause}, first: $first, orderBy: date, orderDirection: desc) {
74022
+ psmDailyMetrics: psmdailyMetrics(${whereClause}, first: $first, orderBy: date, orderDirection: desc) {
73871
74023
  id
73872
74024
  date
73873
74025
  totalSwapVolume
@@ -74591,7 +74743,7 @@ var DiamondHandsGraph = class {
74591
74743
  }` : ""}
74592
74744
 
74593
74745
  ${includeKind("psm") ? `
74594
- psmTransactions(
74746
+ psmTransactions: psmtransactions(
74595
74747
  ${buildTimeWhereClause()}
74596
74748
  first: $limit, orderBy: timestamp, orderDirection: $orderDirection
74597
74749
  ) {
@@ -85612,23 +85764,28 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85612
85764
  * @throws if timeout is reached before subgraph catches up
85613
85765
  */
85614
85766
  // ============================================================================
85615
- // HIGH-LEVEL API - Agent Delegation (auto-renew) — SEPOLIA ONLY
85767
+ // HIGH-LEVEL API - Agent Delegation (auto-renew)
85616
85768
  // ============================================================================
85617
- /** Guard: the AgentDelegationRegistry MVP is deployed on Sepolia only. */
85618
- async assertAgentDelegationSepolia() {
85619
- const chainId = Number((await this.getProviderOrThrow().getNetwork()).chainId);
85620
- if (chainId !== 11155111) {
85621
- throw new SDKError({
85622
- message: `Agent auto-renew delegation is Sepolia-only (chainId 11155111); got ${chainId}`,
85623
- category: "NETWORK",
85624
- severity: "HIGH"
85625
- /* HIGH */
85626
- });
85627
- }
85769
+ /**
85770
+ * Guard: resolve the AgentDelegationRegistry for the configured network.
85771
+ *
85772
+ * Deployment presence IS the availability test — there is deliberately no chainId
85773
+ * allow-list here. The registry is deployed per network (Sepolia 2026-07, mainnet
85774
+ * 2026-08 agent-stack release) and `getNetworkConfig` populates the address from the
85775
+ * generated deployment table, so a chain without a deployment resolves to `""` and
85776
+ * fails closed below. Adding a chain therefore needs no SDK code change — which is
85777
+ * exactly how the previous hardcoded `chainId !== 11155111` gate went stale and kept
85778
+ * the mainnet toggle dark after the registry shipped.
85779
+ *
85780
+ * Callers that need the availability answer WITHOUT throwing (e.g. to decide whether to
85781
+ * render a toggle at all) should ask the deployment table directly rather than calling this
85782
+ * and catching — `ALL_DEPLOYMENTS` is published on the `@gvnrdao/dh-sdk/deployments` subpath.
85783
+ */
85784
+ agentDelegationRegistryOrThrow() {
85628
85785
  const addr = this.config.contractAddresses?.agentDelegationRegistry;
85629
85786
  if (!addr) {
85630
85787
  throw new SDKError({
85631
- message: "AgentDelegationRegistry address not configured \u2014 provide contractAddresses.agentDelegationRegistry",
85788
+ message: "AgentDelegationRegistry is not available on this network \u2014 no deployment address is configured (contractAddresses.agentDelegationRegistry)",
85632
85789
  category: "CONFIGURATION",
85633
85790
  severity: "HIGH"
85634
85791
  /* HIGH */
@@ -85641,7 +85798,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85641
85798
  * Pure view — no signer required.
85642
85799
  */
85643
85800
  async getAutoRenewStatus(positionId, user) {
85644
- const addr = await this.assertAgentDelegationSepolia();
85801
+ const addr = this.agentDelegationRegistryOrThrow();
85645
85802
  const registry = AgentDelegationRegistry__factory.connect(addr, this.getProviderOrThrow());
85646
85803
  const pid = this.toBytes32(positionId);
85647
85804
  const grant = await registry.getLoanGrant(pid);
@@ -85661,7 +85818,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85661
85818
  * registers it, then records the position's renew grant. Borrower-signed.
85662
85819
  */
85663
85820
  async enableAutoRenew(positionId, options) {
85664
- const addr = await this.assertAgentDelegationSepolia();
85821
+ const addr = this.agentDelegationRegistryOrThrow();
85665
85822
  const pdrAddr = this.config.contractAddresses?.positionDelegateRegistry;
85666
85823
  if (!pdrAddr) {
85667
85824
  throw new SDKError({
@@ -85702,7 +85859,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85702
85859
  }
85703
85860
  /** Disable auto-renew delegation for a position (clears the grant). Borrower-signed. */
85704
85861
  async disableAutoRenew(positionId) {
85705
- const addr = await this.assertAgentDelegationSepolia();
85862
+ const addr = this.agentDelegationRegistryOrThrow();
85706
85863
  const signer = this.getSignerOrThrow();
85707
85864
  const user = await signer.getAddress();
85708
85865
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
@@ -87123,6 +87280,12 @@ var LitOpsSession = class {
87123
87280
  address() {
87124
87281
  return this.wallet.address;
87125
87282
  }
87283
+ /** A JWT is cached and not about to expire — reads in external mode consult this
87284
+ * instead of `token()` so they NEVER summon the wallet (plan 10 A0.7). */
87285
+ hasValidToken() {
87286
+ const now = Math.floor(Date.now() / 1e3);
87287
+ return this.cached !== null && this.cached.expiresAtSec - REFRESH_LEEWAY_SEC > now;
87288
+ }
87126
87289
  /** A valid Bearer token, logging in (or re-logging) as needed. Throws with a legible
87127
87290
  * message on failure — the gateway maps it to the taxonomy. */
87128
87291
  async token() {
@@ -87180,9 +87343,240 @@ function decodeJwtExp(token) {
87180
87343
  }
87181
87344
 
87182
87345
  // src/boundary/upstream/real/write-ops.ts
87346
+ var import_ethers33 = require("ethers");
87347
+
87348
+ // src/signer/types.ts
87349
+ var OperationDeclined = class extends Error {
87350
+ };
87351
+
87352
+ // src/boundary/upstream/real/write-ops.ts
87353
+ init_tx_validator();
87354
+
87355
+ // src/boundary/upstream/shared/external-bridge/page-crypto.ts
87183
87356
  var import_ethers32 = require("ethers");
87357
+ var PERSONAL_SIGN_LAYOUTS = {
87358
+ "dh-op-envelope-v1": {
87359
+ types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87360
+ fieldOrder: ["positionId", "timestamp", "chainId", "amount", "action"],
87361
+ hashUtf8Fields: ["action"]
87362
+ }
87363
+ };
87364
+ function hashForLayout(layout, fields) {
87365
+ const def = PERSONAL_SIGN_LAYOUTS[layout];
87366
+ if (!def) throw new Error(`page-crypto: unknown layout "${layout}"`);
87367
+ const hashUtf8 = new Set(def.hashUtf8Fields);
87368
+ const values = def.fieldOrder.map((name) => {
87369
+ const raw = fields[name];
87370
+ if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
87371
+ return hashUtf8.has(name) ? import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(raw)) : raw;
87372
+ });
87373
+ return import_ethers32.ethers.solidityPackedKeccak256(def.types, values);
87374
+ }
87375
+ var PAGE_CRYPTO_JS = `"use strict";
87376
+ (function () {
87377
+ // keccak-f[1600] \u2014 25 lanes of 64-bit BigInt, state[x + 5*y]. Validated bit-for-bit
87378
+ // against ethers.keccak256 across empty/short/rate-boundary inputs (page-crypto.test.ts).
87379
+ var MASK64 = (1n << 64n) - 1n;
87380
+
87381
+ function rotl64(x, n) {
87382
+ x &= MASK64;
87383
+ var nn = BigInt(n % 64);
87384
+ if (nn === 0n) return x;
87385
+ return ((x << nn) | (x >> (64n - nn))) & MASK64;
87386
+ }
87387
+
87388
+ var RC = [
87389
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
87390
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
87391
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
87392
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
87393
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
87394
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n
87395
+ ];
87396
+
87397
+ // r[x][y] rotation offsets, flat index x + 5*y.
87398
+ var ROT = [
87399
+ 0, 1, 62, 28, 27,
87400
+ 36, 44, 6, 55, 20,
87401
+ 3, 10, 43, 25, 39,
87402
+ 41, 45, 15, 21, 8,
87403
+ 18, 2, 61, 56, 14
87404
+ ];
87405
+
87406
+ function keccakF1600(state) {
87407
+ for (var round = 0; round < 24; round++) {
87408
+ var C = new Array(5);
87409
+ for (var x = 0; x < 5; x++) {
87410
+ C[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20];
87411
+ }
87412
+ var D = new Array(5);
87413
+ for (var x2 = 0; x2 < 5; x2++) {
87414
+ D[x2] = C[(x2 + 4) % 5] ^ rotl64(C[(x2 + 1) % 5], 1);
87415
+ }
87416
+ for (var x3 = 0; x3 < 5; x3++) {
87417
+ for (var y = 0; y < 5; y++) {
87418
+ state[x3 + 5 * y] ^= D[x3];
87419
+ }
87420
+ }
87421
+ var B = new Array(25);
87422
+ for (var x4 = 0; x4 < 5; x4++) {
87423
+ for (var y2 = 0; y2 < 5; y2++) {
87424
+ var newX = y2;
87425
+ var newY = (2 * x4 + 3 * y2) % 5;
87426
+ B[newX + 5 * newY] = rotl64(state[x4 + 5 * y2], ROT[x4 + 5 * y2]);
87427
+ }
87428
+ }
87429
+ for (var x5 = 0; x5 < 5; x5++) {
87430
+ for (var y3 = 0; y3 < 5; y3++) {
87431
+ var idx = x5 + 5 * y3;
87432
+ state[idx] = (B[idx] ^ (~B[(x5 + 1) % 5 + 5 * y3] & B[(x5 + 2) % 5 + 5 * y3])) & MASK64;
87433
+ }
87434
+ }
87435
+ state[0] = (state[0] ^ RC[round]) & MASK64;
87436
+ }
87437
+ }
87438
+
87439
+ function keccak256Bytes(bytes) {
87440
+ var rateBytes = 136; // 1088-bit rate (keccak256: capacity 512 bits)
87441
+ var state = new Array(25).fill(0n);
87442
+
87443
+ // Original-Keccak multi-rate padding (pad10*1, domain byte 0x01 \u2014 NOT NIST SHA3's 0x06).
87444
+ var padLen = rateBytes - (bytes.length % rateBytes);
87445
+ var padded = new Uint8Array(bytes.length + padLen);
87446
+ padded.set(bytes);
87447
+ padded[bytes.length] ^= 0x01;
87448
+ padded[padded.length - 1] ^= 0x80;
87449
+
87450
+ for (var off = 0; off < padded.length; off += rateBytes) {
87451
+ for (var i = 0; i < rateBytes / 8; i++) {
87452
+ var lane = 0n;
87453
+ for (var b = 7; b >= 0; b--) {
87454
+ lane = (lane << 8n) | BigInt(padded[off + i * 8 + b]);
87455
+ }
87456
+ state[i] ^= lane;
87457
+ }
87458
+ keccakF1600(state);
87459
+ }
87460
+
87461
+ var out = new Uint8Array(32);
87462
+ for (var j = 0; j < 4; j++) {
87463
+ var laneOut = state[j];
87464
+ for (var b2 = 0; b2 < 8; b2++) {
87465
+ out[j * 8 + b2] = Number(laneOut & 0xffn);
87466
+ laneOut >>= 8n;
87467
+ }
87468
+ }
87469
+ return out;
87470
+ }
87471
+
87472
+ function bytesToHex(bytes) {
87473
+ var hex = "0x";
87474
+ for (var i = 0; i < bytes.length; i++) {
87475
+ hex += bytes[i].toString(16).padStart(2, "0");
87476
+ }
87477
+ return hex;
87478
+ }
87479
+
87480
+ function hexToBytes(hex) {
87481
+ if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) {
87482
+ throw new Error("dhPageCrypto: not a 0x-hex string: " + String(hex));
87483
+ }
87484
+ var clean = hex.slice(2);
87485
+ if (clean.length % 2 !== 0) {
87486
+ throw new Error("dhPageCrypto: odd-length hex string: " + hex);
87487
+ }
87488
+ var out = new Uint8Array(clean.length / 2);
87489
+ for (var i = 0; i < out.length; i++) {
87490
+ out[i] = parseInt(clean.substr(i * 2, 2), 16);
87491
+ }
87492
+ return out;
87493
+ }
87494
+
87495
+ function keccak256HexOfBytes(hexStr) {
87496
+ return bytesToHex(keccak256Bytes(hexToBytes(hexStr)));
87497
+ }
87498
+
87499
+ function keccak256Utf8(str) {
87500
+ return bytesToHex(keccak256Bytes(new TextEncoder().encode(String(str))));
87501
+ }
87502
+
87503
+ function uint256ToBytes32(decStr) {
87504
+ if (typeof decStr !== "string" || !/^[0-9]+$/.test(decStr)) {
87505
+ throw new Error("dhPageCrypto: not a decimal uint256 string: " + String(decStr));
87506
+ }
87507
+ var n = BigInt(decStr);
87508
+ if (n > (2n ** 256n) - 1n) {
87509
+ throw new Error("dhPageCrypto: uint256 out of range: " + decStr);
87510
+ }
87511
+ var bytes = new Uint8Array(32);
87512
+ for (var i = 31; i >= 0; i--) {
87513
+ bytes[i] = Number(n & 0xffn);
87514
+ n >>= 8n;
87515
+ }
87516
+ return bytes;
87517
+ }
87518
+
87519
+ function requireBytes32(hex, fieldName) {
87520
+ var bytes = hexToBytes(hex);
87521
+ if (bytes.length !== 32) {
87522
+ throw new Error("dhPageCrypto: field \\"" + fieldName + "\\" must be exactly 32 bytes, got " + bytes.length);
87523
+ }
87524
+ return bytes;
87525
+ }
87526
+
87527
+ // Embedded verbatim from PERSONAL_SIGN_LAYOUTS (page-crypto.ts) \u2014 see the anti-drift note
87528
+ // in that file's header comment. Do not hand-edit; this is generated at module load.
87529
+ var PERSONAL_SIGN_LAYOUTS = ${JSON.stringify(PERSONAL_SIGN_LAYOUTS)};
87530
+
87531
+ function packAndHash(layout, fields) {
87532
+ var def = PERSONAL_SIGN_LAYOUTS[layout];
87533
+ if (!def) {
87534
+ throw new Error("dhPageCrypto: unknown layout \\"" + layout + "\\"");
87535
+ }
87536
+ var hashUtf8 = {};
87537
+ for (var h = 0; h < def.hashUtf8Fields.length; h++) {
87538
+ hashUtf8[def.hashUtf8Fields[h]] = true;
87539
+ }
87540
+ var parts = [];
87541
+ var totalLen = 0;
87542
+ for (var i = 0; i < def.fieldOrder.length; i++) {
87543
+ var name = def.fieldOrder[i];
87544
+ var type = def.types[i];
87545
+ var raw = fields ? fields[name] : undefined;
87546
+ if (raw === undefined || raw === null) {
87547
+ throw new Error("dhPageCrypto: layout \\"" + layout + "\\" missing field \\"" + name + "\\"");
87548
+ }
87549
+ var valueHex = hashUtf8[name] ? keccak256Utf8(String(raw)) : raw;
87550
+ var part;
87551
+ if (type === "bytes32") {
87552
+ part = requireBytes32(valueHex, name);
87553
+ } else if (type === "uint256") {
87554
+ part = uint256ToBytes32(valueHex);
87555
+ } else {
87556
+ throw new Error("dhPageCrypto: unsupported packed type \\"" + type + "\\" in layout \\"" + layout + "\\"");
87557
+ }
87558
+ parts.push(part);
87559
+ totalLen += part.length;
87560
+ }
87561
+ var packed = new Uint8Array(totalLen);
87562
+ var offset = 0;
87563
+ for (var p = 0; p < parts.length; p++) {
87564
+ packed.set(parts[p], offset);
87565
+ offset += parts[p].length;
87566
+ }
87567
+ return keccak256HexOfBytes(bytesToHex(packed));
87568
+ }
87569
+
87570
+ globalThis.dhPageCrypto = {
87571
+ keccak256HexOfBytes: keccak256HexOfBytes,
87572
+ keccak256Utf8: keccak256Utf8,
87573
+ packAndHash: packAndHash
87574
+ };
87575
+ })();
87576
+ `;
87184
87577
 
87185
87578
  // src/boundary/upstream/real/validation-context.ts
87579
+ init_tx_validator();
87186
87580
  function buildValidationContext(network, chainId) {
87187
87581
  const sdkKey = chainId === 31337 ? "localhost" : chainId === 11155111 ? "sepolia" : network.toLowerCase();
87188
87582
  const contracts = getContractsByNetwork(sdkKey);
@@ -87202,14 +87596,10 @@ function psmMainnetWriteRefusal(network, chainId) {
87202
87596
  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
87597
  };
87204
87598
  }
87205
- var QUANTUM_SECONDS3 = 60;
87206
87599
  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
- }
87600
+ var OP_LAYOUT = "dh-op-envelope-v1";
87211
87601
  function randomNonceHex() {
87212
- return "0x" + Buffer.from(import_ethers32.ethers.randomBytes(16)).toString("hex");
87602
+ return "0x" + Buffer.from(import_ethers33.ethers.randomBytes(16)).toString("hex");
87213
87603
  }
87214
87604
  async function postJson(url2, body, headers) {
87215
87605
  const res = await fetch(url2, {
@@ -87249,15 +87639,55 @@ function buildWriteOps(deps) {
87249
87639
  })
87250
87640
  );
87251
87641
  const failed = (op, e) => upFail({ kind: "unavailable", source: SOURCE5, message: `${op} failed to reach lit-ops`, raw: String(e) });
87642
+ 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) });
87643
+ function opAuthSpec(p) {
87644
+ return {
87645
+ action: p.action,
87646
+ layout: OP_LAYOUT,
87647
+ stamp: (quantumTs) => {
87648
+ const fields = {
87649
+ positionId: p.positionId,
87650
+ timestamp: String(quantumTs),
87651
+ chainId: String(chainId),
87652
+ amount: p.amount.toString(),
87653
+ action: p.action
87654
+ };
87655
+ return { fields, hashHex: hashForLayout(OP_LAYOUT, fields), card: p.card(fields) };
87656
+ }
87657
+ };
87658
+ }
87659
+ function toCardPayload(tx2) {
87660
+ return {
87661
+ to: String(tx2["to"] ?? ""),
87662
+ data: String(tx2["data"] ?? "0x"),
87663
+ value: tx2["value"] != null ? import_ethers33.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
87664
+ chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
87665
+ };
87666
+ }
87252
87667
  async function executeAndBroadcast(p) {
87253
- const userSignature = await dhSigner.signAuthMessage(p.messageHash);
87668
+ let authRes;
87669
+ try {
87670
+ authRes = await dhSigner.signAuthorization(p.spec);
87671
+ } catch (e) {
87672
+ return submitFailure(`${p.op} authorization`, e);
87673
+ }
87674
+ const digest = p.spec.stamp(authRes.quantumTs).hashHex;
87254
87675
  const borrowerAddress = await dhSigner.getBorrowerAddress();
87255
- const headers = await session.authHeader();
87676
+ let headers;
87677
+ try {
87678
+ headers = await session.authHeader();
87679
+ } catch (e) {
87680
+ return upFail({
87681
+ kind: "unavailable",
87682
+ source: SOURCE5,
87683
+ message: `${p.op} could not establish the lit-ops login session (broker unreachable, or throttling logins): ${e instanceof Error ? e.message : String(e)}`
87684
+ });
87685
+ }
87256
87686
  let execJson;
87257
87687
  try {
87258
87688
  execJson = await postJson(
87259
87689
  `${config.serviceEndpoint}/api/lit/${p.op}/execute`,
87260
- { authMessage: p.authMessage, userSignature, borrowerAddress },
87690
+ { authMessage: p.authMessage(authRes.quantumTs), userSignature: authRes.signature, borrowerAddress },
87261
87691
  headers
87262
87692
  );
87263
87693
  } catch (e) {
@@ -87281,12 +87711,13 @@ function buildWriteOps(deps) {
87281
87711
  } catch (e) {
87282
87712
  return upFail({ kind: "rejected", source: SOURCE5, message: `approve tx failed the M-9 whitelist: ${e.message}` });
87283
87713
  }
87284
- const signedApprove = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedApproveTx));
87285
87714
  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"]);
87715
+ await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedApproveTx), {
87716
+ action: `${p.spec.action} (UCD approve)`,
87717
+ card: cardForTx(toCardPayload(unsignedApproveTx))
87718
+ });
87288
87719
  } catch (e) {
87289
- return failed(`${p.op} (UCD approve broadcast)`, e);
87720
+ return submitFailure(`${p.op} (UCD approve)`, e);
87290
87721
  }
87291
87722
  }
87292
87723
  }
@@ -87299,23 +87730,18 @@ function buildWriteOps(deps) {
87299
87730
  } catch (e) {
87300
87731
  return upFail({ kind: "rejected", source: SOURCE5, message: `unsigned tx failed the M-9 whitelist: ${e.message}` });
87301
87732
  }
87302
- const signedTx = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedTx));
87303
- let broadcastJson;
87733
+ let submitted;
87304
87734
  try {
87305
87735
  const meta = p.broadcastMeta(data);
87306
- broadcastJson = await postJson(
87307
- `${config.serviceEndpoint}/api/lit/broadcast`,
87308
- { signedTx, ...meta ? { [p.broadcastMetaKey]: meta } : {} },
87309
- headers
87310
- );
87736
+ submitted = await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedTx), {
87737
+ action: p.spec.action,
87738
+ card: cardForTx(toCardPayload(unsignedTx)),
87739
+ ...meta ? { broadcast: { key: p.broadcastMetaKey, meta } } : {}
87740
+ });
87311
87741
  } catch (e) {
87312
- return failed(`${p.op} broadcast`, e);
87742
+ return submitFailure(`${p.op} broadcast`, e);
87313
87743
  }
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() });
87744
+ return upOk({ data, txHash: submitted.txHash, digest }, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87319
87745
  }
87320
87746
  return {
87321
87747
  createPosition: async (p) => {
@@ -87357,15 +87783,21 @@ function buildWriteOps(deps) {
87357
87783
  mint: async (p) => {
87358
87784
  const amountWei = BigInt(p.amountUcdWei);
87359
87785
  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
87786
  const r = await executeAndBroadcast({
87366
87787
  op: "mint",
87367
- authMessage: { positionId: p.positionId, timestamp, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87368
- messageHash,
87788
+ spec: opAuthSpec({
87789
+ action,
87790
+ positionId: p.positionId,
87791
+ amount: amountWei,
87792
+ card: (f) => [
87793
+ "Authorize: mint UCD against your BTC collateral (this signature authorizes the operation; the transaction that executes it is approved separately)",
87794
+ `Position: ${p.positionId}`,
87795
+ `Amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
87796
+ `Chain id: ${chainId}`,
87797
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87798
+ ]
87799
+ }),
87800
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87369
87801
  validation: (data) => {
87370
87802
  const mintFee2 = data["mintFee"];
87371
87803
  if (typeof mintFee2 !== "string" || mintFee2.length === 0) {
@@ -87388,7 +87820,7 @@ function buildWriteOps(deps) {
87388
87820
  mintedUcdWei: minted,
87389
87821
  feeUcdWei: mintFee,
87390
87822
  echoedAmountUcdWei: minted,
87391
- authorization: auth(action, `mint ${import_ethers32.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87823
+ authorization: auth(action, `mint ${import_ethers33.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87392
87824
  },
87393
87825
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87394
87826
  );
@@ -87396,15 +87828,21 @@ function buildWriteOps(deps) {
87396
87828
  repay: async (p) => {
87397
87829
  const amountWei = BigInt(p.amountUcdWei);
87398
87830
  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
87831
  const r = await executeAndBroadcast({
87405
87832
  op: "repay",
87406
- authMessage: { positionId: p.positionId, timestamp, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87407
- messageHash,
87833
+ spec: opAuthSpec({
87834
+ action,
87835
+ positionId: p.positionId,
87836
+ amount: amountWei,
87837
+ card: (f) => [
87838
+ "Authorize: pay down UCD debt (this signature authorizes the operation; the transaction that executes it is approved separately)",
87839
+ `Position: ${p.positionId}`,
87840
+ `Payment amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
87841
+ `Chain id: ${chainId}`,
87842
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87843
+ ]
87844
+ }),
87845
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87408
87846
  validation: () => ({ kind: "repay", positionId: p.positionId, amountWei: amountWei.toString() }),
87409
87847
  approveValidation: () => {
87410
87848
  const vctx = buildValidationContext(config.network, chainId);
@@ -87423,22 +87861,28 @@ function buildWriteOps(deps) {
87423
87861
  txRef: { kind: "eth-tx", id: r.value.txHash },
87424
87862
  paidUcdWei: paid,
87425
87863
  echoedAmountUcdWei: paid,
87426
- authorization: auth(action, `repay ${import_ethers32.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
87864
+ authorization: auth(action, `repay ${import_ethers33.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
87427
87865
  },
87428
87866
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87429
87867
  );
87430
87868
  },
87431
87869
  extend: async (p) => {
87432
87870
  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
87871
  const r = await executeAndBroadcast({
87439
87872
  op: "renew",
87440
- authMessage: { positionId: p.positionId, timestamp, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() },
87441
- messageHash,
87873
+ spec: opAuthSpec({
87874
+ action,
87875
+ positionId: p.positionId,
87876
+ amount: BigInt(p.selectedTerm),
87877
+ card: (f) => [
87878
+ "Authorize: extend (renew) the position term (this signature authorizes the operation; the transaction that executes it is approved separately)",
87879
+ `Position: ${p.positionId}`,
87880
+ `New term: ${p.selectedTerm} months`,
87881
+ `Chain id: ${chainId}`,
87882
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87883
+ ]
87884
+ }),
87885
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() }),
87442
87886
  validation: () => ({ kind: "extend", positionId: p.positionId, selectedTerm: p.selectedTerm }),
87443
87887
  broadcastMetaKey: "renewMeta",
87444
87888
  broadcastMeta: () => ({ positionId: p.positionId, borrowerAddress: p.borrower, selectedTerm: p.selectedTerm, chainId })
@@ -87514,20 +87958,18 @@ function buildWriteOps(deps) {
87514
87958
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
87515
87959
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
87516
87960
  const tokenSymbol = isSwap ? "USDC" : "UCD";
87517
- const headers = await session.authHeader();
87518
87961
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
87519
87962
  if (!quoteR.ok) return upFail(quoteR.failure);
87520
- const broadcast = async (leg, tx2) => {
87963
+ const broadcast = async (leg, action, tx2) => {
87521
87964
  try {
87522
87965
  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() });
87966
+ const submitted = await dhSigner.submitValidatedTx(populated, {
87967
+ action,
87968
+ card: cardForTx(toCardPayload(tx2))
87969
+ });
87970
+ return upOk(submitted.txHash, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87529
87971
  } catch (e) {
87530
- return failed(leg, e);
87972
+ return submitFailure(leg, e);
87531
87973
  }
87532
87974
  };
87533
87975
  const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
@@ -87541,7 +87983,7 @@ function buildWriteOps(deps) {
87541
87983
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
87542
87984
  }
87543
87985
  const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
87544
- const approveHashR = await broadcast("psmSwap (approve)", approveTx);
87986
+ const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
87545
87987
  if (!approveHashR.ok) return approveHashR;
87546
87988
  const approveHash = approveHashR.value;
87547
87989
  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 +87998,7 @@ function buildWriteOps(deps) {
87556
87998
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
87557
87999
  }
87558
88000
  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);
88001
+ const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
87560
88002
  if (!execHashR.ok) {
87561
88003
  const f = execHashR.failure;
87562
88004
  return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
@@ -87640,33 +88082,296 @@ function buildWriteOps(deps) {
87640
88082
  }
87641
88083
 
87642
88084
  // src/signer/eoa-dh.ts
87643
- var import_ethers33 = require("ethers");
88085
+ var import_ethers34 = require("ethers");
87644
88086
  var EoaDHSigner = class {
87645
- kind = "eoa-env";
87646
- wallet;
87647
- constructor(wallet) {
88087
+ constructor(wallet, broadcast, clock = Date.now) {
87648
88088
  this.wallet = wallet;
88089
+ this.broadcast = broadcast;
88090
+ this.clock = clock;
87649
88091
  }
88092
+ kind = "eoa-env";
87650
88093
  async getBorrowerAddress() {
87651
88094
  return this.wallet.getAddress();
87652
88095
  }
87653
88096
  async getAuthSignerAddress() {
87654
88097
  return this.wallet.getAddress();
87655
88098
  }
87656
- async signAuthMessage(messageHash) {
87657
- return this.wallet.signMessage(import_ethers33.ethers.getBytes(messageHash));
88099
+ async signAuthorization(spec) {
88100
+ const quantumTs = nextQuantumTimestamp(this.clock());
88101
+ const { fields, hashHex } = spec.stamp(quantumTs);
88102
+ const signature = await this.wallet.signMessage(import_ethers34.ethers.getBytes(hashHex));
88103
+ return { signature, quantumTs, fields };
87658
88104
  }
87659
88105
  async wrapInnerTx(innerTx) {
87660
88106
  return innerTx;
87661
88107
  }
87662
- async signTransaction(outerTx) {
87663
- return this.wallet.signTransaction(outerTx);
88108
+ async submitValidatedTx(outerTx, ctx) {
88109
+ const signed = await this.wallet.signTransaction(outerTx);
88110
+ const txHash = await this.broadcast(signed, ctx.broadcast ? { [ctx.broadcast.key]: ctx.broadcast.meta } : void 0);
88111
+ return { txHash, signer: await this.wallet.getAddress(), scheme: "eip712-eoa" };
87664
88112
  }
87665
88113
  getEthersSigner() {
87666
88114
  return this.wallet;
87667
88115
  }
87668
88116
  };
87669
88117
 
88118
+ // src/signer/external-eoa.ts
88119
+ var import_node_crypto5 = require("crypto");
88120
+ var import_ethers36 = require("ethers");
88121
+
88122
+ // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
88123
+ var import_ethers35 = require("ethers");
88124
+ function eq2(a, b) {
88125
+ return a.toLowerCase() === b.toLowerCase();
88126
+ }
88127
+ function compareLandedTx(landed, approved, borrower) {
88128
+ 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;
88129
+ if (mismatch) {
88130
+ return {
88131
+ status: "mismatch",
88132
+ hash: landed.hash,
88133
+ 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`
88134
+ };
88135
+ }
88136
+ if (!eq2(landed.from, borrower)) {
88137
+ return {
88138
+ status: "mismatch",
88139
+ hash: landed.hash,
88140
+ reason: `tx ${landed.hash} was signed by ${landed.from}, not the borrower ${borrower} \u2014 already on-chain; do NOT retry, re-read state`
88141
+ };
88142
+ }
88143
+ return { status: "verified", from: landed.from, hash: landed.hash };
88144
+ }
88145
+ function verifyRawSignedTx(rawSignedTx, approved, borrower) {
88146
+ const parsed = import_ethers35.ethers.Transaction.from(rawSignedTx);
88147
+ if (!parsed.from || !parsed.to || !parsed.hash) {
88148
+ return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
88149
+ }
88150
+ return compareLandedTx(
88151
+ { from: parsed.from, to: parsed.to, data: parsed.data, value: parsed.value, chainId: parsed.chainId, hash: parsed.hash },
88152
+ approved,
88153
+ borrower
88154
+ );
88155
+ }
88156
+ async function verifyBroadcastTxByHash(provider, hash, approved, borrower, budget) {
88157
+ let tx2 = null;
88158
+ for (let i = 0; i < budget.attempts && tx2 === null; i++) {
88159
+ tx2 = await provider.getTransaction(hash);
88160
+ if (tx2 === null && i < budget.attempts - 1) await new Promise((r) => setTimeout(r, budget.delayMs));
88161
+ }
88162
+ if (tx2 === null || !tx2.from || !tx2.to) {
88163
+ return {
88164
+ status: "unknown",
88165
+ hash,
88166
+ 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).`
88167
+ };
88168
+ }
88169
+ return compareLandedTx(
88170
+ { from: tx2.from, to: tx2.to, data: tx2.data, value: tx2.value, chainId: BigInt(tx2.chainId), hash: tx2.hash },
88171
+ approved,
88172
+ borrower
88173
+ );
88174
+ }
88175
+
88176
+ // src/signer/external-eoa.ts
88177
+ var DEFAULT_BUDGET = { attempts: 30, delayMs: 3e3 };
88178
+ var ExternalEoaDHSigner = class {
88179
+ constructor(deps) {
88180
+ this.deps = deps;
88181
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88182
+ }
88183
+ kind = "external-eoa";
88184
+ budget;
88185
+ async getBorrowerAddress() {
88186
+ return this.deps.borrower;
88187
+ }
88188
+ async getAuthSignerAddress() {
88189
+ return this.deps.borrower;
88190
+ }
88191
+ async signAuthorization(spec) {
88192
+ const initialTs = nextQuantumTimestamp(Date.now());
88193
+ const initial = spec.stamp(initialTs);
88194
+ let used = { quantumTs: initialTs, fields: initial.fields };
88195
+ const outcome = await this.deps.bridge.requestSignature(
88196
+ {
88197
+ id: (0, import_node_crypto5.randomUUID)(),
88198
+ kind: "personal-sign",
88199
+ action: spec.action,
88200
+ card: initial.card,
88201
+ expectedSigner: this.deps.borrower,
88202
+ chainId: this.deps.chainId,
88203
+ personalSign: { layout: spec.layout, fields: initial.fields, hashHex: initial.hashHex }
88204
+ },
88205
+ {
88206
+ finalize: async () => {
88207
+ const ts = nextQuantumTimestamp(Date.now());
88208
+ const s = spec.stamp(ts);
88209
+ used = { quantumTs: ts, fields: s.fields };
88210
+ return { personalSign: { layout: spec.layout, fields: s.fields, hashHex: s.hashHex }, card: s.card };
88211
+ }
88212
+ }
88213
+ );
88214
+ if (outcome.status !== "approved" || !outcome.signature) {
88215
+ throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
88216
+ }
88217
+ const finalHash = spec.stamp(used.quantumTs).hashHex;
88218
+ const recovered = import_ethers36.ethers.verifyMessage(import_ethers36.ethers.getBytes(finalHash), outcome.signature);
88219
+ if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
88220
+ throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
88221
+ }
88222
+ return { signature: outcome.signature, quantumTs: used.quantumTs, fields: used.fields };
88223
+ }
88224
+ async wrapInnerTx(innerTx) {
88225
+ return innerTx;
88226
+ }
88227
+ async submitValidatedTx(outerTx, ctx) {
88228
+ const approved = toApprovedTx(outerTx, this.deps.chainId);
88229
+ const outcome = await this.deps.bridge.requestSignature({
88230
+ id: (0, import_node_crypto5.randomUUID)(),
88231
+ kind: "transaction",
88232
+ action: ctx.action,
88233
+ card: ctx.card,
88234
+ expectedSigner: this.deps.borrower,
88235
+ chainId: this.deps.chainId,
88236
+ tx: approved
88237
+ });
88238
+ if (outcome.status !== "approved") {
88239
+ throw new OperationDeclined(`the ${ctx.action} transaction was not approved: ${describeOutcome(outcome)}`);
88240
+ }
88241
+ const verdict = await this.resolveLanded(outcome, approved);
88242
+ if (verdict.status !== "verified") {
88243
+ throw new Error(verdict.reason);
88244
+ }
88245
+ return { txHash: verdict.hash, signer: verdict.from, scheme: "external-wallet" };
88246
+ }
88247
+ async resolveLanded(outcome, approved) {
88248
+ if (outcome.rawSignedTx) {
88249
+ const verdict = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88250
+ if (verdict.status === "verified") await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88251
+ return verdict;
88252
+ }
88253
+ if (!outcome.txHash) {
88254
+ return { status: "unknown", hash: "0x", reason: "the wallet approved but returned neither a tx hash nor a signed transaction" };
88255
+ }
88256
+ return verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88257
+ }
88258
+ getEthersSigner() {
88259
+ return new BridgeEthersSigner(this.deps);
88260
+ }
88261
+ };
88262
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers36.ethers.AbstractSigner {
88263
+ constructor(deps) {
88264
+ super(deps.provider);
88265
+ this.deps = deps;
88266
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88267
+ }
88268
+ budget;
88269
+ async getAddress() {
88270
+ return this.deps.borrower;
88271
+ }
88272
+ async signMessage(_message) {
88273
+ throw new Error(
88274
+ "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."
88275
+ );
88276
+ }
88277
+ async signTypedData(domain, types, value) {
88278
+ const typedData = {
88279
+ domain,
88280
+ types,
88281
+ primaryType: Object.keys(types)[0] ?? "EIP712",
88282
+ message: value
88283
+ };
88284
+ const outcome = await this.deps.bridge.requestSignature({
88285
+ id: (0, import_node_crypto5.randomUUID)(),
88286
+ kind: "typed-data",
88287
+ action: "login",
88288
+ card: cardForTypedData("login", typedData),
88289
+ expectedSigner: this.deps.borrower,
88290
+ chainId: this.deps.chainId,
88291
+ typedData
88292
+ });
88293
+ if (outcome.status !== "approved" || !outcome.signature) {
88294
+ throw new OperationDeclined(`the login signature was not approved: ${describeOutcome(outcome)}`);
88295
+ }
88296
+ return outcome.signature;
88297
+ }
88298
+ async sendTransaction(tx2) {
88299
+ if (!tx2.to || typeof tx2.data !== "string") {
88300
+ throw new Error("BridgeEthersSigner.sendTransaction: tx.to and hex tx.data are required");
88301
+ }
88302
+ const approved = {
88303
+ to: tx2.to,
88304
+ data: tx2.data,
88305
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88306
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
88307
+ };
88308
+ const card = cardForTx(approved);
88309
+ const outcome = await this.deps.bridge.requestSignature({
88310
+ id: (0, import_node_crypto5.randomUUID)(),
88311
+ kind: "transaction",
88312
+ action: describeFn(approved.data),
88313
+ card,
88314
+ expectedSigner: this.deps.borrower,
88315
+ chainId: approved.chainId,
88316
+ tx: { ...approved, ...tx2.gasLimit != null ? { gas: import_ethers36.ethers.toBeHex(BigInt(String(tx2.gasLimit))) } : {}, txType: 2 }
88317
+ });
88318
+ if (outcome.status !== "approved") {
88319
+ throw new OperationDeclined(`the transaction was not approved: ${describeOutcome(outcome)}`);
88320
+ }
88321
+ let hash;
88322
+ if (outcome.rawSignedTx) {
88323
+ const v = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88324
+ if (v.status !== "verified") throw new Error(v.reason);
88325
+ await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88326
+ hash = v.hash;
88327
+ } else if (outcome.txHash) {
88328
+ const v = await verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88329
+ if (v.status !== "verified") throw new Error(v.reason);
88330
+ hash = v.hash;
88331
+ } else {
88332
+ throw new Error("the wallet approved but returned neither a tx hash nor a signed transaction");
88333
+ }
88334
+ const resp = await this.provider.getTransaction(hash);
88335
+ if (!resp) throw new Error(`tx ${hash} verified but the provider no longer returns it`);
88336
+ return resp;
88337
+ }
88338
+ async signTransaction(_tx) {
88339
+ throw new Error("BridgeEthersSigner: browser wallets cannot raw-sign a transaction \u2014 use sendTransaction (self-broadcast).");
88340
+ }
88341
+ connect(provider) {
88342
+ return new _BridgeEthersSigner({ ...this.deps, provider });
88343
+ }
88344
+ };
88345
+ function toApprovedTx(tx2, fallbackChainId) {
88346
+ if (!tx2.to || typeof tx2.data !== "string") throw new Error("submitValidatedTx: tx.to and hex tx.data are required");
88347
+ return {
88348
+ to: tx2.to,
88349
+ data: tx2.data,
88350
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88351
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
88352
+ };
88353
+ }
88354
+ function describeFn(data) {
88355
+ try {
88356
+ const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
88357
+ return decodeSignable2(data).name;
88358
+ } catch {
88359
+ return "operation";
88360
+ }
88361
+ }
88362
+ function describeOutcome(outcome) {
88363
+ switch (outcome.status) {
88364
+ case "rejected":
88365
+ return outcome.reason;
88366
+ case "expired":
88367
+ return "the approval request expired without a wallet decision \u2014 reopen the approval page and retry";
88368
+ case "invalidated":
88369
+ return outcome.reason;
88370
+ default:
88371
+ return outcome.status;
88372
+ }
88373
+ }
88374
+
87670
88375
  // src/boundary/upstream/real/plugin.ts
87671
88376
  var STATUS_BY_INDEX = [
87672
88377
  "PENDING_DEPOSIT",
@@ -87684,10 +88389,11 @@ var POSITION_DETAILS_ABI = [
87684
88389
  var PAUSABLE_ABI = ["function paused() view returns (bool)"];
87685
88390
  var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
87686
88391
  var RealUpstreamPlugin = class {
87687
- constructor(config, wallet) {
88392
+ constructor(config, wallet, runtime) {
87688
88393
  this.config = config;
87689
- this.provider = new import_ethers34.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
88394
+ this.provider = new import_ethers37.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
87690
88395
  this.wallet = wallet ?? null;
88396
+ this.runtime = runtime ?? null;
87691
88397
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
87692
88398
  this.contracts = getContractsByNetwork(config.network) ?? {};
87693
88399
  this.indexer = {
@@ -87811,7 +88517,7 @@ var RealUpstreamPlugin = class {
87811
88517
  })
87812
88518
  )
87813
88519
  };
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.`;
88520
+ 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
88521
  const readOnly = (op) => Promise.resolve(
87816
88522
  upFail({
87817
88523
  kind: "unavailable",
@@ -87820,16 +88526,10 @@ var RealUpstreamPlugin = class {
87820
88526
  })
87821
88527
  );
87822
88528
  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
- });
88529
+ if (writesArmed && this.runtime) {
88530
+ this.ops = this.resolvingOps();
88531
+ } else if (writesArmed && this.wallet && this.session) {
88532
+ this.ops = this.keystoreGateway(this.wallet.connect(this.provider), this.session);
87833
88533
  } else {
87834
88534
  this.ops = {
87835
88535
  createPosition: () => readOnly("createPosition"),
@@ -87862,10 +88562,17 @@ var RealUpstreamPlugin = class {
87862
88562
  provider;
87863
88563
  session;
87864
88564
  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).
88565
+ runtime;
88566
+ /** Per-identity caches (plan 10 A3): keys are `<mode>:<address lowercased>` — a mode
88567
+ * switch resolves a different key, so stale constructions are never reused. */
88568
+ sdkCache = /* @__PURE__ */ new Map();
88569
+ sdkInFlight = /* @__PURE__ */ new Map();
88570
+ sessionCache = /* @__PURE__ */ new Map();
88571
+ opsGatewayCache = /* @__PURE__ */ new Map();
88572
+ externalSigners = /* @__PURE__ */ new Map();
88573
+ /** Pre-warm the KEYSTORE write SDK at boot (0.1.1 parity: the common keystore boot pays
88574
+ * the create cost up front, not on the first write). External-mode SDKs build lazily on
88575
+ * the first write after the mode binds (plan 10 A3 latency honesty).
87869
88576
  *
87870
88577
  * INDEPENDENT of any graph/indexer discovery (plan 08 A4, M8B-4): indexer reads ride
87871
88578
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
@@ -87875,29 +88582,277 @@ var RealUpstreamPlugin = class {
87875
88582
  * (createPosition/withdraw report the uninitialized SDK). */
87876
88583
  async initWriteSdk() {
87877
88584
  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 } } : {}
88585
+ if (!writesArmed) return;
88586
+ if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
88587
+ const wallet = this.wallet ?? this.runtime?.keystore.signer() ?? null;
88588
+ if (!wallet) return;
88589
+ await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
88590
+ }
88591
+ /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
88592
+ * the write gateways report the uninitialized SDK honestly, never fake readiness. */
88593
+ async ensureSdk(key, signer) {
88594
+ if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
88595
+ const inFlight = this.sdkInFlight.get(key);
88596
+ if (inFlight) return inFlight;
88597
+ const build = (async () => {
88598
+ try {
88599
+ const v = this.config.validatorVersion;
88600
+ const builtWrite = await DiamondHandsSDK.create({
88601
+ mode: "service",
88602
+ serviceEndpoint: this.config.serviceEndpoint,
88603
+ contractSigner: signer,
88604
+ authSigner: signer,
88605
+ provider: this.provider,
88606
+ ethRpcUrl: this.config.rpcUrl,
88607
+ chainId: this.config.chainId,
88608
+ litNetwork: this.config.litNetwork,
88609
+ // No `subgraphs`: in service mode the SDK queries THROUGH the lit-ops proxy and
88610
+ // ignores any provided URL — the old `/v1/init`-discovered value was dead weight
88611
+ // nesting writes under indexer discovery (the M8B-4 coupling this removes).
88612
+ ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
88613
+ });
88614
+ return isSuccess(builtWrite) ? builtWrite.value : null;
88615
+ } catch {
88616
+ return null;
88617
+ }
88618
+ })();
88619
+ this.sdkInFlight.set(key, build);
88620
+ const built = await build;
88621
+ this.sdkInFlight.delete(key);
88622
+ this.sdkCache.set(key, built);
88623
+ return built;
88624
+ }
88625
+ wallet;
88626
+ // ---- per-call signer resolution (plan 10 A3) ----
88627
+ /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
88628
+ * carries the service endpoint and the authenticated session header. It throws
88629
+ * `OperationDeclined` when lit-ops REFUSES the signed tx (a decision), a plain Error on
88630
+ * transport/shape trouble; write-ops maps the two to distinct failure kinds. */
88631
+ litOpsBroadcast(session) {
88632
+ return async (signedTx, extra) => {
88633
+ const res = await fetch(`${this.config.serviceEndpoint}/api/lit/broadcast`, {
88634
+ method: "POST",
88635
+ headers: { "Content-Type": "application/json", ...await session.authHeader() },
88636
+ body: JSON.stringify({ signedTx, ...extra ?? {} })
87895
88637
  });
87896
- if (isSuccess(builtWrite)) this.writeSdk = builtWrite.value;
87897
- } catch {
88638
+ const text = await res.text();
88639
+ let json;
88640
+ try {
88641
+ json = JSON.parse(text);
88642
+ } catch {
88643
+ throw new Error(`lit-ops broadcast returned non-JSON (HTTP ${res.status}): ${text.slice(0, 200)}`);
88644
+ }
88645
+ if (!res.ok && json["error"] === void 0) {
88646
+ throw new Error(`lit-ops broadcast HTTP ${res.status}: ${text.slice(0, 200)}`);
88647
+ }
88648
+ if (json["success"] !== true) {
88649
+ const reason = json["error"];
88650
+ throw new OperationDeclined(`lit-ops declined the signed transaction: ${typeof reason === "string" ? reason : "no reason given"}`);
88651
+ }
88652
+ const txHash = String((json["data"] ?? {})["txHash"] ?? "");
88653
+ if (!txHash) throw new Error("lit-ops broadcast returned no txHash");
88654
+ return txHash;
88655
+ };
88656
+ }
88657
+ keystoreGateway(wallet, session) {
88658
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88659
+ return buildWriteOps({
88660
+ config: this.config,
88661
+ chainId: this.config.chainId,
88662
+ dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
88663
+ session,
88664
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88665
+ readDetails: (id) => this.readPositionDetails(id),
88666
+ psm: () => this.psmCalls()
88667
+ });
88668
+ }
88669
+ sessionFor(key, signer) {
88670
+ let s = this.sessionCache.get(key);
88671
+ if (!s) {
88672
+ s = new LitOpsSession(signer, this.config.serviceEndpoint, this.config.chainId);
88673
+ this.sessionCache.set(key, s);
88674
+ }
88675
+ return s;
88676
+ }
88677
+ /** Verify-by-hash budget for external self-broadcast (A0.3): mainnet Chipotle
88678
+ * roundtrips exceed 60s, so the write-path budget is 300s there (F-MAIN-4). */
88679
+ verifyBudget() {
88680
+ return this.config.network === "mainnet" ? { attempts: 100, delayMs: 3e3 } : void 0;
88681
+ }
88682
+ /** The armed-boot ops surface: every method resolves the CURRENT signer mode first, so
88683
+ * the refusal-truth matrix is decided at call time, never frozen at boot. */
88684
+ resolvingOps() {
88685
+ const call = (k) => (async (p) => {
88686
+ const r = await this.resolveOpsGateway();
88687
+ if (!r.ok) return upFail(r.failure);
88688
+ return r.gateway[k](p);
88689
+ });
88690
+ return {
88691
+ createPosition: call("createPosition"),
88692
+ mint: call("mint"),
88693
+ repay: call("repay"),
88694
+ extend: call("extend"),
88695
+ withdraw: call("withdraw"),
88696
+ allowlistWithdrawalAddress: call("allowlistWithdrawalAddress"),
88697
+ psmSwap: call("psmSwap"),
88698
+ delegationSetup: call("delegationSetup"),
88699
+ delegationGrant: call("delegationGrant"),
88700
+ recoverStaleSpend: call("recoverStaleSpend")
88701
+ };
88702
+ }
88703
+ async resolveOpsGateway() {
88704
+ const rt = this.runtime;
88705
+ const mode = rt.manager.mode();
88706
+ if (mode === "none") {
88707
+ return {
88708
+ ok: false,
88709
+ failure: {
88710
+ kind: "signer-missing",
88711
+ source: "real-ops",
88712
+ 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."
88713
+ }
88714
+ };
87898
88715
  }
88716
+ if (mode === "keystore") {
88717
+ const ready = await rt.keystore.ensureReady();
88718
+ const wallet = rt.keystore.signer();
88719
+ if (!ready.ok || !wallet) {
88720
+ return {
88721
+ ok: false,
88722
+ failure: {
88723
+ kind: "signer-missing",
88724
+ source: "real-ops",
88725
+ message: `the keystore signer is not ready (SIGNER_UNAVAILABLE): ${ready.ok ? "no keystore material" : ready.reason}`
88726
+ }
88727
+ };
88728
+ }
88729
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88730
+ let gateway = this.opsGatewayCache.get(key);
88731
+ if (!gateway) {
88732
+ const connected = wallet.connect(this.provider);
88733
+ gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
88734
+ this.opsGatewayCache.set(key, gateway);
88735
+ }
88736
+ await this.ensureSdk(key, wallet.connect(this.provider));
88737
+ return { ok: true, gateway };
88738
+ }
88739
+ if (mode === "external") {
88740
+ const borrower = await rt.manager.resolveBorrowerForWrite();
88741
+ if (!borrower) {
88742
+ return {
88743
+ ok: false,
88744
+ failure: {
88745
+ kind: "signer-missing",
88746
+ source: "real-ops",
88747
+ 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."
88748
+ }
88749
+ };
88750
+ }
88751
+ const key = `external:${borrower.toLowerCase()}`;
88752
+ let gateway = this.opsGatewayCache.get(key);
88753
+ if (!gateway) {
88754
+ const budget = this.verifyBudget();
88755
+ const deps = {
88756
+ bridge: rt.bridge,
88757
+ provider: this.provider,
88758
+ chainId: this.config.chainId,
88759
+ borrower,
88760
+ ...budget ? { verifyBudget: budget } : {}
88761
+ };
88762
+ const bridgeSigner = new BridgeEthersSigner(deps);
88763
+ this.externalSigners.set(key, bridgeSigner);
88764
+ const session = this.sessionFor(key, {
88765
+ address: borrower,
88766
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88767
+ });
88768
+ gateway = buildWriteOps({
88769
+ config: this.config,
88770
+ chainId: this.config.chainId,
88771
+ dhSigner: new ExternalEoaDHSigner(deps),
88772
+ session,
88773
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88774
+ readDetails: (id) => this.readPositionDetails(id),
88775
+ psm: () => this.psmCalls()
88776
+ });
88777
+ this.opsGatewayCache.set(key, gateway);
88778
+ }
88779
+ await this.ensureSdk(key, this.externalSigners.get(key));
88780
+ return { ok: true, gateway };
88781
+ }
88782
+ return {
88783
+ ok: false,
88784
+ failure: {
88785
+ kind: "signer-missing",
88786
+ source: "real-ops",
88787
+ message: `signer mode '${mode}' is not available on the real adapter \u2014 use 'external' or 'keystore' (signer_setup).`
88788
+ }
88789
+ };
88790
+ }
88791
+ /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
88792
+ * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
88793
+ * the first verified ceremony fixes the identity. */
88794
+ async connectExternal() {
88795
+ if (!this.runtime) return { ok: false, reason: "this construction has no signer runtime" };
88796
+ const { manager } = this.runtime;
88797
+ if (manager.mode() !== "external") {
88798
+ return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
88799
+ }
88800
+ const borrower = manager.borrowerForWrite();
88801
+ if (!borrower) {
88802
+ return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
88803
+ }
88804
+ const key = `external:${borrower.toLowerCase()}`;
88805
+ const budget = this.verifyBudget();
88806
+ const bridgeSigner = this.externalSigners.get(key) ?? new BridgeEthersSigner({
88807
+ bridge: this.runtime.bridge,
88808
+ provider: this.provider,
88809
+ chainId: this.config.chainId,
88810
+ borrower,
88811
+ ...budget ? { verifyBudget: budget } : {}
88812
+ });
88813
+ this.externalSigners.set(key, bridgeSigner);
88814
+ const session = this.sessionFor(key, {
88815
+ address: borrower,
88816
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88817
+ });
88818
+ await session.token();
88819
+ manager.bind(borrower);
88820
+ return { ok: true, address: borrower };
88821
+ }
88822
+ /** The authenticated-read session for the CURRENT mode. Reads NEVER summon the wallet
88823
+ * (A0.7): external mode without a live JWT refuses, naming the explicit connect action. */
88824
+ resolveReadSession() {
88825
+ if (!this.runtime) {
88826
+ 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." };
88827
+ }
88828
+ const mode = this.runtime.manager.mode();
88829
+ if (mode === "keystore") {
88830
+ const wallet = this.runtime.keystore.signer();
88831
+ if (!wallet) {
88832
+ 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." };
88833
+ }
88834
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88835
+ return { ok: true, session: this.sessionFor(key, wallet.connect(this.provider)) };
88836
+ }
88837
+ if (mode === "external") {
88838
+ const borrower = this.runtime.manager.borrowerForWrite();
88839
+ const session = borrower ? this.sessionCache.get(`external:${borrower.toLowerCase()}`) : void 0;
88840
+ if (session && session.hasValidToken()) return { ok: true, session };
88841
+ return {
88842
+ ok: false,
88843
+ 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."
88844
+ };
88845
+ }
88846
+ return {
88847
+ ok: false,
88848
+ 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."
88849
+ };
88850
+ }
88851
+ /** Capability truth for boundary://info (plan 10 B3): can authenticated reads run RIGHT
88852
+ * NOW without summoning a wallet? */
88853
+ authenticatedReadsAvailable() {
88854
+ return this.resolveReadSession().ok;
87899
88855
  }
87900
- wallet;
87901
88856
  describe() {
87902
88857
  return {
87903
88858
  adapter: "real",
@@ -87905,7 +88860,8 @@ var RealUpstreamPlugin = class {
87905
88860
  };
87906
88861
  }
87907
88862
  dispose() {
87908
- this.writeSdk?.dispose();
88863
+ for (const sdk of this.sdkCache.values()) sdk?.dispose();
88864
+ this.sdkCache.clear();
87909
88865
  this.provider.destroy();
87910
88866
  }
87911
88867
  // ---- helpers ----
@@ -87965,19 +88921,20 @@ var RealUpstreamPlugin = class {
87965
88921
  * present, else `_meta` from the document result (this is reading one response, not a
87966
88922
  * fallback path). Null when the document selects no `_meta` (e.g. PositionById). */
87967
88923
  async graphProxy(document2, variables) {
87968
- if (!this.session) {
88924
+ const sessionR = this.resolveReadSession();
88925
+ if (!sessionR.ok) {
87969
88926
  return upFail({
87970
88927
  kind: "signer-missing",
87971
88928
  // → SIGNER_UNAVAILABLE (same contract as the other authenticated reads)
87972
88929
  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."
88930
+ 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
88931
  });
87975
88932
  }
87976
88933
  let res;
87977
88934
  try {
87978
88935
  res = await fetch(`${this.config.serviceEndpoint}/api/lit/graph/query?chainId=${this.config.chainId}`, {
87979
88936
  method: "POST",
87980
- headers: { "Content-Type": "application/json", ...await this.session.authHeader() },
88937
+ headers: { "Content-Type": "application/json", ...await sessionR.session.authHeader() },
87981
88938
  body: JSON.stringify({ query: document2, variables })
87982
88939
  });
87983
88940
  } catch (e) {
@@ -88042,9 +88999,9 @@ var RealUpstreamPlugin = class {
88042
88999
  };
88043
89000
  }
88044
89001
  /** Public (unauthenticated) lit-ops GET. */
88045
- async publicRead(path4, map) {
89002
+ async publicRead(path5, map) {
88046
89003
  try {
88047
- const res = await fetch(`${this.config.serviceEndpoint}${path4}`);
89004
+ const res = await fetch(`${this.config.serviceEndpoint}${path5}`);
88048
89005
  const text = await res.text();
88049
89006
  if (!res.ok) {
88050
89007
  return upFail({
@@ -88061,18 +89018,19 @@ var RealUpstreamPlugin = class {
88061
89018
  }
88062
89019
  }
88063
89020
  /** Authenticated lit-ops GET → mapped value. Never throws; maps failures to the taxonomy. */
88064
- async opsRead(path4, map) {
88065
- if (!this.session) {
89021
+ async opsRead(path5, map) {
89022
+ const sessionR = this.resolveReadSession();
89023
+ if (!sessionR.ok) {
88066
89024
  return upFail({
88067
89025
  kind: "signer-missing",
88068
89026
  // → SIGNER_UNAVAILABLE (documented contract, pinned by REAL-08)
88069
89027
  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."
89028
+ message: `this read is authenticated (lit-ops login): ${sessionR.reason}`
88071
89029
  });
88072
89030
  }
88073
89031
  let res;
88074
89032
  try {
88075
- res = await fetch(`${this.config.serviceEndpoint}${path4}`, { headers: await this.session.authHeader() });
89033
+ res = await fetch(`${this.config.serviceEndpoint}${path5}`, { headers: await sessionR.session.authHeader() });
88076
89034
  } catch (e) {
88077
89035
  return upFail({ kind: "unavailable", source: "lit-ops", message: `lit-ops is unreachable`, raw: String(e) });
88078
89036
  }
@@ -88121,7 +89079,7 @@ var RealUpstreamPlugin = class {
88121
89079
  const pm = this.contracts["PositionManager"];
88122
89080
  if (!pm) return false;
88123
89081
  try {
88124
- const c = new import_ethers34.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
89082
+ const c = new import_ethers37.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
88125
89083
  return Boolean(await c["paused"]());
88126
89084
  } catch {
88127
89085
  return false;
@@ -88130,16 +89088,16 @@ var RealUpstreamPlugin = class {
88130
89088
  async readPositionDetails(id) {
88131
89089
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
88132
89090
  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);
89091
+ const c = new import_ethers37.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
88134
89092
  let d;
88135
89093
  try {
88136
- d = await c["getPositionDetails"](import_ethers34.ethers.zeroPadValue(id, 32));
89094
+ d = await c["getPositionDetails"](import_ethers37.ethers.zeroPadValue(id, 32));
88137
89095
  } catch (e) {
88138
89096
  if (e.code === "CALL_EXCEPTION") return null;
88139
89097
  throw e;
88140
89098
  }
88141
89099
  const borrower = String(d["borrower"]);
88142
- if (borrower === import_ethers34.ethers.ZeroAddress) return null;
89100
+ if (borrower === import_ethers37.ethers.ZeroAddress) return null;
88143
89101
  return {
88144
89102
  positionId: String(d["positionId"]),
88145
89103
  pkpId: String(d["pkpId"]),
@@ -88163,7 +89121,7 @@ var RealUpstreamPlugin = class {
88163
89121
  // src/boundary/upstream/shared/external-bridge/bridge.ts
88164
89122
  var fs4 = __toESM(require("fs"));
88165
89123
  var http3 = __toESM(require("http"));
88166
- var import_node_crypto5 = require("crypto");
89124
+ var import_node_crypto6 = require("crypto");
88167
89125
 
88168
89126
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
88169
89127
  function renderApprovalPage(sessionId) {
@@ -88210,12 +89168,16 @@ function renderApprovalPage(sessionId) {
88210
89168
  <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
88211
89169
  Use a mobile wallet instead (WalletConnect)
88212
89170
  </button>
89171
+ <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
88213
89172
  <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>
89173
+ <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
89174
  </div>
88216
89175
  </div>
88217
89176
  </main>
88218
89177
  <script>
89178
+ ${PAGE_CRYPTO_JS}
89179
+ </script>
89180
+ <script>
88219
89181
  "use strict";
88220
89182
  const SESSION = ${JSON.stringify(sessionId)};
88221
89183
  // One-time token leaves the address bar (and history) immediately.
@@ -88331,11 +89293,33 @@ document.getElementById("approve").onclick = async () => {
88331
89293
  const req = current;
88332
89294
  try {
88333
89295
  if (req.kind === "transaction") {
89296
+ const params = { from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value };
89297
+ if (req.tx.gas) params.gas = req.tx.gas; // hint only \u2014 the wallet may re-estimate
88334
89298
  const txHash = await window.ethereum.request({
88335
89299
  method: "eth_sendTransaction",
88336
- params: [{ from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value }],
89300
+ params: [params],
88337
89301
  });
88338
89302
  await post("/result", { requestId: req.id, approved: true, account: account, txHash: txHash });
89303
+ } else if (req.kind === "personal-sign") {
89304
+ // A0.9 sign-at-presence: fetch the FRESHLY quantum-stamped payload at the click\u2026
89305
+ const fr = await post("/finalize", { requestId: req.id });
89306
+ const fbody = await fr.json();
89307
+ if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
89308
+ const fresh = fbody.request;
89309
+ // \u2026re-render what will actually sign\u2026
89310
+ current = fresh; renderRequest();
89311
+ // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
89312
+ const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
89313
+ if (recomputed.toLowerCase() !== fresh.personalSign.hashHex.toLowerCase()) {
89314
+ 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" });
89315
+ clearRequest("REFUSED: the signature request did not match its own displayed fields. Nothing was signed.");
89316
+ return;
89317
+ }
89318
+ const signature = await window.ethereum.request({
89319
+ method: "personal_sign",
89320
+ params: [fresh.personalSign.hashHex, account],
89321
+ });
89322
+ await post("/result", { requestId: req.id, approved: true, account: account, signature: signature });
88339
89323
  } else {
88340
89324
  // MetaMask's v4 schema REQUIRES an EIP712Domain entry in "types" (ethers' signer
88341
89325
  // API forbids the same entry) \u2014 derive it here from the domain's present fields.
@@ -88368,8 +89352,13 @@ document.getElementById("wc-connect").onclick = async () => {
88368
89352
  const uriEl = document.getElementById("wc-uri");
88369
89353
  uriEl.textContent = body.uri;
88370
89354
  uriEl.classList.remove("hidden");
89355
+ if (body.qrSvg) {
89356
+ const qrEl = document.getElementById("wc-qr");
89357
+ qrEl.innerHTML = body.qrSvg; // server-generated SVG from OUR loopback process
89358
+ qrEl.classList.remove("hidden");
89359
+ }
88371
89360
  document.getElementById("wc-hint").classList.remove("hidden");
88372
- showStatus("Pair your mobile wallet with the code below \u2014 it becomes the signing wallet.");
89361
+ showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
88373
89362
  };
88374
89363
 
88375
89364
  connect();
@@ -88456,7 +89445,7 @@ var SignatureBridge = class {
88456
89445
  expiryMs;
88457
89446
  server = null;
88458
89447
  port = 0;
88459
- token = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89448
+ token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88460
89449
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
88461
89450
  * each open mints its own session. The link is NOT signing authority: only recovered
88462
89451
  * OWNER signatures count (M6-9); the token still gates drive-by loopback scans. */
@@ -88488,7 +89477,7 @@ var SignatureBridge = class {
88488
89477
  unlockUrl() {
88489
89478
  if (!this.server) throw new Error("bridge is not started");
88490
89479
  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");
89480
+ this.unlockToken = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88492
89481
  return `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
88493
89482
  }
88494
89483
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2). */
@@ -88543,7 +89532,7 @@ var SignatureBridge = class {
88543
89532
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
88544
89533
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
88545
89534
  */
88546
- requestSignature(request) {
89535
+ requestSignature(request, handlers) {
88547
89536
  if (!this.server) return Promise.resolve({ status: "invalidated", reason: "bridge is not started" });
88548
89537
  if (this.wallet && this.wallet.chainId !== request.chainId) {
88549
89538
  return Promise.resolve({
@@ -88556,7 +89545,8 @@ var SignatureBridge = class {
88556
89545
  request,
88557
89546
  deadlineMs: this.clock() + this.expiryMs,
88558
89547
  resolve,
88559
- settled: false
89548
+ settled: false,
89549
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {}
88560
89550
  };
88561
89551
  this.pending.set(request.id, entry);
88562
89552
  if (this.wcActive) {
@@ -88624,9 +89614,18 @@ var SignatureBridge = class {
88624
89614
  if (req.kind === "transaction") {
88625
89615
  const tx2 = req.tx;
88626
89616
  const txHash = await transport.request("eth_sendTransaction", [
88627
- { from: account, to: tx2.to, data: tx2.data, value: tx2.value }
89617
+ { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
88628
89618
  ]);
88629
89619
  if (!entry.settled) this.settle(entry, { status: "approved", account, txHash });
89620
+ } else if (req.kind === "personal-sign") {
89621
+ if (entry.finalize) {
89622
+ const fresh = await entry.finalize();
89623
+ req.personalSign = fresh.personalSign;
89624
+ req.card = fresh.card;
89625
+ }
89626
+ const ps = req.personalSign;
89627
+ const signature = await transport.request("personal_sign", [ps.hashHex, account]);
89628
+ if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
88630
89629
  } else {
88631
89630
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
88632
89631
  const payload = withEip712DomainType2(req.typedData);
@@ -88678,6 +89677,8 @@ var SignatureBridge = class {
88678
89677
  if (req.method === "POST" && url2.pathname === "/wallet-event")
88679
89678
  return void this.readJson(req, res, (b) => this.onWalletEvent(b, res));
88680
89679
  if (req.method === "POST" && url2.pathname === "/result") return void this.readJson(req, res, (b) => this.onResult(b, res));
89680
+ if (req.method === "POST" && url2.pathname === "/finalize")
89681
+ return void this.readJson(req, res, (b) => void this.onFinalize(b, res));
88681
89682
  this.deny(res, 404, "not found");
88682
89683
  }
88683
89684
  /** Loopback discipline: Host must be this loopback bind; Origin (when a browser sends
@@ -88707,7 +89708,7 @@ var SignatureBridge = class {
88707
89708
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
88708
89709
  return;
88709
89710
  }
88710
- const sessionId = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89711
+ const sessionId = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88711
89712
  this.sessions.set(sessionId, { wallet: null, sse: null });
88712
89713
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88713
89714
  res.end(renderApprovalPage(sessionId));
@@ -88743,8 +89744,13 @@ var SignatureBridge = class {
88743
89744
  });
88744
89745
  }
88745
89746
  const { uri } = await this.wcTransport.createPairing();
89747
+ const { default: qrcode } = await import("qrcode-generator");
89748
+ const qr = qrcode(0, "M");
89749
+ qr.addData(uri);
89750
+ qr.make();
89751
+ const qrSvg = qr.createSvgTag({ cellSize: 4, margin: 8, scalable: true });
88746
89752
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
88747
- res.end(JSON.stringify({ uri }));
89753
+ res.end(JSON.stringify({ uri, qrSvg }));
88748
89754
  } catch (e) {
88749
89755
  this.deny(res, 502, `WalletConnect pairing failed: ${e.message}`);
88750
89756
  }
@@ -88762,7 +89768,7 @@ var SignatureBridge = class {
88762
89768
  return;
88763
89769
  }
88764
89770
  this.unlockToken = null;
88765
- this.unlockSession = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89771
+ this.unlockSession = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88766
89772
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88767
89773
  res.end(renderUnlockPage(this.unlockSession));
88768
89774
  }
@@ -88850,6 +89856,37 @@ var SignatureBridge = class {
88850
89856
  }
88851
89857
  this.ok(res);
88852
89858
  }
89859
+ /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
89860
+ * request. Idempotent for requests without a finalize handler (payload as enqueued). */
89861
+ async onFinalize(body, res) {
89862
+ if (!this.sessionOf(body["sessionId"], res)) return;
89863
+ const entry = this.pending.get(String(body["requestId"] ?? ""));
89864
+ if (!entry || entry.settled) {
89865
+ this.deny(res, 404, "unknown or already-settled requestId");
89866
+ return;
89867
+ }
89868
+ if (entry.request.kind !== "personal-sign") {
89869
+ this.deny(res, 400, "finalize applies only to personal-sign requests");
89870
+ return;
89871
+ }
89872
+ if (entry.finalize) {
89873
+ let fresh;
89874
+ try {
89875
+ fresh = await entry.finalize();
89876
+ } catch (e) {
89877
+ this.deny(res, 502, `finalize failed: ${e.message}`);
89878
+ return;
89879
+ }
89880
+ if (entry.settled) {
89881
+ this.deny(res, 404, "request settled while finalizing");
89882
+ return;
89883
+ }
89884
+ entry.request.personalSign = fresh.personalSign;
89885
+ entry.request.card = fresh.card;
89886
+ }
89887
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
89888
+ res.end(JSON.stringify({ request: entry.request }));
89889
+ }
88853
89890
  onResult(body, res) {
88854
89891
  if (!this.sessionOf(body["sessionId"], res)) return;
88855
89892
  const entry = this.pending.get(String(body["requestId"] ?? ""));
@@ -88874,8 +89911,8 @@ var SignatureBridge = class {
88874
89911
  this.deny(res, 400, "transaction approval requires txHash or rawSignedTx");
88875
89912
  return;
88876
89913
  }
88877
- if (entry.request.kind === "typed-data" && !signature) {
88878
- this.deny(res, 400, "typed-data approval requires signature");
89914
+ if ((entry.request.kind === "typed-data" || entry.request.kind === "personal-sign") && !signature) {
89915
+ this.deny(res, 400, `${entry.request.kind} approval requires signature`);
88879
89916
  return;
88880
89917
  }
88881
89918
  if (entry.collect) {
@@ -89079,9 +90116,13 @@ function resolveRealConfig(env) {
89079
90116
  const missing = [];
89080
90117
  const signer = env["DH_SIGNER"];
89081
90118
  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
- );
90119
+ if (signer === "mock-simulated") {
90120
+ problems.push(
90121
+ "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."
90122
+ );
90123
+ } else if (signer !== "external" && signer !== "keystore") {
90124
+ problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
90125
+ }
89085
90126
  }
89086
90127
  const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "sepolia" : env["DH_NETWORK"];
89087
90128
  if (NETWORKS[network] === void 0) {
@@ -89099,6 +90140,21 @@ function resolveRealConfig(env) {
89099
90140
  if (keystorePath && !keystorePassword || !keystorePath && keystorePassword) {
89100
90141
  problems.push("DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD must be set together (or neither).");
89101
90142
  }
90143
+ const stateDir = env["DH_STATE_DIR"];
90144
+ const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
90145
+ const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
90146
+ const wcProjectId = env["DH_WC_PROJECT_ID"];
90147
+ if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
90148
+ problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
90149
+ }
90150
+ let bridgeOpenBrowser;
90151
+ if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
90152
+ if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
90153
+ problems.push(`DH_BRIDGE_OPEN='${bridgeOpenRaw}' must be 0 or 1.`);
90154
+ } else {
90155
+ bridgeOpenBrowser = bridgeOpenRaw === "1";
90156
+ }
90157
+ }
89102
90158
  const ACK_PHRASE = "I-UNDERSTAND-REAL-FUNDS";
89103
90159
  const ackRaw = env["DH_MAINNET_WRITES_ACK"];
89104
90160
  let mainnetWritesAck;
@@ -89142,6 +90198,11 @@ function resolveRealConfig(env) {
89142
90198
  serviceEndpoint,
89143
90199
  litNetwork,
89144
90200
  ...keystorePath && keystorePassword ? { keystorePath, keystorePassword } : {},
90201
+ ...signer === "external" || signer === "keystore" ? { signer } : {},
90202
+ ...stateDir ? { stateDir } : {},
90203
+ ...bridgeUrlFile ? { bridgeUrlFile } : {},
90204
+ ...bridgeOpenBrowser !== void 0 ? { bridgeOpenBrowser } : {},
90205
+ ...wcProjectId ? { wcProjectId } : {},
89145
90206
  ...validatorVersion !== void 0 ? { validatorVersion } : {},
89146
90207
  ...mainnetWritesAck === true ? { mainnetWritesAck: true } : {}
89147
90208
  }
@@ -89149,14 +90210,15 @@ function resolveRealConfig(env) {
89149
90210
  }
89150
90211
 
89151
90212
  // src/boundary/index.ts
89152
- function fileSignerPersistence(path4) {
90213
+ function fileSignerPersistence(filePath) {
89153
90214
  return {
89154
90215
  load() {
89155
- if (!fs5.existsSync(path4)) return null;
89156
- return JSON.parse(fs5.readFileSync(path4, "utf8"));
90216
+ if (!fs5.existsSync(filePath)) return null;
90217
+ return JSON.parse(fs5.readFileSync(filePath, "utf8"));
89157
90218
  },
89158
90219
  save(state) {
89159
- fs5.writeFileSync(path4, JSON.stringify(state));
90220
+ fs5.mkdirSync(path4.dirname(filePath), { recursive: true });
90221
+ fs5.writeFileSync(filePath, JSON.stringify(state));
89160
90222
  }
89161
90223
  };
89162
90224
  }
@@ -89166,7 +90228,7 @@ function createBoundary(config, opts) {
89166
90228
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
89167
90229
  );
89168
90230
  }
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);
90231
+ 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
90232
  if (opts?.ceremony) {
89171
90233
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
89172
90234
  const boundary2 = new BoundaryCore({
@@ -89175,6 +90237,11 @@ function createBoundary(config, opts) {
89175
90237
  network: "mock",
89176
90238
  chainId: config.chainId ?? 1337,
89177
90239
  ...config.borrower ? { borrowerAddress: config.borrower } : {},
90240
+ capabilities: () => ({
90241
+ reads: { public: true, authenticated: "available" },
90242
+ writes: { enabled: true, signerModes: ["external"], activeMode: "external" },
90243
+ signerSetupTool: false
90244
+ }),
89178
90245
  configFingerprint
89179
90246
  });
89180
90247
  return { boundary: boundary2, mockControl: plugin2.control, dispose: () => plugin2.dispose() };
@@ -89252,6 +90319,16 @@ function createBoundary(config, opts) {
89252
90319
  chainId,
89253
90320
  ...config.borrower ? { borrowerAddress: config.borrower } : {},
89254
90321
  signer: manager,
90322
+ // B3: the mock sandbox runs every ceremony class; reads have no login gate.
90323
+ capabilities: () => ({
90324
+ reads: { public: true, authenticated: "available" },
90325
+ writes: {
90326
+ enabled: true,
90327
+ signerModes: ["external", "keystore", "mock-simulated", "safe", "safe-module"],
90328
+ activeMode: manager.mode()
90329
+ },
90330
+ signerSetupTool: true
90331
+ }),
89255
90332
  configFingerprint
89256
90333
  });
89257
90334
  return {
@@ -89265,18 +90342,73 @@ function createBoundary(config, opts) {
89265
90342
  };
89266
90343
  }
89267
90344
  async function createRealBoundary(config, wallet) {
89268
- const plugin = new RealUpstreamPlugin(config, wallet);
90345
+ const keystore = new KeystoreProvider({
90346
+ ...config.keystorePath ? { keystorePath: config.keystorePath } : {},
90347
+ ...config.keystorePassword ? { keystorePassword: config.keystorePassword } : {}
90348
+ });
90349
+ if (wallet) keystore.adopt(wallet);
90350
+ const stateDir = config.stateDir ?? path4.join(os2.homedir(), ".dh-mcp");
90351
+ const stateFile = path4.join(stateDir, `${config.network}.signer.json`);
90352
+ const chainName = config.network === "mainnet" ? "Ethereum Mainnet" : "Sepolia";
90353
+ const bridge = new SignatureBridge({
90354
+ ...config.bridgeUrlFile ? { urlFile: config.bridgeUrlFile } : {},
90355
+ network: { chainId: config.chainId, chainName, rpcUrl: config.rpcUrl },
90356
+ ...config.wcProjectId ? { wc: { projectId: config.wcProjectId, chainId: config.chainId } } : {},
90357
+ keystoreUnlock: {
90358
+ unlock: (json, password) => keystore.unlock(json, password),
90359
+ unlockConfigured: (password) => keystore.unlockConfigured(password),
90360
+ generate: (password) => keystore.generateAndSave(password, path4.join(stateDir, `${config.network}.keystore.json`))
90361
+ }
90362
+ });
90363
+ const initialMode = config.signer ?? (keystore.materialConfigured() ? "keystore" : "none");
90364
+ const manager = new SignerManager({
90365
+ persistence: fileSignerPersistence(stateFile),
90366
+ initialMode,
90367
+ candidate: () => bridge.walletState()?.account ?? null,
90368
+ pendingCeremonies: () => bridge.pendingCount(),
90369
+ keystore
90370
+ // No safeInfo: the Safe planes are mock-only pending their own plans — manager.use
90371
+ // refuses 'safe'/'safe-module' with the missing-discovery reason, truthfully.
90372
+ });
90373
+ if (initialMode === "external" || manager.mode() === "external") {
90374
+ void bridge.start();
90375
+ }
90376
+ const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
89269
90377
  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);
90378
+ 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);
90379
+ const writesArmed = config.network === "sepolia" || config.network === "mainnet" && config.mainnetWritesAck === true;
90380
+ const capabilities = () => ({
90381
+ reads: {
90382
+ public: true,
90383
+ authenticated: plugin.authenticatedReadsAvailable() ? "available" : "needs-signer"
90384
+ },
90385
+ writes: writesArmed ? { enabled: true, signerModes: ["external", "keystore"], activeMode: manager.mode() } : {
90386
+ enabled: false,
90387
+ reason: "writes are operator-gated on mainnet \u2014 the standing mainnet write block; mainnet writes await their dedicated security review. Reads remain available.",
90388
+ signerModes: [],
90389
+ activeMode: manager.mode()
90390
+ },
90391
+ signerSetupTool: true
90392
+ });
89271
90393
  const boundary = new BoundaryCore({
89272
90394
  plugin,
89273
90395
  adapter: "real",
89274
90396
  network: config.network,
89275
90397
  chainId: config.chainId,
89276
- ...wallet ? { borrowerAddress: wallet.address } : {},
90398
+ // M10-5: the manager IS the identity surface — boundary://info signerKind/borrower
90399
+ // stay live across mode switches instead of freezing a boot-time address.
90400
+ signer: manager,
90401
+ capabilities,
89277
90402
  configFingerprint
89278
90403
  });
89279
- return { boundary, dispose: () => plugin.dispose() };
90404
+ return {
90405
+ boundary,
90406
+ signer: { manager, bridge, keystore, connect: () => plugin.connectExternal() },
90407
+ dispose: () => {
90408
+ plugin.dispose();
90409
+ bridge.close();
90410
+ }
90411
+ };
89280
90412
  }
89281
90413
  // Annotate the CommonJS export names for ESM import in node:
89282
90414
  0 && (module.exports = {