@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/index.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_ethers38 = require("ethers");
15413
+ var import_ethers41 = 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_ethers38.ethers,
18234
+ ...import_ethers41.ethers,
17980
18235
  providers: {
17981
- StaticJsonRpcProvider: import_ethers38.ethers.JsonRpcProvider
18236
+ StaticJsonRpcProvider: import_ethers41.ethers.JsonRpcProvider
17982
18237
  },
17983
- Contract: import_ethers38.ethers.Contract,
17984
- utils: import_ethers38.ethers
18238
+ Contract: import_ethers41.ethers.Contract,
18239
+ utils: import_ethers41.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) {
@@ -51919,9 +52174,13 @@ function resolveRealConfig(env) {
51919
52174
  const missing = [];
51920
52175
  const signer = env["DH_SIGNER"];
51921
52176
  if (signer !== void 0 && signer !== "") {
51922
- problems.push(
51923
- `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.`
51924
- );
52177
+ if (signer === "mock-simulated") {
52178
+ problems.push(
52179
+ "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."
52180
+ );
52181
+ } else if (signer !== "external" && signer !== "keystore") {
52182
+ problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
52183
+ }
51925
52184
  }
51926
52185
  const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "sepolia" : env["DH_NETWORK"];
51927
52186
  if (NETWORKS[network] === void 0) {
@@ -51939,6 +52198,21 @@ function resolveRealConfig(env) {
51939
52198
  if (keystorePath && !keystorePassword || !keystorePath && keystorePassword) {
51940
52199
  problems.push("DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD must be set together (or neither).");
51941
52200
  }
52201
+ const stateDir = env["DH_STATE_DIR"];
52202
+ const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
52203
+ const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
52204
+ const wcProjectId = env["DH_WC_PROJECT_ID"];
52205
+ if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
52206
+ problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
52207
+ }
52208
+ let bridgeOpenBrowser;
52209
+ if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
52210
+ if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
52211
+ problems.push(`DH_BRIDGE_OPEN='${bridgeOpenRaw}' must be 0 or 1.`);
52212
+ } else {
52213
+ bridgeOpenBrowser = bridgeOpenRaw === "1";
52214
+ }
52215
+ }
51942
52216
  const ACK_PHRASE = "I-UNDERSTAND-REAL-FUNDS";
51943
52217
  const ackRaw = env["DH_MAINNET_WRITES_ACK"];
51944
52218
  let mainnetWritesAck;
@@ -51982,6 +52256,11 @@ function resolveRealConfig(env) {
51982
52256
  serviceEndpoint,
51983
52257
  litNetwork,
51984
52258
  ...keystorePath && keystorePassword ? { keystorePath, keystorePassword } : {},
52259
+ ...signer === "external" || signer === "keystore" ? { signer } : {},
52260
+ ...stateDir ? { stateDir } : {},
52261
+ ...bridgeUrlFile ? { bridgeUrlFile } : {},
52262
+ ...bridgeOpenBrowser !== void 0 ? { bridgeOpenBrowser } : {},
52263
+ ...wcProjectId ? { wcProjectId } : {},
51985
52264
  ...validatorVersion !== void 0 ? { validatorVersion } : {},
51986
52265
  ...mainnetWritesAck === true ? { mainnetWritesAck: true } : {}
51987
52266
  }
@@ -51990,11 +52269,13 @@ function resolveRealConfig(env) {
51990
52269
 
51991
52270
  // src/boot.ts
51992
52271
  var fs6 = __toESM(require("fs"));
51993
- var import_ethers35 = require("ethers");
52272
+ var import_ethers38 = require("ethers");
51994
52273
 
51995
52274
  // src/boundary/index.ts
51996
- var import_node_crypto6 = require("crypto");
52275
+ var import_node_crypto7 = require("crypto");
51997
52276
  var fs5 = __toESM(require("fs"));
52277
+ var os2 = __toESM(require("os"));
52278
+ var path4 = __toESM(require("path"));
51998
52279
 
51999
52280
  // src/boundary/envelope.ts
52000
52281
  function okEnvelope(data, source, warnings = []) {
@@ -52710,6 +52991,14 @@ var BoundaryCore = class {
52710
52991
  borrowerAddress: this.deps.borrowerAddress
52711
52992
  } : {},
52712
52993
  ...info.walletStance ? { walletStance: info.walletStance } : {},
52994
+ ...this.deps.capabilities ? {
52995
+ capabilities: {
52996
+ network: this.deps.network,
52997
+ chainId: this.deps.chainId,
52998
+ practiceWorld: this.deps.network !== "mainnet",
52999
+ ...this.deps.capabilities()
53000
+ }
53001
+ } : {},
52713
53002
  configFingerprint: this.deps.configFingerprint
52714
53003
  },
52715
53004
  source
@@ -54200,218 +54489,7 @@ var MockControl = class {
54200
54489
 
54201
54490
  // src/boundary/upstream/mock/tx-builder.ts
54202
54491
  var import_ethers4 = require("ethers");
54203
-
54204
- // src/boundary/upstream/shared/tx-validator.ts
54205
- var import_ethers3 = require("ethers");
54206
- var SIGNABLE_FUNCTIONS = [
54207
- "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)",
54208
- "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
54209
- "function repayPosition(bytes32 positionId, uint256 repaymentAmount) external returns (bool)",
54210
- "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
54211
- "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
54212
- "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)",
54213
- "function approve(address spender, uint256 amount) external returns (bool)",
54214
- "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
54215
- // SimplePSMV2 (plan 08 Part B Phase W1) — the PSM exchange pair, exact signatures.
54216
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
54217
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)"
54218
- ];
54219
- var IFACE = new import_ethers3.ethers.Interface(SIGNABLE_FUNCTIONS);
54220
- function encodeSignable(fn, args) {
54221
- return IFACE.encodeFunctionData(fn, args);
54222
- }
54223
- function decodeSignable(data) {
54224
- return decode(data);
54225
- }
54226
- var TxValidationError = class extends Error {
54227
- constructor(msg) {
54228
- super(`Refusing to sign server-returned transaction: ${msg}`);
54229
- this.name = "TxValidationError";
54230
- }
54231
- };
54232
- function eqAddr(a, b) {
54233
- if (!a || !b) return false;
54234
- try {
54235
- return import_ethers3.ethers.getAddress(a) === import_ethers3.ethers.getAddress(b);
54236
- } catch {
54237
- return false;
54238
- }
54239
- }
54240
- function readToAddress(tx2) {
54241
- const to = tx2["to"];
54242
- if (typeof to !== "string") throw new TxValidationError(`unsignedTx.to is missing or not a string`);
54243
- return to;
54244
- }
54245
- function readData(tx2) {
54246
- const data = tx2["data"];
54247
- if (typeof data !== "string" || !data.startsWith("0x")) throw new TxValidationError(`unsignedTx.data missing or malformed`);
54248
- return data;
54249
- }
54250
- function readChainId(tx2) {
54251
- const c = tx2["chainId"];
54252
- if (c == null) return null;
54253
- if (typeof c === "number") return c;
54254
- if (typeof c === "string") return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
54255
- if (typeof c === "bigint") return Number(c);
54256
- return null;
54257
- }
54258
- function readValue(tx2) {
54259
- const v = tx2["value"];
54260
- if (v == null) return 0n;
54261
- if (typeof v === "string") return BigInt(v.startsWith("0x") ? v : v);
54262
- if (typeof v === "number") return BigInt(v);
54263
- if (typeof v === "bigint") return v;
54264
- if (typeof v?.toBigInt === "function") return v.toBigInt();
54265
- if (typeof v?.toString === "function") return BigInt(v.toString());
54266
- throw new TxValidationError(`unsignedTx.value has unrecognized type`);
54267
- }
54268
- function decode(data) {
54269
- try {
54270
- const parsed = IFACE.parseTransaction({ data });
54271
- if (!parsed) throw new TxValidationError(`unsignedTx.data does not decode against the signable-function whitelist`);
54272
- return { name: parsed.name, args: parsed.args };
54273
- } catch (e) {
54274
- if (e instanceof TxValidationError) throw e;
54275
- throw new TxValidationError(
54276
- `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
54277
- );
54278
- }
54279
- }
54280
- function normalizePositionId(id) {
54281
- const hex = id.startsWith("0x") ? id : `0x${id}`;
54282
- return import_ethers3.ethers.zeroPadValue(hex, 32).toLowerCase();
54283
- }
54284
- function validateUnsignedTx(unsignedTx, expected, vctx) {
54285
- const txChainId = readChainId(unsignedTx);
54286
- if (txChainId != null && txChainId !== vctx.chainId) {
54287
- throw new TxValidationError(`chainId mismatch \u2014 tx says ${txChainId}, expected ${vctx.chainId}`);
54288
- }
54289
- const value = readValue(unsignedTx);
54290
- if (value !== 0n) throw new TxValidationError(`unsignedTx.value is non-zero (${value})`);
54291
- const to = readToAddress(unsignedTx);
54292
- const data = readData(unsignedTx);
54293
- const { name, args } = decode(data);
54294
- const pm = vctx.contracts.PositionManager;
54295
- switch (expected.kind) {
54296
- case "mint": {
54297
- if (name !== "mintUCD") throw new TxValidationError(`expected mintUCD, server returned ${name}`);
54298
- if (!eqAddr(to, pm)) throw new TxValidationError(`mintUCD must target PositionManager (${pm}), got ${to}`);
54299
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54300
- throw new TxValidationError(`positionId mismatch`);
54301
- if (BigInt(String(args[1])).toString() !== expected.amountWei)
54302
- throw new TxValidationError(`mintAmount mismatch`);
54303
- if (BigInt(String(args[2])).toString() !== expected.mintFeeWei)
54304
- throw new TxValidationError(`mintFee mismatch`);
54305
- break;
54306
- }
54307
- case "repay": {
54308
- if (name !== "makePayment" && name !== "repayPosition")
54309
- throw new TxValidationError(`expected makePayment/repayPosition, server returned ${name}`);
54310
- if (!eqAddr(to, pm)) throw new TxValidationError(`${name} must target PositionManager`);
54311
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54312
- throw new TxValidationError(`positionId mismatch`);
54313
- if (BigInt(String(args[1])).toString() !== expected.amountWei)
54314
- throw new TxValidationError(`paymentAmount mismatch`);
54315
- break;
54316
- }
54317
- case "extend": {
54318
- if (name !== "extendPosition") throw new TxValidationError(`expected extendPosition, server returned ${name}`);
54319
- if (!eqAddr(to, pm)) throw new TxValidationError(`extendPosition must target PositionManager`);
54320
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54321
- throw new TxValidationError(`positionId mismatch`);
54322
- if (Number(args[1]) !== expected.selectedTerm) throw new TxValidationError(`selectedTerm mismatch`);
54323
- if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
54324
- const txFee = BigInt(String(args[5]));
54325
- const upper = BigInt(expected.upperBoundProRataFeeWei);
54326
- if (txFee > upper) throw new TxValidationError(`proRataRenewalFee=${txFee} exceeds upper bound=${upper}`);
54327
- }
54328
- break;
54329
- }
54330
- case "withdraw-btc": {
54331
- if (name !== "withdrawBTC") throw new TxValidationError(`expected withdrawBTC, server returned ${name}`);
54332
- if (!eqAddr(to, pm)) throw new TxValidationError(`withdrawBTC must target PositionManager`);
54333
- const paramsTuple = args[0];
54334
- if (String(paramsTuple[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54335
- throw new TxValidationError(`positionId mismatch`);
54336
- if (String(paramsTuple[5]) !== expected.btcAddress) throw new TxValidationError(`btcAddress mismatch`);
54337
- if (expected.upperBoundTotalDeduction != null) {
54338
- const txDeduction = BigInt(String(paramsTuple[6]));
54339
- const upper = BigInt(expected.upperBoundTotalDeduction);
54340
- if (txDeduction > upper)
54341
- throw new TxValidationError(
54342
- `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}`
54343
- );
54344
- }
54345
- break;
54346
- }
54347
- case "ucd-approve": {
54348
- if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
54349
- const ucd = vctx.contracts.UCDToken;
54350
- if (!eqAddr(to, ucd)) throw new TxValidationError(`approve must target UCDToken`);
54351
- if (!expected.spenderCandidates.some((s) => eqAddr(String(args[0]), s)))
54352
- throw new TxValidationError(`approve spender not in expected set`);
54353
- const amt = BigInt(String(args[1]));
54354
- const min = BigInt(expected.minAmountWei);
54355
- if (amt < min) throw new TxValidationError(`approve amount ${amt} is less than required ${min}`);
54356
- if (amt > min * 1000n) throw new TxValidationError(`approve amount ${amt} exceeds sanity cap`);
54357
- break;
54358
- }
54359
- case "stablecoin-approve": {
54360
- if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
54361
- if (!eqAddr(to, expected.tokenAddress))
54362
- throw new TxValidationError(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
54363
- if (!eqAddr(String(args[0]), expected.spender))
54364
- throw new TxValidationError(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
54365
- if (BigInt(String(args[1])).toString() !== expected.amountUnits)
54366
- throw new TxValidationError(
54367
- `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
54368
- );
54369
- break;
54370
- }
54371
- case "ucd-approve-controller": {
54372
- if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
54373
- if (!eqAddr(to, expected.ucdTokenAddress))
54374
- throw new TxValidationError(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
54375
- if (!eqAddr(String(args[0]), expected.spender))
54376
- throw new TxValidationError(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
54377
- if (BigInt(String(args[1])).toString() !== expected.amountWei)
54378
- throw new TxValidationError(
54379
- `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
54380
- );
54381
- break;
54382
- }
54383
- case "psm-swap": {
54384
- if (name !== "swap") throw new TxValidationError(`expected swap, server returned ${name}`);
54385
- if (!eqAddr(to, expected.psmAddress)) throw new TxValidationError(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
54386
- if (!eqAddr(String(args[0]), expected.stablecoin)) throw new TxValidationError(`swap stablecoin mismatch`);
54387
- if (BigInt(String(args[1])).toString() !== expected.amountIn) throw new TxValidationError(`swap amountIn mismatch`);
54388
- if (BigInt(String(args[2])).toString() !== expected.minOut) throw new TxValidationError(`swap minUcdOut mismatch`);
54389
- if (BigInt(expected.minOut) === 0n)
54390
- throw new TxValidationError(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
54391
- break;
54392
- }
54393
- case "psm-redeem": {
54394
- if (name !== "redeem") throw new TxValidationError(`expected redeem, server returned ${name}`);
54395
- if (!eqAddr(to, expected.psmAddress)) throw new TxValidationError(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
54396
- if (!eqAddr(String(args[0]), expected.stablecoin)) throw new TxValidationError(`redeem stablecoin mismatch`);
54397
- if (BigInt(String(args[1])).toString() !== expected.amountUcdWei) throw new TxValidationError(`redeem ucdAmount mismatch`);
54398
- if (BigInt(String(args[2])).toString() !== expected.minOut) throw new TxValidationError(`redeem minStablecoinOut mismatch`);
54399
- if (BigInt(expected.minOut) === 0n)
54400
- throw new TxValidationError(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
54401
- break;
54402
- }
54403
- case "set-position-delegate": {
54404
- if (name !== "setPositionDelegate") throw new TxValidationError(`expected setPositionDelegate`);
54405
- if (!eqAddr(to, expected.registryAddress)) throw new TxValidationError(`setPositionDelegate wrong target`);
54406
- if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
54407
- throw new TxValidationError(`positionId mismatch`);
54408
- if (!eqAddr(String(args[1]), expected.delegate)) throw new TxValidationError(`delegate mismatch`);
54409
- break;
54410
- }
54411
- }
54412
- }
54413
-
54414
- // src/boundary/upstream/mock/tx-builder.ts
54492
+ init_tx_validator();
54415
54493
  var ZERO32 = import_ethers4.ethers.ZeroHash;
54416
54494
  var EMPTY_SIG = "0x" + "00".repeat(65);
54417
54495
  function tx(ctx, data) {
@@ -54614,6 +54692,12 @@ var KeystoreProvider = class {
54614
54692
  signer() {
54615
54693
  return this.wallet;
54616
54694
  }
54695
+ /** Adopt an ALREADY-DECRYPTED wallet (plan 10 OV-8: the real boot keeps its eager
54696
+ * decrypt with loud typed errors; the provider consumes the result instead of paying
54697
+ * scrypt twice). */
54698
+ adopt(wallet) {
54699
+ this.wallet = wallet;
54700
+ }
54617
54701
  /** Material exists (unlocked already, or the env pair is set) — `use keystore` succeeds. */
54618
54702
  materialConfigured() {
54619
54703
  return this.wallet !== null || Boolean(this.env.keystorePath && this.env.keystorePassword);
@@ -55488,6 +55572,7 @@ var import_ethers9 = require("ethers");
55488
55572
 
55489
55573
  // src/boundary/upstream/shared/external-bridge/card.ts
55490
55574
  var import_ethers7 = require("ethers");
55575
+ init_tx_validator();
55491
55576
  function formatUcd(wei) {
55492
55577
  const negative = wei < 0n;
55493
55578
  const abs = negative ? -wei : wei;
@@ -55528,6 +55613,23 @@ function cardForTx(tx2) {
55528
55613
  if (args.length >= 7) lines.push(ucdLine("Renewal fee, at most (ADDED TO YOUR DEBT \u2014 wallet not charged)", args[5]));
55529
55614
  return [...lines, ...head];
55530
55615
  }
55616
+ case "createPosition":
55617
+ return [
55618
+ "Operation: create a new borrowing position (your wallet is the borrower)",
55619
+ `Term: ${Number(args[4])} months`,
55620
+ `Position key (PKP id): ${String(args[0])}`,
55621
+ `BTC vault (mainnet form): ${String(args[2])}`,
55622
+ `BTC vault (regtest form): ${String(args[3])}`,
55623
+ `Validator generation: ${Number(args[5])}`,
55624
+ ...head
55625
+ ];
55626
+ case "addAddress":
55627
+ return [
55628
+ "Operation: allowlist a Bitcoin withdrawal destination for YOUR account",
55629
+ `BTC address to allowlist: ${String(args[0])}`,
55630
+ "Withdrawals to this address become possible only after the registry's on-chain delay",
55631
+ ...head
55632
+ ];
55531
55633
  case "approve":
55532
55634
  return [
55533
55635
  "Operation: token allowance approval (EXACT amount \u2014 never unlimited)",
@@ -55595,6 +55697,9 @@ function recoverOperationSigner(payload, signature) {
55595
55697
  );
55596
55698
  }
55597
55699
 
55700
+ // src/boundary/upstream/mock/external-ceremony.ts
55701
+ init_tx_validator();
55702
+
55598
55703
  // src/signer/keystore-signer.ts
55599
55704
  var import_ethers8 = require("ethers");
55600
55705
  var LOGIN_DOMAIN = (chainId) => ({ name: "Diamond Hands", version: "1", chainId });
@@ -55828,6 +55933,7 @@ function openInBrowser(url2) {
55828
55933
 
55829
55934
  // src/boundary/upstream/mock/keystore-ceremony.ts
55830
55935
  var import_ethers10 = require("ethers");
55936
+ init_tx_validator();
55831
55937
  var SOURCE2 = "keystore-signer";
55832
55938
  var KeystoreCeremony = class {
55833
55939
  constructor(deps) {
@@ -55903,6 +56009,7 @@ var KeystoreCeremony = class {
55903
56009
  // src/boundary/upstream/mock/safe-ceremony.ts
55904
56010
  var import_node_crypto4 = require("crypto");
55905
56011
  var import_ethers11 = require("ethers");
56012
+ init_tx_validator();
55906
56013
 
55907
56014
  // src/boundary/upstream/shared/quantum.ts
55908
56015
  var QUANTUM_WINDOW_SECONDS = 60;
@@ -55916,6 +56023,10 @@ function isAuthFresh(issuedAtSec, nowSec) {
55916
56023
  function isStrictCurrentQuantum(issuedAtSec, nowSec) {
55917
56024
  return issuedAtSec <= nowSec && Math.floor(issuedAtSec / QUANTUM_WINDOW_SECONDS) === Math.floor(nowSec / QUANTUM_WINDOW_SECONDS);
55918
56025
  }
56026
+ function nextQuantumTimestamp(nowMs) {
56027
+ const now = Math.floor(nowMs / 1e3);
56028
+ return Math.floor(now / QUANTUM_WINDOW_SECONDS) * QUANTUM_WINDOW_SECONDS + QUANTUM_WINDOW_SECONDS;
56029
+ }
55919
56030
 
55920
56031
  // src/boundary/upstream/mock/safe-ceremony.ts
55921
56032
  var SOURCE3 = "safe-ceremony";
@@ -56306,6 +56417,7 @@ var SafeCeremony = class {
56306
56417
 
56307
56418
  // src/boundary/upstream/mock/safe-module-ceremony.ts
56308
56419
  var import_ethers12 = require("ethers");
56420
+ init_tx_validator();
56309
56421
  var SOURCE4 = "safe-module";
56310
56422
  var SafeModuleCeremony = class {
56311
56423
  constructor(deps) {
@@ -56467,7 +56579,7 @@ var SafeModuleCeremony = class {
56467
56579
  };
56468
56580
 
56469
56581
  // src/boundary/upstream/real/plugin.ts
56470
- var import_ethers34 = require("ethers");
56582
+ var import_ethers37 = require("ethers");
56471
56583
 
56472
56584
  // ../sdk/dist/index.mjs
56473
56585
  var import_ethers13 = require("ethers");
@@ -57846,9 +57958,9 @@ function isVisitable(thing) {
57846
57958
  function removeBrackets(key) {
57847
57959
  return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
57848
57960
  }
57849
- function renderKey(path4, key, dots) {
57850
- if (!path4) return key;
57851
- return path4.concat(key).map(function each(token, i) {
57961
+ function renderKey(path5, key, dots) {
57962
+ if (!path5) return key;
57963
+ return path5.concat(key).map(function each(token, i) {
57852
57964
  token = removeBrackets(token);
57853
57965
  return !dots && i ? "[" + token + "]" : token;
57854
57966
  }).join(dots ? "." : "");
@@ -57902,13 +58014,13 @@ function toFormData(obj, formData, options) {
57902
58014
  }
57903
58015
  return value;
57904
58016
  }
57905
- function defaultVisitor(value, key, path4) {
58017
+ function defaultVisitor(value, key, path5) {
57906
58018
  let arr = value;
57907
58019
  if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) {
57908
- formData.append(renderKey(path4, key, dots), convertValue(value));
58020
+ formData.append(renderKey(path5, key, dots), convertValue(value));
57909
58021
  return false;
57910
58022
  }
57911
- if (value && !path4 && typeof value === "object") {
58023
+ if (value && !path5 && typeof value === "object") {
57912
58024
  if (utils_default.endsWith(key, "{}")) {
57913
58025
  key = metaTokens ? key : key.slice(0, -2);
57914
58026
  value = JSON.stringify(value);
@@ -57927,7 +58039,7 @@ function toFormData(obj, formData, options) {
57927
58039
  if (isVisitable(value)) {
57928
58040
  return true;
57929
58041
  }
57930
- formData.append(renderKey(path4, key, dots), convertValue(value));
58042
+ formData.append(renderKey(path5, key, dots), convertValue(value));
57931
58043
  return false;
57932
58044
  }
57933
58045
  const stack = [];
@@ -57936,7 +58048,7 @@ function toFormData(obj, formData, options) {
57936
58048
  convertValue,
57937
58049
  isVisitable
57938
58050
  });
57939
- function build(value, path4, depth = 0) {
58051
+ function build(value, path5, depth = 0) {
57940
58052
  if (utils_default.isUndefined(value)) return;
57941
58053
  if (depth > maxDepth) {
57942
58054
  throw new AxiosError_default(
@@ -57945,13 +58057,13 @@ function toFormData(obj, formData, options) {
57945
58057
  );
57946
58058
  }
57947
58059
  if (stack.indexOf(value) !== -1) {
57948
- throw Error("Circular reference detected in " + path4.join("."));
58060
+ throw Error("Circular reference detected in " + path5.join("."));
57949
58061
  }
57950
58062
  stack.push(value);
57951
58063
  utils_default.forEach(value, function each(el, key) {
57952
- const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path4, exposedHelpers);
58064
+ const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path5, exposedHelpers);
57953
58065
  if (result === true) {
57954
- build(el, path4 ? path4.concat(key) : [key], depth + 1);
58066
+ build(el, path5 ? path5.concat(key) : [key], depth + 1);
57955
58067
  }
57956
58068
  });
57957
58069
  stack.pop();
@@ -58162,7 +58274,7 @@ var platform_default = {
58162
58274
  // ../sdk/node_modules/axios/lib/helpers/toURLEncodedForm.js
58163
58275
  function toURLEncodedForm(data, options) {
58164
58276
  return toFormData_default(data, new platform_default.classes.URLSearchParams(), {
58165
- visitor: function(value, key, path4, helpers) {
58277
+ visitor: function(value, key, path5, helpers) {
58166
58278
  if (platform_default.isNode && utils_default.isBuffer(value)) {
58167
58279
  this.append(key, value.toString("base64"));
58168
58280
  return false;
@@ -58192,11 +58304,11 @@ function arrayToObject(arr) {
58192
58304
  return obj;
58193
58305
  }
58194
58306
  function formDataToJSON(formData) {
58195
- function buildPath(path4, value, target, index) {
58196
- let name = path4[index++];
58307
+ function buildPath(path5, value, target, index) {
58308
+ let name = path5[index++];
58197
58309
  if (name === "__proto__") return true;
58198
58310
  const isNumericKey = Number.isFinite(+name);
58199
- const isLast = index >= path4.length;
58311
+ const isLast = index >= path5.length;
58200
58312
  name = !name && utils_default.isArray(target) ? target.length : name;
58201
58313
  if (isLast) {
58202
58314
  if (utils_default.hasOwnProp(target, name)) {
@@ -58209,7 +58321,7 @@ function formDataToJSON(formData) {
58209
58321
  if (!utils_default.hasOwnProp(target, name) || !utils_default.isObject(target[name])) {
58210
58322
  target[name] = [];
58211
58323
  }
58212
- const result = buildPath(path4, value, target[name], index);
58324
+ const result = buildPath(path5, value, target[name], index);
58213
58325
  if (result && utils_default.isArray(target[name])) {
58214
58326
  target[name] = arrayToObject(target[name]);
58215
58327
  }
@@ -59665,9 +59777,9 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
59665
59777
  auth = urlUsername + ":" + urlPassword;
59666
59778
  }
59667
59779
  auth && headers.delete("authorization");
59668
- let path4;
59780
+ let path5;
59669
59781
  try {
59670
- path4 = buildURL(
59782
+ path5 = buildURL(
59671
59783
  parsed.pathname + parsed.search,
59672
59784
  config.params,
59673
59785
  config.paramsSerializer
@@ -59685,7 +59797,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
59685
59797
  false
59686
59798
  );
59687
59799
  const options = Object.assign(/* @__PURE__ */ Object.create(null), {
59688
- path: path4,
59800
+ path: path5,
59689
59801
  method,
59690
59802
  headers: toByteStringHeaderObject(headers),
59691
59803
  agents: { http: config.httpAgent, https: config.httpsAgent },
@@ -60028,14 +60140,14 @@ var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PUR
60028
60140
  var cookies_default = platform_default.hasStandardBrowserEnv ? (
60029
60141
  // Standard browser envs support document.cookie
60030
60142
  {
60031
- write(name, value, expires, path4, domain, secure, sameSite) {
60143
+ write(name, value, expires, path5, domain, secure, sameSite) {
60032
60144
  if (typeof document === "undefined") return;
60033
60145
  const cookie = [`${name}=${encodeURIComponent(value)}`];
60034
60146
  if (utils_default.isNumber(expires)) {
60035
60147
  cookie.push(`expires=${new Date(expires).toUTCString()}`);
60036
60148
  }
60037
- if (utils_default.isString(path4)) {
60038
- cookie.push(`path=${path4}`);
60149
+ if (utils_default.isString(path5)) {
60150
+ cookie.push(`path=${path5}`);
60039
60151
  }
60040
60152
  if (utils_default.isString(domain)) {
60041
60153
  cookie.push(`domain=${domain}`);
@@ -60053,9 +60165,9 @@ var cookies_default = platform_default.hasStandardBrowserEnv ? (
60053
60165
  const cookies = document.cookie.split(";");
60054
60166
  for (let i = 0; i < cookies.length; i++) {
60055
60167
  const cookie = cookies[i].replace(/^\s+/, "");
60056
- const eq2 = cookie.indexOf("=");
60057
- if (eq2 !== -1 && cookie.slice(0, eq2) === name) {
60058
- return decodeURIComponent(cookie.slice(eq2 + 1));
60168
+ const eq3 = cookie.indexOf("=");
60169
+ if (eq3 !== -1 && cookie.slice(0, eq3) === name) {
60170
+ return decodeURIComponent(cookie.slice(eq3 + 1));
60059
60171
  }
60060
60172
  }
60061
60173
  return null;
@@ -61861,7 +61973,7 @@ var init_deployment_addresses = __esm2({
61861
61973
  LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9",
61862
61974
  CircuitBreakerModule: "0xF7b545d3a4Ee056D06909AB367E2F7bFFE3cB1BC",
61863
61975
  AdminModule: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
61864
- PositionManagerViews: "0x9225647a30bbACA4Acc0491B786869036914242e",
61976
+ PositionManagerViews: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
61865
61977
  PositionManager: "0x12A1836e56139ccaD8722B89519d84233efc224B",
61866
61978
  OperationAuthorizationRegistry: "0xD4505645b724754f5170a2027804a4265e860d44",
61867
61979
  ContractVersionRegistry: "0x5e18f77d01940dA5B1D986D373D9A6ad0767008d",
@@ -61939,13 +62051,13 @@ var init_deployment_addresses = __esm2({
61939
62051
  block: 25472957
61940
62052
  },
61941
62053
  PositionManager: {
61942
- previousImplementation: "0x9f52BaBB40FbFC5863e45B1A4014cB433950c684",
61943
- newImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
61944
- upgradedAt: "2026-07-06T08:42:47.000Z",
61945
- upgradedBy: "AdminModule/Safe audit-batch upgradeToAndCall; executed by 0x2002827d34A781883Ec4c83c36ECC140c3911F2B in tx 0xa1fbe31cb71736514a868e681573dff22c9fab91d69cec157a24a30e29eadbe6 (block 25472368)",
61946
- reason: "Reconciled from chain \u2014 mainnet audit rollout batch (cross-ref onchain-auth/.safe-batches/mainnet-audit-execute.json)",
61947
- executeTx: "0xa1fbe31cb71736514a868e681573dff22c9fab91d69cec157a24a30e29eadbe6",
61948
- block: 25472368
62054
+ previousImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
62055
+ newImplementation: "0x2e7170d6Fb15A876dB726732e72e63109bcB916d",
62056
+ upgradedAt: "2026-08-03T08:34:23.000Z",
62057
+ 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)",
62058
+ 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.",
62059
+ executeTx: "0xf1f8d5fc13f45d7a3f932bf1a2d6e29381fdd41cd31298ad785bf7688df07fe6",
62060
+ block: 25673200
61949
62061
  },
61950
62062
  LoanOperationsManagerModule: {
61951
62063
  previousImplementation: "0x56671D671e492Dae625413d463D47605Cf54edf6",
@@ -61989,6 +62101,16 @@ var init_deployment_addresses = __esm2({
61989
62101
  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.",
61990
62102
  executeTx: "0xf0f237f6c4e958c37de556571908283c59c3fba6ebf9fa3cefb956f37e315a10",
61991
62103
  block: 25669024
62104
+ },
62105
+ PositionManagerViews: {
62106
+ previousImplementation: "0x9225647a30bbACA4Acc0491B786869036914242e",
62107
+ newImplementation: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
62108
+ proxy: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
62109
+ upgradedAt: "2026-08-03T08:34:23.000Z",
62110
+ 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",
62111
+ 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.",
62112
+ executeTx: "0xf1f8d5fc13f45d7a3f932bf1a2d6e29381fdd41cd31298ad785bf7688df07fe6",
62113
+ block: 25673200
61992
62114
  }
61993
62115
  },
61994
62116
  latestEnv: {
@@ -62022,10 +62144,10 @@ var init_deployment_addresses = __esm2({
62022
62144
  ADMIN_MODULE_IMPL: "0xb4C5C7E051A1e672F014B25CB5D55B225Aa0D512",
62023
62145
  BTC_SPEND_AUTHORIZER: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
62024
62146
  BTC_SPEND_AUTHORIZER_IMPL: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
62025
- POSITION_MANAGER_VIEWS: "0x9225647a30bbACA4Acc0491B786869036914242e",
62026
- POSITION_MANAGER_VIEWS_IMPL: "0x9225647a30bbACA4Acc0491B786869036914242e",
62147
+ POSITION_MANAGER_VIEWS: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
62148
+ POSITION_MANAGER_VIEWS_IMPL: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
62027
62149
  POSITION_MANAGER: "0x12A1836e56139ccaD8722B89519d84233efc224B",
62028
- POSITION_MANAGER_IMPL: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
62150
+ POSITION_MANAGER_IMPL: "0x2e7170d6Fb15A876dB726732e72e63109bcB916d",
62029
62151
  LOAN_OPERATIONS_MANAGER_MODULE: "0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",
62030
62152
  LOAN_OPERATIONS_MANAGER_MODULE_IMPL: "0x7d90aAB4466f59BA9aC9C7a9BF14dC53734336e7",
62031
62153
  UPGRADE_VALIDATOR: "0xC46Ae71F22e3741A6CF46E399aE914C4868fEbed",
@@ -62051,7 +62173,7 @@ var init_deployment_addresses = __esm2({
62051
62173
  LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9",
62052
62174
  CircuitBreakerModule: "0xF7b545d3a4Ee056D06909AB367E2F7bFFE3cB1BC",
62053
62175
  AdminModule: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
62054
- PositionManagerViews: "0x9225647a30bbACA4Acc0491B786869036914242e",
62176
+ PositionManagerViews: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
62055
62177
  PositionManager: "0x12A1836e56139ccaD8722B89519d84233efc224B",
62056
62178
  OperationAuthorizationRegistry: "0xD4505645b724754f5170a2027804a4265e860d44",
62057
62179
  ContractVersionRegistry: "0x5e18f77d01940dA5B1D986D373D9A6ad0767008d",
@@ -67875,6 +67997,7 @@ function sessionStoreKey(address, chainId, endpoint) {
67875
67997
  return STORE_PREFIX + `${address.trim().toLowerCase()}:${chainId}:${endpoint.replace(/\/+$/, "")}`;
67876
67998
  }
67877
67999
  var PENDING_ENVELOPE_TTL_SECONDS = 8 * 60;
68000
+ var EOA_PENDING_ENVELOPE_TTL_SECONDS = 60;
67878
68001
  function pendingEnvelopeKey(sessionKey) {
67879
68002
  return sessionKey + ":pending";
67880
68003
  }
@@ -67922,7 +68045,7 @@ var LocalStorageSessionStore = class {
67922
68045
  } catch {
67923
68046
  }
67924
68047
  }
67925
- loadPending(key) {
68048
+ loadPending(key, maxAgeSeconds = PENDING_ENVELOPE_TTL_SECONDS) {
67926
68049
  let raw;
67927
68050
  try {
67928
68051
  raw = window.localStorage.getItem(pendingEnvelopeKey(key));
@@ -67939,7 +68062,7 @@ var LocalStorageSessionStore = class {
67939
68062
  return null;
67940
68063
  }
67941
68064
  const nowSec = Math.floor(Date.now() / 1e3);
67942
- if (!isPendingEnvelopeShape(parsed) || nowSec >= parsed.issuedAt + PENDING_ENVELOPE_TTL_SECONDS) {
68065
+ if (!isPendingEnvelopeShape(parsed) || nowSec >= parsed.issuedAt + maxAgeSeconds) {
67943
68066
  this.clearPending(key);
67944
68067
  return null;
67945
68068
  }
@@ -67973,12 +68096,12 @@ var MemorySessionStore = class {
67973
68096
  clear(key) {
67974
68097
  this.entries.delete(key);
67975
68098
  }
67976
- loadPending(key) {
68099
+ loadPending(key, maxAgeSeconds = PENDING_ENVELOPE_TTL_SECONDS) {
67977
68100
  const envelope = this.pending.get(key);
67978
68101
  if (!envelope)
67979
68102
  return null;
67980
68103
  const nowSec = Math.floor(Date.now() / 1e3);
67981
- if (nowSec >= envelope.issuedAt + PENDING_ENVELOPE_TTL_SECONDS) {
68104
+ if (nowSec >= envelope.issuedAt + maxAgeSeconds) {
67982
68105
  this.pending.delete(key);
67983
68106
  return null;
67984
68107
  }
@@ -68010,15 +68133,23 @@ var REFRESH_LEEWAY_SECONDS = 30;
68010
68133
  var LOGIN_RETRY_BASE_MS = 3e4;
68011
68134
  var LOGIN_RETRY_MAX_MS = 5 * 6e4;
68012
68135
  var ServerLoginError = class extends Error {
68013
- constructor(message, status) {
68136
+ constructor(message, status, reason) {
68014
68137
  super(message);
68015
68138
  this.status = status;
68139
+ this.reason = reason;
68016
68140
  this.name = "ServerLoginError";
68017
68141
  }
68018
68142
  };
68019
68143
  function isLoginRejection(error) {
68020
68144
  return error instanceof ServerLoginError && error.status >= 400 && error.status < 500 && error.status !== 429;
68021
68145
  }
68146
+ var SPENT_ENVELOPE_REASONS = /* @__PURE__ */ new Set(["replayed_nonce", "expired_issuedAt"]);
68147
+ function isSpentEnvelope(error) {
68148
+ if (!isLoginRejection(error))
68149
+ return false;
68150
+ const { reason, status } = error;
68151
+ return reason ? SPENT_ENVELOPE_REASONS.has(reason) : status === 409;
68152
+ }
68022
68153
  var ServerSession = class {
68023
68154
  signer;
68024
68155
  serviceEndpoint;
@@ -68049,6 +68180,12 @@ var ServerSession = class {
68049
68180
  * `clear()` can drop the persisted token without an async address lookup.
68050
68181
  */
68051
68182
  lastStoreKey = null;
68183
+ /**
68184
+ * Whether the signer is a smart-contract wallet, memoized after the first
68185
+ * `eth_getCode`. Decides which of the server's two first-use windows bounds
68186
+ * envelope reuse; a signer cannot change kind for the life of the session.
68187
+ */
68188
+ contractSigner = null;
68052
68189
  constructor(opts) {
68053
68190
  assertSafeServiceEndpoint(opts.serviceEndpoint);
68054
68191
  this.signer = opts.signer;
@@ -68247,6 +68384,34 @@ var ServerSession = class {
68247
68384
  return null;
68248
68385
  }
68249
68386
  }
68387
+ /**
68388
+ * How long a pending envelope for THIS signer may be reused, in seconds.
68389
+ *
68390
+ * The server grants an EOA 120s to make an envelope's first use and a contract
68391
+ * wallet 600s, so one local TTL is necessarily wrong for one of them. Deployed
68392
+ * code has bytecode; an EOA does not — one `eth_getCode`, memoized, settles it.
68393
+ *
68394
+ * Reports the CONTRACT window when it cannot tell, which is the behavior that
68395
+ * shipped before the split. The asymmetry is intended: guessing "EOA" for a
68396
+ * Safe hands it a new message and orphans the owner signatures already
68397
+ * collected, while guessing "contract" for an EOA now costs one rejected
68398
+ * attempt, because a rejection clears the envelope.
68399
+ */
68400
+ async pendingEnvelopeTtl() {
68401
+ if (this.contractSigner === null) {
68402
+ try {
68403
+ const provider = this.signer.provider;
68404
+ if (!provider)
68405
+ return PENDING_ENVELOPE_TTL_SECONDS;
68406
+ const address = await this.signer.getAddress();
68407
+ const code = await provider.getCode(address);
68408
+ this.contractSigner = typeof code === "string" && code !== "0x";
68409
+ } catch {
68410
+ return PENDING_ENVELOPE_TTL_SECONDS;
68411
+ }
68412
+ }
68413
+ return this.contractSigner ? PENDING_ENVELOPE_TTL_SECONDS : EOA_PENDING_ENVELOPE_TTL_SECONDS;
68414
+ }
68250
68415
  async getOrRefresh() {
68251
68416
  const nowSec = this.now();
68252
68417
  if (this.cached && this.cached.expiresAt - REFRESH_LEEWAY_SECONDS > nowSec) {
@@ -68268,10 +68433,10 @@ var ServerSession = class {
68268
68433
  }
68269
68434
  this.onSignaturePrompt?.();
68270
68435
  let session;
68436
+ const store = this.store;
68437
+ const storeKey = store ? this.lastStoreKey : null;
68271
68438
  try {
68272
- const store = this.store;
68273
- const storeKey = store ? this.lastStoreKey : null;
68274
- const reuse = storeKey ? store.loadPending?.(storeKey) ?? void 0 : void 0;
68439
+ const reuse = storeKey ? store.loadPending?.(storeKey, await this.pendingEnvelopeTtl()) ?? void 0 : void 0;
68275
68440
  const payload = await buildSignedLoginPayload(
68276
68441
  this.signer,
68277
68442
  this.chainId,
@@ -68294,6 +68459,9 @@ var ServerSession = class {
68294
68459
  this.onSignatureResolved?.(true);
68295
68460
  } catch (error) {
68296
68461
  this.onSignatureResolved?.(false);
68462
+ if (storeKey && isSpentEnvelope(error)) {
68463
+ store.clearPending?.(storeKey);
68464
+ }
68297
68465
  const failures = (this.promptBackoff?.failures ?? 0) + 1;
68298
68466
  this.promptBackoff = {
68299
68467
  failures,
@@ -68322,9 +68490,17 @@ var ServerSession = class {
68322
68490
  });
68323
68491
  if (!res.ok) {
68324
68492
  const detail = await res.text().catch(() => "");
68493
+ let reason;
68494
+ try {
68495
+ const parsed = JSON.parse(detail);
68496
+ if (typeof parsed?.reason === "string")
68497
+ reason = parsed.reason;
68498
+ } catch {
68499
+ }
68325
68500
  throw new ServerLoginError(
68326
68501
  `lit-ops-server login failed: HTTP ${res.status} ${detail.slice(0, 200)}`,
68327
- res.status
68502
+ res.status,
68503
+ reason
68328
68504
  );
68329
68505
  }
68330
68506
  const body = await res.json();
@@ -73898,7 +74074,7 @@ var DiamondHandsGraph = class {
73898
74074
  async getPSMConfiguration() {
73899
74075
  const query = `
73900
74076
  query GetPSMConfiguration {
73901
- psmConfiguration(id: "psm") {
74077
+ psmConfiguration: psmconfiguration(id: "psm") {
73902
74078
  id
73903
74079
  version
73904
74080
  redeemEnabled
@@ -74020,7 +74196,7 @@ var DiamondHandsGraph = class {
74020
74196
  const whereClause = whereConditions.length > 0 ? `where: { ${whereConditions.join(", ")} }` : "";
74021
74197
  const query = `
74022
74198
  query GetPSMTransactions($first: Int!, $skip: Int!) {
74023
- psmTransactions(${whereClause}, first: $first, skip: $skip, orderBy: timestamp, orderDirection: desc) {
74199
+ psmTransactions: psmtransactions(${whereClause}, first: $first, skip: $skip, orderBy: timestamp, orderDirection: desc) {
74024
74200
  id
74025
74201
  type
74026
74202
  user
@@ -74055,7 +74231,7 @@ var DiamondHandsGraph = class {
74055
74231
  const whereClause = whereConditions.length > 0 ? `where: { ${whereConditions.join(", ")} }` : "";
74056
74232
  const query = `
74057
74233
  query GetPSMDailyMetrics($first: Int!) {
74058
- psmDailyMetrics(${whereClause}, first: $first, orderBy: date, orderDirection: desc) {
74234
+ psmDailyMetrics: psmdailyMetrics(${whereClause}, first: $first, orderBy: date, orderDirection: desc) {
74059
74235
  id
74060
74236
  date
74061
74237
  totalSwapVolume
@@ -74779,7 +74955,7 @@ var DiamondHandsGraph = class {
74779
74955
  }` : ""}
74780
74956
 
74781
74957
  ${includeKind("psm") ? `
74782
- psmTransactions(
74958
+ psmTransactions: psmtransactions(
74783
74959
  ${buildTimeWhereClause()}
74784
74960
  first: $limit, orderBy: timestamp, orderDirection: $orderDirection
74785
74961
  ) {
@@ -85800,23 +85976,28 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85800
85976
  * @throws if timeout is reached before subgraph catches up
85801
85977
  */
85802
85978
  // ============================================================================
85803
- // HIGH-LEVEL API - Agent Delegation (auto-renew) — SEPOLIA ONLY
85979
+ // HIGH-LEVEL API - Agent Delegation (auto-renew)
85804
85980
  // ============================================================================
85805
- /** Guard: the AgentDelegationRegistry MVP is deployed on Sepolia only. */
85806
- async assertAgentDelegationSepolia() {
85807
- const chainId = Number((await this.getProviderOrThrow().getNetwork()).chainId);
85808
- if (chainId !== 11155111) {
85809
- throw new SDKError({
85810
- message: `Agent auto-renew delegation is Sepolia-only (chainId 11155111); got ${chainId}`,
85811
- category: "NETWORK",
85812
- severity: "HIGH"
85813
- /* HIGH */
85814
- });
85815
- }
85981
+ /**
85982
+ * Guard: resolve the AgentDelegationRegistry for the configured network.
85983
+ *
85984
+ * Deployment presence IS the availability test — there is deliberately no chainId
85985
+ * allow-list here. The registry is deployed per network (Sepolia 2026-07, mainnet
85986
+ * 2026-08 agent-stack release) and `getNetworkConfig` populates the address from the
85987
+ * generated deployment table, so a chain without a deployment resolves to `""` and
85988
+ * fails closed below. Adding a chain therefore needs no SDK code change — which is
85989
+ * exactly how the previous hardcoded `chainId !== 11155111` gate went stale and kept
85990
+ * the mainnet toggle dark after the registry shipped.
85991
+ *
85992
+ * Callers that need the availability answer WITHOUT throwing (e.g. to decide whether to
85993
+ * render a toggle at all) should ask the deployment table directly rather than calling this
85994
+ * and catching — `ALL_DEPLOYMENTS` is published on the `@gvnrdao/dh-sdk/deployments` subpath.
85995
+ */
85996
+ agentDelegationRegistryOrThrow() {
85816
85997
  const addr = this.config.contractAddresses?.agentDelegationRegistry;
85817
85998
  if (!addr) {
85818
85999
  throw new SDKError({
85819
- message: "AgentDelegationRegistry address not configured \u2014 provide contractAddresses.agentDelegationRegistry",
86000
+ message: "AgentDelegationRegistry is not available on this network \u2014 no deployment address is configured (contractAddresses.agentDelegationRegistry)",
85820
86001
  category: "CONFIGURATION",
85821
86002
  severity: "HIGH"
85822
86003
  /* HIGH */
@@ -85829,7 +86010,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85829
86010
  * Pure view — no signer required.
85830
86011
  */
85831
86012
  async getAutoRenewStatus(positionId, user) {
85832
- const addr = await this.assertAgentDelegationSepolia();
86013
+ const addr = this.agentDelegationRegistryOrThrow();
85833
86014
  const registry = AgentDelegationRegistry__factory.connect(addr, this.getProviderOrThrow());
85834
86015
  const pid = this.toBytes32(positionId);
85835
86016
  const grant = await registry.getLoanGrant(pid);
@@ -85849,7 +86030,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85849
86030
  * registers it, then records the position's renew grant. Borrower-signed.
85850
86031
  */
85851
86032
  async enableAutoRenew(positionId, options) {
85852
- const addr = await this.assertAgentDelegationSepolia();
86033
+ const addr = this.agentDelegationRegistryOrThrow();
85853
86034
  const pdrAddr = this.config.contractAddresses?.positionDelegateRegistry;
85854
86035
  if (!pdrAddr) {
85855
86036
  throw new SDKError({
@@ -85890,7 +86071,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
85890
86071
  }
85891
86072
  /** Disable auto-renew delegation for a position (clears the grant). Borrower-signed. */
85892
86073
  async disableAutoRenew(positionId) {
85893
- const addr = await this.assertAgentDelegationSepolia();
86074
+ const addr = this.agentDelegationRegistryOrThrow();
85894
86075
  const signer = this.getSignerOrThrow();
85895
86076
  const user = await signer.getAddress();
85896
86077
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
@@ -87311,6 +87492,12 @@ var LitOpsSession = class {
87311
87492
  address() {
87312
87493
  return this.wallet.address;
87313
87494
  }
87495
+ /** A JWT is cached and not about to expire — reads in external mode consult this
87496
+ * instead of `token()` so they NEVER summon the wallet (plan 10 A0.7). */
87497
+ hasValidToken() {
87498
+ const now = Math.floor(Date.now() / 1e3);
87499
+ return this.cached !== null && this.cached.expiresAtSec - REFRESH_LEEWAY_SEC > now;
87500
+ }
87314
87501
  /** A valid Bearer token, logging in (or re-logging) as needed. Throws with a legible
87315
87502
  * message on failure — the gateway maps it to the taxonomy. */
87316
87503
  async token() {
@@ -87368,9 +87555,240 @@ function decodeJwtExp(token) {
87368
87555
  }
87369
87556
 
87370
87557
  // src/boundary/upstream/real/write-ops.ts
87558
+ var import_ethers33 = require("ethers");
87559
+
87560
+ // src/signer/types.ts
87561
+ var OperationDeclined = class extends Error {
87562
+ };
87563
+
87564
+ // src/boundary/upstream/real/write-ops.ts
87565
+ init_tx_validator();
87566
+
87567
+ // src/boundary/upstream/shared/external-bridge/page-crypto.ts
87371
87568
  var import_ethers32 = require("ethers");
87569
+ var PERSONAL_SIGN_LAYOUTS = {
87570
+ "dh-op-envelope-v1": {
87571
+ types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87572
+ fieldOrder: ["positionId", "timestamp", "chainId", "amount", "action"],
87573
+ hashUtf8Fields: ["action"]
87574
+ }
87575
+ };
87576
+ function hashForLayout(layout, fields) {
87577
+ const def = PERSONAL_SIGN_LAYOUTS[layout];
87578
+ if (!def) throw new Error(`page-crypto: unknown layout "${layout}"`);
87579
+ const hashUtf8 = new Set(def.hashUtf8Fields);
87580
+ const values = def.fieldOrder.map((name) => {
87581
+ const raw = fields[name];
87582
+ if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
87583
+ return hashUtf8.has(name) ? import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(raw)) : raw;
87584
+ });
87585
+ return import_ethers32.ethers.solidityPackedKeccak256(def.types, values);
87586
+ }
87587
+ var PAGE_CRYPTO_JS = `"use strict";
87588
+ (function () {
87589
+ // keccak-f[1600] \u2014 25 lanes of 64-bit BigInt, state[x + 5*y]. Validated bit-for-bit
87590
+ // against ethers.keccak256 across empty/short/rate-boundary inputs (page-crypto.test.ts).
87591
+ var MASK64 = (1n << 64n) - 1n;
87592
+
87593
+ function rotl64(x, n) {
87594
+ x &= MASK64;
87595
+ var nn = BigInt(n % 64);
87596
+ if (nn === 0n) return x;
87597
+ return ((x << nn) | (x >> (64n - nn))) & MASK64;
87598
+ }
87599
+
87600
+ var RC = [
87601
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
87602
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
87603
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
87604
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
87605
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
87606
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n
87607
+ ];
87608
+
87609
+ // r[x][y] rotation offsets, flat index x + 5*y.
87610
+ var ROT = [
87611
+ 0, 1, 62, 28, 27,
87612
+ 36, 44, 6, 55, 20,
87613
+ 3, 10, 43, 25, 39,
87614
+ 41, 45, 15, 21, 8,
87615
+ 18, 2, 61, 56, 14
87616
+ ];
87617
+
87618
+ function keccakF1600(state) {
87619
+ for (var round = 0; round < 24; round++) {
87620
+ var C = new Array(5);
87621
+ for (var x = 0; x < 5; x++) {
87622
+ C[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20];
87623
+ }
87624
+ var D = new Array(5);
87625
+ for (var x2 = 0; x2 < 5; x2++) {
87626
+ D[x2] = C[(x2 + 4) % 5] ^ rotl64(C[(x2 + 1) % 5], 1);
87627
+ }
87628
+ for (var x3 = 0; x3 < 5; x3++) {
87629
+ for (var y = 0; y < 5; y++) {
87630
+ state[x3 + 5 * y] ^= D[x3];
87631
+ }
87632
+ }
87633
+ var B = new Array(25);
87634
+ for (var x4 = 0; x4 < 5; x4++) {
87635
+ for (var y2 = 0; y2 < 5; y2++) {
87636
+ var newX = y2;
87637
+ var newY = (2 * x4 + 3 * y2) % 5;
87638
+ B[newX + 5 * newY] = rotl64(state[x4 + 5 * y2], ROT[x4 + 5 * y2]);
87639
+ }
87640
+ }
87641
+ for (var x5 = 0; x5 < 5; x5++) {
87642
+ for (var y3 = 0; y3 < 5; y3++) {
87643
+ var idx = x5 + 5 * y3;
87644
+ state[idx] = (B[idx] ^ (~B[(x5 + 1) % 5 + 5 * y3] & B[(x5 + 2) % 5 + 5 * y3])) & MASK64;
87645
+ }
87646
+ }
87647
+ state[0] = (state[0] ^ RC[round]) & MASK64;
87648
+ }
87649
+ }
87650
+
87651
+ function keccak256Bytes(bytes) {
87652
+ var rateBytes = 136; // 1088-bit rate (keccak256: capacity 512 bits)
87653
+ var state = new Array(25).fill(0n);
87654
+
87655
+ // Original-Keccak multi-rate padding (pad10*1, domain byte 0x01 \u2014 NOT NIST SHA3's 0x06).
87656
+ var padLen = rateBytes - (bytes.length % rateBytes);
87657
+ var padded = new Uint8Array(bytes.length + padLen);
87658
+ padded.set(bytes);
87659
+ padded[bytes.length] ^= 0x01;
87660
+ padded[padded.length - 1] ^= 0x80;
87661
+
87662
+ for (var off = 0; off < padded.length; off += rateBytes) {
87663
+ for (var i = 0; i < rateBytes / 8; i++) {
87664
+ var lane = 0n;
87665
+ for (var b = 7; b >= 0; b--) {
87666
+ lane = (lane << 8n) | BigInt(padded[off + i * 8 + b]);
87667
+ }
87668
+ state[i] ^= lane;
87669
+ }
87670
+ keccakF1600(state);
87671
+ }
87672
+
87673
+ var out = new Uint8Array(32);
87674
+ for (var j = 0; j < 4; j++) {
87675
+ var laneOut = state[j];
87676
+ for (var b2 = 0; b2 < 8; b2++) {
87677
+ out[j * 8 + b2] = Number(laneOut & 0xffn);
87678
+ laneOut >>= 8n;
87679
+ }
87680
+ }
87681
+ return out;
87682
+ }
87683
+
87684
+ function bytesToHex(bytes) {
87685
+ var hex = "0x";
87686
+ for (var i = 0; i < bytes.length; i++) {
87687
+ hex += bytes[i].toString(16).padStart(2, "0");
87688
+ }
87689
+ return hex;
87690
+ }
87691
+
87692
+ function hexToBytes(hex) {
87693
+ if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) {
87694
+ throw new Error("dhPageCrypto: not a 0x-hex string: " + String(hex));
87695
+ }
87696
+ var clean = hex.slice(2);
87697
+ if (clean.length % 2 !== 0) {
87698
+ throw new Error("dhPageCrypto: odd-length hex string: " + hex);
87699
+ }
87700
+ var out = new Uint8Array(clean.length / 2);
87701
+ for (var i = 0; i < out.length; i++) {
87702
+ out[i] = parseInt(clean.substr(i * 2, 2), 16);
87703
+ }
87704
+ return out;
87705
+ }
87706
+
87707
+ function keccak256HexOfBytes(hexStr) {
87708
+ return bytesToHex(keccak256Bytes(hexToBytes(hexStr)));
87709
+ }
87710
+
87711
+ function keccak256Utf8(str) {
87712
+ return bytesToHex(keccak256Bytes(new TextEncoder().encode(String(str))));
87713
+ }
87714
+
87715
+ function uint256ToBytes32(decStr) {
87716
+ if (typeof decStr !== "string" || !/^[0-9]+$/.test(decStr)) {
87717
+ throw new Error("dhPageCrypto: not a decimal uint256 string: " + String(decStr));
87718
+ }
87719
+ var n = BigInt(decStr);
87720
+ if (n > (2n ** 256n) - 1n) {
87721
+ throw new Error("dhPageCrypto: uint256 out of range: " + decStr);
87722
+ }
87723
+ var bytes = new Uint8Array(32);
87724
+ for (var i = 31; i >= 0; i--) {
87725
+ bytes[i] = Number(n & 0xffn);
87726
+ n >>= 8n;
87727
+ }
87728
+ return bytes;
87729
+ }
87730
+
87731
+ function requireBytes32(hex, fieldName) {
87732
+ var bytes = hexToBytes(hex);
87733
+ if (bytes.length !== 32) {
87734
+ throw new Error("dhPageCrypto: field \\"" + fieldName + "\\" must be exactly 32 bytes, got " + bytes.length);
87735
+ }
87736
+ return bytes;
87737
+ }
87738
+
87739
+ // Embedded verbatim from PERSONAL_SIGN_LAYOUTS (page-crypto.ts) \u2014 see the anti-drift note
87740
+ // in that file's header comment. Do not hand-edit; this is generated at module load.
87741
+ var PERSONAL_SIGN_LAYOUTS = ${JSON.stringify(PERSONAL_SIGN_LAYOUTS)};
87742
+
87743
+ function packAndHash(layout, fields) {
87744
+ var def = PERSONAL_SIGN_LAYOUTS[layout];
87745
+ if (!def) {
87746
+ throw new Error("dhPageCrypto: unknown layout \\"" + layout + "\\"");
87747
+ }
87748
+ var hashUtf8 = {};
87749
+ for (var h = 0; h < def.hashUtf8Fields.length; h++) {
87750
+ hashUtf8[def.hashUtf8Fields[h]] = true;
87751
+ }
87752
+ var parts = [];
87753
+ var totalLen = 0;
87754
+ for (var i = 0; i < def.fieldOrder.length; i++) {
87755
+ var name = def.fieldOrder[i];
87756
+ var type = def.types[i];
87757
+ var raw = fields ? fields[name] : undefined;
87758
+ if (raw === undefined || raw === null) {
87759
+ throw new Error("dhPageCrypto: layout \\"" + layout + "\\" missing field \\"" + name + "\\"");
87760
+ }
87761
+ var valueHex = hashUtf8[name] ? keccak256Utf8(String(raw)) : raw;
87762
+ var part;
87763
+ if (type === "bytes32") {
87764
+ part = requireBytes32(valueHex, name);
87765
+ } else if (type === "uint256") {
87766
+ part = uint256ToBytes32(valueHex);
87767
+ } else {
87768
+ throw new Error("dhPageCrypto: unsupported packed type \\"" + type + "\\" in layout \\"" + layout + "\\"");
87769
+ }
87770
+ parts.push(part);
87771
+ totalLen += part.length;
87772
+ }
87773
+ var packed = new Uint8Array(totalLen);
87774
+ var offset = 0;
87775
+ for (var p = 0; p < parts.length; p++) {
87776
+ packed.set(parts[p], offset);
87777
+ offset += parts[p].length;
87778
+ }
87779
+ return keccak256HexOfBytes(bytesToHex(packed));
87780
+ }
87781
+
87782
+ globalThis.dhPageCrypto = {
87783
+ keccak256HexOfBytes: keccak256HexOfBytes,
87784
+ keccak256Utf8: keccak256Utf8,
87785
+ packAndHash: packAndHash
87786
+ };
87787
+ })();
87788
+ `;
87372
87789
 
87373
87790
  // src/boundary/upstream/real/validation-context.ts
87791
+ init_tx_validator();
87374
87792
  function buildValidationContext(network, chainId) {
87375
87793
  const sdkKey = chainId === 31337 ? "localhost" : chainId === 11155111 ? "sepolia" : network.toLowerCase();
87376
87794
  const contracts = getContractsByNetwork(sdkKey);
@@ -87390,14 +87808,10 @@ function psmMainnetWriteRefusal(network, chainId) {
87390
87808
  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.`
87391
87809
  };
87392
87810
  }
87393
- var QUANTUM_SECONDS3 = 60;
87394
87811
  var SOURCE5 = "real-ops";
87395
- function nextQuantumTimestamp() {
87396
- const now = Math.floor(Date.now() / 1e3);
87397
- return Math.floor(now / QUANTUM_SECONDS3) * QUANTUM_SECONDS3 + QUANTUM_SECONDS3;
87398
- }
87812
+ var OP_LAYOUT = "dh-op-envelope-v1";
87399
87813
  function randomNonceHex() {
87400
- return "0x" + Buffer.from(import_ethers32.ethers.randomBytes(16)).toString("hex");
87814
+ return "0x" + Buffer.from(import_ethers33.ethers.randomBytes(16)).toString("hex");
87401
87815
  }
87402
87816
  async function postJson(url2, body, headers) {
87403
87817
  const res = await fetch(url2, {
@@ -87437,15 +87851,55 @@ function buildWriteOps(deps) {
87437
87851
  })
87438
87852
  );
87439
87853
  const failed = (op, e) => upFail({ kind: "unavailable", source: SOURCE5, message: `${op} failed to reach lit-ops`, raw: String(e) });
87854
+ 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) });
87855
+ function opAuthSpec(p) {
87856
+ return {
87857
+ action: p.action,
87858
+ layout: OP_LAYOUT,
87859
+ stamp: (quantumTs) => {
87860
+ const fields = {
87861
+ positionId: p.positionId,
87862
+ timestamp: String(quantumTs),
87863
+ chainId: String(chainId),
87864
+ amount: p.amount.toString(),
87865
+ action: p.action
87866
+ };
87867
+ return { fields, hashHex: hashForLayout(OP_LAYOUT, fields), card: p.card(fields) };
87868
+ }
87869
+ };
87870
+ }
87871
+ function toCardPayload(tx2) {
87872
+ return {
87873
+ to: String(tx2["to"] ?? ""),
87874
+ data: String(tx2["data"] ?? "0x"),
87875
+ value: tx2["value"] != null ? import_ethers33.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
87876
+ chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
87877
+ };
87878
+ }
87440
87879
  async function executeAndBroadcast(p) {
87441
- const userSignature = await dhSigner.signAuthMessage(p.messageHash);
87880
+ let authRes;
87881
+ try {
87882
+ authRes = await dhSigner.signAuthorization(p.spec);
87883
+ } catch (e) {
87884
+ return submitFailure(`${p.op} authorization`, e);
87885
+ }
87886
+ const digest = p.spec.stamp(authRes.quantumTs).hashHex;
87442
87887
  const borrowerAddress = await dhSigner.getBorrowerAddress();
87443
- const headers = await session.authHeader();
87888
+ let headers;
87889
+ try {
87890
+ headers = await session.authHeader();
87891
+ } catch (e) {
87892
+ return upFail({
87893
+ kind: "unavailable",
87894
+ source: SOURCE5,
87895
+ message: `${p.op} could not establish the lit-ops login session (broker unreachable, or throttling logins): ${e instanceof Error ? e.message : String(e)}`
87896
+ });
87897
+ }
87444
87898
  let execJson;
87445
87899
  try {
87446
87900
  execJson = await postJson(
87447
87901
  `${config.serviceEndpoint}/api/lit/${p.op}/execute`,
87448
- { authMessage: p.authMessage, userSignature, borrowerAddress },
87902
+ { authMessage: p.authMessage(authRes.quantumTs), userSignature: authRes.signature, borrowerAddress },
87449
87903
  headers
87450
87904
  );
87451
87905
  } catch (e) {
@@ -87469,12 +87923,13 @@ function buildWriteOps(deps) {
87469
87923
  } catch (e) {
87470
87924
  return upFail({ kind: "rejected", source: SOURCE5, message: `approve tx failed the M-9 whitelist: ${e.message}` });
87471
87925
  }
87472
- const signedApprove = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedApproveTx));
87473
87926
  try {
87474
- const approveJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx: signedApprove }, headers);
87475
- if (approveJson["success"] !== true) return declined(`${p.op} (UCD approve)`, approveJson["error"]);
87927
+ await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedApproveTx), {
87928
+ action: `${p.spec.action} (UCD approve)`,
87929
+ card: cardForTx(toCardPayload(unsignedApproveTx))
87930
+ });
87476
87931
  } catch (e) {
87477
- return failed(`${p.op} (UCD approve broadcast)`, e);
87932
+ return submitFailure(`${p.op} (UCD approve)`, e);
87478
87933
  }
87479
87934
  }
87480
87935
  }
@@ -87487,23 +87942,18 @@ function buildWriteOps(deps) {
87487
87942
  } catch (e) {
87488
87943
  return upFail({ kind: "rejected", source: SOURCE5, message: `unsigned tx failed the M-9 whitelist: ${e.message}` });
87489
87944
  }
87490
- const signedTx = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedTx));
87491
- let broadcastJson;
87945
+ let submitted;
87492
87946
  try {
87493
87947
  const meta = p.broadcastMeta(data);
87494
- broadcastJson = await postJson(
87495
- `${config.serviceEndpoint}/api/lit/broadcast`,
87496
- { signedTx, ...meta ? { [p.broadcastMetaKey]: meta } : {} },
87497
- headers
87498
- );
87948
+ submitted = await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedTx), {
87949
+ action: p.spec.action,
87950
+ card: cardForTx(toCardPayload(unsignedTx)),
87951
+ ...meta ? { broadcast: { key: p.broadcastMetaKey, meta } } : {}
87952
+ });
87499
87953
  } catch (e) {
87500
- return failed(`${p.op} broadcast`, e);
87954
+ return submitFailure(`${p.op} broadcast`, e);
87501
87955
  }
87502
- if (broadcastJson["success"] !== true) return declined(`${p.op} broadcast`, broadcastJson["error"]);
87503
- const bData = broadcastJson["data"] ?? {};
87504
- const txHash = String(bData["txHash"] ?? "");
87505
- if (!txHash) return upFail({ kind: "malformed", source: SOURCE5, message: `${p.op} broadcast returned no txHash` });
87506
- return upOk({ data, txHash, digest: p.messageHash }, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87956
+ return upOk({ data, txHash: submitted.txHash, digest }, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87507
87957
  }
87508
87958
  return {
87509
87959
  createPosition: async (p) => {
@@ -87545,15 +87995,21 @@ function buildWriteOps(deps) {
87545
87995
  mint: async (p) => {
87546
87996
  const amountWei = BigInt(p.amountUcdWei);
87547
87997
  const action = "mint-ucd";
87548
- const timestamp = nextQuantumTimestamp();
87549
- const messageHash = import_ethers32.ethers.solidityPackedKeccak256(
87550
- ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87551
- [p.positionId, timestamp, chainId, amountWei, import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(action))]
87552
- );
87553
87998
  const r = await executeAndBroadcast({
87554
87999
  op: "mint",
87555
- authMessage: { positionId: p.positionId, timestamp, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87556
- messageHash,
88000
+ spec: opAuthSpec({
88001
+ action,
88002
+ positionId: p.positionId,
88003
+ amount: amountWei,
88004
+ card: (f) => [
88005
+ "Authorize: mint UCD against your BTC collateral (this signature authorizes the operation; the transaction that executes it is approved separately)",
88006
+ `Position: ${p.positionId}`,
88007
+ `Amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
88008
+ `Chain id: ${chainId}`,
88009
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
88010
+ ]
88011
+ }),
88012
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87557
88013
  validation: (data) => {
87558
88014
  const mintFee2 = data["mintFee"];
87559
88015
  if (typeof mintFee2 !== "string" || mintFee2.length === 0) {
@@ -87576,7 +88032,7 @@ function buildWriteOps(deps) {
87576
88032
  mintedUcdWei: minted,
87577
88033
  feeUcdWei: mintFee,
87578
88034
  echoedAmountUcdWei: minted,
87579
- authorization: auth(action, `mint ${import_ethers32.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
88035
+ authorization: auth(action, `mint ${import_ethers33.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87580
88036
  },
87581
88037
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87582
88038
  );
@@ -87584,15 +88040,21 @@ function buildWriteOps(deps) {
87584
88040
  repay: async (p) => {
87585
88041
  const amountWei = BigInt(p.amountUcdWei);
87586
88042
  const action = "make-payment";
87587
- const timestamp = nextQuantumTimestamp();
87588
- const messageHash = import_ethers32.ethers.solidityPackedKeccak256(
87589
- ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87590
- [p.positionId, timestamp, chainId, amountWei, import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(action))]
87591
- );
87592
88043
  const r = await executeAndBroadcast({
87593
88044
  op: "repay",
87594
- authMessage: { positionId: p.positionId, timestamp, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87595
- messageHash,
88045
+ spec: opAuthSpec({
88046
+ action,
88047
+ positionId: p.positionId,
88048
+ amount: amountWei,
88049
+ card: (f) => [
88050
+ "Authorize: pay down UCD debt (this signature authorizes the operation; the transaction that executes it is approved separately)",
88051
+ `Position: ${p.positionId}`,
88052
+ `Payment amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
88053
+ `Chain id: ${chainId}`,
88054
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
88055
+ ]
88056
+ }),
88057
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87596
88058
  validation: () => ({ kind: "repay", positionId: p.positionId, amountWei: amountWei.toString() }),
87597
88059
  approveValidation: () => {
87598
88060
  const vctx = buildValidationContext(config.network, chainId);
@@ -87611,22 +88073,28 @@ function buildWriteOps(deps) {
87611
88073
  txRef: { kind: "eth-tx", id: r.value.txHash },
87612
88074
  paidUcdWei: paid,
87613
88075
  echoedAmountUcdWei: paid,
87614
- authorization: auth(action, `repay ${import_ethers32.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
88076
+ authorization: auth(action, `repay ${import_ethers33.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
87615
88077
  },
87616
88078
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87617
88079
  );
87618
88080
  },
87619
88081
  extend: async (p) => {
87620
88082
  const action = "extend-position";
87621
- const timestamp = nextQuantumTimestamp();
87622
- const messageHash = import_ethers32.ethers.solidityPackedKeccak256(
87623
- ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87624
- [p.positionId, timestamp, chainId, p.selectedTerm, import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(action))]
87625
- );
87626
88083
  const r = await executeAndBroadcast({
87627
88084
  op: "renew",
87628
- authMessage: { positionId: p.positionId, timestamp, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() },
87629
- messageHash,
88085
+ spec: opAuthSpec({
88086
+ action,
88087
+ positionId: p.positionId,
88088
+ amount: BigInt(p.selectedTerm),
88089
+ card: (f) => [
88090
+ "Authorize: extend (renew) the position term (this signature authorizes the operation; the transaction that executes it is approved separately)",
88091
+ `Position: ${p.positionId}`,
88092
+ `New term: ${p.selectedTerm} months`,
88093
+ `Chain id: ${chainId}`,
88094
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
88095
+ ]
88096
+ }),
88097
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() }),
87630
88098
  validation: () => ({ kind: "extend", positionId: p.positionId, selectedTerm: p.selectedTerm }),
87631
88099
  broadcastMetaKey: "renewMeta",
87632
88100
  broadcastMeta: () => ({ positionId: p.positionId, borrowerAddress: p.borrower, selectedTerm: p.selectedTerm, chainId })
@@ -87702,20 +88170,18 @@ function buildWriteOps(deps) {
87702
88170
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
87703
88171
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
87704
88172
  const tokenSymbol = isSwap ? "USDC" : "UCD";
87705
- const headers = await session.authHeader();
87706
88173
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
87707
88174
  if (!quoteR.ok) return upFail(quoteR.failure);
87708
- const broadcast = async (leg, tx2) => {
88175
+ const broadcast = async (leg, action, tx2) => {
87709
88176
  try {
87710
88177
  const populated = await dhSigner.getEthersSigner().populateTransaction(tx2);
87711
- const signed = await dhSigner.signTransaction(populated);
87712
- const j = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx: signed }, headers);
87713
- if (j["success"] !== true) return declined(leg, j["error"]);
87714
- const txHash = String((j["data"] ?? {})["txHash"] ?? "");
87715
- if (!txHash) return upFail({ kind: "malformed", source: SOURCE5, message: `${leg} broadcast returned no txHash` });
87716
- return upOk(txHash, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
88178
+ const submitted = await dhSigner.submitValidatedTx(populated, {
88179
+ action,
88180
+ card: cardForTx(toCardPayload(tx2))
88181
+ });
88182
+ return upOk(submitted.txHash, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87717
88183
  } catch (e) {
87718
- return failed(leg, e);
88184
+ return submitFailure(leg, e);
87719
88185
  }
87720
88186
  };
87721
88187
  const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
@@ -87729,7 +88195,7 @@ function buildWriteOps(deps) {
87729
88195
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
87730
88196
  }
87731
88197
  const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
87732
- const approveHashR = await broadcast("psmSwap (approve)", approveTx);
88198
+ const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
87733
88199
  if (!approveHashR.ok) return approveHashR;
87734
88200
  const approveHash = approveHashR.value;
87735
88201
  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`;
@@ -87744,7 +88210,7 @@ function buildWriteOps(deps) {
87744
88210
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
87745
88211
  }
87746
88212
  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}`;
87747
- const execHashR = await broadcast(`psmSwap (${p.direction})`, execTx);
88213
+ const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
87748
88214
  if (!execHashR.ok) {
87749
88215
  const f = execHashR.failure;
87750
88216
  return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
@@ -87828,33 +88294,296 @@ function buildWriteOps(deps) {
87828
88294
  }
87829
88295
 
87830
88296
  // src/signer/eoa-dh.ts
87831
- var import_ethers33 = require("ethers");
88297
+ var import_ethers34 = require("ethers");
87832
88298
  var EoaDHSigner = class {
87833
- kind = "eoa-env";
87834
- wallet;
87835
- constructor(wallet) {
88299
+ constructor(wallet, broadcast, clock = Date.now) {
87836
88300
  this.wallet = wallet;
88301
+ this.broadcast = broadcast;
88302
+ this.clock = clock;
87837
88303
  }
88304
+ kind = "eoa-env";
87838
88305
  async getBorrowerAddress() {
87839
88306
  return this.wallet.getAddress();
87840
88307
  }
87841
88308
  async getAuthSignerAddress() {
87842
88309
  return this.wallet.getAddress();
87843
88310
  }
87844
- async signAuthMessage(messageHash) {
87845
- return this.wallet.signMessage(import_ethers33.ethers.getBytes(messageHash));
88311
+ async signAuthorization(spec) {
88312
+ const quantumTs = nextQuantumTimestamp(this.clock());
88313
+ const { fields, hashHex } = spec.stamp(quantumTs);
88314
+ const signature = await this.wallet.signMessage(import_ethers34.ethers.getBytes(hashHex));
88315
+ return { signature, quantumTs, fields };
87846
88316
  }
87847
88317
  async wrapInnerTx(innerTx) {
87848
88318
  return innerTx;
87849
88319
  }
87850
- async signTransaction(outerTx) {
87851
- return this.wallet.signTransaction(outerTx);
88320
+ async submitValidatedTx(outerTx, ctx) {
88321
+ const signed = await this.wallet.signTransaction(outerTx);
88322
+ const txHash = await this.broadcast(signed, ctx.broadcast ? { [ctx.broadcast.key]: ctx.broadcast.meta } : void 0);
88323
+ return { txHash, signer: await this.wallet.getAddress(), scheme: "eip712-eoa" };
87852
88324
  }
87853
88325
  getEthersSigner() {
87854
88326
  return this.wallet;
87855
88327
  }
87856
88328
  };
87857
88329
 
88330
+ // src/signer/external-eoa.ts
88331
+ var import_node_crypto5 = require("crypto");
88332
+ var import_ethers36 = require("ethers");
88333
+
88334
+ // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
88335
+ var import_ethers35 = require("ethers");
88336
+ function eq2(a, b) {
88337
+ return a.toLowerCase() === b.toLowerCase();
88338
+ }
88339
+ function compareLandedTx(landed, approved, borrower) {
88340
+ 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;
88341
+ if (mismatch) {
88342
+ return {
88343
+ status: "mismatch",
88344
+ hash: landed.hash,
88345
+ 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`
88346
+ };
88347
+ }
88348
+ if (!eq2(landed.from, borrower)) {
88349
+ return {
88350
+ status: "mismatch",
88351
+ hash: landed.hash,
88352
+ reason: `tx ${landed.hash} was signed by ${landed.from}, not the borrower ${borrower} \u2014 already on-chain; do NOT retry, re-read state`
88353
+ };
88354
+ }
88355
+ return { status: "verified", from: landed.from, hash: landed.hash };
88356
+ }
88357
+ function verifyRawSignedTx(rawSignedTx, approved, borrower) {
88358
+ const parsed = import_ethers35.ethers.Transaction.from(rawSignedTx);
88359
+ if (!parsed.from || !parsed.to || !parsed.hash) {
88360
+ return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
88361
+ }
88362
+ return compareLandedTx(
88363
+ { from: parsed.from, to: parsed.to, data: parsed.data, value: parsed.value, chainId: parsed.chainId, hash: parsed.hash },
88364
+ approved,
88365
+ borrower
88366
+ );
88367
+ }
88368
+ async function verifyBroadcastTxByHash(provider, hash, approved, borrower, budget) {
88369
+ let tx2 = null;
88370
+ for (let i = 0; i < budget.attempts && tx2 === null; i++) {
88371
+ tx2 = await provider.getTransaction(hash);
88372
+ if (tx2 === null && i < budget.attempts - 1) await new Promise((r) => setTimeout(r, budget.delayMs));
88373
+ }
88374
+ if (tx2 === null || !tx2.from || !tx2.to) {
88375
+ return {
88376
+ status: "unknown",
88377
+ hash,
88378
+ 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).`
88379
+ };
88380
+ }
88381
+ return compareLandedTx(
88382
+ { from: tx2.from, to: tx2.to, data: tx2.data, value: tx2.value, chainId: BigInt(tx2.chainId), hash: tx2.hash },
88383
+ approved,
88384
+ borrower
88385
+ );
88386
+ }
88387
+
88388
+ // src/signer/external-eoa.ts
88389
+ var DEFAULT_BUDGET = { attempts: 30, delayMs: 3e3 };
88390
+ var ExternalEoaDHSigner = class {
88391
+ constructor(deps) {
88392
+ this.deps = deps;
88393
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88394
+ }
88395
+ kind = "external-eoa";
88396
+ budget;
88397
+ async getBorrowerAddress() {
88398
+ return this.deps.borrower;
88399
+ }
88400
+ async getAuthSignerAddress() {
88401
+ return this.deps.borrower;
88402
+ }
88403
+ async signAuthorization(spec) {
88404
+ const initialTs = nextQuantumTimestamp(Date.now());
88405
+ const initial = spec.stamp(initialTs);
88406
+ let used = { quantumTs: initialTs, fields: initial.fields };
88407
+ const outcome = await this.deps.bridge.requestSignature(
88408
+ {
88409
+ id: (0, import_node_crypto5.randomUUID)(),
88410
+ kind: "personal-sign",
88411
+ action: spec.action,
88412
+ card: initial.card,
88413
+ expectedSigner: this.deps.borrower,
88414
+ chainId: this.deps.chainId,
88415
+ personalSign: { layout: spec.layout, fields: initial.fields, hashHex: initial.hashHex }
88416
+ },
88417
+ {
88418
+ finalize: async () => {
88419
+ const ts = nextQuantumTimestamp(Date.now());
88420
+ const s = spec.stamp(ts);
88421
+ used = { quantumTs: ts, fields: s.fields };
88422
+ return { personalSign: { layout: spec.layout, fields: s.fields, hashHex: s.hashHex }, card: s.card };
88423
+ }
88424
+ }
88425
+ );
88426
+ if (outcome.status !== "approved" || !outcome.signature) {
88427
+ throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
88428
+ }
88429
+ const finalHash = spec.stamp(used.quantumTs).hashHex;
88430
+ const recovered = import_ethers36.ethers.verifyMessage(import_ethers36.ethers.getBytes(finalHash), outcome.signature);
88431
+ if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
88432
+ throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
88433
+ }
88434
+ return { signature: outcome.signature, quantumTs: used.quantumTs, fields: used.fields };
88435
+ }
88436
+ async wrapInnerTx(innerTx) {
88437
+ return innerTx;
88438
+ }
88439
+ async submitValidatedTx(outerTx, ctx) {
88440
+ const approved = toApprovedTx(outerTx, this.deps.chainId);
88441
+ const outcome = await this.deps.bridge.requestSignature({
88442
+ id: (0, import_node_crypto5.randomUUID)(),
88443
+ kind: "transaction",
88444
+ action: ctx.action,
88445
+ card: ctx.card,
88446
+ expectedSigner: this.deps.borrower,
88447
+ chainId: this.deps.chainId,
88448
+ tx: approved
88449
+ });
88450
+ if (outcome.status !== "approved") {
88451
+ throw new OperationDeclined(`the ${ctx.action} transaction was not approved: ${describeOutcome(outcome)}`);
88452
+ }
88453
+ const verdict = await this.resolveLanded(outcome, approved);
88454
+ if (verdict.status !== "verified") {
88455
+ throw new Error(verdict.reason);
88456
+ }
88457
+ return { txHash: verdict.hash, signer: verdict.from, scheme: "external-wallet" };
88458
+ }
88459
+ async resolveLanded(outcome, approved) {
88460
+ if (outcome.rawSignedTx) {
88461
+ const verdict = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88462
+ if (verdict.status === "verified") await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88463
+ return verdict;
88464
+ }
88465
+ if (!outcome.txHash) {
88466
+ return { status: "unknown", hash: "0x", reason: "the wallet approved but returned neither a tx hash nor a signed transaction" };
88467
+ }
88468
+ return verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88469
+ }
88470
+ getEthersSigner() {
88471
+ return new BridgeEthersSigner(this.deps);
88472
+ }
88473
+ };
88474
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers36.ethers.AbstractSigner {
88475
+ constructor(deps) {
88476
+ super(deps.provider);
88477
+ this.deps = deps;
88478
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88479
+ }
88480
+ budget;
88481
+ async getAddress() {
88482
+ return this.deps.borrower;
88483
+ }
88484
+ async signMessage(_message) {
88485
+ throw new Error(
88486
+ "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."
88487
+ );
88488
+ }
88489
+ async signTypedData(domain, types, value) {
88490
+ const typedData = {
88491
+ domain,
88492
+ types,
88493
+ primaryType: Object.keys(types)[0] ?? "EIP712",
88494
+ message: value
88495
+ };
88496
+ const outcome = await this.deps.bridge.requestSignature({
88497
+ id: (0, import_node_crypto5.randomUUID)(),
88498
+ kind: "typed-data",
88499
+ action: "login",
88500
+ card: cardForTypedData("login", typedData),
88501
+ expectedSigner: this.deps.borrower,
88502
+ chainId: this.deps.chainId,
88503
+ typedData
88504
+ });
88505
+ if (outcome.status !== "approved" || !outcome.signature) {
88506
+ throw new OperationDeclined(`the login signature was not approved: ${describeOutcome(outcome)}`);
88507
+ }
88508
+ return outcome.signature;
88509
+ }
88510
+ async sendTransaction(tx2) {
88511
+ if (!tx2.to || typeof tx2.data !== "string") {
88512
+ throw new Error("BridgeEthersSigner.sendTransaction: tx.to and hex tx.data are required");
88513
+ }
88514
+ const approved = {
88515
+ to: tx2.to,
88516
+ data: tx2.data,
88517
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88518
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
88519
+ };
88520
+ const card = cardForTx(approved);
88521
+ const outcome = await this.deps.bridge.requestSignature({
88522
+ id: (0, import_node_crypto5.randomUUID)(),
88523
+ kind: "transaction",
88524
+ action: describeFn(approved.data),
88525
+ card,
88526
+ expectedSigner: this.deps.borrower,
88527
+ chainId: approved.chainId,
88528
+ tx: { ...approved, ...tx2.gasLimit != null ? { gas: import_ethers36.ethers.toBeHex(BigInt(String(tx2.gasLimit))) } : {}, txType: 2 }
88529
+ });
88530
+ if (outcome.status !== "approved") {
88531
+ throw new OperationDeclined(`the transaction was not approved: ${describeOutcome(outcome)}`);
88532
+ }
88533
+ let hash;
88534
+ if (outcome.rawSignedTx) {
88535
+ const v = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88536
+ if (v.status !== "verified") throw new Error(v.reason);
88537
+ await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88538
+ hash = v.hash;
88539
+ } else if (outcome.txHash) {
88540
+ const v = await verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88541
+ if (v.status !== "verified") throw new Error(v.reason);
88542
+ hash = v.hash;
88543
+ } else {
88544
+ throw new Error("the wallet approved but returned neither a tx hash nor a signed transaction");
88545
+ }
88546
+ const resp = await this.provider.getTransaction(hash);
88547
+ if (!resp) throw new Error(`tx ${hash} verified but the provider no longer returns it`);
88548
+ return resp;
88549
+ }
88550
+ async signTransaction(_tx) {
88551
+ throw new Error("BridgeEthersSigner: browser wallets cannot raw-sign a transaction \u2014 use sendTransaction (self-broadcast).");
88552
+ }
88553
+ connect(provider) {
88554
+ return new _BridgeEthersSigner({ ...this.deps, provider });
88555
+ }
88556
+ };
88557
+ function toApprovedTx(tx2, fallbackChainId) {
88558
+ if (!tx2.to || typeof tx2.data !== "string") throw new Error("submitValidatedTx: tx.to and hex tx.data are required");
88559
+ return {
88560
+ to: tx2.to,
88561
+ data: tx2.data,
88562
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88563
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
88564
+ };
88565
+ }
88566
+ function describeFn(data) {
88567
+ try {
88568
+ const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
88569
+ return decodeSignable2(data).name;
88570
+ } catch {
88571
+ return "operation";
88572
+ }
88573
+ }
88574
+ function describeOutcome(outcome) {
88575
+ switch (outcome.status) {
88576
+ case "rejected":
88577
+ return outcome.reason;
88578
+ case "expired":
88579
+ return "the approval request expired without a wallet decision \u2014 reopen the approval page and retry";
88580
+ case "invalidated":
88581
+ return outcome.reason;
88582
+ default:
88583
+ return outcome.status;
88584
+ }
88585
+ }
88586
+
87858
88587
  // src/boundary/upstream/real/plugin.ts
87859
88588
  var STATUS_BY_INDEX = [
87860
88589
  "PENDING_DEPOSIT",
@@ -87872,10 +88601,11 @@ var POSITION_DETAILS_ABI = [
87872
88601
  var PAUSABLE_ABI = ["function paused() view returns (bool)"];
87873
88602
  var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
87874
88603
  var RealUpstreamPlugin = class {
87875
- constructor(config, wallet) {
88604
+ constructor(config, wallet, runtime) {
87876
88605
  this.config = config;
87877
- this.provider = new import_ethers34.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
88606
+ this.provider = new import_ethers37.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
87878
88607
  this.wallet = wallet ?? null;
88608
+ this.runtime = runtime ?? null;
87879
88609
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
87880
88610
  this.contracts = getContractsByNetwork(config.network) ?? {};
87881
88611
  this.indexer = {
@@ -87999,7 +88729,7 @@ var RealUpstreamPlugin = class {
87999
88729
  })
88000
88730
  )
88001
88731
  };
88002
- 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.`;
88732
+ 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.`;
88003
88733
  const readOnly = (op) => Promise.resolve(
88004
88734
  upFail({
88005
88735
  kind: "unavailable",
@@ -88008,16 +88738,10 @@ var RealUpstreamPlugin = class {
88008
88738
  })
88009
88739
  );
88010
88740
  const writesArmed = this.config.network === "sepolia" || this.config.network === "mainnet" && this.config.mainnetWritesAck === true;
88011
- if (writesArmed && this.wallet && this.session) {
88012
- this.ops = buildWriteOps({
88013
- config: this.config,
88014
- chainId: this.config.chainId,
88015
- dhSigner: new EoaDHSigner(this.wallet.connect(this.provider)),
88016
- session: this.session,
88017
- getWriteSdk: () => this.writeSdk,
88018
- readDetails: (id) => this.readPositionDetails(id),
88019
- psm: () => this.psmCalls()
88020
- });
88741
+ if (writesArmed && this.runtime) {
88742
+ this.ops = this.resolvingOps();
88743
+ } else if (writesArmed && this.wallet && this.session) {
88744
+ this.ops = this.keystoreGateway(this.wallet.connect(this.provider), this.session);
88021
88745
  } else {
88022
88746
  this.ops = {
88023
88747
  createPosition: () => readOnly("createPosition"),
@@ -88050,10 +88774,17 @@ var RealUpstreamPlugin = class {
88050
88774
  provider;
88051
88775
  session;
88052
88776
  contracts;
88053
- /** Signer-bearing SDK for the WRITE gateways (sepolia, or armed mainnet). Null until
88054
- * initWriteSdk. */
88055
- writeSdk = null;
88056
- /** Build the signer-bearing WRITE SDK (sepolia only; a no-op otherwise).
88777
+ runtime;
88778
+ /** Per-identity caches (plan 10 A3): keys are `<mode>:<address lowercased>` — a mode
88779
+ * switch resolves a different key, so stale constructions are never reused. */
88780
+ sdkCache = /* @__PURE__ */ new Map();
88781
+ sdkInFlight = /* @__PURE__ */ new Map();
88782
+ sessionCache = /* @__PURE__ */ new Map();
88783
+ opsGatewayCache = /* @__PURE__ */ new Map();
88784
+ externalSigners = /* @__PURE__ */ new Map();
88785
+ /** Pre-warm the KEYSTORE write SDK at boot (0.1.1 parity: the common keystore boot pays
88786
+ * the create cost up front, not on the first write). External-mode SDKs build lazily on
88787
+ * the first write after the mode binds (plan 10 A3 latency honesty).
88057
88788
  *
88058
88789
  * INDEPENDENT of any graph/indexer discovery (plan 08 A4, M8B-4): indexer reads ride
88059
88790
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
@@ -88063,29 +88794,277 @@ var RealUpstreamPlugin = class {
88063
88794
  * (createPosition/withdraw report the uninitialized SDK). */
88064
88795
  async initWriteSdk() {
88065
88796
  const writesArmed = this.config.network === "sepolia" || this.config.network === "mainnet" && this.config.mainnetWritesAck === true;
88066
- if (!this.wallet || !writesArmed) return;
88067
- try {
88068
- const signer = this.wallet.connect(this.provider);
88069
- const v = this.config.validatorVersion;
88070
- const builtWrite = await DiamondHandsSDK.create({
88071
- mode: "service",
88072
- serviceEndpoint: this.config.serviceEndpoint,
88073
- contractSigner: signer,
88074
- authSigner: signer,
88075
- provider: this.provider,
88076
- ethRpcUrl: this.config.rpcUrl,
88077
- chainId: this.config.chainId,
88078
- litNetwork: this.config.litNetwork,
88079
- // No `subgraphs`: in service mode the SDK queries THROUGH the lit-ops proxy and
88080
- // ignores any provided URL — the old `/v1/init`-discovered value was dead weight
88081
- // nesting writes under indexer discovery (the M8B-4 coupling this removes).
88082
- ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
88797
+ if (!writesArmed) return;
88798
+ if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
88799
+ const wallet = this.wallet ?? this.runtime?.keystore.signer() ?? null;
88800
+ if (!wallet) return;
88801
+ await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
88802
+ }
88803
+ /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
88804
+ * the write gateways report the uninitialized SDK honestly, never fake readiness. */
88805
+ async ensureSdk(key, signer) {
88806
+ if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
88807
+ const inFlight = this.sdkInFlight.get(key);
88808
+ if (inFlight) return inFlight;
88809
+ const build = (async () => {
88810
+ try {
88811
+ const v = this.config.validatorVersion;
88812
+ const builtWrite = await DiamondHandsSDK.create({
88813
+ mode: "service",
88814
+ serviceEndpoint: this.config.serviceEndpoint,
88815
+ contractSigner: signer,
88816
+ authSigner: signer,
88817
+ provider: this.provider,
88818
+ ethRpcUrl: this.config.rpcUrl,
88819
+ chainId: this.config.chainId,
88820
+ litNetwork: this.config.litNetwork,
88821
+ // No `subgraphs`: in service mode the SDK queries THROUGH the lit-ops proxy and
88822
+ // ignores any provided URL — the old `/v1/init`-discovered value was dead weight
88823
+ // nesting writes under indexer discovery (the M8B-4 coupling this removes).
88824
+ ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
88825
+ });
88826
+ return isSuccess(builtWrite) ? builtWrite.value : null;
88827
+ } catch {
88828
+ return null;
88829
+ }
88830
+ })();
88831
+ this.sdkInFlight.set(key, build);
88832
+ const built = await build;
88833
+ this.sdkInFlight.delete(key);
88834
+ this.sdkCache.set(key, built);
88835
+ return built;
88836
+ }
88837
+ wallet;
88838
+ // ---- per-call signer resolution (plan 10 A3) ----
88839
+ /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
88840
+ * carries the service endpoint and the authenticated session header. It throws
88841
+ * `OperationDeclined` when lit-ops REFUSES the signed tx (a decision), a plain Error on
88842
+ * transport/shape trouble; write-ops maps the two to distinct failure kinds. */
88843
+ litOpsBroadcast(session) {
88844
+ return async (signedTx, extra) => {
88845
+ const res = await fetch(`${this.config.serviceEndpoint}/api/lit/broadcast`, {
88846
+ method: "POST",
88847
+ headers: { "Content-Type": "application/json", ...await session.authHeader() },
88848
+ body: JSON.stringify({ signedTx, ...extra ?? {} })
88083
88849
  });
88084
- if (isSuccess(builtWrite)) this.writeSdk = builtWrite.value;
88085
- } catch {
88850
+ const text = await res.text();
88851
+ let json;
88852
+ try {
88853
+ json = JSON.parse(text);
88854
+ } catch {
88855
+ throw new Error(`lit-ops broadcast returned non-JSON (HTTP ${res.status}): ${text.slice(0, 200)}`);
88856
+ }
88857
+ if (!res.ok && json["error"] === void 0) {
88858
+ throw new Error(`lit-ops broadcast HTTP ${res.status}: ${text.slice(0, 200)}`);
88859
+ }
88860
+ if (json["success"] !== true) {
88861
+ const reason = json["error"];
88862
+ throw new OperationDeclined(`lit-ops declined the signed transaction: ${typeof reason === "string" ? reason : "no reason given"}`);
88863
+ }
88864
+ const txHash = String((json["data"] ?? {})["txHash"] ?? "");
88865
+ if (!txHash) throw new Error("lit-ops broadcast returned no txHash");
88866
+ return txHash;
88867
+ };
88868
+ }
88869
+ keystoreGateway(wallet, session) {
88870
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88871
+ return buildWriteOps({
88872
+ config: this.config,
88873
+ chainId: this.config.chainId,
88874
+ dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
88875
+ session,
88876
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88877
+ readDetails: (id) => this.readPositionDetails(id),
88878
+ psm: () => this.psmCalls()
88879
+ });
88880
+ }
88881
+ sessionFor(key, signer) {
88882
+ let s = this.sessionCache.get(key);
88883
+ if (!s) {
88884
+ s = new LitOpsSession(signer, this.config.serviceEndpoint, this.config.chainId);
88885
+ this.sessionCache.set(key, s);
88886
+ }
88887
+ return s;
88888
+ }
88889
+ /** Verify-by-hash budget for external self-broadcast (A0.3): mainnet Chipotle
88890
+ * roundtrips exceed 60s, so the write-path budget is 300s there (F-MAIN-4). */
88891
+ verifyBudget() {
88892
+ return this.config.network === "mainnet" ? { attempts: 100, delayMs: 3e3 } : void 0;
88893
+ }
88894
+ /** The armed-boot ops surface: every method resolves the CURRENT signer mode first, so
88895
+ * the refusal-truth matrix is decided at call time, never frozen at boot. */
88896
+ resolvingOps() {
88897
+ const call = (k) => (async (p) => {
88898
+ const r = await this.resolveOpsGateway();
88899
+ if (!r.ok) return upFail(r.failure);
88900
+ return r.gateway[k](p);
88901
+ });
88902
+ return {
88903
+ createPosition: call("createPosition"),
88904
+ mint: call("mint"),
88905
+ repay: call("repay"),
88906
+ extend: call("extend"),
88907
+ withdraw: call("withdraw"),
88908
+ allowlistWithdrawalAddress: call("allowlistWithdrawalAddress"),
88909
+ psmSwap: call("psmSwap"),
88910
+ delegationSetup: call("delegationSetup"),
88911
+ delegationGrant: call("delegationGrant"),
88912
+ recoverStaleSpend: call("recoverStaleSpend")
88913
+ };
88914
+ }
88915
+ async resolveOpsGateway() {
88916
+ const rt = this.runtime;
88917
+ const mode = rt.manager.mode();
88918
+ if (mode === "none") {
88919
+ return {
88920
+ ok: false,
88921
+ failure: {
88922
+ kind: "signer-missing",
88923
+ source: "real-ops",
88924
+ 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."
88925
+ }
88926
+ };
88086
88927
  }
88928
+ if (mode === "keystore") {
88929
+ const ready = await rt.keystore.ensureReady();
88930
+ const wallet = rt.keystore.signer();
88931
+ if (!ready.ok || !wallet) {
88932
+ return {
88933
+ ok: false,
88934
+ failure: {
88935
+ kind: "signer-missing",
88936
+ source: "real-ops",
88937
+ message: `the keystore signer is not ready (SIGNER_UNAVAILABLE): ${ready.ok ? "no keystore material" : ready.reason}`
88938
+ }
88939
+ };
88940
+ }
88941
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88942
+ let gateway = this.opsGatewayCache.get(key);
88943
+ if (!gateway) {
88944
+ const connected = wallet.connect(this.provider);
88945
+ gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
88946
+ this.opsGatewayCache.set(key, gateway);
88947
+ }
88948
+ await this.ensureSdk(key, wallet.connect(this.provider));
88949
+ return { ok: true, gateway };
88950
+ }
88951
+ if (mode === "external") {
88952
+ const borrower = await rt.manager.resolveBorrowerForWrite();
88953
+ if (!borrower) {
88954
+ return {
88955
+ ok: false,
88956
+ failure: {
88957
+ kind: "signer-missing",
88958
+ source: "real-ops",
88959
+ 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."
88960
+ }
88961
+ };
88962
+ }
88963
+ const key = `external:${borrower.toLowerCase()}`;
88964
+ let gateway = this.opsGatewayCache.get(key);
88965
+ if (!gateway) {
88966
+ const budget = this.verifyBudget();
88967
+ const deps = {
88968
+ bridge: rt.bridge,
88969
+ provider: this.provider,
88970
+ chainId: this.config.chainId,
88971
+ borrower,
88972
+ ...budget ? { verifyBudget: budget } : {}
88973
+ };
88974
+ const bridgeSigner = new BridgeEthersSigner(deps);
88975
+ this.externalSigners.set(key, bridgeSigner);
88976
+ const session = this.sessionFor(key, {
88977
+ address: borrower,
88978
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88979
+ });
88980
+ gateway = buildWriteOps({
88981
+ config: this.config,
88982
+ chainId: this.config.chainId,
88983
+ dhSigner: new ExternalEoaDHSigner(deps),
88984
+ session,
88985
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88986
+ readDetails: (id) => this.readPositionDetails(id),
88987
+ psm: () => this.psmCalls()
88988
+ });
88989
+ this.opsGatewayCache.set(key, gateway);
88990
+ }
88991
+ await this.ensureSdk(key, this.externalSigners.get(key));
88992
+ return { ok: true, gateway };
88993
+ }
88994
+ return {
88995
+ ok: false,
88996
+ failure: {
88997
+ kind: "signer-missing",
88998
+ source: "real-ops",
88999
+ message: `signer mode '${mode}' is not available on the real adapter \u2014 use 'external' or 'keystore' (signer_setup).`
89000
+ }
89001
+ };
89002
+ }
89003
+ /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
89004
+ * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
89005
+ * the first verified ceremony fixes the identity. */
89006
+ async connectExternal() {
89007
+ if (!this.runtime) return { ok: false, reason: "this construction has no signer runtime" };
89008
+ const { manager } = this.runtime;
89009
+ if (manager.mode() !== "external") {
89010
+ return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
89011
+ }
89012
+ const borrower = manager.borrowerForWrite();
89013
+ if (!borrower) {
89014
+ return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
89015
+ }
89016
+ const key = `external:${borrower.toLowerCase()}`;
89017
+ const budget = this.verifyBudget();
89018
+ const bridgeSigner = this.externalSigners.get(key) ?? new BridgeEthersSigner({
89019
+ bridge: this.runtime.bridge,
89020
+ provider: this.provider,
89021
+ chainId: this.config.chainId,
89022
+ borrower,
89023
+ ...budget ? { verifyBudget: budget } : {}
89024
+ });
89025
+ this.externalSigners.set(key, bridgeSigner);
89026
+ const session = this.sessionFor(key, {
89027
+ address: borrower,
89028
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
89029
+ });
89030
+ await session.token();
89031
+ manager.bind(borrower);
89032
+ return { ok: true, address: borrower };
89033
+ }
89034
+ /** The authenticated-read session for the CURRENT mode. Reads NEVER summon the wallet
89035
+ * (A0.7): external mode without a live JWT refuses, naming the explicit connect action. */
89036
+ resolveReadSession() {
89037
+ if (!this.runtime) {
89038
+ 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." };
89039
+ }
89040
+ const mode = this.runtime.manager.mode();
89041
+ if (mode === "keystore") {
89042
+ const wallet = this.runtime.keystore.signer();
89043
+ if (!wallet) {
89044
+ 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." };
89045
+ }
89046
+ const key = `keystore:${wallet.address.toLowerCase()}`;
89047
+ return { ok: true, session: this.sessionFor(key, wallet.connect(this.provider)) };
89048
+ }
89049
+ if (mode === "external") {
89050
+ const borrower = this.runtime.manager.borrowerForWrite();
89051
+ const session = borrower ? this.sessionCache.get(`external:${borrower.toLowerCase()}`) : void 0;
89052
+ if (session && session.hasValidToken()) return { ok: true, session };
89053
+ return {
89054
+ ok: false,
89055
+ 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."
89056
+ };
89057
+ }
89058
+ return {
89059
+ ok: false,
89060
+ 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."
89061
+ };
89062
+ }
89063
+ /** Capability truth for boundary://info (plan 10 B3): can authenticated reads run RIGHT
89064
+ * NOW without summoning a wallet? */
89065
+ authenticatedReadsAvailable() {
89066
+ return this.resolveReadSession().ok;
88087
89067
  }
88088
- wallet;
88089
89068
  describe() {
88090
89069
  return {
88091
89070
  adapter: "real",
@@ -88093,7 +89072,8 @@ var RealUpstreamPlugin = class {
88093
89072
  };
88094
89073
  }
88095
89074
  dispose() {
88096
- this.writeSdk?.dispose();
89075
+ for (const sdk of this.sdkCache.values()) sdk?.dispose();
89076
+ this.sdkCache.clear();
88097
89077
  this.provider.destroy();
88098
89078
  }
88099
89079
  // ---- helpers ----
@@ -88153,19 +89133,20 @@ var RealUpstreamPlugin = class {
88153
89133
  * present, else `_meta` from the document result (this is reading one response, not a
88154
89134
  * fallback path). Null when the document selects no `_meta` (e.g. PositionById). */
88155
89135
  async graphProxy(document2, variables) {
88156
- if (!this.session) {
89136
+ const sessionR = this.resolveReadSession();
89137
+ if (!sessionR.ok) {
88157
89138
  return upFail({
88158
89139
  kind: "signer-missing",
88159
89140
  // → SIGNER_UNAVAILABLE (same contract as the other authenticated reads)
88160
89141
  source: "subgraph",
88161
- 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."
89142
+ 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.`
88162
89143
  });
88163
89144
  }
88164
89145
  let res;
88165
89146
  try {
88166
89147
  res = await fetch(`${this.config.serviceEndpoint}/api/lit/graph/query?chainId=${this.config.chainId}`, {
88167
89148
  method: "POST",
88168
- headers: { "Content-Type": "application/json", ...await this.session.authHeader() },
89149
+ headers: { "Content-Type": "application/json", ...await sessionR.session.authHeader() },
88169
89150
  body: JSON.stringify({ query: document2, variables })
88170
89151
  });
88171
89152
  } catch (e) {
@@ -88230,9 +89211,9 @@ var RealUpstreamPlugin = class {
88230
89211
  };
88231
89212
  }
88232
89213
  /** Public (unauthenticated) lit-ops GET. */
88233
- async publicRead(path4, map) {
89214
+ async publicRead(path5, map) {
88234
89215
  try {
88235
- const res = await fetch(`${this.config.serviceEndpoint}${path4}`);
89216
+ const res = await fetch(`${this.config.serviceEndpoint}${path5}`);
88236
89217
  const text = await res.text();
88237
89218
  if (!res.ok) {
88238
89219
  return upFail({
@@ -88249,18 +89230,19 @@ var RealUpstreamPlugin = class {
88249
89230
  }
88250
89231
  }
88251
89232
  /** Authenticated lit-ops GET → mapped value. Never throws; maps failures to the taxonomy. */
88252
- async opsRead(path4, map) {
88253
- if (!this.session) {
89233
+ async opsRead(path5, map) {
89234
+ const sessionR = this.resolveReadSession();
89235
+ if (!sessionR.ok) {
88254
89236
  return upFail({
88255
89237
  kind: "signer-missing",
88256
89238
  // → SIGNER_UNAVAILABLE (documented contract, pinned by REAL-08)
88257
89239
  source: "lit-ops",
88258
- message: "no signer configured \u2014 this read is authenticated (lit-ops login). Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
89240
+ message: `this read is authenticated (lit-ops login): ${sessionR.reason}`
88259
89241
  });
88260
89242
  }
88261
89243
  let res;
88262
89244
  try {
88263
- res = await fetch(`${this.config.serviceEndpoint}${path4}`, { headers: await this.session.authHeader() });
89245
+ res = await fetch(`${this.config.serviceEndpoint}${path5}`, { headers: await sessionR.session.authHeader() });
88264
89246
  } catch (e) {
88265
89247
  return upFail({ kind: "unavailable", source: "lit-ops", message: `lit-ops is unreachable`, raw: String(e) });
88266
89248
  }
@@ -88309,7 +89291,7 @@ var RealUpstreamPlugin = class {
88309
89291
  const pm = this.contracts["PositionManager"];
88310
89292
  if (!pm) return false;
88311
89293
  try {
88312
- const c = new import_ethers34.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
89294
+ const c = new import_ethers37.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
88313
89295
  return Boolean(await c["paused"]());
88314
89296
  } catch {
88315
89297
  return false;
@@ -88318,16 +89300,16 @@ var RealUpstreamPlugin = class {
88318
89300
  async readPositionDetails(id) {
88319
89301
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
88320
89302
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
88321
- const c = new import_ethers34.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
89303
+ const c = new import_ethers37.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
88322
89304
  let d;
88323
89305
  try {
88324
- d = await c["getPositionDetails"](import_ethers34.ethers.zeroPadValue(id, 32));
89306
+ d = await c["getPositionDetails"](import_ethers37.ethers.zeroPadValue(id, 32));
88325
89307
  } catch (e) {
88326
89308
  if (e.code === "CALL_EXCEPTION") return null;
88327
89309
  throw e;
88328
89310
  }
88329
89311
  const borrower = String(d["borrower"]);
88330
- if (borrower === import_ethers34.ethers.ZeroAddress) return null;
89312
+ if (borrower === import_ethers37.ethers.ZeroAddress) return null;
88331
89313
  return {
88332
89314
  positionId: String(d["positionId"]),
88333
89315
  pkpId: String(d["pkpId"]),
@@ -88351,7 +89333,7 @@ var RealUpstreamPlugin = class {
88351
89333
  // src/boundary/upstream/shared/external-bridge/bridge.ts
88352
89334
  var fs4 = __toESM(require("fs"));
88353
89335
  var http3 = __toESM(require("http"));
88354
- var import_node_crypto5 = require("crypto");
89336
+ var import_node_crypto6 = require("crypto");
88355
89337
 
88356
89338
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
88357
89339
  function renderApprovalPage(sessionId) {
@@ -88398,12 +89380,16 @@ function renderApprovalPage(sessionId) {
88398
89380
  <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
88399
89381
  Use a mobile wallet instead (WalletConnect)
88400
89382
  </button>
89383
+ <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
88401
89384
  <div id="wc-uri" class="card hidden" style="user-select:all; word-break:break-all; font-size:12px;"></div>
88402
- <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>
89385
+ <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>
88403
89386
  </div>
88404
89387
  </div>
88405
89388
  </main>
88406
89389
  <script>
89390
+ ${PAGE_CRYPTO_JS}
89391
+ </script>
89392
+ <script>
88407
89393
  "use strict";
88408
89394
  const SESSION = ${JSON.stringify(sessionId)};
88409
89395
  // One-time token leaves the address bar (and history) immediately.
@@ -88519,11 +89505,33 @@ document.getElementById("approve").onclick = async () => {
88519
89505
  const req = current;
88520
89506
  try {
88521
89507
  if (req.kind === "transaction") {
89508
+ const params = { from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value };
89509
+ if (req.tx.gas) params.gas = req.tx.gas; // hint only \u2014 the wallet may re-estimate
88522
89510
  const txHash = await window.ethereum.request({
88523
89511
  method: "eth_sendTransaction",
88524
- params: [{ from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value }],
89512
+ params: [params],
88525
89513
  });
88526
89514
  await post("/result", { requestId: req.id, approved: true, account: account, txHash: txHash });
89515
+ } else if (req.kind === "personal-sign") {
89516
+ // A0.9 sign-at-presence: fetch the FRESHLY quantum-stamped payload at the click\u2026
89517
+ const fr = await post("/finalize", { requestId: req.id });
89518
+ const fbody = await fr.json();
89519
+ if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
89520
+ const fresh = fbody.request;
89521
+ // \u2026re-render what will actually sign\u2026
89522
+ current = fresh; renderRequest();
89523
+ // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
89524
+ const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
89525
+ if (recomputed.toLowerCase() !== fresh.personalSign.hashHex.toLowerCase()) {
89526
+ 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" });
89527
+ clearRequest("REFUSED: the signature request did not match its own displayed fields. Nothing was signed.");
89528
+ return;
89529
+ }
89530
+ const signature = await window.ethereum.request({
89531
+ method: "personal_sign",
89532
+ params: [fresh.personalSign.hashHex, account],
89533
+ });
89534
+ await post("/result", { requestId: req.id, approved: true, account: account, signature: signature });
88527
89535
  } else {
88528
89536
  // MetaMask's v4 schema REQUIRES an EIP712Domain entry in "types" (ethers' signer
88529
89537
  // API forbids the same entry) \u2014 derive it here from the domain's present fields.
@@ -88556,8 +89564,13 @@ document.getElementById("wc-connect").onclick = async () => {
88556
89564
  const uriEl = document.getElementById("wc-uri");
88557
89565
  uriEl.textContent = body.uri;
88558
89566
  uriEl.classList.remove("hidden");
89567
+ if (body.qrSvg) {
89568
+ const qrEl = document.getElementById("wc-qr");
89569
+ qrEl.innerHTML = body.qrSvg; // server-generated SVG from OUR loopback process
89570
+ qrEl.classList.remove("hidden");
89571
+ }
88559
89572
  document.getElementById("wc-hint").classList.remove("hidden");
88560
- showStatus("Pair your mobile wallet with the code below \u2014 it becomes the signing wallet.");
89573
+ showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
88561
89574
  };
88562
89575
 
88563
89576
  connect();
@@ -88644,7 +89657,7 @@ var SignatureBridge = class {
88644
89657
  expiryMs;
88645
89658
  server = null;
88646
89659
  port = 0;
88647
- token = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89660
+ token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88648
89661
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
88649
89662
  * each open mints its own session. The link is NOT signing authority: only recovered
88650
89663
  * OWNER signatures count (M6-9); the token still gates drive-by loopback scans. */
@@ -88676,7 +89689,7 @@ var SignatureBridge = class {
88676
89689
  unlockUrl() {
88677
89690
  if (!this.server) throw new Error("bridge is not started");
88678
89691
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
88679
- this.unlockToken = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89692
+ this.unlockToken = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88680
89693
  return `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
88681
89694
  }
88682
89695
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2). */
@@ -88731,7 +89744,7 @@ var SignatureBridge = class {
88731
89744
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
88732
89745
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
88733
89746
  */
88734
- requestSignature(request) {
89747
+ requestSignature(request, handlers) {
88735
89748
  if (!this.server) return Promise.resolve({ status: "invalidated", reason: "bridge is not started" });
88736
89749
  if (this.wallet && this.wallet.chainId !== request.chainId) {
88737
89750
  return Promise.resolve({
@@ -88744,7 +89757,8 @@ var SignatureBridge = class {
88744
89757
  request,
88745
89758
  deadlineMs: this.clock() + this.expiryMs,
88746
89759
  resolve,
88747
- settled: false
89760
+ settled: false,
89761
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {}
88748
89762
  };
88749
89763
  this.pending.set(request.id, entry);
88750
89764
  if (this.wcActive) {
@@ -88812,9 +89826,18 @@ var SignatureBridge = class {
88812
89826
  if (req.kind === "transaction") {
88813
89827
  const tx2 = req.tx;
88814
89828
  const txHash = await transport.request("eth_sendTransaction", [
88815
- { from: account, to: tx2.to, data: tx2.data, value: tx2.value }
89829
+ { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
88816
89830
  ]);
88817
89831
  if (!entry.settled) this.settle(entry, { status: "approved", account, txHash });
89832
+ } else if (req.kind === "personal-sign") {
89833
+ if (entry.finalize) {
89834
+ const fresh = await entry.finalize();
89835
+ req.personalSign = fresh.personalSign;
89836
+ req.card = fresh.card;
89837
+ }
89838
+ const ps = req.personalSign;
89839
+ const signature = await transport.request("personal_sign", [ps.hashHex, account]);
89840
+ if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
88818
89841
  } else {
88819
89842
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
88820
89843
  const payload = withEip712DomainType2(req.typedData);
@@ -88866,6 +89889,8 @@ var SignatureBridge = class {
88866
89889
  if (req.method === "POST" && url2.pathname === "/wallet-event")
88867
89890
  return void this.readJson(req, res, (b) => this.onWalletEvent(b, res));
88868
89891
  if (req.method === "POST" && url2.pathname === "/result") return void this.readJson(req, res, (b) => this.onResult(b, res));
89892
+ if (req.method === "POST" && url2.pathname === "/finalize")
89893
+ return void this.readJson(req, res, (b) => void this.onFinalize(b, res));
88869
89894
  this.deny(res, 404, "not found");
88870
89895
  }
88871
89896
  /** Loopback discipline: Host must be this loopback bind; Origin (when a browser sends
@@ -88895,7 +89920,7 @@ var SignatureBridge = class {
88895
89920
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
88896
89921
  return;
88897
89922
  }
88898
- const sessionId = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89923
+ const sessionId = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88899
89924
  this.sessions.set(sessionId, { wallet: null, sse: null });
88900
89925
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88901
89926
  res.end(renderApprovalPage(sessionId));
@@ -88931,8 +89956,13 @@ var SignatureBridge = class {
88931
89956
  });
88932
89957
  }
88933
89958
  const { uri } = await this.wcTransport.createPairing();
89959
+ const { default: qrcode } = await import("qrcode-generator");
89960
+ const qr = qrcode(0, "M");
89961
+ qr.addData(uri);
89962
+ qr.make();
89963
+ const qrSvg = qr.createSvgTag({ cellSize: 4, margin: 8, scalable: true });
88934
89964
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
88935
- res.end(JSON.stringify({ uri }));
89965
+ res.end(JSON.stringify({ uri, qrSvg }));
88936
89966
  } catch (e) {
88937
89967
  this.deny(res, 502, `WalletConnect pairing failed: ${e.message}`);
88938
89968
  }
@@ -88950,7 +89980,7 @@ var SignatureBridge = class {
88950
89980
  return;
88951
89981
  }
88952
89982
  this.unlockToken = null;
88953
- this.unlockSession = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89983
+ this.unlockSession = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88954
89984
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88955
89985
  res.end(renderUnlockPage(this.unlockSession));
88956
89986
  }
@@ -89038,6 +90068,37 @@ var SignatureBridge = class {
89038
90068
  }
89039
90069
  this.ok(res);
89040
90070
  }
90071
+ /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
90072
+ * request. Idempotent for requests without a finalize handler (payload as enqueued). */
90073
+ async onFinalize(body, res) {
90074
+ if (!this.sessionOf(body["sessionId"], res)) return;
90075
+ const entry = this.pending.get(String(body["requestId"] ?? ""));
90076
+ if (!entry || entry.settled) {
90077
+ this.deny(res, 404, "unknown or already-settled requestId");
90078
+ return;
90079
+ }
90080
+ if (entry.request.kind !== "personal-sign") {
90081
+ this.deny(res, 400, "finalize applies only to personal-sign requests");
90082
+ return;
90083
+ }
90084
+ if (entry.finalize) {
90085
+ let fresh;
90086
+ try {
90087
+ fresh = await entry.finalize();
90088
+ } catch (e) {
90089
+ this.deny(res, 502, `finalize failed: ${e.message}`);
90090
+ return;
90091
+ }
90092
+ if (entry.settled) {
90093
+ this.deny(res, 404, "request settled while finalizing");
90094
+ return;
90095
+ }
90096
+ entry.request.personalSign = fresh.personalSign;
90097
+ entry.request.card = fresh.card;
90098
+ }
90099
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
90100
+ res.end(JSON.stringify({ request: entry.request }));
90101
+ }
89041
90102
  onResult(body, res) {
89042
90103
  if (!this.sessionOf(body["sessionId"], res)) return;
89043
90104
  const entry = this.pending.get(String(body["requestId"] ?? ""));
@@ -89062,8 +90123,8 @@ var SignatureBridge = class {
89062
90123
  this.deny(res, 400, "transaction approval requires txHash or rawSignedTx");
89063
90124
  return;
89064
90125
  }
89065
- if (entry.request.kind === "typed-data" && !signature) {
89066
- this.deny(res, 400, "typed-data approval requires signature");
90126
+ if ((entry.request.kind === "typed-data" || entry.request.kind === "personal-sign") && !signature) {
90127
+ this.deny(res, 400, `${entry.request.kind} approval requires signature`);
89067
90128
  return;
89068
90129
  }
89069
90130
  if (entry.collect) {
@@ -89149,14 +90210,15 @@ data: ${JSON.stringify(payload)}
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
 
89282
90414
  // src/boot.ts
@@ -89314,8 +90446,8 @@ async function buildBoundary(configResult) {
89314
90446
  );
89315
90447
  }
89316
90448
  try {
89317
- const decrypted = await import_ethers35.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
89318
- if (!(decrypted instanceof import_ethers35.ethers.Wallet)) {
90449
+ const decrypted = await import_ethers38.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
90450
+ if (!(decrypted instanceof import_ethers38.ethers.Wallet)) {
89319
90451
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
89320
90452
  }
89321
90453
  wallet = decrypted;
@@ -89326,8 +90458,8 @@ async function buildBoundary(configResult) {
89326
90458
  );
89327
90459
  }
89328
90460
  }
89329
- const { boundary, dispose } = await createRealBoundary(config, wallet);
89330
- return { boundaryResult: { ok: true, boundary }, dispose };
90461
+ const { boundary, signer, dispose } = await createRealBoundary(config, wallet);
90462
+ return { boundaryResult: { ok: true, boundary }, signer, dispose };
89331
90463
  }
89332
90464
 
89333
90465
  // src/server.ts
@@ -89335,7 +90467,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
89335
90467
 
89336
90468
  // src/tools/loan.ts
89337
90469
  var import_zod = require("zod");
89338
- var import_ethers36 = require("ethers");
90470
+ var import_ethers39 = require("ethers");
89339
90471
 
89340
90472
  // src/util/format.ts
89341
90473
  function bigintReplacer(_key, value) {
@@ -89507,7 +90639,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
89507
90639
  const b = getB();
89508
90640
  if (!b.ok) return renderError(b.error);
89509
90641
  return renderEnvelope(
89510
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers36.parseEther)(amountUcd.toString()).toString() })
90642
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers39.parseEther)(amountUcd.toString()).toString() })
89511
90643
  );
89512
90644
  })
89513
90645
  );
@@ -89545,7 +90677,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
89545
90677
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
89546
90678
  amountUcdWei = detail.data.debtUcdWei;
89547
90679
  } else {
89548
- amountUcdWei = (0, import_ethers36.parseEther)(amountUcd.toString()).toString();
90680
+ amountUcdWei = (0, import_ethers39.parseEther)(amountUcd.toString()).toString();
89549
90681
  }
89550
90682
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
89551
90683
  })
@@ -90116,7 +91248,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
90116
91248
 
90117
91249
  // src/tools/signer.ts
90118
91250
  var import_zod6 = require("zod");
90119
- var import_ethers37 = require("ethers");
91251
+ var import_ethers40 = require("ethers");
90120
91252
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
90121
91253
  function looksSecretShaped(value) {
90122
91254
  return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
@@ -90128,9 +91260,9 @@ function registerSignerTool(server, runtime) {
90128
91260
  "signer_setup",
90129
91261
  {
90130
91262
  title: "Choose how operations are authorized",
90131
- description: "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (unbind the discovered wallet identity), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe.",
91263
+ description: "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (unbind the discovered wallet identity), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat), 'connect' (external mode, real protocol: run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe.",
90132
91264
  inputSchema: {
90133
- action: import_zod6.z.enum(["status", "use", "reset-borrower", "unlock-keystore"]).describe("What to do \u2014 'status' explains everything"),
91265
+ action: import_zod6.z.enum(["status", "use", "reset-borrower", "unlock-keystore", "connect"]).describe("What to do \u2014 'status' explains everything"),
90134
91266
  mode: import_zod6.z.string().optional().describe("For 'use': external | keystore | safe | safe-module | mock-simulated"),
90135
91267
  safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
90136
91268
  },
@@ -90141,7 +91273,7 @@ function registerSignerTool(server, runtime) {
90141
91273
  if (mode !== void 0 && !MODES.includes(mode)) {
90142
91274
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${MODES.join(" | ")}`);
90143
91275
  }
90144
- if (safeAddress !== void 0 && !import_ethers37.ethers.isAddress(safeAddress)) {
91276
+ if (safeAddress !== void 0 && !import_ethers40.ethers.isAddress(safeAddress)) {
90145
91277
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
90146
91278
  }
90147
91279
  if (action === "status") {
@@ -90184,6 +91316,20 @@ function registerSignerTool(server, runtime) {
90184
91316
  }
90185
91317
  return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
90186
91318
  }
91319
+ if (action === "connect") {
91320
+ if (!runtime.connect) {
91321
+ return validationFailed(
91322
+ "action 'connect' applies to the real protocol's external mode (lit-ops login). This adapter has no separate login step \u2014 pick a mode with 'use' and writes will ceremony as needed."
91323
+ );
91324
+ }
91325
+ const r = await runtime.connect();
91326
+ if (!r.ok) return validationFailed(r.reason);
91327
+ return ok({
91328
+ connected: true,
91329
+ address: r.address,
91330
+ next: "Logged in \u2014 authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
91331
+ });
91332
+ }
90187
91333
  if (action === "reset-borrower") {
90188
91334
  manager.resetBorrower();
90189
91335
  return ok({ reset: true, next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower." });
@@ -90208,6 +91354,7 @@ var import_zod7 = require("zod");
90208
91354
  var GUIDE_TOPICS = [
90209
91355
  "getting-started",
90210
91356
  "first-setup",
91357
+ "connect-wallet",
90211
91358
  "lifecycle",
90212
91359
  "fees",
90213
91360
  "psm",
@@ -90226,10 +91373,16 @@ without selling it. Your BTC sits in a custody vault tied to your position; you
90226
91373
  against it, pay it back whenever you like, and take your BTC out again.
90227
91374
 
90228
91375
  **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
90229
- topic, and always say plainly whether this session is PRACTICE or REAL:
90230
- - \`boundary://info\` (or \`protocol_status\`) tells you: adapter \`mock\` = a PRACTICE
90231
- sandbox \u2014 no real money anywhere. Adapter \`real\` = live protocol funds. SAY THIS
90232
- EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
91376
+ topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
91377
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
91378
+ are enabled (and the true reason when not), and which signer modes this build offers;
91379
+ never promise a capability it does not list. The money truth has THREE cases:
91380
+ - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
91381
+ - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
91382
+ the test network: real ceremonies and signatures, PRACTICE money (test funds).
91383
+ - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
91384
+ explicitly arms them; the capabilities block states which applies.
91385
+ SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
90233
91386
 
90234
91387
  A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
90235
91388
  authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
@@ -90237,22 +91390,37 @@ calls. Every operation that moves funds requires the user's explicit confirmatio
90237
91390
  (\`confirmed: true\`) \u2014 nothing is ever silent.`,
90238
91391
  "first-setup": `# First setup \u2014 from zero to ready, by conversation only
90239
91392
 
91393
+ Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
91394
+ \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
91395
+ host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
91396
+ developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
91397
+ install matrix.
91398
+
90240
91399
  Nothing needs a config file. Three steps:
90241
91400
 
90242
- **1. Know your world.** Read \`protocol_status\` and tell the user: practice (mock) or real,
90243
- the BTC network, current terms (\`protocol_terms\`).
91401
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
91402
+ \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
91403
+ (practice money) or mainnet (real money); whether writes are enabled here and which
91404
+ signer modes exist; current terms (\`protocol_terms\`).
90244
91405
 
90245
91406
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
90246
- - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\`. The user
90247
- opens the approval page link (returned by the tool), connects MetaMask \u2014 or taps
90248
- "Use a mobile wallet" for WalletConnect \u2014 and then APPROVES EACH OPERATION in their own
90249
- wallet. Their wallet address becomes their borrowing identity automatically.
91407
+ - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
91408
+ on the real adapter and the mock. The approval page auto-opens in the browser (its URL
91409
+ is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
91410
+ / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
91411
+ their own wallet. The first verified signature binds their wallet address as the
91412
+ borrower. Full walkthrough: \`guide connect-wallet\`.
90250
91413
  - **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
90251
- signs after each confirmation. If no keystore exists yet, call \`signer_setup\` action
90252
- \`unlock-keystore\`: a SECURE LOCAL PAGE opens where the user types the password or
90253
- generates a fresh keystore. NEVER ask for or accept a password in the conversation \u2014
90254
- if a user pastes one, tell them to use the unlock page instead.
91414
+ signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
91415
+ \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
91416
+ LOCAL PAGE opens where the user types the password or generates a fresh keystore.
91417
+ NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
91418
+ them to use the unlock page instead.
91419
+ - **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
91420
+ real adapter they refuse with that true reason. Try them in a mock world.
90255
91421
  - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
91422
+ - **No signer is also a valid start:** every public read works without one \u2014
91423
+ \`position_list {borrower}\` with the user's address needs no signer and no login.
90256
91424
 
90257
91425
  **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
90258
91426
  \`confirmed: true\` from the user). Then deposit BTC to the vault address
@@ -90260,6 +91428,55 @@ the BTC network, current terms (\`protocol_terms\`).
90260
91428
  and mint with \`loan_mint\`.
90261
91429
 
90262
91430
  The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
91431
+ "connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
91432
+
91433
+ External mode means the user approves every operation in their OWN wallet \u2014 a browser
91434
+ extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
91435
+ the mock.
91436
+
91437
+ **The walkthrough:**
91438
+ 1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
91439
+ desktop browser; its URL is ALSO in the tool result (loopback-only \u2014 open it on the
91440
+ same machine the server runs on).
91441
+ 2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
91442
+ WalletConnect QR code or paste the pairing code.
91443
+ 3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
91444
+ login ceremony explicitly (one typed-data signature in the wallet).
91445
+ 4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
91446
+ across sessions (\`signer_setup reset-borrower\` unbinds it).
91447
+ 5. From then on, every fund-moving operation shows an approval card in the wallet,
91448
+ decoded from the exact transaction bytes \u2014 what you read IS what executes. Declining
91449
+ always safely cancels.
91450
+
91451
+ **Popup cadence \u2014 exactly this many wallet interactions per operation:**
91452
+
91453
+ | Operation | Wallet interactions (external mode) |
91454
+ |---|---|
91455
+ | login (per login-session lifetime) | 1 typed-data |
91456
+ | create position | 1 tx (plus 1 login typed-data the first time \u2014 the protocol SDK keeps its own session) |
91457
+ | mint | 1 personal-sign + 1 tx |
91458
+ | repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
91459
+ | extend | 1 personal-sign + 1 tx |
91460
+ | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
91461
+ | withdraw BTC | not available in external mode yet (refuses with that reason); keystore mode works, no popups |
91462
+ | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
91463
+
91464
+ **Honesty notes (say these plainly):**
91465
+ - **Reads never pop the wallet.** If a read needs a login the user does not have, the
91466
+ tool refuses legibly and the user says "connect my wallet" (\`signer_setup\` action
91467
+ \`connect\`). The wallet never appears unrequested.
91468
+ - **Logins expire.** When the session token dies mid-conversation, the next
91469
+ authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
91470
+ surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
91471
+ login means "wait and retry", not a wallet failure.
91472
+ - **Withdraw-BTC under external mode is not shipped yet** (the SDK signing-context seam
91473
+ is pending) \u2014 it refuses with that true reason; keystore-mode withdraw works.
91474
+ - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
91475
+ (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
91476
+ hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
91477
+ card states the live figure.
91478
+ - **Mainnet:** writes are disabled unless the operator explicitly arms them, and the
91479
+ minimum mint is 10 UCD.`,
90263
91480
  lifecycle: `# The full lifecycle \u2014 exact calls
90264
91481
 
90265
91482
  1. **Create** \u2014 \`loan_create {selectedTerm, confirmed:true}\` \u2192 position id, vault address.
@@ -90355,12 +91572,23 @@ Every fund-moving operation needs TWO things, always in this order:
90355
91572
  1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
90356
91573
  must ask, never assume.
90357
91574
  2. **A cryptographic authorization** by the chosen signer mode:
90358
- - \`external\` \u2014 the user approves in their OWN wallet (browser popup or WalletConnect
90359
- mobile). The approval card in the wallet shows EXACTLY what executes \u2014 amounts are
90360
- decoded from the transaction itself, never re-formatted.
91575
+ - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
91576
+ mobile via QR/paste-code). Real adapter and mock. The approval card in the wallet
91577
+ shows EXACTLY what executes \u2014 amounts are decoded from the transaction itself, never
91578
+ re-formatted. Walkthrough: \`guide connect-wallet\`.
90361
91579
  - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
91580
+ Real adapter and mock.
91581
+ - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
91582
+ refuse with that true reason (their planes ship in their own deliveries).
90362
91583
  - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
90363
91584
 
91585
+ **Reads never summon the wallet.** Public reads need no signer at all. Authenticated
91586
+ reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
91587
+ (\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
91588
+ only ever caused by a write ceremony or that explicit connect. The login (one typed-data
91589
+ signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
91590
+ way \u2014 reconnect on the user's word.
91591
+
90364
91592
  Results carry \`authorization\`: \`scheme\` (external-wallet | eip712-eoa | mock-signature),
90365
91593
  \`signer\` (who signed), \`card\` (what was signed, human-readable), \`digest\` (the signature
90366
91594
  or transaction hash). Declining in the wallet ALWAYS safely cancels the operation.
@@ -90380,6 +91608,10 @@ signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companie
90380
91608
  teams use Safes so no single key controls the funds. Diamond Hands supports a Safe AS THE
90381
91609
  BORROWER: the position belongs to the Safe, and operations are authorized by its owners.
90382
91610
 
91611
+ **Adapter truth:** the Safe borrower plane is PRACTICE-ONLY today \u2014 on the real adapter,
91612
+ \`signer_setup use safe\` refuses with exactly that reason. Everything below runs in mock
91613
+ worlds until the Safe plane's own delivery; never present it as available on real.
91614
+
90383
91615
  **Setup:** \`signer_setup\` action \`use\`, mode \`safe\`, with \`safeAddress\`. Owners and
90384
91616
  threshold are DISCOVERED from the Safe itself \u2014 never typed in. (Practice worlds: create
90385
91617
  a test Safe first with \`mock_control deploy-safe\`.) If keystore material is already
@@ -90396,8 +91628,9 @@ AUTOMATICALLY \u2014 do not send the user to the unlock page in that case.
90396
91628
 
90397
91629
  **Withdrawals have one extra rule:** the destination BTC address must be ALLOWLISTED for
90398
91630
  the Safe first \u2014 \`loan_allowlist_destination\` (its own owner-signed ceremony; the address
90399
- becomes usable after a delay \u2014 immediately in practice worlds, up to 24h on the real
90400
- protocol). A withdrawal to an unlisted address refuses with exactly this instruction.
91631
+ becomes usable after a delay READ LIVE from the chain \u2014 immediate in practice worlds,
91632
+ 24 hours on mainnet, where allowlisting and withdrawing happen on different days). A
91633
+ withdrawal to an unlisted address refuses with exactly this instruction.
90401
91634
 
90402
91635
  **Timing honesty (multi-owner Safes, later phases):** authorizations for mint/pay/renew
90403
91636
  expire after ~3 minutes, and withdrawal authorizations within the minute \u2014 so a multi-
@@ -90410,6 +91643,10 @@ Multi-owner Safes cannot practically sign every operation inside the protocol's
90410
91643
  signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
90411
91644
  tightly-caged AGENT key; afterwards daily work runs without disturbing them.
90412
91645
 
91646
+ **Adapter truth:** delegation (mode \`safe-module\`) is PRACTICE-ONLY today \u2014 on the real
91647
+ adapter it refuses with exactly that reason, pending its own delivery. Everything below
91648
+ runs in mock worlds; never present it as available on real.
91649
+
90413
91650
  **Setup (mode \`safe-module\`):** \`signer_setup use safe-module\` with your Safe's address,
90414
91651
  then \`loan_delegation_setup\` \u2014 ONE durable Safe transaction the owners sign at their
90415
91652
  leisure (no time window). It enables the Safe's AgentModule, binds the agent key, registers
@@ -90460,8 +91697,19 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
90460
91697
  user believe practice gains/losses are real, or vice versa.`,
90461
91698
  troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
90462
91699
 
90463
- - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Run \`signer_setup status\`
90464
- and follow \`first-setup\` step 2.
91700
+ - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
91701
+ keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
91702
+ "connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
91703
+ status\` explains what is active; \`first-setup\` step 2 has the full choice.
91704
+ - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
91705
+ the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
91706
+ EXPIRED login refuses the same way \u2014 reconnect on the user's word.
91707
+ - **Mainnet write refused** \u2014 mainnet writes are disabled unless the operator explicitly
91708
+ arms them; the refusal is the standing gate, not a bug. Reads keep working.
91709
+ - **External-mode withdraw refused** \u2014 withdraw-BTC under external mode is not shipped
91710
+ yet (the SDK signing-context seam is pending); keystore-mode withdraw works.
91711
+ - **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
91712
+ That is the broker throttle, not a wallet failure.
90465
91713
  - **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
90466
91714
  unknown field). The message names the exact problem; fix the input, don't retry blindly.
90467
91715
  - **UPSTREAM_REJECTED** \u2014 the protocol said no: over the mint ceiling, repaying more than
@@ -90473,7 +91721,12 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
90473
91721
  - **STATE_DIVERGENCE / STALE_DATA warnings** \u2014 sources disagree or lag; the envelope says
90474
91722
  which source and when from. Prefer chain-sourced values; re-read before acting.
90475
91723
  - Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
90476
- Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.`,
91724
+ Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
91725
+ - **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
91726
+ the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
91727
+ Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
91728
+ Node \u2265 18 on PATH. Remedies: the one-line installer (self-contained binary, absolute
91729
+ path in the printed snippet), or the \`.mcpb\` bundle on macOS/Windows Claude Desktop.`,
90477
91730
  glossary: `# Glossary \u2014 map the user's words to the protocol's
90478
91731
 
90479
91732
  Synonym sets (treat these as the SAME intent):
@@ -90500,21 +91753,24 @@ not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitco
90500
91753
  };
90501
91754
  var GUIDE_INDEX = `# Diamond Hands guide \u2014 topics
90502
91755
 
90503
- - getting-started \u2014 what this product is, practice-vs-real honesty
91756
+ - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
90504
91757
  - first-setup \u2014 zero to ready by conversation (authorization choice included)
91758
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty
90505
91759
  - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
90506
91760
  - fees \u2014 the two fee models, plainly
90507
91761
  - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
90508
- - authorization \u2014 confirmation + signature: what protects every operation
90509
- - safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing
90510
- - delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners
91762
+ - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
91763
+ - safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today
91764
+ - delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today
90511
91765
  - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
90512
- - troubleshooting \u2014 error codes in plain words
91766
+ - troubleshooting \u2014 error codes in plain words, with the real remedies
90513
91767
  - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
90514
91768
 
90515
91769
  Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
90516
91770
  selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
90517
- signature ceremony. State whether the world is PRACTICE (mock) or REAL, early and always.`;
91771
+ signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
91772
+ and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
91773
+ only mainnet is real money.`;
90518
91774
 
90519
91775
  // src/tools/guide.ts
90520
91776
  function registerGuideTool(server) {
@@ -90523,7 +91779,7 @@ function registerGuideTool(server) {
90523
91779
  "guide",
90524
91780
  {
90525
91781
  title: "Diamond Hands product guide",
90526
- description: `Curated guidance on using Diamond Hands \u2014 START HERE for new users. Topics: ${GUIDE_TOPICS.join(" | ")}. No topic = the index + orientation. Covers first setup (choosing how to authorize by conversation), the full lifecycle with exact tool names, fees, safety, troubleshooting, and a synonym glossary for mapping ANY user's vocabulary (any language) to the right tools.`,
91782
+ description: `Curated guidance on using Diamond Hands \u2014 START HERE for new users. Topics: ${GUIDE_TOPICS.join(" | ")}. No topic = the index + orientation. Covers first setup (choosing how to authorize by conversation), connecting the user's own wallet, the full lifecycle with exact tool names, fees, safety, troubleshooting, and a synonym glossary for mapping ANY user's vocabulary (any language) to the right tools.`,
90527
91783
  inputSchema: {
90528
91784
  topic: import_zod7.z.string().optional().describe(`One of: ${GUIDE_TOPICS.join(" | ")} (omit for the index)`)
90529
91785
  },
@@ -90553,14 +91809,29 @@ function registerGuideResources(server) {
90553
91809
  function registerGuidePrompts(server) {
90554
91810
  server.prompt(
90555
91811
  "onboard-me",
90556
- "Walk a brand-new user through Diamond Hands: what it is, practice-vs-real, choosing how to authorize, and their first position.",
91812
+ "Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
90557
91813
  () => ({
90558
91814
  messages: [
90559
91815
  {
90560
91816
  role: "user",
90561
91817
  content: {
90562
91818
  type: "text",
90563
- text: "I'm new to Diamond Hands. Read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status and boundary://info, then walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money, help me choose how to authorize operations (my own wallet vs automatic keystore \u2014 ask me), and then help me open my first position. Ask before every operation; never assume confirmation."
91819
+ text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. Ask before every operation; never assume confirmation."
91820
+ }
91821
+ }
91822
+ ]
91823
+ })
91824
+ );
91825
+ server.prompt(
91826
+ "connect-wallet",
91827
+ "Connect the user's own wallet as the signer: approval page, extension or WalletConnect QR, first-signature binding, per-operation approvals.",
91828
+ () => ({
91829
+ messages: [
91830
+ {
91831
+ role: "user",
91832
+ content: {
91833
+ type: "text",
91834
+ text: "I want to approve operations with my own wallet. Read guide 'connect-wallet', check boundary://info capabilities to confirm external mode is available here, then run signer_setup action 'use' mode 'external' and walk me through it IN MY LANGUAGE: the approval page (it auto-opens; the URL is also in the tool result), connecting my browser extension or scanning the WalletConnect QR code, how my first signature binds my wallet as the borrower, and exactly how many wallet interactions each operation costs (the popup-cadence table). Remind me that reads never pop my wallet and that declining in the wallet always cancels safely."
90564
91835
  }
90565
91836
  }
90566
91837
  ]
@@ -90679,7 +91950,7 @@ function registerBoundaryInfoResource(server, getB) {
90679
91950
  "boundary://info",
90680
91951
  {
90681
91952
  title: "Boundary identity",
90682
- description: "Which world this server is talking to: adapter kind (mock/real), network + chainId (which chain \u2014 state it), practiceWorld (true = NO REAL MONEY: mock sandbox or a testnet \u2014 tell the user plainly), active data sources, signer identity (when configured), config fingerprint. Never key material. Timestamp bases: each source's fetchedAt is the DATA's as-of time at that source; the envelope-level source line on tool results is the READ time \u2014 they legitimately differ.",
91953
+ description: "Which world this server is talking to: adapter kind (mock/real), network + chainId (which chain \u2014 state it), practiceWorld (true = NO REAL MONEY: mock sandbox or a testnet \u2014 tell the user plainly), active data sources, signer identity (when configured), config fingerprint, and the `capabilities` block (reads/writes availability with the TRUE reason when disabled, offered signer modes, active mode) \u2014 READ THIS BEFORE PROMISING ANY FLOW; never describe a capability it does not list. Never key material. Timestamp bases: each source's fetchedAt is the DATA's as-of time at that source; the envelope-level source line on tool results is the READ time \u2014 they legitimately differ.",
90683
91954
  mimeType: "application/json"
90684
91955
  },
90685
91956
  async (uri) => {
@@ -90694,12 +91965,16 @@ function registerBoundaryInfoResource(server, getB) {
90694
91965
  }
90695
91966
 
90696
91967
  // src/server.ts
90697
- var SERVER_VERSION = "0.1.1";
91968
+ var SERVER_VERSION = "0.2.1";
91969
+ var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives.";
90698
91970
  function createServer2(deps) {
90699
- const server = new import_mcp2.McpServer({
90700
- name: "diamond-hands",
90701
- version: SERVER_VERSION
90702
- });
91971
+ const server = new import_mcp2.McpServer(
91972
+ {
91973
+ name: "diamond-hands",
91974
+ version: SERVER_VERSION
91975
+ },
91976
+ { instructions: SERVER_INSTRUCTIONS }
91977
+ );
90703
91978
  const getB = () => deps.boundaryResult;
90704
91979
  registerLoanTools(server, getB, deps.mockControl ? "mock" : "real");
90705
91980
  registerPositionTools(server, getB);
@@ -90722,6 +91997,11 @@ function createServer2(deps) {
90722
91997
  }
90723
91998
 
90724
91999
  // src/index.ts
92000
+ if (process.argv.includes("--version")) {
92001
+ process.stdout.write(`${SERVER_VERSION}
92002
+ `);
92003
+ process.exit(0);
92004
+ }
90725
92005
  async function main() {
90726
92006
  const configResult = resolveBoundaryConfig(process.env);
90727
92007
  const boot = await buildBoundary(configResult);