@gvnrdao/dh-mcp 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +67 -26
  2. package/dist/boundary.js +1507 -444
  3. package/dist/index.js +1687 -492
  4. package/package.json +2 -1
package/dist/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;
@@ -87311,6 +87423,12 @@ var LitOpsSession = class {
87311
87423
  address() {
87312
87424
  return this.wallet.address;
87313
87425
  }
87426
+ /** A JWT is cached and not about to expire — reads in external mode consult this
87427
+ * instead of `token()` so they NEVER summon the wallet (plan 10 A0.7). */
87428
+ hasValidToken() {
87429
+ const now = Math.floor(Date.now() / 1e3);
87430
+ return this.cached !== null && this.cached.expiresAtSec - REFRESH_LEEWAY_SEC > now;
87431
+ }
87314
87432
  /** A valid Bearer token, logging in (or re-logging) as needed. Throws with a legible
87315
87433
  * message on failure — the gateway maps it to the taxonomy. */
87316
87434
  async token() {
@@ -87368,9 +87486,240 @@ function decodeJwtExp(token) {
87368
87486
  }
87369
87487
 
87370
87488
  // src/boundary/upstream/real/write-ops.ts
87489
+ var import_ethers33 = require("ethers");
87490
+
87491
+ // src/signer/types.ts
87492
+ var OperationDeclined = class extends Error {
87493
+ };
87494
+
87495
+ // src/boundary/upstream/real/write-ops.ts
87496
+ init_tx_validator();
87497
+
87498
+ // src/boundary/upstream/shared/external-bridge/page-crypto.ts
87371
87499
  var import_ethers32 = require("ethers");
87500
+ var PERSONAL_SIGN_LAYOUTS = {
87501
+ "dh-op-envelope-v1": {
87502
+ types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
87503
+ fieldOrder: ["positionId", "timestamp", "chainId", "amount", "action"],
87504
+ hashUtf8Fields: ["action"]
87505
+ }
87506
+ };
87507
+ function hashForLayout(layout, fields) {
87508
+ const def = PERSONAL_SIGN_LAYOUTS[layout];
87509
+ if (!def) throw new Error(`page-crypto: unknown layout "${layout}"`);
87510
+ const hashUtf8 = new Set(def.hashUtf8Fields);
87511
+ const values = def.fieldOrder.map((name) => {
87512
+ const raw = fields[name];
87513
+ if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
87514
+ return hashUtf8.has(name) ? import_ethers32.ethers.keccak256(import_ethers32.ethers.toUtf8Bytes(raw)) : raw;
87515
+ });
87516
+ return import_ethers32.ethers.solidityPackedKeccak256(def.types, values);
87517
+ }
87518
+ var PAGE_CRYPTO_JS = `"use strict";
87519
+ (function () {
87520
+ // keccak-f[1600] \u2014 25 lanes of 64-bit BigInt, state[x + 5*y]. Validated bit-for-bit
87521
+ // against ethers.keccak256 across empty/short/rate-boundary inputs (page-crypto.test.ts).
87522
+ var MASK64 = (1n << 64n) - 1n;
87523
+
87524
+ function rotl64(x, n) {
87525
+ x &= MASK64;
87526
+ var nn = BigInt(n % 64);
87527
+ if (nn === 0n) return x;
87528
+ return ((x << nn) | (x >> (64n - nn))) & MASK64;
87529
+ }
87530
+
87531
+ var RC = [
87532
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
87533
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
87534
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
87535
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
87536
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
87537
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n
87538
+ ];
87539
+
87540
+ // r[x][y] rotation offsets, flat index x + 5*y.
87541
+ var ROT = [
87542
+ 0, 1, 62, 28, 27,
87543
+ 36, 44, 6, 55, 20,
87544
+ 3, 10, 43, 25, 39,
87545
+ 41, 45, 15, 21, 8,
87546
+ 18, 2, 61, 56, 14
87547
+ ];
87548
+
87549
+ function keccakF1600(state) {
87550
+ for (var round = 0; round < 24; round++) {
87551
+ var C = new Array(5);
87552
+ for (var x = 0; x < 5; x++) {
87553
+ C[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20];
87554
+ }
87555
+ var D = new Array(5);
87556
+ for (var x2 = 0; x2 < 5; x2++) {
87557
+ D[x2] = C[(x2 + 4) % 5] ^ rotl64(C[(x2 + 1) % 5], 1);
87558
+ }
87559
+ for (var x3 = 0; x3 < 5; x3++) {
87560
+ for (var y = 0; y < 5; y++) {
87561
+ state[x3 + 5 * y] ^= D[x3];
87562
+ }
87563
+ }
87564
+ var B = new Array(25);
87565
+ for (var x4 = 0; x4 < 5; x4++) {
87566
+ for (var y2 = 0; y2 < 5; y2++) {
87567
+ var newX = y2;
87568
+ var newY = (2 * x4 + 3 * y2) % 5;
87569
+ B[newX + 5 * newY] = rotl64(state[x4 + 5 * y2], ROT[x4 + 5 * y2]);
87570
+ }
87571
+ }
87572
+ for (var x5 = 0; x5 < 5; x5++) {
87573
+ for (var y3 = 0; y3 < 5; y3++) {
87574
+ var idx = x5 + 5 * y3;
87575
+ state[idx] = (B[idx] ^ (~B[(x5 + 1) % 5 + 5 * y3] & B[(x5 + 2) % 5 + 5 * y3])) & MASK64;
87576
+ }
87577
+ }
87578
+ state[0] = (state[0] ^ RC[round]) & MASK64;
87579
+ }
87580
+ }
87581
+
87582
+ function keccak256Bytes(bytes) {
87583
+ var rateBytes = 136; // 1088-bit rate (keccak256: capacity 512 bits)
87584
+ var state = new Array(25).fill(0n);
87585
+
87586
+ // Original-Keccak multi-rate padding (pad10*1, domain byte 0x01 \u2014 NOT NIST SHA3's 0x06).
87587
+ var padLen = rateBytes - (bytes.length % rateBytes);
87588
+ var padded = new Uint8Array(bytes.length + padLen);
87589
+ padded.set(bytes);
87590
+ padded[bytes.length] ^= 0x01;
87591
+ padded[padded.length - 1] ^= 0x80;
87592
+
87593
+ for (var off = 0; off < padded.length; off += rateBytes) {
87594
+ for (var i = 0; i < rateBytes / 8; i++) {
87595
+ var lane = 0n;
87596
+ for (var b = 7; b >= 0; b--) {
87597
+ lane = (lane << 8n) | BigInt(padded[off + i * 8 + b]);
87598
+ }
87599
+ state[i] ^= lane;
87600
+ }
87601
+ keccakF1600(state);
87602
+ }
87603
+
87604
+ var out = new Uint8Array(32);
87605
+ for (var j = 0; j < 4; j++) {
87606
+ var laneOut = state[j];
87607
+ for (var b2 = 0; b2 < 8; b2++) {
87608
+ out[j * 8 + b2] = Number(laneOut & 0xffn);
87609
+ laneOut >>= 8n;
87610
+ }
87611
+ }
87612
+ return out;
87613
+ }
87614
+
87615
+ function bytesToHex(bytes) {
87616
+ var hex = "0x";
87617
+ for (var i = 0; i < bytes.length; i++) {
87618
+ hex += bytes[i].toString(16).padStart(2, "0");
87619
+ }
87620
+ return hex;
87621
+ }
87622
+
87623
+ function hexToBytes(hex) {
87624
+ if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) {
87625
+ throw new Error("dhPageCrypto: not a 0x-hex string: " + String(hex));
87626
+ }
87627
+ var clean = hex.slice(2);
87628
+ if (clean.length % 2 !== 0) {
87629
+ throw new Error("dhPageCrypto: odd-length hex string: " + hex);
87630
+ }
87631
+ var out = new Uint8Array(clean.length / 2);
87632
+ for (var i = 0; i < out.length; i++) {
87633
+ out[i] = parseInt(clean.substr(i * 2, 2), 16);
87634
+ }
87635
+ return out;
87636
+ }
87637
+
87638
+ function keccak256HexOfBytes(hexStr) {
87639
+ return bytesToHex(keccak256Bytes(hexToBytes(hexStr)));
87640
+ }
87641
+
87642
+ function keccak256Utf8(str) {
87643
+ return bytesToHex(keccak256Bytes(new TextEncoder().encode(String(str))));
87644
+ }
87645
+
87646
+ function uint256ToBytes32(decStr) {
87647
+ if (typeof decStr !== "string" || !/^[0-9]+$/.test(decStr)) {
87648
+ throw new Error("dhPageCrypto: not a decimal uint256 string: " + String(decStr));
87649
+ }
87650
+ var n = BigInt(decStr);
87651
+ if (n > (2n ** 256n) - 1n) {
87652
+ throw new Error("dhPageCrypto: uint256 out of range: " + decStr);
87653
+ }
87654
+ var bytes = new Uint8Array(32);
87655
+ for (var i = 31; i >= 0; i--) {
87656
+ bytes[i] = Number(n & 0xffn);
87657
+ n >>= 8n;
87658
+ }
87659
+ return bytes;
87660
+ }
87661
+
87662
+ function requireBytes32(hex, fieldName) {
87663
+ var bytes = hexToBytes(hex);
87664
+ if (bytes.length !== 32) {
87665
+ throw new Error("dhPageCrypto: field \\"" + fieldName + "\\" must be exactly 32 bytes, got " + bytes.length);
87666
+ }
87667
+ return bytes;
87668
+ }
87669
+
87670
+ // Embedded verbatim from PERSONAL_SIGN_LAYOUTS (page-crypto.ts) \u2014 see the anti-drift note
87671
+ // in that file's header comment. Do not hand-edit; this is generated at module load.
87672
+ var PERSONAL_SIGN_LAYOUTS = ${JSON.stringify(PERSONAL_SIGN_LAYOUTS)};
87673
+
87674
+ function packAndHash(layout, fields) {
87675
+ var def = PERSONAL_SIGN_LAYOUTS[layout];
87676
+ if (!def) {
87677
+ throw new Error("dhPageCrypto: unknown layout \\"" + layout + "\\"");
87678
+ }
87679
+ var hashUtf8 = {};
87680
+ for (var h = 0; h < def.hashUtf8Fields.length; h++) {
87681
+ hashUtf8[def.hashUtf8Fields[h]] = true;
87682
+ }
87683
+ var parts = [];
87684
+ var totalLen = 0;
87685
+ for (var i = 0; i < def.fieldOrder.length; i++) {
87686
+ var name = def.fieldOrder[i];
87687
+ var type = def.types[i];
87688
+ var raw = fields ? fields[name] : undefined;
87689
+ if (raw === undefined || raw === null) {
87690
+ throw new Error("dhPageCrypto: layout \\"" + layout + "\\" missing field \\"" + name + "\\"");
87691
+ }
87692
+ var valueHex = hashUtf8[name] ? keccak256Utf8(String(raw)) : raw;
87693
+ var part;
87694
+ if (type === "bytes32") {
87695
+ part = requireBytes32(valueHex, name);
87696
+ } else if (type === "uint256") {
87697
+ part = uint256ToBytes32(valueHex);
87698
+ } else {
87699
+ throw new Error("dhPageCrypto: unsupported packed type \\"" + type + "\\" in layout \\"" + layout + "\\"");
87700
+ }
87701
+ parts.push(part);
87702
+ totalLen += part.length;
87703
+ }
87704
+ var packed = new Uint8Array(totalLen);
87705
+ var offset = 0;
87706
+ for (var p = 0; p < parts.length; p++) {
87707
+ packed.set(parts[p], offset);
87708
+ offset += parts[p].length;
87709
+ }
87710
+ return keccak256HexOfBytes(bytesToHex(packed));
87711
+ }
87712
+
87713
+ globalThis.dhPageCrypto = {
87714
+ keccak256HexOfBytes: keccak256HexOfBytes,
87715
+ keccak256Utf8: keccak256Utf8,
87716
+ packAndHash: packAndHash
87717
+ };
87718
+ })();
87719
+ `;
87372
87720
 
87373
87721
  // src/boundary/upstream/real/validation-context.ts
87722
+ init_tx_validator();
87374
87723
  function buildValidationContext(network, chainId) {
87375
87724
  const sdkKey = chainId === 31337 ? "localhost" : chainId === 11155111 ? "sepolia" : network.toLowerCase();
87376
87725
  const contracts = getContractsByNetwork(sdkKey);
@@ -87390,14 +87739,10 @@ function psmMainnetWriteRefusal(network, chainId) {
87390
87739
  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
87740
  };
87392
87741
  }
87393
- var QUANTUM_SECONDS3 = 60;
87394
87742
  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
- }
87743
+ var OP_LAYOUT = "dh-op-envelope-v1";
87399
87744
  function randomNonceHex() {
87400
- return "0x" + Buffer.from(import_ethers32.ethers.randomBytes(16)).toString("hex");
87745
+ return "0x" + Buffer.from(import_ethers33.ethers.randomBytes(16)).toString("hex");
87401
87746
  }
87402
87747
  async function postJson(url2, body, headers) {
87403
87748
  const res = await fetch(url2, {
@@ -87437,15 +87782,55 @@ function buildWriteOps(deps) {
87437
87782
  })
87438
87783
  );
87439
87784
  const failed = (op, e) => upFail({ kind: "unavailable", source: SOURCE5, message: `${op} failed to reach lit-ops`, raw: String(e) });
87785
+ 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) });
87786
+ function opAuthSpec(p) {
87787
+ return {
87788
+ action: p.action,
87789
+ layout: OP_LAYOUT,
87790
+ stamp: (quantumTs) => {
87791
+ const fields = {
87792
+ positionId: p.positionId,
87793
+ timestamp: String(quantumTs),
87794
+ chainId: String(chainId),
87795
+ amount: p.amount.toString(),
87796
+ action: p.action
87797
+ };
87798
+ return { fields, hashHex: hashForLayout(OP_LAYOUT, fields), card: p.card(fields) };
87799
+ }
87800
+ };
87801
+ }
87802
+ function toCardPayload(tx2) {
87803
+ return {
87804
+ to: String(tx2["to"] ?? ""),
87805
+ data: String(tx2["data"] ?? "0x"),
87806
+ value: tx2["value"] != null ? import_ethers33.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
87807
+ chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
87808
+ };
87809
+ }
87440
87810
  async function executeAndBroadcast(p) {
87441
- const userSignature = await dhSigner.signAuthMessage(p.messageHash);
87811
+ let authRes;
87812
+ try {
87813
+ authRes = await dhSigner.signAuthorization(p.spec);
87814
+ } catch (e) {
87815
+ return submitFailure(`${p.op} authorization`, e);
87816
+ }
87817
+ const digest = p.spec.stamp(authRes.quantumTs).hashHex;
87442
87818
  const borrowerAddress = await dhSigner.getBorrowerAddress();
87443
- const headers = await session.authHeader();
87819
+ let headers;
87820
+ try {
87821
+ headers = await session.authHeader();
87822
+ } catch (e) {
87823
+ return upFail({
87824
+ kind: "unavailable",
87825
+ source: SOURCE5,
87826
+ message: `${p.op} could not establish the lit-ops login session (broker unreachable, or throttling logins): ${e instanceof Error ? e.message : String(e)}`
87827
+ });
87828
+ }
87444
87829
  let execJson;
87445
87830
  try {
87446
87831
  execJson = await postJson(
87447
87832
  `${config.serviceEndpoint}/api/lit/${p.op}/execute`,
87448
- { authMessage: p.authMessage, userSignature, borrowerAddress },
87833
+ { authMessage: p.authMessage(authRes.quantumTs), userSignature: authRes.signature, borrowerAddress },
87449
87834
  headers
87450
87835
  );
87451
87836
  } catch (e) {
@@ -87469,12 +87854,13 @@ function buildWriteOps(deps) {
87469
87854
  } catch (e) {
87470
87855
  return upFail({ kind: "rejected", source: SOURCE5, message: `approve tx failed the M-9 whitelist: ${e.message}` });
87471
87856
  }
87472
- const signedApprove = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedApproveTx));
87473
87857
  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"]);
87858
+ await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedApproveTx), {
87859
+ action: `${p.spec.action} (UCD approve)`,
87860
+ card: cardForTx(toCardPayload(unsignedApproveTx))
87861
+ });
87476
87862
  } catch (e) {
87477
- return failed(`${p.op} (UCD approve broadcast)`, e);
87863
+ return submitFailure(`${p.op} (UCD approve)`, e);
87478
87864
  }
87479
87865
  }
87480
87866
  }
@@ -87487,23 +87873,18 @@ function buildWriteOps(deps) {
87487
87873
  } catch (e) {
87488
87874
  return upFail({ kind: "rejected", source: SOURCE5, message: `unsigned tx failed the M-9 whitelist: ${e.message}` });
87489
87875
  }
87490
- const signedTx = await dhSigner.signTransaction(await dhSigner.wrapInnerTx(unsignedTx));
87491
- let broadcastJson;
87876
+ let submitted;
87492
87877
  try {
87493
87878
  const meta = p.broadcastMeta(data);
87494
- broadcastJson = await postJson(
87495
- `${config.serviceEndpoint}/api/lit/broadcast`,
87496
- { signedTx, ...meta ? { [p.broadcastMetaKey]: meta } : {} },
87497
- headers
87498
- );
87879
+ submitted = await dhSigner.submitValidatedTx(await dhSigner.wrapInnerTx(unsignedTx), {
87880
+ action: p.spec.action,
87881
+ card: cardForTx(toCardPayload(unsignedTx)),
87882
+ ...meta ? { broadcast: { key: p.broadcastMetaKey, meta } } : {}
87883
+ });
87499
87884
  } catch (e) {
87500
- return failed(`${p.op} broadcast`, e);
87885
+ return submitFailure(`${p.op} broadcast`, e);
87501
87886
  }
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() });
87887
+ return upOk({ data, txHash: submitted.txHash, digest }, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87507
87888
  }
87508
87889
  return {
87509
87890
  createPosition: async (p) => {
@@ -87545,15 +87926,21 @@ function buildWriteOps(deps) {
87545
87926
  mint: async (p) => {
87546
87927
  const amountWei = BigInt(p.amountUcdWei);
87547
87928
  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
87929
  const r = await executeAndBroadcast({
87554
87930
  op: "mint",
87555
- authMessage: { positionId: p.positionId, timestamp, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87556
- messageHash,
87931
+ spec: opAuthSpec({
87932
+ action,
87933
+ positionId: p.positionId,
87934
+ amount: amountWei,
87935
+ card: (f) => [
87936
+ "Authorize: mint UCD against your BTC collateral (this signature authorizes the operation; the transaction that executes it is approved separately)",
87937
+ `Position: ${p.positionId}`,
87938
+ `Amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
87939
+ `Chain id: ${chainId}`,
87940
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87941
+ ]
87942
+ }),
87943
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, amount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87557
87944
  validation: (data) => {
87558
87945
  const mintFee2 = data["mintFee"];
87559
87946
  if (typeof mintFee2 !== "string" || mintFee2.length === 0) {
@@ -87576,7 +87963,7 @@ function buildWriteOps(deps) {
87576
87963
  mintedUcdWei: minted,
87577
87964
  feeUcdWei: mintFee,
87578
87965
  echoedAmountUcdWei: minted,
87579
- authorization: auth(action, `mint ${import_ethers32.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87966
+ authorization: auth(action, `mint ${import_ethers33.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
87580
87967
  },
87581
87968
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87582
87969
  );
@@ -87584,15 +87971,21 @@ function buildWriteOps(deps) {
87584
87971
  repay: async (p) => {
87585
87972
  const amountWei = BigInt(p.amountUcdWei);
87586
87973
  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
87974
  const r = await executeAndBroadcast({
87593
87975
  op: "repay",
87594
- authMessage: { positionId: p.positionId, timestamp, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() },
87595
- messageHash,
87976
+ spec: opAuthSpec({
87977
+ action,
87978
+ positionId: p.positionId,
87979
+ amount: amountWei,
87980
+ card: (f) => [
87981
+ "Authorize: pay down UCD debt (this signature authorizes the operation; the transaction that executes it is approved separately)",
87982
+ `Position: ${p.positionId}`,
87983
+ `Payment amount: ${formatUcd(amountWei)} UCD (${amountWei.toString()} wei)`,
87984
+ `Chain id: ${chainId}`,
87985
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
87986
+ ]
87987
+ }),
87988
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, paymentAmount: amountWei.toString(), action, mode, nonce: randomNonceHex() }),
87596
87989
  validation: () => ({ kind: "repay", positionId: p.positionId, amountWei: amountWei.toString() }),
87597
87990
  approveValidation: () => {
87598
87991
  const vctx = buildValidationContext(config.network, chainId);
@@ -87611,22 +88004,28 @@ function buildWriteOps(deps) {
87611
88004
  txRef: { kind: "eth-tx", id: r.value.txHash },
87612
88005
  paidUcdWei: paid,
87613
88006
  echoedAmountUcdWei: paid,
87614
- authorization: auth(action, `repay ${import_ethers32.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
88007
+ authorization: auth(action, `repay ${import_ethers33.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
87615
88008
  },
87616
88009
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
87617
88010
  );
87618
88011
  },
87619
88012
  extend: async (p) => {
87620
88013
  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
88014
  const r = await executeAndBroadcast({
87627
88015
  op: "renew",
87628
- authMessage: { positionId: p.positionId, timestamp, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() },
87629
- messageHash,
88016
+ spec: opAuthSpec({
88017
+ action,
88018
+ positionId: p.positionId,
88019
+ amount: BigInt(p.selectedTerm),
88020
+ card: (f) => [
88021
+ "Authorize: extend (renew) the position term (this signature authorizes the operation; the transaction that executes it is approved separately)",
88022
+ `Position: ${p.positionId}`,
88023
+ `New term: ${p.selectedTerm} months`,
88024
+ `Chain id: ${chainId}`,
88025
+ `Authorization timestamp (quantum window): ${f["timestamp"]}`
88026
+ ]
88027
+ }),
88028
+ authMessage: (ts) => ({ positionId: p.positionId, timestamp: ts, chainId, newTerm: p.selectedTerm, action, mode, nonce: randomNonceHex() }),
87630
88029
  validation: () => ({ kind: "extend", positionId: p.positionId, selectedTerm: p.selectedTerm }),
87631
88030
  broadcastMetaKey: "renewMeta",
87632
88031
  broadcastMeta: () => ({ positionId: p.positionId, borrowerAddress: p.borrower, selectedTerm: p.selectedTerm, chainId })
@@ -87702,20 +88101,18 @@ function buildWriteOps(deps) {
87702
88101
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
87703
88102
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
87704
88103
  const tokenSymbol = isSwap ? "USDC" : "UCD";
87705
- const headers = await session.authHeader();
87706
88104
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
87707
88105
  if (!quoteR.ok) return upFail(quoteR.failure);
87708
- const broadcast = async (leg, tx2) => {
88106
+ const broadcast = async (leg, action, tx2) => {
87709
88107
  try {
87710
88108
  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() });
88109
+ const submitted = await dhSigner.submitValidatedTx(populated, {
88110
+ action,
88111
+ card: cardForTx(toCardPayload(tx2))
88112
+ });
88113
+ return upOk(submitted.txHash, { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
87717
88114
  } catch (e) {
87718
- return failed(leg, e);
88115
+ return submitFailure(leg, e);
87719
88116
  }
87720
88117
  };
87721
88118
  const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
@@ -87729,7 +88126,7 @@ function buildWriteOps(deps) {
87729
88126
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
87730
88127
  }
87731
88128
  const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
87732
- const approveHashR = await broadcast("psmSwap (approve)", approveTx);
88129
+ const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
87733
88130
  if (!approveHashR.ok) return approveHashR;
87734
88131
  const approveHash = approveHashR.value;
87735
88132
  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 +88141,7 @@ function buildWriteOps(deps) {
87744
88141
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
87745
88142
  }
87746
88143
  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);
88144
+ const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
87748
88145
  if (!execHashR.ok) {
87749
88146
  const f = execHashR.failure;
87750
88147
  return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
@@ -87828,33 +88225,296 @@ function buildWriteOps(deps) {
87828
88225
  }
87829
88226
 
87830
88227
  // src/signer/eoa-dh.ts
87831
- var import_ethers33 = require("ethers");
88228
+ var import_ethers34 = require("ethers");
87832
88229
  var EoaDHSigner = class {
87833
- kind = "eoa-env";
87834
- wallet;
87835
- constructor(wallet) {
88230
+ constructor(wallet, broadcast, clock = Date.now) {
87836
88231
  this.wallet = wallet;
88232
+ this.broadcast = broadcast;
88233
+ this.clock = clock;
87837
88234
  }
88235
+ kind = "eoa-env";
87838
88236
  async getBorrowerAddress() {
87839
88237
  return this.wallet.getAddress();
87840
88238
  }
87841
88239
  async getAuthSignerAddress() {
87842
88240
  return this.wallet.getAddress();
87843
88241
  }
87844
- async signAuthMessage(messageHash) {
87845
- return this.wallet.signMessage(import_ethers33.ethers.getBytes(messageHash));
88242
+ async signAuthorization(spec) {
88243
+ const quantumTs = nextQuantumTimestamp(this.clock());
88244
+ const { fields, hashHex } = spec.stamp(quantumTs);
88245
+ const signature = await this.wallet.signMessage(import_ethers34.ethers.getBytes(hashHex));
88246
+ return { signature, quantumTs, fields };
87846
88247
  }
87847
88248
  async wrapInnerTx(innerTx) {
87848
88249
  return innerTx;
87849
88250
  }
87850
- async signTransaction(outerTx) {
87851
- return this.wallet.signTransaction(outerTx);
88251
+ async submitValidatedTx(outerTx, ctx) {
88252
+ const signed = await this.wallet.signTransaction(outerTx);
88253
+ const txHash = await this.broadcast(signed, ctx.broadcast ? { [ctx.broadcast.key]: ctx.broadcast.meta } : void 0);
88254
+ return { txHash, signer: await this.wallet.getAddress(), scheme: "eip712-eoa" };
87852
88255
  }
87853
88256
  getEthersSigner() {
87854
88257
  return this.wallet;
87855
88258
  }
87856
88259
  };
87857
88260
 
88261
+ // src/signer/external-eoa.ts
88262
+ var import_node_crypto5 = require("crypto");
88263
+ var import_ethers36 = require("ethers");
88264
+
88265
+ // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
88266
+ var import_ethers35 = require("ethers");
88267
+ function eq2(a, b) {
88268
+ return a.toLowerCase() === b.toLowerCase();
88269
+ }
88270
+ function compareLandedTx(landed, approved, borrower) {
88271
+ 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;
88272
+ if (mismatch) {
88273
+ return {
88274
+ status: "mismatch",
88275
+ hash: landed.hash,
88276
+ 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`
88277
+ };
88278
+ }
88279
+ if (!eq2(landed.from, borrower)) {
88280
+ return {
88281
+ status: "mismatch",
88282
+ hash: landed.hash,
88283
+ reason: `tx ${landed.hash} was signed by ${landed.from}, not the borrower ${borrower} \u2014 already on-chain; do NOT retry, re-read state`
88284
+ };
88285
+ }
88286
+ return { status: "verified", from: landed.from, hash: landed.hash };
88287
+ }
88288
+ function verifyRawSignedTx(rawSignedTx, approved, borrower) {
88289
+ const parsed = import_ethers35.ethers.Transaction.from(rawSignedTx);
88290
+ if (!parsed.from || !parsed.to || !parsed.hash) {
88291
+ return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
88292
+ }
88293
+ return compareLandedTx(
88294
+ { from: parsed.from, to: parsed.to, data: parsed.data, value: parsed.value, chainId: parsed.chainId, hash: parsed.hash },
88295
+ approved,
88296
+ borrower
88297
+ );
88298
+ }
88299
+ async function verifyBroadcastTxByHash(provider, hash, approved, borrower, budget) {
88300
+ let tx2 = null;
88301
+ for (let i = 0; i < budget.attempts && tx2 === null; i++) {
88302
+ tx2 = await provider.getTransaction(hash);
88303
+ if (tx2 === null && i < budget.attempts - 1) await new Promise((r) => setTimeout(r, budget.delayMs));
88304
+ }
88305
+ if (tx2 === null || !tx2.from || !tx2.to) {
88306
+ return {
88307
+ status: "unknown",
88308
+ hash,
88309
+ 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).`
88310
+ };
88311
+ }
88312
+ return compareLandedTx(
88313
+ { from: tx2.from, to: tx2.to, data: tx2.data, value: tx2.value, chainId: BigInt(tx2.chainId), hash: tx2.hash },
88314
+ approved,
88315
+ borrower
88316
+ );
88317
+ }
88318
+
88319
+ // src/signer/external-eoa.ts
88320
+ var DEFAULT_BUDGET = { attempts: 30, delayMs: 3e3 };
88321
+ var ExternalEoaDHSigner = class {
88322
+ constructor(deps) {
88323
+ this.deps = deps;
88324
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88325
+ }
88326
+ kind = "external-eoa";
88327
+ budget;
88328
+ async getBorrowerAddress() {
88329
+ return this.deps.borrower;
88330
+ }
88331
+ async getAuthSignerAddress() {
88332
+ return this.deps.borrower;
88333
+ }
88334
+ async signAuthorization(spec) {
88335
+ const initialTs = nextQuantumTimestamp(Date.now());
88336
+ const initial = spec.stamp(initialTs);
88337
+ let used = { quantumTs: initialTs, fields: initial.fields };
88338
+ const outcome = await this.deps.bridge.requestSignature(
88339
+ {
88340
+ id: (0, import_node_crypto5.randomUUID)(),
88341
+ kind: "personal-sign",
88342
+ action: spec.action,
88343
+ card: initial.card,
88344
+ expectedSigner: this.deps.borrower,
88345
+ chainId: this.deps.chainId,
88346
+ personalSign: { layout: spec.layout, fields: initial.fields, hashHex: initial.hashHex }
88347
+ },
88348
+ {
88349
+ finalize: async () => {
88350
+ const ts = nextQuantumTimestamp(Date.now());
88351
+ const s = spec.stamp(ts);
88352
+ used = { quantumTs: ts, fields: s.fields };
88353
+ return { personalSign: { layout: spec.layout, fields: s.fields, hashHex: s.hashHex }, card: s.card };
88354
+ }
88355
+ }
88356
+ );
88357
+ if (outcome.status !== "approved" || !outcome.signature) {
88358
+ throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
88359
+ }
88360
+ const finalHash = spec.stamp(used.quantumTs).hashHex;
88361
+ const recovered = import_ethers36.ethers.verifyMessage(import_ethers36.ethers.getBytes(finalHash), outcome.signature);
88362
+ if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
88363
+ throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
88364
+ }
88365
+ return { signature: outcome.signature, quantumTs: used.quantumTs, fields: used.fields };
88366
+ }
88367
+ async wrapInnerTx(innerTx) {
88368
+ return innerTx;
88369
+ }
88370
+ async submitValidatedTx(outerTx, ctx) {
88371
+ const approved = toApprovedTx(outerTx, this.deps.chainId);
88372
+ const outcome = await this.deps.bridge.requestSignature({
88373
+ id: (0, import_node_crypto5.randomUUID)(),
88374
+ kind: "transaction",
88375
+ action: ctx.action,
88376
+ card: ctx.card,
88377
+ expectedSigner: this.deps.borrower,
88378
+ chainId: this.deps.chainId,
88379
+ tx: approved
88380
+ });
88381
+ if (outcome.status !== "approved") {
88382
+ throw new OperationDeclined(`the ${ctx.action} transaction was not approved: ${describeOutcome(outcome)}`);
88383
+ }
88384
+ const verdict = await this.resolveLanded(outcome, approved);
88385
+ if (verdict.status !== "verified") {
88386
+ throw new Error(verdict.reason);
88387
+ }
88388
+ return { txHash: verdict.hash, signer: verdict.from, scheme: "external-wallet" };
88389
+ }
88390
+ async resolveLanded(outcome, approved) {
88391
+ if (outcome.rawSignedTx) {
88392
+ const verdict = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88393
+ if (verdict.status === "verified") await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88394
+ return verdict;
88395
+ }
88396
+ if (!outcome.txHash) {
88397
+ return { status: "unknown", hash: "0x", reason: "the wallet approved but returned neither a tx hash nor a signed transaction" };
88398
+ }
88399
+ return verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88400
+ }
88401
+ getEthersSigner() {
88402
+ return new BridgeEthersSigner(this.deps);
88403
+ }
88404
+ };
88405
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers36.ethers.AbstractSigner {
88406
+ constructor(deps) {
88407
+ super(deps.provider);
88408
+ this.deps = deps;
88409
+ this.budget = deps.verifyBudget ?? DEFAULT_BUDGET;
88410
+ }
88411
+ budget;
88412
+ async getAddress() {
88413
+ return this.deps.borrower;
88414
+ }
88415
+ async signMessage(_message) {
88416
+ throw new Error(
88417
+ "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."
88418
+ );
88419
+ }
88420
+ async signTypedData(domain, types, value) {
88421
+ const typedData = {
88422
+ domain,
88423
+ types,
88424
+ primaryType: Object.keys(types)[0] ?? "EIP712",
88425
+ message: value
88426
+ };
88427
+ const outcome = await this.deps.bridge.requestSignature({
88428
+ id: (0, import_node_crypto5.randomUUID)(),
88429
+ kind: "typed-data",
88430
+ action: "login",
88431
+ card: cardForTypedData("login", typedData),
88432
+ expectedSigner: this.deps.borrower,
88433
+ chainId: this.deps.chainId,
88434
+ typedData
88435
+ });
88436
+ if (outcome.status !== "approved" || !outcome.signature) {
88437
+ throw new OperationDeclined(`the login signature was not approved: ${describeOutcome(outcome)}`);
88438
+ }
88439
+ return outcome.signature;
88440
+ }
88441
+ async sendTransaction(tx2) {
88442
+ if (!tx2.to || typeof tx2.data !== "string") {
88443
+ throw new Error("BridgeEthersSigner.sendTransaction: tx.to and hex tx.data are required");
88444
+ }
88445
+ const approved = {
88446
+ to: tx2.to,
88447
+ data: tx2.data,
88448
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88449
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
88450
+ };
88451
+ const card = cardForTx(approved);
88452
+ const outcome = await this.deps.bridge.requestSignature({
88453
+ id: (0, import_node_crypto5.randomUUID)(),
88454
+ kind: "transaction",
88455
+ action: describeFn(approved.data),
88456
+ card,
88457
+ expectedSigner: this.deps.borrower,
88458
+ chainId: approved.chainId,
88459
+ tx: { ...approved, ...tx2.gasLimit != null ? { gas: import_ethers36.ethers.toBeHex(BigInt(String(tx2.gasLimit))) } : {}, txType: 2 }
88460
+ });
88461
+ if (outcome.status !== "approved") {
88462
+ throw new OperationDeclined(`the transaction was not approved: ${describeOutcome(outcome)}`);
88463
+ }
88464
+ let hash;
88465
+ if (outcome.rawSignedTx) {
88466
+ const v = verifyRawSignedTx(outcome.rawSignedTx, approved, this.deps.borrower);
88467
+ if (v.status !== "verified") throw new Error(v.reason);
88468
+ await this.deps.provider.broadcastTransaction(outcome.rawSignedTx).catch(() => void 0);
88469
+ hash = v.hash;
88470
+ } else if (outcome.txHash) {
88471
+ const v = await verifyBroadcastTxByHash(this.deps.provider, outcome.txHash, approved, this.deps.borrower, this.budget);
88472
+ if (v.status !== "verified") throw new Error(v.reason);
88473
+ hash = v.hash;
88474
+ } else {
88475
+ throw new Error("the wallet approved but returned neither a tx hash nor a signed transaction");
88476
+ }
88477
+ const resp = await this.provider.getTransaction(hash);
88478
+ if (!resp) throw new Error(`tx ${hash} verified but the provider no longer returns it`);
88479
+ return resp;
88480
+ }
88481
+ async signTransaction(_tx) {
88482
+ throw new Error("BridgeEthersSigner: browser wallets cannot raw-sign a transaction \u2014 use sendTransaction (self-broadcast).");
88483
+ }
88484
+ connect(provider) {
88485
+ return new _BridgeEthersSigner({ ...this.deps, provider });
88486
+ }
88487
+ };
88488
+ function toApprovedTx(tx2, fallbackChainId) {
88489
+ if (!tx2.to || typeof tx2.data !== "string") throw new Error("submitValidatedTx: tx.to and hex tx.data are required");
88490
+ return {
88491
+ to: tx2.to,
88492
+ data: tx2.data,
88493
+ value: tx2.value != null ? import_ethers36.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
88494
+ chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
88495
+ };
88496
+ }
88497
+ function describeFn(data) {
88498
+ try {
88499
+ const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
88500
+ return decodeSignable2(data).name;
88501
+ } catch {
88502
+ return "operation";
88503
+ }
88504
+ }
88505
+ function describeOutcome(outcome) {
88506
+ switch (outcome.status) {
88507
+ case "rejected":
88508
+ return outcome.reason;
88509
+ case "expired":
88510
+ return "the approval request expired without a wallet decision \u2014 reopen the approval page and retry";
88511
+ case "invalidated":
88512
+ return outcome.reason;
88513
+ default:
88514
+ return outcome.status;
88515
+ }
88516
+ }
88517
+
87858
88518
  // src/boundary/upstream/real/plugin.ts
87859
88519
  var STATUS_BY_INDEX = [
87860
88520
  "PENDING_DEPOSIT",
@@ -87872,10 +88532,11 @@ var POSITION_DETAILS_ABI = [
87872
88532
  var PAUSABLE_ABI = ["function paused() view returns (bool)"];
87873
88533
  var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
87874
88534
  var RealUpstreamPlugin = class {
87875
- constructor(config, wallet) {
88535
+ constructor(config, wallet, runtime) {
87876
88536
  this.config = config;
87877
- this.provider = new import_ethers34.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
88537
+ this.provider = new import_ethers37.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
87878
88538
  this.wallet = wallet ?? null;
88539
+ this.runtime = runtime ?? null;
87879
88540
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
87880
88541
  this.contracts = getContractsByNetwork(config.network) ?? {};
87881
88542
  this.indexer = {
@@ -87999,7 +88660,7 @@ var RealUpstreamPlugin = class {
87999
88660
  })
88000
88661
  )
88001
88662
  };
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.`;
88663
+ 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
88664
  const readOnly = (op) => Promise.resolve(
88004
88665
  upFail({
88005
88666
  kind: "unavailable",
@@ -88008,16 +88669,10 @@ var RealUpstreamPlugin = class {
88008
88669
  })
88009
88670
  );
88010
88671
  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
- });
88672
+ if (writesArmed && this.runtime) {
88673
+ this.ops = this.resolvingOps();
88674
+ } else if (writesArmed && this.wallet && this.session) {
88675
+ this.ops = this.keystoreGateway(this.wallet.connect(this.provider), this.session);
88021
88676
  } else {
88022
88677
  this.ops = {
88023
88678
  createPosition: () => readOnly("createPosition"),
@@ -88050,10 +88705,17 @@ var RealUpstreamPlugin = class {
88050
88705
  provider;
88051
88706
  session;
88052
88707
  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).
88708
+ runtime;
88709
+ /** Per-identity caches (plan 10 A3): keys are `<mode>:<address lowercased>` — a mode
88710
+ * switch resolves a different key, so stale constructions are never reused. */
88711
+ sdkCache = /* @__PURE__ */ new Map();
88712
+ sdkInFlight = /* @__PURE__ */ new Map();
88713
+ sessionCache = /* @__PURE__ */ new Map();
88714
+ opsGatewayCache = /* @__PURE__ */ new Map();
88715
+ externalSigners = /* @__PURE__ */ new Map();
88716
+ /** Pre-warm the KEYSTORE write SDK at boot (0.1.1 parity: the common keystore boot pays
88717
+ * the create cost up front, not on the first write). External-mode SDKs build lazily on
88718
+ * the first write after the mode binds (plan 10 A3 latency honesty).
88057
88719
  *
88058
88720
  * INDEPENDENT of any graph/indexer discovery (plan 08 A4, M8B-4): indexer reads ride
88059
88721
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
@@ -88063,29 +88725,277 @@ var RealUpstreamPlugin = class {
88063
88725
  * (createPosition/withdraw report the uninitialized SDK). */
88064
88726
  async initWriteSdk() {
88065
88727
  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 } } : {}
88728
+ if (!writesArmed) return;
88729
+ if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
88730
+ const wallet = this.wallet ?? this.runtime?.keystore.signer() ?? null;
88731
+ if (!wallet) return;
88732
+ await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
88733
+ }
88734
+ /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
88735
+ * the write gateways report the uninitialized SDK honestly, never fake readiness. */
88736
+ async ensureSdk(key, signer) {
88737
+ if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
88738
+ const inFlight = this.sdkInFlight.get(key);
88739
+ if (inFlight) return inFlight;
88740
+ const build = (async () => {
88741
+ try {
88742
+ const v = this.config.validatorVersion;
88743
+ const builtWrite = await DiamondHandsSDK.create({
88744
+ mode: "service",
88745
+ serviceEndpoint: this.config.serviceEndpoint,
88746
+ contractSigner: signer,
88747
+ authSigner: signer,
88748
+ provider: this.provider,
88749
+ ethRpcUrl: this.config.rpcUrl,
88750
+ chainId: this.config.chainId,
88751
+ litNetwork: this.config.litNetwork,
88752
+ // No `subgraphs`: in service mode the SDK queries THROUGH the lit-ops proxy and
88753
+ // ignores any provided URL — the old `/v1/init`-discovered value was dead weight
88754
+ // nesting writes under indexer discovery (the M8B-4 coupling this removes).
88755
+ ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
88756
+ });
88757
+ return isSuccess(builtWrite) ? builtWrite.value : null;
88758
+ } catch {
88759
+ return null;
88760
+ }
88761
+ })();
88762
+ this.sdkInFlight.set(key, build);
88763
+ const built = await build;
88764
+ this.sdkInFlight.delete(key);
88765
+ this.sdkCache.set(key, built);
88766
+ return built;
88767
+ }
88768
+ wallet;
88769
+ // ---- per-call signer resolution (plan 10 A3) ----
88770
+ /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
88771
+ * carries the service endpoint and the authenticated session header. It throws
88772
+ * `OperationDeclined` when lit-ops REFUSES the signed tx (a decision), a plain Error on
88773
+ * transport/shape trouble; write-ops maps the two to distinct failure kinds. */
88774
+ litOpsBroadcast(session) {
88775
+ return async (signedTx, extra) => {
88776
+ const res = await fetch(`${this.config.serviceEndpoint}/api/lit/broadcast`, {
88777
+ method: "POST",
88778
+ headers: { "Content-Type": "application/json", ...await session.authHeader() },
88779
+ body: JSON.stringify({ signedTx, ...extra ?? {} })
88083
88780
  });
88084
- if (isSuccess(builtWrite)) this.writeSdk = builtWrite.value;
88085
- } catch {
88781
+ const text = await res.text();
88782
+ let json;
88783
+ try {
88784
+ json = JSON.parse(text);
88785
+ } catch {
88786
+ throw new Error(`lit-ops broadcast returned non-JSON (HTTP ${res.status}): ${text.slice(0, 200)}`);
88787
+ }
88788
+ if (!res.ok && json["error"] === void 0) {
88789
+ throw new Error(`lit-ops broadcast HTTP ${res.status}: ${text.slice(0, 200)}`);
88790
+ }
88791
+ if (json["success"] !== true) {
88792
+ const reason = json["error"];
88793
+ throw new OperationDeclined(`lit-ops declined the signed transaction: ${typeof reason === "string" ? reason : "no reason given"}`);
88794
+ }
88795
+ const txHash = String((json["data"] ?? {})["txHash"] ?? "");
88796
+ if (!txHash) throw new Error("lit-ops broadcast returned no txHash");
88797
+ return txHash;
88798
+ };
88799
+ }
88800
+ keystoreGateway(wallet, session) {
88801
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88802
+ return buildWriteOps({
88803
+ config: this.config,
88804
+ chainId: this.config.chainId,
88805
+ dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
88806
+ session,
88807
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88808
+ readDetails: (id) => this.readPositionDetails(id),
88809
+ psm: () => this.psmCalls()
88810
+ });
88811
+ }
88812
+ sessionFor(key, signer) {
88813
+ let s = this.sessionCache.get(key);
88814
+ if (!s) {
88815
+ s = new LitOpsSession(signer, this.config.serviceEndpoint, this.config.chainId);
88816
+ this.sessionCache.set(key, s);
88817
+ }
88818
+ return s;
88819
+ }
88820
+ /** Verify-by-hash budget for external self-broadcast (A0.3): mainnet Chipotle
88821
+ * roundtrips exceed 60s, so the write-path budget is 300s there (F-MAIN-4). */
88822
+ verifyBudget() {
88823
+ return this.config.network === "mainnet" ? { attempts: 100, delayMs: 3e3 } : void 0;
88824
+ }
88825
+ /** The armed-boot ops surface: every method resolves the CURRENT signer mode first, so
88826
+ * the refusal-truth matrix is decided at call time, never frozen at boot. */
88827
+ resolvingOps() {
88828
+ const call = (k) => (async (p) => {
88829
+ const r = await this.resolveOpsGateway();
88830
+ if (!r.ok) return upFail(r.failure);
88831
+ return r.gateway[k](p);
88832
+ });
88833
+ return {
88834
+ createPosition: call("createPosition"),
88835
+ mint: call("mint"),
88836
+ repay: call("repay"),
88837
+ extend: call("extend"),
88838
+ withdraw: call("withdraw"),
88839
+ allowlistWithdrawalAddress: call("allowlistWithdrawalAddress"),
88840
+ psmSwap: call("psmSwap"),
88841
+ delegationSetup: call("delegationSetup"),
88842
+ delegationGrant: call("delegationGrant"),
88843
+ recoverStaleSpend: call("recoverStaleSpend")
88844
+ };
88845
+ }
88846
+ async resolveOpsGateway() {
88847
+ const rt = this.runtime;
88848
+ const mode = rt.manager.mode();
88849
+ if (mode === "none") {
88850
+ return {
88851
+ ok: false,
88852
+ failure: {
88853
+ kind: "signer-missing",
88854
+ source: "real-ops",
88855
+ 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."
88856
+ }
88857
+ };
88858
+ }
88859
+ if (mode === "keystore") {
88860
+ const ready = await rt.keystore.ensureReady();
88861
+ const wallet = rt.keystore.signer();
88862
+ if (!ready.ok || !wallet) {
88863
+ return {
88864
+ ok: false,
88865
+ failure: {
88866
+ kind: "signer-missing",
88867
+ source: "real-ops",
88868
+ message: `the keystore signer is not ready (SIGNER_UNAVAILABLE): ${ready.ok ? "no keystore material" : ready.reason}`
88869
+ }
88870
+ };
88871
+ }
88872
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88873
+ let gateway = this.opsGatewayCache.get(key);
88874
+ if (!gateway) {
88875
+ const connected = wallet.connect(this.provider);
88876
+ gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
88877
+ this.opsGatewayCache.set(key, gateway);
88878
+ }
88879
+ await this.ensureSdk(key, wallet.connect(this.provider));
88880
+ return { ok: true, gateway };
88086
88881
  }
88882
+ if (mode === "external") {
88883
+ const borrower = await rt.manager.resolveBorrowerForWrite();
88884
+ if (!borrower) {
88885
+ return {
88886
+ ok: false,
88887
+ failure: {
88888
+ kind: "signer-missing",
88889
+ source: "real-ops",
88890
+ 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."
88891
+ }
88892
+ };
88893
+ }
88894
+ const key = `external:${borrower.toLowerCase()}`;
88895
+ let gateway = this.opsGatewayCache.get(key);
88896
+ if (!gateway) {
88897
+ const budget = this.verifyBudget();
88898
+ const deps = {
88899
+ bridge: rt.bridge,
88900
+ provider: this.provider,
88901
+ chainId: this.config.chainId,
88902
+ borrower,
88903
+ ...budget ? { verifyBudget: budget } : {}
88904
+ };
88905
+ const bridgeSigner = new BridgeEthersSigner(deps);
88906
+ this.externalSigners.set(key, bridgeSigner);
88907
+ const session = this.sessionFor(key, {
88908
+ address: borrower,
88909
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88910
+ });
88911
+ gateway = buildWriteOps({
88912
+ config: this.config,
88913
+ chainId: this.config.chainId,
88914
+ dhSigner: new ExternalEoaDHSigner(deps),
88915
+ session,
88916
+ getWriteSdk: () => this.sdkCache.get(key) ?? null,
88917
+ readDetails: (id) => this.readPositionDetails(id),
88918
+ psm: () => this.psmCalls()
88919
+ });
88920
+ this.opsGatewayCache.set(key, gateway);
88921
+ }
88922
+ await this.ensureSdk(key, this.externalSigners.get(key));
88923
+ return { ok: true, gateway };
88924
+ }
88925
+ return {
88926
+ ok: false,
88927
+ failure: {
88928
+ kind: "signer-missing",
88929
+ source: "real-ops",
88930
+ message: `signer mode '${mode}' is not available on the real adapter \u2014 use 'external' or 'keystore' (signer_setup).`
88931
+ }
88932
+ };
88933
+ }
88934
+ /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
88935
+ * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
88936
+ * the first verified ceremony fixes the identity. */
88937
+ async connectExternal() {
88938
+ if (!this.runtime) return { ok: false, reason: "this construction has no signer runtime" };
88939
+ const { manager } = this.runtime;
88940
+ if (manager.mode() !== "external") {
88941
+ return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
88942
+ }
88943
+ const borrower = manager.borrowerForWrite();
88944
+ if (!borrower) {
88945
+ return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
88946
+ }
88947
+ const key = `external:${borrower.toLowerCase()}`;
88948
+ const budget = this.verifyBudget();
88949
+ const bridgeSigner = this.externalSigners.get(key) ?? new BridgeEthersSigner({
88950
+ bridge: this.runtime.bridge,
88951
+ provider: this.provider,
88952
+ chainId: this.config.chainId,
88953
+ borrower,
88954
+ ...budget ? { verifyBudget: budget } : {}
88955
+ });
88956
+ this.externalSigners.set(key, bridgeSigner);
88957
+ const session = this.sessionFor(key, {
88958
+ address: borrower,
88959
+ signTypedData: (d, t, v) => bridgeSigner.signTypedData(d, t, v)
88960
+ });
88961
+ await session.token();
88962
+ manager.bind(borrower);
88963
+ return { ok: true, address: borrower };
88964
+ }
88965
+ /** The authenticated-read session for the CURRENT mode. Reads NEVER summon the wallet
88966
+ * (A0.7): external mode without a live JWT refuses, naming the explicit connect action. */
88967
+ resolveReadSession() {
88968
+ if (!this.runtime) {
88969
+ 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." };
88970
+ }
88971
+ const mode = this.runtime.manager.mode();
88972
+ if (mode === "keystore") {
88973
+ const wallet = this.runtime.keystore.signer();
88974
+ if (!wallet) {
88975
+ 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." };
88976
+ }
88977
+ const key = `keystore:${wallet.address.toLowerCase()}`;
88978
+ return { ok: true, session: this.sessionFor(key, wallet.connect(this.provider)) };
88979
+ }
88980
+ if (mode === "external") {
88981
+ const borrower = this.runtime.manager.borrowerForWrite();
88982
+ const session = borrower ? this.sessionCache.get(`external:${borrower.toLowerCase()}`) : void 0;
88983
+ if (session && session.hasValidToken()) return { ok: true, session };
88984
+ return {
88985
+ ok: false,
88986
+ 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."
88987
+ };
88988
+ }
88989
+ return {
88990
+ ok: false,
88991
+ 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."
88992
+ };
88993
+ }
88994
+ /** Capability truth for boundary://info (plan 10 B3): can authenticated reads run RIGHT
88995
+ * NOW without summoning a wallet? */
88996
+ authenticatedReadsAvailable() {
88997
+ return this.resolveReadSession().ok;
88087
88998
  }
88088
- wallet;
88089
88999
  describe() {
88090
89000
  return {
88091
89001
  adapter: "real",
@@ -88093,7 +89003,8 @@ var RealUpstreamPlugin = class {
88093
89003
  };
88094
89004
  }
88095
89005
  dispose() {
88096
- this.writeSdk?.dispose();
89006
+ for (const sdk of this.sdkCache.values()) sdk?.dispose();
89007
+ this.sdkCache.clear();
88097
89008
  this.provider.destroy();
88098
89009
  }
88099
89010
  // ---- helpers ----
@@ -88153,19 +89064,20 @@ var RealUpstreamPlugin = class {
88153
89064
  * present, else `_meta` from the document result (this is reading one response, not a
88154
89065
  * fallback path). Null when the document selects no `_meta` (e.g. PositionById). */
88155
89066
  async graphProxy(document2, variables) {
88156
- if (!this.session) {
89067
+ const sessionR = this.resolveReadSession();
89068
+ if (!sessionR.ok) {
88157
89069
  return upFail({
88158
89070
  kind: "signer-missing",
88159
89071
  // → SIGNER_UNAVAILABLE (same contract as the other authenticated reads)
88160
89072
  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."
89073
+ 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
89074
  });
88163
89075
  }
88164
89076
  let res;
88165
89077
  try {
88166
89078
  res = await fetch(`${this.config.serviceEndpoint}/api/lit/graph/query?chainId=${this.config.chainId}`, {
88167
89079
  method: "POST",
88168
- headers: { "Content-Type": "application/json", ...await this.session.authHeader() },
89080
+ headers: { "Content-Type": "application/json", ...await sessionR.session.authHeader() },
88169
89081
  body: JSON.stringify({ query: document2, variables })
88170
89082
  });
88171
89083
  } catch (e) {
@@ -88230,9 +89142,9 @@ var RealUpstreamPlugin = class {
88230
89142
  };
88231
89143
  }
88232
89144
  /** Public (unauthenticated) lit-ops GET. */
88233
- async publicRead(path4, map) {
89145
+ async publicRead(path5, map) {
88234
89146
  try {
88235
- const res = await fetch(`${this.config.serviceEndpoint}${path4}`);
89147
+ const res = await fetch(`${this.config.serviceEndpoint}${path5}`);
88236
89148
  const text = await res.text();
88237
89149
  if (!res.ok) {
88238
89150
  return upFail({
@@ -88249,18 +89161,19 @@ var RealUpstreamPlugin = class {
88249
89161
  }
88250
89162
  }
88251
89163
  /** Authenticated lit-ops GET → mapped value. Never throws; maps failures to the taxonomy. */
88252
- async opsRead(path4, map) {
88253
- if (!this.session) {
89164
+ async opsRead(path5, map) {
89165
+ const sessionR = this.resolveReadSession();
89166
+ if (!sessionR.ok) {
88254
89167
  return upFail({
88255
89168
  kind: "signer-missing",
88256
89169
  // → SIGNER_UNAVAILABLE (documented contract, pinned by REAL-08)
88257
89170
  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."
89171
+ message: `this read is authenticated (lit-ops login): ${sessionR.reason}`
88259
89172
  });
88260
89173
  }
88261
89174
  let res;
88262
89175
  try {
88263
- res = await fetch(`${this.config.serviceEndpoint}${path4}`, { headers: await this.session.authHeader() });
89176
+ res = await fetch(`${this.config.serviceEndpoint}${path5}`, { headers: await sessionR.session.authHeader() });
88264
89177
  } catch (e) {
88265
89178
  return upFail({ kind: "unavailable", source: "lit-ops", message: `lit-ops is unreachable`, raw: String(e) });
88266
89179
  }
@@ -88309,7 +89222,7 @@ var RealUpstreamPlugin = class {
88309
89222
  const pm = this.contracts["PositionManager"];
88310
89223
  if (!pm) return false;
88311
89224
  try {
88312
- const c = new import_ethers34.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
89225
+ const c = new import_ethers37.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
88313
89226
  return Boolean(await c["paused"]());
88314
89227
  } catch {
88315
89228
  return false;
@@ -88318,16 +89231,16 @@ var RealUpstreamPlugin = class {
88318
89231
  async readPositionDetails(id) {
88319
89232
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
88320
89233
  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);
89234
+ const c = new import_ethers37.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
88322
89235
  let d;
88323
89236
  try {
88324
- d = await c["getPositionDetails"](import_ethers34.ethers.zeroPadValue(id, 32));
89237
+ d = await c["getPositionDetails"](import_ethers37.ethers.zeroPadValue(id, 32));
88325
89238
  } catch (e) {
88326
89239
  if (e.code === "CALL_EXCEPTION") return null;
88327
89240
  throw e;
88328
89241
  }
88329
89242
  const borrower = String(d["borrower"]);
88330
- if (borrower === import_ethers34.ethers.ZeroAddress) return null;
89243
+ if (borrower === import_ethers37.ethers.ZeroAddress) return null;
88331
89244
  return {
88332
89245
  positionId: String(d["positionId"]),
88333
89246
  pkpId: String(d["pkpId"]),
@@ -88351,7 +89264,7 @@ var RealUpstreamPlugin = class {
88351
89264
  // src/boundary/upstream/shared/external-bridge/bridge.ts
88352
89265
  var fs4 = __toESM(require("fs"));
88353
89266
  var http3 = __toESM(require("http"));
88354
- var import_node_crypto5 = require("crypto");
89267
+ var import_node_crypto6 = require("crypto");
88355
89268
 
88356
89269
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
88357
89270
  function renderApprovalPage(sessionId) {
@@ -88398,12 +89311,16 @@ function renderApprovalPage(sessionId) {
88398
89311
  <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
88399
89312
  Use a mobile wallet instead (WalletConnect)
88400
89313
  </button>
89314
+ <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
88401
89315
  <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>
89316
+ <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
89317
  </div>
88404
89318
  </div>
88405
89319
  </main>
88406
89320
  <script>
89321
+ ${PAGE_CRYPTO_JS}
89322
+ </script>
89323
+ <script>
88407
89324
  "use strict";
88408
89325
  const SESSION = ${JSON.stringify(sessionId)};
88409
89326
  // One-time token leaves the address bar (and history) immediately.
@@ -88519,11 +89436,33 @@ document.getElementById("approve").onclick = async () => {
88519
89436
  const req = current;
88520
89437
  try {
88521
89438
  if (req.kind === "transaction") {
89439
+ const params = { from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value };
89440
+ if (req.tx.gas) params.gas = req.tx.gas; // hint only \u2014 the wallet may re-estimate
88522
89441
  const txHash = await window.ethereum.request({
88523
89442
  method: "eth_sendTransaction",
88524
- params: [{ from: account, to: req.tx.to, data: req.tx.data, value: req.tx.value }],
89443
+ params: [params],
88525
89444
  });
88526
89445
  await post("/result", { requestId: req.id, approved: true, account: account, txHash: txHash });
89446
+ } else if (req.kind === "personal-sign") {
89447
+ // A0.9 sign-at-presence: fetch the FRESHLY quantum-stamped payload at the click\u2026
89448
+ const fr = await post("/finalize", { requestId: req.id });
89449
+ const fbody = await fr.json();
89450
+ if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
89451
+ const fresh = fbody.request;
89452
+ // \u2026re-render what will actually sign\u2026
89453
+ current = fresh; renderRequest();
89454
+ // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
89455
+ const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
89456
+ if (recomputed.toLowerCase() !== fresh.personalSign.hashHex.toLowerCase()) {
89457
+ 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" });
89458
+ clearRequest("REFUSED: the signature request did not match its own displayed fields. Nothing was signed.");
89459
+ return;
89460
+ }
89461
+ const signature = await window.ethereum.request({
89462
+ method: "personal_sign",
89463
+ params: [fresh.personalSign.hashHex, account],
89464
+ });
89465
+ await post("/result", { requestId: req.id, approved: true, account: account, signature: signature });
88527
89466
  } else {
88528
89467
  // MetaMask's v4 schema REQUIRES an EIP712Domain entry in "types" (ethers' signer
88529
89468
  // API forbids the same entry) \u2014 derive it here from the domain's present fields.
@@ -88556,8 +89495,13 @@ document.getElementById("wc-connect").onclick = async () => {
88556
89495
  const uriEl = document.getElementById("wc-uri");
88557
89496
  uriEl.textContent = body.uri;
88558
89497
  uriEl.classList.remove("hidden");
89498
+ if (body.qrSvg) {
89499
+ const qrEl = document.getElementById("wc-qr");
89500
+ qrEl.innerHTML = body.qrSvg; // server-generated SVG from OUR loopback process
89501
+ qrEl.classList.remove("hidden");
89502
+ }
88559
89503
  document.getElementById("wc-hint").classList.remove("hidden");
88560
- showStatus("Pair your mobile wallet with the code below \u2014 it becomes the signing wallet.");
89504
+ showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
88561
89505
  };
88562
89506
 
88563
89507
  connect();
@@ -88644,7 +89588,7 @@ var SignatureBridge = class {
88644
89588
  expiryMs;
88645
89589
  server = null;
88646
89590
  port = 0;
88647
- token = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89591
+ token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88648
89592
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
88649
89593
  * each open mints its own session. The link is NOT signing authority: only recovered
88650
89594
  * OWNER signatures count (M6-9); the token still gates drive-by loopback scans. */
@@ -88676,7 +89620,7 @@ var SignatureBridge = class {
88676
89620
  unlockUrl() {
88677
89621
  if (!this.server) throw new Error("bridge is not started");
88678
89622
  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");
89623
+ this.unlockToken = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88680
89624
  return `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
88681
89625
  }
88682
89626
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2). */
@@ -88731,7 +89675,7 @@ var SignatureBridge = class {
88731
89675
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
88732
89676
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
88733
89677
  */
88734
- requestSignature(request) {
89678
+ requestSignature(request, handlers) {
88735
89679
  if (!this.server) return Promise.resolve({ status: "invalidated", reason: "bridge is not started" });
88736
89680
  if (this.wallet && this.wallet.chainId !== request.chainId) {
88737
89681
  return Promise.resolve({
@@ -88744,7 +89688,8 @@ var SignatureBridge = class {
88744
89688
  request,
88745
89689
  deadlineMs: this.clock() + this.expiryMs,
88746
89690
  resolve,
88747
- settled: false
89691
+ settled: false,
89692
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {}
88748
89693
  };
88749
89694
  this.pending.set(request.id, entry);
88750
89695
  if (this.wcActive) {
@@ -88812,9 +89757,18 @@ var SignatureBridge = class {
88812
89757
  if (req.kind === "transaction") {
88813
89758
  const tx2 = req.tx;
88814
89759
  const txHash = await transport.request("eth_sendTransaction", [
88815
- { from: account, to: tx2.to, data: tx2.data, value: tx2.value }
89760
+ { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
88816
89761
  ]);
88817
89762
  if (!entry.settled) this.settle(entry, { status: "approved", account, txHash });
89763
+ } else if (req.kind === "personal-sign") {
89764
+ if (entry.finalize) {
89765
+ const fresh = await entry.finalize();
89766
+ req.personalSign = fresh.personalSign;
89767
+ req.card = fresh.card;
89768
+ }
89769
+ const ps = req.personalSign;
89770
+ const signature = await transport.request("personal_sign", [ps.hashHex, account]);
89771
+ if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
88818
89772
  } else {
88819
89773
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
88820
89774
  const payload = withEip712DomainType2(req.typedData);
@@ -88866,6 +89820,8 @@ var SignatureBridge = class {
88866
89820
  if (req.method === "POST" && url2.pathname === "/wallet-event")
88867
89821
  return void this.readJson(req, res, (b) => this.onWalletEvent(b, res));
88868
89822
  if (req.method === "POST" && url2.pathname === "/result") return void this.readJson(req, res, (b) => this.onResult(b, res));
89823
+ if (req.method === "POST" && url2.pathname === "/finalize")
89824
+ return void this.readJson(req, res, (b) => void this.onFinalize(b, res));
88869
89825
  this.deny(res, 404, "not found");
88870
89826
  }
88871
89827
  /** Loopback discipline: Host must be this loopback bind; Origin (when a browser sends
@@ -88895,7 +89851,7 @@ var SignatureBridge = class {
88895
89851
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
88896
89852
  return;
88897
89853
  }
88898
- const sessionId = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89854
+ const sessionId = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88899
89855
  this.sessions.set(sessionId, { wallet: null, sse: null });
88900
89856
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88901
89857
  res.end(renderApprovalPage(sessionId));
@@ -88931,8 +89887,13 @@ var SignatureBridge = class {
88931
89887
  });
88932
89888
  }
88933
89889
  const { uri } = await this.wcTransport.createPairing();
89890
+ const { default: qrcode } = await import("qrcode-generator");
89891
+ const qr = qrcode(0, "M");
89892
+ qr.addData(uri);
89893
+ qr.make();
89894
+ const qrSvg = qr.createSvgTag({ cellSize: 4, margin: 8, scalable: true });
88934
89895
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
88935
- res.end(JSON.stringify({ uri }));
89896
+ res.end(JSON.stringify({ uri, qrSvg }));
88936
89897
  } catch (e) {
88937
89898
  this.deny(res, 502, `WalletConnect pairing failed: ${e.message}`);
88938
89899
  }
@@ -88950,7 +89911,7 @@ var SignatureBridge = class {
88950
89911
  return;
88951
89912
  }
88952
89913
  this.unlockToken = null;
88953
- this.unlockSession = (0, import_node_crypto5.randomBytes)(24).toString("hex");
89914
+ this.unlockSession = (0, import_node_crypto6.randomBytes)(24).toString("hex");
88954
89915
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88955
89916
  res.end(renderUnlockPage(this.unlockSession));
88956
89917
  }
@@ -89038,6 +89999,37 @@ var SignatureBridge = class {
89038
89999
  }
89039
90000
  this.ok(res);
89040
90001
  }
90002
+ /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
90003
+ * request. Idempotent for requests without a finalize handler (payload as enqueued). */
90004
+ async onFinalize(body, res) {
90005
+ if (!this.sessionOf(body["sessionId"], res)) return;
90006
+ const entry = this.pending.get(String(body["requestId"] ?? ""));
90007
+ if (!entry || entry.settled) {
90008
+ this.deny(res, 404, "unknown or already-settled requestId");
90009
+ return;
90010
+ }
90011
+ if (entry.request.kind !== "personal-sign") {
90012
+ this.deny(res, 400, "finalize applies only to personal-sign requests");
90013
+ return;
90014
+ }
90015
+ if (entry.finalize) {
90016
+ let fresh;
90017
+ try {
90018
+ fresh = await entry.finalize();
90019
+ } catch (e) {
90020
+ this.deny(res, 502, `finalize failed: ${e.message}`);
90021
+ return;
90022
+ }
90023
+ if (entry.settled) {
90024
+ this.deny(res, 404, "request settled while finalizing");
90025
+ return;
90026
+ }
90027
+ entry.request.personalSign = fresh.personalSign;
90028
+ entry.request.card = fresh.card;
90029
+ }
90030
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
90031
+ res.end(JSON.stringify({ request: entry.request }));
90032
+ }
89041
90033
  onResult(body, res) {
89042
90034
  if (!this.sessionOf(body["sessionId"], res)) return;
89043
90035
  const entry = this.pending.get(String(body["requestId"] ?? ""));
@@ -89062,8 +90054,8 @@ var SignatureBridge = class {
89062
90054
  this.deny(res, 400, "transaction approval requires txHash or rawSignedTx");
89063
90055
  return;
89064
90056
  }
89065
- if (entry.request.kind === "typed-data" && !signature) {
89066
- this.deny(res, 400, "typed-data approval requires signature");
90057
+ if ((entry.request.kind === "typed-data" || entry.request.kind === "personal-sign") && !signature) {
90058
+ this.deny(res, 400, `${entry.request.kind} approval requires signature`);
89067
90059
  return;
89068
90060
  }
89069
90061
  if (entry.collect) {
@@ -89149,14 +90141,15 @@ data: ${JSON.stringify(payload)}
89149
90141
  };
89150
90142
 
89151
90143
  // src/boundary/index.ts
89152
- function fileSignerPersistence(path4) {
90144
+ function fileSignerPersistence(filePath) {
89153
90145
  return {
89154
90146
  load() {
89155
- if (!fs5.existsSync(path4)) return null;
89156
- return JSON.parse(fs5.readFileSync(path4, "utf8"));
90147
+ if (!fs5.existsSync(filePath)) return null;
90148
+ return JSON.parse(fs5.readFileSync(filePath, "utf8"));
89157
90149
  },
89158
90150
  save(state) {
89159
- fs5.writeFileSync(path4, JSON.stringify(state));
90151
+ fs5.mkdirSync(path4.dirname(filePath), { recursive: true });
90152
+ fs5.writeFileSync(filePath, JSON.stringify(state));
89160
90153
  }
89161
90154
  };
89162
90155
  }
@@ -89166,7 +90159,7 @@ function createBoundary(config, opts) {
89166
90159
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
89167
90160
  );
89168
90161
  }
89169
- const configFingerprint = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
90162
+ const configFingerprint = (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
89170
90163
  if (opts?.ceremony) {
89171
90164
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
89172
90165
  const boundary2 = new BoundaryCore({
@@ -89175,6 +90168,11 @@ function createBoundary(config, opts) {
89175
90168
  network: "mock",
89176
90169
  chainId: config.chainId ?? 1337,
89177
90170
  ...config.borrower ? { borrowerAddress: config.borrower } : {},
90171
+ capabilities: () => ({
90172
+ reads: { public: true, authenticated: "available" },
90173
+ writes: { enabled: true, signerModes: ["external"], activeMode: "external" },
90174
+ signerSetupTool: false
90175
+ }),
89178
90176
  configFingerprint
89179
90177
  });
89180
90178
  return { boundary: boundary2, mockControl: plugin2.control, dispose: () => plugin2.dispose() };
@@ -89252,6 +90250,16 @@ function createBoundary(config, opts) {
89252
90250
  chainId,
89253
90251
  ...config.borrower ? { borrowerAddress: config.borrower } : {},
89254
90252
  signer: manager,
90253
+ // B3: the mock sandbox runs every ceremony class; reads have no login gate.
90254
+ capabilities: () => ({
90255
+ reads: { public: true, authenticated: "available" },
90256
+ writes: {
90257
+ enabled: true,
90258
+ signerModes: ["external", "keystore", "mock-simulated", "safe", "safe-module"],
90259
+ activeMode: manager.mode()
90260
+ },
90261
+ signerSetupTool: true
90262
+ }),
89255
90263
  configFingerprint
89256
90264
  });
89257
90265
  return {
@@ -89265,18 +90273,73 @@ function createBoundary(config, opts) {
89265
90273
  };
89266
90274
  }
89267
90275
  async function createRealBoundary(config, wallet) {
89268
- const plugin = new RealUpstreamPlugin(config, wallet);
90276
+ const keystore = new KeystoreProvider({
90277
+ ...config.keystorePath ? { keystorePath: config.keystorePath } : {},
90278
+ ...config.keystorePassword ? { keystorePassword: config.keystorePassword } : {}
90279
+ });
90280
+ if (wallet) keystore.adopt(wallet);
90281
+ const stateDir = config.stateDir ?? path4.join(os2.homedir(), ".dh-mcp");
90282
+ const stateFile = path4.join(stateDir, `${config.network}.signer.json`);
90283
+ const chainName = config.network === "mainnet" ? "Ethereum Mainnet" : "Sepolia";
90284
+ const bridge = new SignatureBridge({
90285
+ ...config.bridgeUrlFile ? { urlFile: config.bridgeUrlFile } : {},
90286
+ network: { chainId: config.chainId, chainName, rpcUrl: config.rpcUrl },
90287
+ ...config.wcProjectId ? { wc: { projectId: config.wcProjectId, chainId: config.chainId } } : {},
90288
+ keystoreUnlock: {
90289
+ unlock: (json, password) => keystore.unlock(json, password),
90290
+ unlockConfigured: (password) => keystore.unlockConfigured(password),
90291
+ generate: (password) => keystore.generateAndSave(password, path4.join(stateDir, `${config.network}.keystore.json`))
90292
+ }
90293
+ });
90294
+ const initialMode = config.signer ?? (keystore.materialConfigured() ? "keystore" : "none");
90295
+ const manager = new SignerManager({
90296
+ persistence: fileSignerPersistence(stateFile),
90297
+ initialMode,
90298
+ candidate: () => bridge.walletState()?.account ?? null,
90299
+ pendingCeremonies: () => bridge.pendingCount(),
90300
+ keystore
90301
+ // No safeInfo: the Safe planes are mock-only pending their own plans — manager.use
90302
+ // refuses 'safe'/'safe-module' with the missing-discovery reason, truthfully.
90303
+ });
90304
+ if (initialMode === "external" || manager.mode() === "external") {
90305
+ void bridge.start();
90306
+ }
90307
+ const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
89269
90308
  await plugin.initWriteSdk();
89270
- const configFingerprint = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
90309
+ const configFingerprint = (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
90310
+ const writesArmed = config.network === "sepolia" || config.network === "mainnet" && config.mainnetWritesAck === true;
90311
+ const capabilities = () => ({
90312
+ reads: {
90313
+ public: true,
90314
+ authenticated: plugin.authenticatedReadsAvailable() ? "available" : "needs-signer"
90315
+ },
90316
+ writes: writesArmed ? { enabled: true, signerModes: ["external", "keystore"], activeMode: manager.mode() } : {
90317
+ enabled: false,
90318
+ reason: "writes are operator-gated on mainnet \u2014 the standing mainnet write block; mainnet writes await their dedicated security review. Reads remain available.",
90319
+ signerModes: [],
90320
+ activeMode: manager.mode()
90321
+ },
90322
+ signerSetupTool: true
90323
+ });
89271
90324
  const boundary = new BoundaryCore({
89272
90325
  plugin,
89273
90326
  adapter: "real",
89274
90327
  network: config.network,
89275
90328
  chainId: config.chainId,
89276
- ...wallet ? { borrowerAddress: wallet.address } : {},
90329
+ // M10-5: the manager IS the identity surface — boundary://info signerKind/borrower
90330
+ // stay live across mode switches instead of freezing a boot-time address.
90331
+ signer: manager,
90332
+ capabilities,
89277
90333
  configFingerprint
89278
90334
  });
89279
- return { boundary, dispose: () => plugin.dispose() };
90335
+ return {
90336
+ boundary,
90337
+ signer: { manager, bridge, keystore, connect: () => plugin.connectExternal() },
90338
+ dispose: () => {
90339
+ plugin.dispose();
90340
+ bridge.close();
90341
+ }
90342
+ };
89280
90343
  }
89281
90344
 
89282
90345
  // src/boot.ts
@@ -89314,8 +90377,8 @@ async function buildBoundary(configResult) {
89314
90377
  );
89315
90378
  }
89316
90379
  try {
89317
- const decrypted = await import_ethers35.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
89318
- if (!(decrypted instanceof import_ethers35.ethers.Wallet)) {
90380
+ const decrypted = await import_ethers38.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
90381
+ if (!(decrypted instanceof import_ethers38.ethers.Wallet)) {
89319
90382
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
89320
90383
  }
89321
90384
  wallet = decrypted;
@@ -89326,8 +90389,8 @@ async function buildBoundary(configResult) {
89326
90389
  );
89327
90390
  }
89328
90391
  }
89329
- const { boundary, dispose } = await createRealBoundary(config, wallet);
89330
- return { boundaryResult: { ok: true, boundary }, dispose };
90392
+ const { boundary, signer, dispose } = await createRealBoundary(config, wallet);
90393
+ return { boundaryResult: { ok: true, boundary }, signer, dispose };
89331
90394
  }
89332
90395
 
89333
90396
  // src/server.ts
@@ -89335,7 +90398,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
89335
90398
 
89336
90399
  // src/tools/loan.ts
89337
90400
  var import_zod = require("zod");
89338
- var import_ethers36 = require("ethers");
90401
+ var import_ethers39 = require("ethers");
89339
90402
 
89340
90403
  // src/util/format.ts
89341
90404
  function bigintReplacer(_key, value) {
@@ -89507,7 +90570,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
89507
90570
  const b = getB();
89508
90571
  if (!b.ok) return renderError(b.error);
89509
90572
  return renderEnvelope(
89510
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers36.parseEther)(amountUcd.toString()).toString() })
90573
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers39.parseEther)(amountUcd.toString()).toString() })
89511
90574
  );
89512
90575
  })
89513
90576
  );
@@ -89545,7 +90608,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
89545
90608
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
89546
90609
  amountUcdWei = detail.data.debtUcdWei;
89547
90610
  } else {
89548
- amountUcdWei = (0, import_ethers36.parseEther)(amountUcd.toString()).toString();
90611
+ amountUcdWei = (0, import_ethers39.parseEther)(amountUcd.toString()).toString();
89549
90612
  }
89550
90613
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
89551
90614
  })
@@ -90116,7 +91179,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
90116
91179
 
90117
91180
  // src/tools/signer.ts
90118
91181
  var import_zod6 = require("zod");
90119
- var import_ethers37 = require("ethers");
91182
+ var import_ethers40 = require("ethers");
90120
91183
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
90121
91184
  function looksSecretShaped(value) {
90122
91185
  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 +91191,9 @@ function registerSignerTool(server, runtime) {
90128
91191
  "signer_setup",
90129
91192
  {
90130
91193
  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.",
91194
+ 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
91195
  inputSchema: {
90133
- action: import_zod6.z.enum(["status", "use", "reset-borrower", "unlock-keystore"]).describe("What to do \u2014 'status' explains everything"),
91196
+ action: import_zod6.z.enum(["status", "use", "reset-borrower", "unlock-keystore", "connect"]).describe("What to do \u2014 'status' explains everything"),
90134
91197
  mode: import_zod6.z.string().optional().describe("For 'use': external | keystore | safe | safe-module | mock-simulated"),
90135
91198
  safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
90136
91199
  },
@@ -90141,7 +91204,7 @@ function registerSignerTool(server, runtime) {
90141
91204
  if (mode !== void 0 && !MODES.includes(mode)) {
90142
91205
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${MODES.join(" | ")}`);
90143
91206
  }
90144
- if (safeAddress !== void 0 && !import_ethers37.ethers.isAddress(safeAddress)) {
91207
+ if (safeAddress !== void 0 && !import_ethers40.ethers.isAddress(safeAddress)) {
90145
91208
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
90146
91209
  }
90147
91210
  if (action === "status") {
@@ -90184,6 +91247,20 @@ function registerSignerTool(server, runtime) {
90184
91247
  }
90185
91248
  return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
90186
91249
  }
91250
+ if (action === "connect") {
91251
+ if (!runtime.connect) {
91252
+ return validationFailed(
91253
+ "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."
91254
+ );
91255
+ }
91256
+ const r = await runtime.connect();
91257
+ if (!r.ok) return validationFailed(r.reason);
91258
+ return ok({
91259
+ connected: true,
91260
+ address: r.address,
91261
+ next: "Logged in \u2014 authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
91262
+ });
91263
+ }
90187
91264
  if (action === "reset-borrower") {
90188
91265
  manager.resetBorrower();
90189
91266
  return ok({ reset: true, next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower." });
@@ -90208,6 +91285,7 @@ var import_zod7 = require("zod");
90208
91285
  var GUIDE_TOPICS = [
90209
91286
  "getting-started",
90210
91287
  "first-setup",
91288
+ "connect-wallet",
90211
91289
  "lifecycle",
90212
91290
  "fees",
90213
91291
  "psm",
@@ -90226,10 +91304,16 @@ without selling it. Your BTC sits in a custody vault tied to your position; you
90226
91304
  against it, pay it back whenever you like, and take your BTC out again.
90227
91305
 
90228
91306
  **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.
91307
+ topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
91308
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
91309
+ are enabled (and the true reason when not), and which signer modes this build offers;
91310
+ never promise a capability it does not list. The money truth has THREE cases:
91311
+ - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
91312
+ - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
91313
+ the test network: real ceremonies and signatures, PRACTICE money (test funds).
91314
+ - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
91315
+ explicitly arms them; the capabilities block states which applies.
91316
+ SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
90233
91317
 
90234
91318
  A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
90235
91319
  authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
@@ -90239,20 +91323,29 @@ calls. Every operation that moves funds requires the user's explicit confirmatio
90239
91323
 
90240
91324
  Nothing needs a config file. Three steps:
90241
91325
 
90242
- **1. Know your world.** Read \`protocol_status\` and tell the user: practice (mock) or real,
90243
- the BTC network, current terms (\`protocol_terms\`).
91326
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
91327
+ \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
91328
+ (practice money) or mainnet (real money); whether writes are enabled here and which
91329
+ signer modes exist; current terms (\`protocol_terms\`).
90244
91330
 
90245
91331
  **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.
91332
+ - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
91333
+ on the real adapter and the mock. The approval page auto-opens in the browser (its URL
91334
+ is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
91335
+ / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
91336
+ their own wallet. The first verified signature binds their wallet address as the
91337
+ borrower. Full walkthrough: \`guide connect-wallet\`.
90250
91338
  - **"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.
91339
+ signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
91340
+ \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
91341
+ LOCAL PAGE opens where the user types the password or generates a fresh keystore.
91342
+ NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
91343
+ them to use the unlock page instead.
91344
+ - **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
91345
+ real adapter they refuse with that true reason. Try them in a mock world.
90255
91346
  - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
91347
+ - **No signer is also a valid start:** every public read works without one \u2014
91348
+ \`position_list {borrower}\` with the user's address needs no signer and no login.
90256
91349
 
90257
91350
  **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
90258
91351
  \`confirmed: true\` from the user). Then deposit BTC to the vault address
@@ -90260,6 +91353,55 @@ the BTC network, current terms (\`protocol_terms\`).
90260
91353
  and mint with \`loan_mint\`.
90261
91354
 
90262
91355
  The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
91356
+ "connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
91357
+
91358
+ External mode means the user approves every operation in their OWN wallet \u2014 a browser
91359
+ extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
91360
+ the mock.
91361
+
91362
+ **The walkthrough:**
91363
+ 1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
91364
+ desktop browser; its URL is ALSO in the tool result (loopback-only \u2014 open it on the
91365
+ same machine the server runs on).
91366
+ 2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
91367
+ WalletConnect QR code or paste the pairing code.
91368
+ 3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
91369
+ login ceremony explicitly (one typed-data signature in the wallet).
91370
+ 4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
91371
+ across sessions (\`signer_setup reset-borrower\` unbinds it).
91372
+ 5. From then on, every fund-moving operation shows an approval card in the wallet,
91373
+ decoded from the exact transaction bytes \u2014 what you read IS what executes. Declining
91374
+ always safely cancels.
91375
+
91376
+ **Popup cadence \u2014 exactly this many wallet interactions per operation:**
91377
+
91378
+ | Operation | Wallet interactions (external mode) |
91379
+ |---|---|
91380
+ | login (per login-session lifetime) | 1 typed-data |
91381
+ | create position | 1 tx (plus 1 login typed-data the first time \u2014 the protocol SDK keeps its own session) |
91382
+ | mint | 1 personal-sign + 1 tx |
91383
+ | repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
91384
+ | extend | 1 personal-sign + 1 tx |
91385
+ | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
91386
+ | withdraw BTC | not available in external mode yet (refuses with that reason); keystore mode works, no popups |
91387
+ | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
91388
+
91389
+ **Honesty notes (say these plainly):**
91390
+ - **Reads never pop the wallet.** If a read needs a login the user does not have, the
91391
+ tool refuses legibly and the user says "connect my wallet" (\`signer_setup\` action
91392
+ \`connect\`). The wallet never appears unrequested.
91393
+ - **Logins expire.** When the session token dies mid-conversation, the next
91394
+ authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
91395
+ surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
91396
+ login means "wait and retry", not a wallet failure.
91397
+ - **Withdraw-BTC under external mode is not shipped yet** (the SDK signing-context seam
91398
+ is pending) \u2014 it refuses with that true reason; keystore-mode withdraw works.
91399
+ - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
91400
+ (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
91401
+ hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
91402
+ card states the live figure.
91403
+ - **Mainnet:** writes are disabled unless the operator explicitly arms them, and the
91404
+ minimum mint is 10 UCD.`,
90263
91405
  lifecycle: `# The full lifecycle \u2014 exact calls
90264
91406
 
90265
91407
  1. **Create** \u2014 \`loan_create {selectedTerm, confirmed:true}\` \u2192 position id, vault address.
@@ -90355,12 +91497,23 @@ Every fund-moving operation needs TWO things, always in this order:
90355
91497
  1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
90356
91498
  must ask, never assume.
90357
91499
  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.
91500
+ - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
91501
+ mobile via QR/paste-code). Real adapter and mock. The approval card in the wallet
91502
+ shows EXACTLY what executes \u2014 amounts are decoded from the transaction itself, never
91503
+ re-formatted. Walkthrough: \`guide connect-wallet\`.
90361
91504
  - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
91505
+ Real adapter and mock.
91506
+ - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
91507
+ refuse with that true reason (their planes ship in their own deliveries).
90362
91508
  - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
90363
91509
 
91510
+ **Reads never summon the wallet.** Public reads need no signer at all. Authenticated
91511
+ reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
91512
+ (\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
91513
+ only ever caused by a write ceremony or that explicit connect. The login (one typed-data
91514
+ signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
91515
+ way \u2014 reconnect on the user's word.
91516
+
90364
91517
  Results carry \`authorization\`: \`scheme\` (external-wallet | eip712-eoa | mock-signature),
90365
91518
  \`signer\` (who signed), \`card\` (what was signed, human-readable), \`digest\` (the signature
90366
91519
  or transaction hash). Declining in the wallet ALWAYS safely cancels the operation.
@@ -90380,6 +91533,10 @@ signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companie
90380
91533
  teams use Safes so no single key controls the funds. Diamond Hands supports a Safe AS THE
90381
91534
  BORROWER: the position belongs to the Safe, and operations are authorized by its owners.
90382
91535
 
91536
+ **Adapter truth:** the Safe borrower plane is PRACTICE-ONLY today \u2014 on the real adapter,
91537
+ \`signer_setup use safe\` refuses with exactly that reason. Everything below runs in mock
91538
+ worlds until the Safe plane's own delivery; never present it as available on real.
91539
+
90383
91540
  **Setup:** \`signer_setup\` action \`use\`, mode \`safe\`, with \`safeAddress\`. Owners and
90384
91541
  threshold are DISCOVERED from the Safe itself \u2014 never typed in. (Practice worlds: create
90385
91542
  a test Safe first with \`mock_control deploy-safe\`.) If keystore material is already
@@ -90396,8 +91553,9 @@ AUTOMATICALLY \u2014 do not send the user to the unlock page in that case.
90396
91553
 
90397
91554
  **Withdrawals have one extra rule:** the destination BTC address must be ALLOWLISTED for
90398
91555
  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.
91556
+ becomes usable after a delay READ LIVE from the chain \u2014 immediate in practice worlds,
91557
+ 24 hours on mainnet, where allowlisting and withdrawing happen on different days). A
91558
+ withdrawal to an unlisted address refuses with exactly this instruction.
90401
91559
 
90402
91560
  **Timing honesty (multi-owner Safes, later phases):** authorizations for mint/pay/renew
90403
91561
  expire after ~3 minutes, and withdrawal authorizations within the minute \u2014 so a multi-
@@ -90410,6 +91568,10 @@ Multi-owner Safes cannot practically sign every operation inside the protocol's
90410
91568
  signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
90411
91569
  tightly-caged AGENT key; afterwards daily work runs without disturbing them.
90412
91570
 
91571
+ **Adapter truth:** delegation (mode \`safe-module\`) is PRACTICE-ONLY today \u2014 on the real
91572
+ adapter it refuses with exactly that reason, pending its own delivery. Everything below
91573
+ runs in mock worlds; never present it as available on real.
91574
+
90413
91575
  **Setup (mode \`safe-module\`):** \`signer_setup use safe-module\` with your Safe's address,
90414
91576
  then \`loan_delegation_setup\` \u2014 ONE durable Safe transaction the owners sign at their
90415
91577
  leisure (no time window). It enables the Safe's AgentModule, binds the agent key, registers
@@ -90460,8 +91622,19 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
90460
91622
  user believe practice gains/losses are real, or vice versa.`,
90461
91623
  troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
90462
91624
 
90463
- - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Run \`signer_setup status\`
90464
- and follow \`first-setup\` step 2.
91625
+ - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
91626
+ keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
91627
+ "connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
91628
+ status\` explains what is active; \`first-setup\` step 2 has the full choice.
91629
+ - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
91630
+ the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
91631
+ EXPIRED login refuses the same way \u2014 reconnect on the user's word.
91632
+ - **Mainnet write refused** \u2014 mainnet writes are disabled unless the operator explicitly
91633
+ arms them; the refusal is the standing gate, not a bug. Reads keep working.
91634
+ - **External-mode withdraw refused** \u2014 withdraw-BTC under external mode is not shipped
91635
+ yet (the SDK signing-context seam is pending); keystore-mode withdraw works.
91636
+ - **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
91637
+ That is the broker throttle, not a wallet failure.
90465
91638
  - **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
90466
91639
  unknown field). The message names the exact problem; fix the input, don't retry blindly.
90467
91640
  - **UPSTREAM_REJECTED** \u2014 the protocol said no: over the mint ceiling, repaying more than
@@ -90500,21 +91673,24 @@ not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitco
90500
91673
  };
90501
91674
  var GUIDE_INDEX = `# Diamond Hands guide \u2014 topics
90502
91675
 
90503
- - getting-started \u2014 what this product is, practice-vs-real honesty
91676
+ - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
90504
91677
  - first-setup \u2014 zero to ready by conversation (authorization choice included)
91678
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty
90505
91679
  - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
90506
91680
  - fees \u2014 the two fee models, plainly
90507
91681
  - 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
91682
+ - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
91683
+ - safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today
91684
+ - 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
91685
  - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
90512
- - troubleshooting \u2014 error codes in plain words
91686
+ - troubleshooting \u2014 error codes in plain words, with the real remedies
90513
91687
  - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
90514
91688
 
90515
91689
  Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
90516
91690
  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.`;
91691
+ signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
91692
+ and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
91693
+ only mainnet is real money.`;
90518
91694
 
90519
91695
  // src/tools/guide.ts
90520
91696
  function registerGuideTool(server) {
@@ -90523,7 +91699,7 @@ function registerGuideTool(server) {
90523
91699
  "guide",
90524
91700
  {
90525
91701
  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.`,
91702
+ 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
91703
  inputSchema: {
90528
91704
  topic: import_zod7.z.string().optional().describe(`One of: ${GUIDE_TOPICS.join(" | ")} (omit for the index)`)
90529
91705
  },
@@ -90553,14 +91729,29 @@ function registerGuideResources(server) {
90553
91729
  function registerGuidePrompts(server) {
90554
91730
  server.prompt(
90555
91731
  "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.",
91732
+ "Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
90557
91733
  () => ({
90558
91734
  messages: [
90559
91735
  {
90560
91736
  role: "user",
90561
91737
  content: {
90562
91738
  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."
91739
+ 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."
91740
+ }
91741
+ }
91742
+ ]
91743
+ })
91744
+ );
91745
+ server.prompt(
91746
+ "connect-wallet",
91747
+ "Connect the user's own wallet as the signer: approval page, extension or WalletConnect QR, first-signature binding, per-operation approvals.",
91748
+ () => ({
91749
+ messages: [
91750
+ {
91751
+ role: "user",
91752
+ content: {
91753
+ type: "text",
91754
+ 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
91755
  }
90565
91756
  }
90566
91757
  ]
@@ -90679,7 +91870,7 @@ function registerBoundaryInfoResource(server, getB) {
90679
91870
  "boundary://info",
90680
91871
  {
90681
91872
  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.",
91873
+ 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
91874
  mimeType: "application/json"
90684
91875
  },
90685
91876
  async (uri) => {
@@ -90694,12 +91885,16 @@ function registerBoundaryInfoResource(server, getB) {
90694
91885
  }
90695
91886
 
90696
91887
  // src/server.ts
90697
- var SERVER_VERSION = "0.1.1";
91888
+ var SERVER_VERSION = "0.2.0";
91889
+ 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
91890
  function createServer2(deps) {
90699
- const server = new import_mcp2.McpServer({
90700
- name: "diamond-hands",
90701
- version: SERVER_VERSION
90702
- });
91891
+ const server = new import_mcp2.McpServer(
91892
+ {
91893
+ name: "diamond-hands",
91894
+ version: SERVER_VERSION
91895
+ },
91896
+ { instructions: SERVER_INSTRUCTIONS }
91897
+ );
90703
91898
  const getB = () => deps.boundaryResult;
90704
91899
  registerLoanTools(server, getB, deps.mockControl ? "mock" : "real");
90705
91900
  registerPositionTools(server, getB);