@gvnrdao/dh-mcp 0.5.15 → 0.5.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15431,7 +15431,7 @@ ${errorReport}`);
15431
15431
  }
15432
15432
  init_debug_logger();
15433
15433
  init_session_signature_cache();
15434
- var import_ethers42 = require("ethers");
15434
+ var import_ethers52 = require("ethers");
15435
15435
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15436
15436
  var GRACE_PERIOD_DAYS = 30;
15437
15437
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -18347,12 +18347,12 @@ ${auth.clientId}`;
18347
18347
  }
18348
18348
  async function executeVaultSnapshot(params) {
18349
18349
  global.ethers = {
18350
- ...import_ethers42.ethers,
18350
+ ...import_ethers52.ethers,
18351
18351
  providers: {
18352
- StaticJsonRpcProvider: import_ethers42.ethers.JsonRpcProvider
18352
+ StaticJsonRpcProvider: import_ethers52.ethers.JsonRpcProvider
18353
18353
  },
18354
- Contract: import_ethers42.ethers.Contract,
18355
- utils: import_ethers42.ethers
18354
+ Contract: import_ethers52.ethers.Contract,
18355
+ utils: import_ethers52.ethers
18356
18356
  // v6 moved utils to top level
18357
18357
  };
18358
18358
  global.Lit = {
@@ -25561,7 +25561,10 @@ var require_lit_core_lit_action_client = __commonJS({
25561
25561
  "node_modules/@gvnrdao/dh-lit-ops/dist/utils/lit-core-lit-action-client.js"(exports2) {
25562
25562
  "use strict";
25563
25563
  Object.defineProperty(exports2, "__esModule", { value: true });
25564
+ exports2.CORE_API_TRANSPORT_FAILURE_MARKER = void 0;
25564
25565
  exports2.normalizeCoreLitActionResult = normalizeCoreLitActionResult;
25566
+ exports2.describeErrorWithCause = describeErrorWithCause;
25567
+ exports2.isCoreApiTransportError = isCoreApiTransportError;
25565
25568
  exports2.executeLitActionViaCoreApi = executeLitActionViaCoreApi;
25566
25569
  var fetch_lit_action_from_ipfs_1 = require_fetch_lit_action_from_ipfs();
25567
25570
  function parseResponsePayload(raw) {
@@ -25612,6 +25615,27 @@ var require_lit_core_lit_action_client = __commonJS({
25612
25615
  const fromEnv = process.env.LIT_CORE_API_BASE_URL;
25613
25616
  return (explicit || fromEnv || "https://api.chipotle.litprotocol.com").replace(/\/$/, "");
25614
25617
  }
25618
+ exports2.CORE_API_TRANSPORT_FAILURE_MARKER = "Lit Core lit_action transport failure";
25619
+ function describeErrorWithCause(e) {
25620
+ const parts = [];
25621
+ let current = e;
25622
+ const seen = /* @__PURE__ */ new Set();
25623
+ while (current != null && !seen.has(current) && parts.length < 5) {
25624
+ seen.add(current);
25625
+ if (current instanceof Error) {
25626
+ const code = current.code;
25627
+ parts.push(typeof code === "string" && !current.message.includes(code) ? `${code}: ${current.message}` : current.message);
25628
+ current = current.cause;
25629
+ } else {
25630
+ parts.push(String(current));
25631
+ break;
25632
+ }
25633
+ }
25634
+ return parts.length === 0 ? String(e) : parts.join(" <- ");
25635
+ }
25636
+ function isCoreApiTransportError(message) {
25637
+ return message.includes(exports2.CORE_API_TRANSPORT_FAILURE_MARKER);
25638
+ }
25615
25639
  async function executeLitActionViaCoreApi(options) {
25616
25640
  let resolvedCode = options.code || "";
25617
25641
  if (!resolvedCode.trim()) {
@@ -25673,13 +25697,11 @@ var require_lit_core_lit_action_client = __commonJS({
25673
25697
  return normalizeCoreLitActionResult(body);
25674
25698
  } catch (e) {
25675
25699
  const msg = e instanceof Error ? e.message : String(e);
25700
+ const error = msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : `${exports2.CORE_API_TRANSPORT_FAILURE_MARKER}: ${describeErrorWithCause(e)}`;
25676
25701
  if (options.debug) {
25677
- console.error("\u274C [executeLitActionViaCoreApi]", msg);
25702
+ console.error("\u274C [executeLitActionViaCoreApi]", error);
25678
25703
  }
25679
- return {
25680
- success: false,
25681
- error: msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : msg
25682
- };
25704
+ return { success: false, error };
25683
25705
  } finally {
25684
25706
  clearTimeout(timer);
25685
25707
  }
@@ -26661,7 +26683,8 @@ var require_lit_ops_module = __commonJS({
26661
26683
  const borrowerAddress = borrowerOverride ?? this.config.serverAddress ?? await this.config.signer.getAddress();
26662
26684
  const pkpValidatorInfo = DH_LIT_ACTIONS_CHIPOTLE.pkpValidator;
26663
26685
  const validatorWalletAddress = process.env.LIT_PKP_VALIDATOR_WALLET_OVERRIDE || pkpValidatorInfo?.validatorWalletAddress;
26664
- const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(e instanceof Error ? e.message : String(e));
26686
+ const errorMessage = (e) => e instanceof Error ? e.message : String(e);
26687
+ const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(errorMessage(e));
26665
26688
  const propagationRetries = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_RETRIES) || 8;
26666
26689
  const propagationDelayMs = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_DELAY_MS) || 15e3;
26667
26690
  let coreResponse;
@@ -26682,10 +26705,12 @@ var require_lit_ops_module = __commonJS({
26682
26705
  coreResponse = exec.response;
26683
26706
  break;
26684
26707
  } catch (e) {
26685
- if (!isWalletPropagationError(e) || attempt === propagationRetries) {
26708
+ const propagating = isWalletPropagationError(e);
26709
+ const transport = (0, lit_core_lit_action_client_1.isCoreApiTransportError)(errorMessage(e));
26710
+ if (!propagating && !transport || attempt === propagationRetries) {
26686
26711
  throw e;
26687
26712
  }
26688
- console.log(`[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
26713
+ console.log(propagating ? `[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms` : `[ChipotlePKP] vault PKP ${pkpId} validator call failed in transport (${errorMessage(e)}); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
26689
26714
  await new Promise((r) => setTimeout(r, propagationDelayMs));
26690
26715
  }
26691
26716
  }
@@ -40410,7 +40435,7 @@ var require_dist3 = __commonJS({
40410
40435
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
40411
40436
  };
40412
40437
  Object.defineProperty(exports2, "__esModule", { value: true });
40413
- exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
40438
+ exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
40414
40439
  __exportStar(require_interfaces(), exports2);
40415
40440
  var dh_lit_actions_1 = require_pkg_src();
40416
40441
  Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
@@ -40480,6 +40505,15 @@ var require_dist3 = __commonJS({
40480
40505
  Object.defineProperty(exports2, "normalizeCoreLitActionResult", { enumerable: true, get: function() {
40481
40506
  return lit_core_lit_action_client_1.normalizeCoreLitActionResult;
40482
40507
  } });
40508
+ Object.defineProperty(exports2, "describeErrorWithCause", { enumerable: true, get: function() {
40509
+ return lit_core_lit_action_client_1.describeErrorWithCause;
40510
+ } });
40511
+ Object.defineProperty(exports2, "isCoreApiTransportError", { enumerable: true, get: function() {
40512
+ return lit_core_lit_action_client_1.isCoreApiTransportError;
40513
+ } });
40514
+ Object.defineProperty(exports2, "CORE_API_TRANSPORT_FAILURE_MARKER", { enumerable: true, get: function() {
40515
+ return lit_core_lit_action_client_1.CORE_API_TRANSPORT_FAILURE_MARKER;
40516
+ } });
40483
40517
  var bitcoin_signature_1 = require_bitcoin_signature();
40484
40518
  Object.defineProperty(exports2, "convertEthereumSignatureToBitcoinDER", { enumerable: true, get: function() {
40485
40519
  return bitcoin_signature_1.convertEthereumSignatureToBitcoinDER;
@@ -40847,7 +40881,7 @@ function resolveRealConfig(env) {
40847
40881
 
40848
40882
  // src/boot.ts
40849
40883
  var fs6 = __toESM(require("fs"));
40850
- var import_ethers39 = require("ethers");
40884
+ var import_ethers49 = require("ethers");
40851
40885
 
40852
40886
  // src/boundary/index.ts
40853
40887
  var import_node_crypto8 = require("crypto");
@@ -41264,7 +41298,7 @@ var BoundaryCore = class {
41264
41298
  const inToken = toUcd ? s.stablecoinSymbol : "UCD";
41265
41299
  const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
41266
41300
  const amountIn = parseDecimalUnits(p.amount, inDecimals);
41267
- const refuse = (refusal, message, details) => ({
41301
+ const refuse3 = (refusal, message, details) => ({
41268
41302
  env: errEnvelope(
41269
41303
  boundaryError("UPSTREAM_REJECTED", message, {
41270
41304
  source: statusR.source.id,
@@ -41275,13 +41309,13 @@ var BoundaryCore = class {
41275
41309
  });
41276
41310
  const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
41277
41311
  if (s.paused) {
41278
- return refuse(
41312
+ return refuse3(
41279
41313
  "psm-paused",
41280
41314
  "the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
41281
41315
  );
41282
41316
  }
41283
41317
  if (!toUcd && !s.redeemEnabled) {
41284
- return refuse(
41318
+ return refuse3(
41285
41319
  "redeem-disabled",
41286
41320
  `redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
41287
41321
  );
@@ -41292,20 +41326,20 @@ var BoundaryCore = class {
41292
41326
  const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
41293
41327
  const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
41294
41328
  if (amountIn < min) {
41295
- return refuse(
41329
+ return refuse3(
41296
41330
  "below-min",
41297
41331
  `${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
41298
41332
  { amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
41299
41333
  );
41300
41334
  }
41301
41335
  if (max === 0n) {
41302
- return refuse(
41336
+ return refuse3(
41303
41337
  "direction-disabled",
41304
41338
  `the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
41305
41339
  );
41306
41340
  }
41307
41341
  if (amountIn > max) {
41308
- return refuse(
41342
+ return refuse3(
41309
41343
  "above-max",
41310
41344
  `${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
41311
41345
  { amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
@@ -41325,7 +41359,7 @@ var BoundaryCore = class {
41325
41359
  if (!toUcd) {
41326
41360
  const available = BigInt(s.availableReserves);
41327
41361
  if (available < amountOut) {
41328
- return refuse(
41362
+ return refuse3(
41329
41363
  "insufficient-reserves",
41330
41364
  `the PSM cannot pay this redemption: available reserves ${formatDecimalUnits(available, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${available} smallest units), required ${formatDecimalUnits(amountOut, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${amountOut} smallest units).`,
41331
41365
  { available: available.toString(), required: amountOut.toString(), unit: outUnit }
@@ -41401,20 +41435,31 @@ var BoundaryCore = class {
41401
41435
  const inDecimals = toUcd ? s.stablecoinDecimals : 18;
41402
41436
  const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
41403
41437
  const viaSafe = this.deps.signer?.mode() === "safe";
41438
+ const a = v.allowance;
41439
+ const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
41440
+ const approvalsHuman = v.approvals.length === 0 ? `No approval was needed: the standing ${a.tokenSymbol} allowance to ${a.spenderContract} (${fmtIn(a.before)}) already covered the amount.` : v.approvals.map(
41441
+ (leg) => leg.step === "reset-approve" ? `reset the partial ${a.tokenSymbol} allowance to ${a.spenderContract} (${fmtIn(a.before)}) to 0` : `approved EXACTLY ${fmtIn(leg.amount)} to ${a.spenderContract}`
41442
+ ).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
41404
41443
  const data = {
41405
41444
  direction: p.direction,
41406
41445
  contractCall: q.contractCall,
41407
- approve: {
41408
- txRef: v.approve.txRef,
41409
- token: v.approve.tokenSymbol,
41410
- tokenAddress: v.approve.tokenAddress,
41411
- spenderAddress: v.approve.spenderAddress,
41412
- spenderContract: v.approve.spenderContract,
41413
- spenderReason: v.approve.spenderContract === "SimplePSMV2" ? "the PSM contract itself pulls the USDC it converts (transferFrom), so the USDC allowance goes to the PSM" : "the PSM burns your UCD THROUGH the UCDController (controller.burnFromPsm), so the UCD allowance goes to the UCDController \u2014 a different contract than the PSM, by design",
41414
- amount: v.approve.amount,
41446
+ allowance: {
41447
+ token: a.tokenSymbol,
41448
+ tokenAddress: a.tokenAddress,
41449
+ spenderAddress: a.spenderAddress,
41450
+ spenderContract: a.spenderContract,
41451
+ spenderReason: a.spenderContract === "SimplePSMV2" ? "the PSM contract itself pulls the USDC it converts (transferFrom), so the USDC allowance goes to the PSM" : "the PSM burns your UCD THROUGH the UCDController (controller.burnFromPsm), so the UCD allowance goes to the UCDController \u2014 a different contract than the PSM, by design",
41452
+ before: a.before,
41415
41453
  amountUnit: q.amountInUnit,
41416
- authorization: v.approve.authorization
41454
+ basis: "approvals are planned against the allowance read before signing: none when it already covers the amount; an exact approve when it is 0; a partial allowance is reset to 0 first (some tokens refuse a non-zero \u2192 non-zero approve). Every approve is EXACTLY the input amount \u2014 never unlimited."
41417
41455
  },
41456
+ approvals: v.approvals.map((leg) => ({
41457
+ step: leg.step,
41458
+ txRef: leg.txRef,
41459
+ amount: leg.amount,
41460
+ amountUnit: q.amountInUnit,
41461
+ authorization: leg.authorization
41462
+ })),
41418
41463
  execute: {
41419
41464
  txRef: v.execute.txRef,
41420
41465
  amountIn: v.execute.amountIn,
@@ -41436,7 +41481,7 @@ var BoundaryCore = class {
41436
41481
  note: viaSafe ? "output lands AT THE SAFE \u2014 both transactions execute BY the Safe (the Safe is msg.sender, and the contract pays msg.sender only; there is no recipient parameter)" : "output goes to the signer's own address \u2014 the contract pays msg.sender only; there is no recipient parameter"
41437
41482
  },
41438
41483
  balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
41439
- human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}). Ceremony 1: approved EXACTLY ${formatDecimalUnits(BigInt(v.approve.amount), inDecimals)} ${v.approve.tokenSymbol} to ${v.approve.spenderContract}. Ceremony 2: ${q.contractCall} executed with floor ${formatDecimalUnits(BigInt(v.execute.minOut), outDecimals)} ${q.amountOutToken} (quote \u2212 ${PSM_FLOOR_TOLERANCE_BPS} bps). ` + (viaSafe ? `Both executed BY the Safe as consecutive Safe transactions; output to the Safe: ${auth.borrower}.` : `Output to the signer: ${auth.borrower}.`)
41484
+ human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}). ${approvalsHuman} Ceremony ${v.approvals.length + 1}: ${q.contractCall} executed with floor ${formatDecimalUnits(BigInt(v.execute.minOut), outDecimals)} ${q.amountOutToken} (quote \u2212 ${PSM_FLOOR_TOLERANCE_BPS} bps). ` + (viaSafe ? `All executed BY the Safe as consecutive Safe transactions; output to the Safe: ${auth.borrower}.` : `Output to the signer: ${auth.borrower}.`)
41440
41485
  };
41441
41486
  return okEnvelope(data, r.source, warnings);
41442
41487
  }
@@ -43295,6 +43340,16 @@ function buildExtendTx(ctx, p) {
43295
43340
  );
43296
43341
  }
43297
43342
 
43343
+ // src/boundary/upstream/shared/psm-approval-steps.ts
43344
+ function psmApprovalSteps(allowanceBefore, amountIn) {
43345
+ if (allowanceBefore >= amountIn) return [];
43346
+ if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
43347
+ return [
43348
+ { step: "reset-approve", amount: 0n },
43349
+ { step: "approve", amount: amountIn }
43350
+ ];
43351
+ }
43352
+
43298
43353
  // src/boundary/upstream/mock/sink-contracts.ts
43299
43354
  var import_ethers5 = require("ethers");
43300
43355
  function sinkAddress(label) {
@@ -44121,8 +44176,9 @@ var MockUpstreamPlugin = class {
44121
44176
  return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
44122
44177
  });
44123
44178
  }
44124
- /** PSM exchange pair (plan 08 W1): TWO ceremonies in ONE ops call — the exact-amount
44125
- * approve (spender asymmetric by direction, contract truth), then the swap/redeem with
44179
+ /** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
44180
+ * or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
44181
+ * asymmetric by direction, contract truth), then the swap/redeem with
44126
44182
  * its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
44127
44183
  * AFTER the approve reports the step that declined AND the residual exact-amount
44128
44184
  * allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
@@ -44141,55 +44197,75 @@ var MockUpstreamPlugin = class {
44141
44197
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
44142
44198
  const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
44143
44199
  const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
44144
- const residualNote = `the approve step already completed \u2014 an exact-amount allowance of ${p.amountIn} ${tokenUnit} to ${spenderContract} remains standing; it authorizes only that amount and nothing else. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
44145
- const approveCard = `approve exactly ${p.amountIn} ${tokenUnit} to ${spenderContract} (${spenderReason})`;
44200
+ const standing = this.world.psmAllowancesOf(p.borrower);
44201
+ const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
44202
+ const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
44203
+ const landed = [];
44204
+ const residualNote = () => {
44205
+ const last = landed[landed.length - 1];
44206
+ const state = !last ? `no approve ran \u2014 the pre-existing allowance of ${allowanceBefore} ${tokenUnit} to ${spenderContract} is unchanged` : last === "reset-approve" ? `the reset step already completed \u2014 the allowance to ${spenderContract} is now 0; nothing is authorized` : `the approve step already completed \u2014 an exact-amount allowance of ${p.amountIn} ${tokenUnit} to ${spenderContract} remains standing; it authorizes only that amount and nothing else`;
44207
+ return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
44208
+ };
44146
44209
  const executeCard = `${isSwap ? "exchange" : "redeem"} ${p.amountIn} ${tokenUnit} via the PSM (contract ${p.direction}): quote ${plan.value.out} ${outUnit} (fee ${plan.value.fee} ${outUnit}), floor ${p.minOut} ${outUnit} \u2014 output to ${p.borrower}`;
44147
44210
  const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
44148
44211
  const cer = this.ceremonyNow();
44149
- let approveAuth = null;
44150
- if (cer) {
44151
- const chainId = cer.txContext().chainId;
44152
- const approveTx = buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount: p.amountIn });
44153
- const r = await cer.authorizeTx({
44154
- action: "psm-approve",
44155
- borrower: p.borrower,
44156
- tx: approveTx,
44157
- expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn }
44158
- });
44159
- if (!r.ok) {
44160
- return upFail({
44161
- kind: "rejected",
44162
- source: "mock-ops",
44163
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(r.failure)} \u2014 no allowance was granted and no funds moved`
44212
+ const approvals = [];
44213
+ for (const s of steps) {
44214
+ const amount = s.amount.toString();
44215
+ const isReset = s.step === "reset-approve";
44216
+ const label = isReset ? "RESET-APPROVE" : "APPROVE";
44217
+ const stopNote = landed.length > 0 ? residualNote() : isReset ? `the partial allowance of ${allowanceBefore} ${tokenUnit} to ${spenderContract} is unchanged and no funds moved` : "no allowance was granted and no funds moved";
44218
+ const card = isReset ? `reset the standing allowance of ${allowanceBefore} ${tokenUnit} to ${spenderContract} to 0 (required before an exact-amount approve; ${spenderReason})` : `approve exactly ${amount} ${tokenUnit} to ${spenderContract} (${spenderReason})`;
44219
+ let legAuth = null;
44220
+ if (cer) {
44221
+ const chainId = cer.txContext().chainId;
44222
+ const r = await cer.authorizeTx({
44223
+ action: "psm-approve",
44224
+ borrower: p.borrower,
44225
+ tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
44226
+ expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
44164
44227
  });
44228
+ if (!r.ok) {
44229
+ return upFail({
44230
+ kind: "rejected",
44231
+ source: "mock-ops",
44232
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
44233
+ });
44234
+ }
44235
+ this.bindIfDiscovering(r.authorization);
44236
+ legAuth = r.authorization;
44165
44237
  }
44166
- this.bindIfDiscovering(r.authorization);
44167
- approveAuth = r.authorization;
44168
- }
44169
- const step1 = await this.write("psmSwap", () => {
44170
- const sig = approveAuth ? { ok: true, authorization: approveAuth } : this.sign("psm-approve", p.borrower, approveCard);
44171
- if (!sig.ok) {
44172
- return upFail({
44173
- kind: "rejected",
44174
- source: "mock-ops",
44175
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(sig.failure)} \u2014 no allowance was granted and no funds moved`
44238
+ const leg = await this.write("psmSwap", () => {
44239
+ const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
44240
+ if (!sig.ok) {
44241
+ return upFail({
44242
+ kind: "rejected",
44243
+ source: "mock-ops",
44244
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
44245
+ });
44246
+ }
44247
+ const applied = this.applyAuthorized(sig.authorization, () => {
44248
+ this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
44249
+ return { ok: true, value: void 0 };
44176
44250
  });
44177
- }
44178
- const applied = this.applyAuthorized(sig.authorization, () => {
44179
- this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount: p.amountIn });
44180
- return { ok: true, value: void 0 };
44251
+ if (!applied.ok) {
44252
+ return upFail({
44253
+ kind: "rejected",
44254
+ source: "mock-ops",
44255
+ message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
44256
+ });
44257
+ }
44258
+ return upOk(sig.authorization, this.src("mock-ops"));
44181
44259
  });
44182
- if (!applied.ok) {
44183
- return upFail({
44184
- kind: "rejected",
44185
- source: "mock-ops",
44186
- message: `psmSwap failed at the APPROVE step: ${applied.reason} \u2014 no allowance was granted and no funds moved`
44187
- });
44188
- }
44189
- return upOk(sig.authorization, this.src("mock-ops"));
44190
- });
44191
- if (!step1.ok) return step1;
44192
- const aAuth = step1.value;
44260
+ if (!leg.ok) return leg;
44261
+ landed.push(s.step);
44262
+ approvals.push({
44263
+ step: s.step,
44264
+ txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
44265
+ amount,
44266
+ authorization: leg.value
44267
+ });
44268
+ }
44193
44269
  let executeAuth = null;
44194
44270
  if (cer) {
44195
44271
  const chainId = cer.txContext().chainId;
@@ -44204,7 +44280,7 @@ var MockUpstreamPlugin = class {
44204
44280
  return upFail({
44205
44281
  kind: "rejected",
44206
44282
  source: "mock-ops",
44207
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
44283
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
44208
44284
  });
44209
44285
  }
44210
44286
  executeAuth = r.authorization;
@@ -44215,23 +44291,16 @@ var MockUpstreamPlugin = class {
44215
44291
  return upFail({
44216
44292
  kind: "rejected",
44217
44293
  source: "mock-ops",
44218
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
44294
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
44219
44295
  });
44220
44296
  }
44221
44297
  const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
44222
- if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
44298
+ if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
44223
44299
  const bal = this.world.balancesOf(p.borrower);
44224
44300
  return upOk(
44225
44301
  {
44226
- approve: {
44227
- txRef: approveAuth ? { kind: "eth-tx", id: aAuth.digest } : this.world.nextTxRef(),
44228
- tokenSymbol,
44229
- tokenAddress,
44230
- spenderAddress,
44231
- spenderContract,
44232
- amount: p.amountIn,
44233
- authorization: aAuth
44234
- },
44302
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
44303
+ approvals,
44235
44304
  execute: {
44236
44305
  txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
44237
44306
  amountIn: p.amountIn,
@@ -45412,7 +45481,7 @@ var SafeModuleCeremony = class {
45412
45481
  };
45413
45482
 
45414
45483
  // src/boundary/upstream/real/plugin.ts
45415
- var import_ethers38 = require("ethers");
45484
+ var import_ethers48 = require("ethers");
45416
45485
 
45417
45486
  // node_modules/@gvnrdao/dh-sdk/dist/index.mjs
45418
45487
  var import_ethers13 = require("ethers");
@@ -51503,8 +51572,12 @@ var {
51503
51572
  var import_ethers27 = require("ethers");
51504
51573
  var import_ethers28 = require("ethers");
51505
51574
  var import_ethers29 = require("ethers");
51506
- var import_dh_lit_ops = __toESM(require_dist3(), 1);
51507
51575
  var import_ethers30 = require("ethers");
51576
+ var import_ethers31 = require("ethers");
51577
+ var import_ethers32 = require("ethers");
51578
+ var import_ethers33 = require("ethers");
51579
+ var import_dh_lit_ops = __toESM(require_dist3(), 1);
51580
+ var import_ethers34 = require("ethers");
51508
51581
  var __create2 = Object.create;
51509
51582
  var __defProp2 = Object.defineProperty;
51510
51583
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -53867,7 +53940,7 @@ ${errorReport}`);
53867
53940
  }
53868
53941
  init_debug_logger();
53869
53942
  init_session_signature_cache();
53870
- var import_ethers192 = __require("ethers");
53943
+ var import_ethers232 = __require("ethers");
53871
53944
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
53872
53945
  var GRACE_PERIOD_DAYS = 30;
53873
53946
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -56795,12 +56868,12 @@ ${auth.clientId}`;
56795
56868
  }
56796
56869
  async function executeVaultSnapshot(params) {
56797
56870
  global.ethers = {
56798
- ...import_ethers192.ethers,
56871
+ ...import_ethers232.ethers,
56799
56872
  providers: {
56800
- StaticJsonRpcProvider: import_ethers192.ethers.JsonRpcProvider
56873
+ StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
56801
56874
  },
56802
- Contract: import_ethers192.ethers.Contract,
56803
- utils: import_ethers192.ethers
56875
+ Contract: import_ethers232.ethers.Contract,
56876
+ utils: import_ethers232.ethers
56804
56877
  // v6 moved utils to top level
56805
56878
  };
56806
56879
  global.Lit = {
@@ -57054,8 +57127,8 @@ function getSepoliaConfig() {
57054
57127
  positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
57055
57128
  positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
57056
57129
  simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
57057
- mockUsdcToken: SEPOLIA_CONTRACTS["MockUSDC"] || "",
57058
- mockUsdtToken: SEPOLIA_CONTRACTS["MockUSDT"] || "",
57130
+ mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
57131
+ mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
57059
57132
  loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
57060
57133
  termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
57061
57134
  circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
@@ -57131,14 +57204,17 @@ function getMainnetConfig() {
57131
57204
  agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
57132
57205
  },
57133
57206
  subgraphs: {
57134
- // KNOWN-WRONG placeholder (see GOAL-PLAN step 2 / dogfood F-CLI-4): this is a
57135
- // SEPOLIA subgraph id in a mainnet (chainId 1) config, and this gateway host
57136
- // needs an Authorization key the SDK does not (and must not) hold — so the
57137
- // URL is doubly unusable. The `CCTPsd…` path segment is the subgraph's
57138
- // PUBLIC ID, not a credential. The fix is a chain-correct SERVER-side proxy
57139
- // (see mcp/docs/SUBGRAPH-PROXY-PLAN.md) — same rule as rpcUrls above:
57140
- // never ship an API-keyed URL in a client config.
57141
- diamondHandsUrl: "https://gateway-arbitrum.network.thegraph.com/api/subgraphs/id/CCTPsdYqco2jChDLLBQTbdJWwoukVoMt1cXeR9ti6r9A"
57207
+ // The MAINNET subgraph on The Graph's decentralized network — the same id
57208
+ // lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
57209
+ // the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
57210
+ // chainId-1 config: unusable as shipped, but a caller who added their own key would have
57211
+ // read Sepolia data as mainnet.
57212
+ //
57213
+ // The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
57214
+ // not) hold, so this URL only works for a standalone caller supplying their own key.
57215
+ // Service mode never uses it — queries go through the lit-ops-server proxy, which adds
57216
+ // the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
57217
+ diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
57142
57218
  },
57143
57219
  litNetwork: "chipotle",
57144
57220
  debug: false
@@ -58159,6 +58235,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
58159
58235
  }
58160
58236
  return { timestamp: result.timestamp, signature: result.signature };
58161
58237
  }
58238
+ function baseMintFeeWei(mintAmountWei, originationFeeBps) {
58239
+ if (mintAmountWei < 0n)
58240
+ throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
58241
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
58242
+ throw new Error(
58243
+ `baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
58244
+ );
58245
+ }
58246
+ return mintAmountWei * BigInt(originationFeeBps) / 10000n;
58247
+ }
58248
+ function debtAfterMintExceedsLoanCap(params) {
58249
+ const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
58250
+ for (const [name, v] of Object.entries(params)) {
58251
+ if (v < 0n)
58252
+ throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
58253
+ }
58254
+ return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
58255
+ }
58256
+ function maxPrincipalWithinLoanCap(params) {
58257
+ const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
58258
+ if (maxLoanWei < 0n || currentDebtWei < 0n) {
58259
+ throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
58260
+ }
58261
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
58262
+ throw new Error(
58263
+ `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
58264
+ );
58265
+ }
58266
+ const room = maxLoanWei - currentDebtWei;
58267
+ if (room <= 0n)
58268
+ return 0n;
58269
+ return room * 10000n / (10000n + BigInt(originationFeeBps));
58270
+ }
58162
58271
  function buildLoginDomain(chainId) {
58163
58272
  return {
58164
58273
  name: "Diamond Hands",
@@ -59568,23 +59677,37 @@ var BitcoinUtils = class {
59568
59677
  return getBitcoinAddressesFromPkp(pkpPublicKey);
59569
59678
  }
59570
59679
  };
59571
- function safeValidateBitcoinAddress(address, network = "regtest") {
59680
+ function networksOfValidAddress(address) {
59681
+ const lower2 = address.toLowerCase();
59682
+ if (lower2.startsWith("bcrt1"))
59683
+ return ["regtest"];
59684
+ if (lower2.startsWith("bc1"))
59685
+ return ["mainnet"];
59686
+ if (lower2.startsWith("tb1"))
59687
+ return ["testnet"];
59688
+ if (address.startsWith("1") || address.startsWith("3"))
59689
+ return ["mainnet"];
59690
+ return ["testnet", "regtest"];
59691
+ }
59692
+ function safeValidateBitcoinAddress(address, network) {
59572
59693
  if (!address || typeof address !== "string") {
59573
59694
  throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
59574
59695
  }
59575
- const base58Pattern = /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/;
59576
- const bech32Pattern = /^(bc1|tb1|bcrt1)[a-z0-9]+$/;
59577
- if (!base58Pattern.test(address) && !bech32Pattern.test(address)) {
59578
- throw new Error(`Invalid Bitcoin address format: ${address}`);
59696
+ if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
59697
+ throw new Error(
59698
+ `Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
59699
+ );
59700
+ }
59701
+ if (!BitcoinUtils.validateAddress(address)) {
59702
+ throw new Error(
59703
+ `Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
59704
+ );
59579
59705
  }
59580
- if (network === "regtest" || network === "testnet") {
59581
- if (!address.startsWith("m") && !address.startsWith("n") && !address.startsWith("2") && !address.startsWith("tb1") && !address.startsWith("bcrt1")) {
59582
- throw new Error(`Invalid ${network} Bitcoin address: ${address} (must start with m, n, 2, tb1, or bcrt1)`);
59583
- }
59584
- } else if (network === "mainnet") {
59585
- if (!address.startsWith("1") && !address.startsWith("3") && !address.startsWith("bc1")) {
59586
- throw new Error(`Invalid mainnet Bitcoin address: ${address} (must start with 1, 3, or bc1)`);
59587
- }
59706
+ const belongsTo = networksOfValidAddress(address);
59707
+ if (!belongsTo.includes(network)) {
59708
+ throw new Error(
59709
+ `Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
59710
+ );
59588
59711
  }
59589
59712
  return address;
59590
59713
  }
@@ -61693,6 +61816,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
61693
61816
  LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
61694
61817
  return LoanStatus2;
61695
61818
  })(LoanStatus || {});
61819
+ var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
61820
+ var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
61821
+ var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
61822
+ async function collectBorrowerDebtRows(fetchPage) {
61823
+ const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
61824
+ const rows = [];
61825
+ for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
61826
+ const batch = await fetchPage(page * pageSize, pageSize);
61827
+ if (batch.length > pageSize) {
61828
+ throw new Error(
61829
+ `Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
61830
+ );
61831
+ }
61832
+ rows.push(...batch);
61833
+ if (batch.length < pageSize) {
61834
+ return rows;
61835
+ }
61836
+ }
61837
+ throw new Error(
61838
+ `Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
61839
+ );
61840
+ }
61841
+ function parseSubgraphLoanStatus(label) {
61842
+ if (typeof label !== "string") {
61843
+ throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
61844
+ }
61845
+ const value = LoanStatus[label];
61846
+ if (typeof value !== "number") {
61847
+ throw new Error(`Unknown subgraph loan status label: "${label}"`);
61848
+ }
61849
+ return value;
61850
+ }
61851
+ function parseSubgraphWei(row) {
61852
+ const raw = row.ucdDebt || "0";
61853
+ if (typeof raw !== "string") {
61854
+ throw new Error(
61855
+ `ucdDebt on position ${row.id} is not a string: ${String(raw)}`
61856
+ );
61857
+ }
61858
+ let wei;
61859
+ try {
61860
+ wei = BigInt(raw);
61861
+ } catch (error) {
61862
+ throw new Error(
61863
+ `ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
61864
+ { cause: error }
61865
+ );
61866
+ }
61867
+ if (wei < 0n) {
61868
+ throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
61869
+ }
61870
+ return wei;
61871
+ }
61872
+ var WEI_PER_UCD = 10n ** 18n;
61873
+ function weiToHumanUcdString(wei) {
61874
+ if (wei < 0n) {
61875
+ throw new Error(`Cannot render negative wei: ${wei}`);
61876
+ }
61877
+ const whole = wei / WEI_PER_UCD;
61878
+ const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
61879
+ return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
61880
+ }
61881
+ var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
61882
+ function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
61883
+ let totalWei = 0n;
61884
+ const counts = /* @__PURE__ */ new Map();
61885
+ for (const row of rows) {
61886
+ totalWei += parseSubgraphWei(row);
61887
+ const status = parseSubgraphLoanStatus(row.status);
61888
+ counts.set(status, (counts.get(status) ?? 0) + 1);
61889
+ }
61890
+ const byStatus = [];
61891
+ for (const status of STATUS_ORDINALS) {
61892
+ const count = counts.get(status);
61893
+ if (count === void 0) {
61894
+ continue;
61895
+ }
61896
+ byStatus.push({ status, statusLabel: LoanStatus[status], count });
61897
+ }
61898
+ return {
61899
+ borrower: borrower.toLowerCase(),
61900
+ loanCount: rows.length,
61901
+ totalUcdDebt: totalWei.toString(),
61902
+ totalUcdDebtHuman: weiToHumanUcdString(totalWei),
61903
+ byStatus,
61904
+ source: "subgraph",
61905
+ fetchedAt
61906
+ };
61907
+ }
61696
61908
  var POSITION_CORE_ABI = [
61697
61909
  "function getPositionDetails(bytes32) view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status, uint40 previousExpiryAt, uint16 totalTerm))"
61698
61910
  ];
@@ -62085,6 +62297,43 @@ var LoanQuery = class {
62085
62297
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
62086
62298
  return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
62087
62299
  }
62300
+ /**
62301
+ * Combined UCD debt + by-status counts for a borrower from ONE pass over the
62302
+ * subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
62303
+ * status labels, `source: "subgraph"`.
62304
+ *
62305
+ * INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
62306
+ * sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
62307
+ * failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
62308
+ * is no partial total.
62309
+ */
62310
+ async getBorrowerUcdDebtSummary(borrower) {
62311
+ const trimmed = typeof borrower === "string" ? borrower.trim() : "";
62312
+ if (!(0, import_ethers25.isAddress)(trimmed)) {
62313
+ return failure(
62314
+ new SDKError({
62315
+ message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
62316
+ category: "VALIDATION",
62317
+ severity: "LOW",
62318
+ context: { borrower: trimmed }
62319
+ })
62320
+ );
62321
+ }
62322
+ return tryCatchAsync(
62323
+ async () => {
62324
+ const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
62325
+ return buildBorrowerUcdDebtSummary(trimmed, rows);
62326
+ },
62327
+ (error) => error instanceof SDKError ? error : new SDKError({
62328
+ message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
62329
+ category: "SUBGRAPH",
62330
+ severity: "MEDIUM",
62331
+ originalError: error instanceof Error ? error : void 0,
62332
+ cause: error,
62333
+ context: { borrower: trimmed }
62334
+ })
62335
+ );
62336
+ }
62088
62337
  /**
62089
62338
  * Get active loans (status = ACTIVE)
62090
62339
  *
@@ -63610,7 +63859,35 @@ var GraphClient = class {
63610
63859
  await new Promise((r) => setTimeout(r, ms));
63611
63860
  }
63612
63861
  };
63613
- var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
63862
+ var GET_USER_POSITIONS_DOCUMENT = `
63863
+ query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
63864
+ user(id: $borrower) {
63865
+ id
63866
+ positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
63867
+ id
63868
+ pkpId
63869
+ borrower {
63870
+ createdAt
63871
+ id
63872
+ }
63873
+ # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
63874
+ ucdMinted
63875
+ ucdPaid
63876
+ ucdDebt
63877
+ collateralRatio
63878
+ requestedCollateralRatio
63879
+ selectedTerm
63880
+ status
63881
+ createdAt
63882
+ createdAtBlock
63883
+ lastUpdated
63884
+ originalTerm
63885
+ remainingDebt
63886
+ expiryAt
63887
+ }
63888
+ }
63889
+ }
63890
+ `;
63614
63891
  function normalizePkpId2(pkpId) {
63615
63892
  const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
63616
63893
  if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
@@ -63928,35 +64205,7 @@ var DiamondHandsGraph = class {
63928
64205
  * Get user positions from subgraph
63929
64206
  */
63930
64207
  async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
63931
- const query = `
63932
- query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
63933
- user(id: $borrower) {
63934
- id
63935
- positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
63936
- id
63937
- pkpId
63938
- borrower {
63939
- createdAt
63940
- id
63941
- }
63942
- # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
63943
- ucdMinted
63944
- ucdPaid
63945
- ucdDebt
63946
- collateralRatio
63947
- requestedCollateralRatio
63948
- selectedTerm
63949
- status
63950
- createdAt
63951
- createdAtBlock
63952
- lastUpdated
63953
- originalTerm
63954
- remainingDebt
63955
- expiryAt
63956
- }
63957
- }
63958
- }
63959
- `;
64208
+ const query = GET_USER_POSITIONS_DOCUMENT;
63960
64209
  const variables = {
63961
64210
  borrower: userAddress.toLowerCase(),
63962
64211
  first: first || void 0,
@@ -63974,6 +64223,45 @@ var DiamondHandsGraph = class {
63974
64223
  }
63975
64224
  return positions;
63976
64225
  }
64226
+ /**
64227
+ * Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
64228
+ * 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
64229
+ * coerces wei to a float and leaves `status` a string cast to the numeric enum).
64230
+ *
64231
+ * Deliberately issues the `GetUserPositions` document rather than a leaner one: the
64232
+ * lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
64233
+ * and that one is already listed, so this needs no server change. The extra fields
64234
+ * cost bytes, not round trips.
64235
+ *
64236
+ * Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
64237
+ */
64238
+ async getBorrowerDebtRows(borrower) {
64239
+ const borrowerId = borrower.toLowerCase();
64240
+ return collectBorrowerDebtRows(async (skip, first) => {
64241
+ const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
64242
+ borrower: borrowerId,
64243
+ first,
64244
+ skip,
64245
+ orderBy: "id",
64246
+ orderDirection: "asc"
64247
+ });
64248
+ if (result?.user == null) {
64249
+ if (skip > 0) {
64250
+ throw new Error(
64251
+ `getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
64252
+ );
64253
+ }
64254
+ return [];
64255
+ }
64256
+ const positions = result.user.positions;
64257
+ if (!Array.isArray(positions)) {
64258
+ throw new Error(
64259
+ `getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
64260
+ );
64261
+ }
64262
+ return positions.filter((p) => p != null);
64263
+ });
64264
+ }
63977
64265
  /**
63978
64266
  * Get user positions, plus an accurate total count.
63979
64267
  *
@@ -70142,6 +70430,603 @@ async function mintAgentPkp(params) {
70142
70430
  clearTimeout(timeout);
70143
70431
  }
70144
70432
  }
70433
+ var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
70434
+ function planAgentBinding(params) {
70435
+ const { isActive, record, nowSeconds } = params;
70436
+ if (isActive)
70437
+ return { kind: "reuse", agent: record.agent };
70438
+ const status = Number(record.status);
70439
+ if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
70440
+ return { kind: "register" };
70441
+ }
70442
+ if (status !== AGENT_STATUS.Active) {
70443
+ throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
70444
+ }
70445
+ if (Number(record.validUntil) > nowSeconds) {
70446
+ throw new Error(
70447
+ "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
70448
+ );
70449
+ }
70450
+ return { kind: "rotate" };
70451
+ }
70452
+ async function describeProviderChainMismatch(provider, chainId) {
70453
+ const actual = Number((await provider.getNetwork()).chainId);
70454
+ if (actual === chainId)
70455
+ return null;
70456
+ return `Network mismatch: the SDK was configured for chainId ${chainId}, but the provider is connected to chainId ${actual}. Switch the wallet/RPC to chainId ${chainId}, or configure the SDK for chainId ${actual}. Nothing was signed.`;
70457
+ }
70458
+ var TxValidationError2 = class extends Error {
70459
+ /**
70460
+ * @param subject What is being refused. Defaults to the server-returned transaction the
70461
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
70462
+ */
70463
+ constructor(msg, subject = "server-returned transaction") {
70464
+ super(`Refusing to sign ${subject}: ${msg}`);
70465
+ this.name = "TxValidationError";
70466
+ }
70467
+ };
70468
+ var SIGNABLE_FUNCTIONS2 = [
70469
+ "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)",
70470
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
70471
+ // used to sit here; it is not a function on any deployed contract — the
70472
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
70473
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
70474
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
70475
+ // it. A signable-function whitelist should not carry calldata shapes the
70476
+ // protocol cannot execute.
70477
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
70478
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
70479
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
70480
+ // Struct-version: matches the actual on-chain function signature and the
70481
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
70482
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
70483
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
70484
+ "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)",
70485
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
70486
+ // function reverts permanently. The trustless replacement
70487
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
70488
+ // entry when its LIT Action ships.
70489
+ "function approve(address spender, uint256 amount) external returns (bool)",
70490
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
70491
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
70492
+ // without an entry here it decoded as "<unparseable>" and the CLI's
70493
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
70494
+ // collateral had no client-side pin at all.
70495
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
70496
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
70497
+ // AgentModule; the parity test documents them as client-only.
70498
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
70499
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
70500
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
70501
+ // this too is client-only and never module-whitelisted.
70502
+ "function addAddress(string btcAddress) external"
70503
+ ];
70504
+ var IFACE2 = new import_ethers31.ethers.Interface(SIGNABLE_FUNCTIONS2);
70505
+ function encodeSignable2(fn, args) {
70506
+ return IFACE2.encodeFunctionData(fn, args);
70507
+ }
70508
+ function decodeSignable2(data) {
70509
+ try {
70510
+ const parsed = IFACE2.parseTransaction({ data });
70511
+ if (!parsed) {
70512
+ throw new TxValidationError2(
70513
+ `unsignedTx.data does not decode against the signable-function whitelist`
70514
+ );
70515
+ }
70516
+ return { name: parsed.name, args: parsed.args };
70517
+ } catch (e) {
70518
+ if (e instanceof TxValidationError2)
70519
+ throw e;
70520
+ throw new TxValidationError2(
70521
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
70522
+ );
70523
+ }
70524
+ }
70525
+ var MAX_GAS_LIMIT = 5000000n;
70526
+ var MAX_FEE_PER_GAS_WEI = 2000000000000n;
70527
+ var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
70528
+ var DEFAULT_FEE_CEILING = {
70529
+ maxGasLimit: MAX_GAS_LIMIT,
70530
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
70531
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
70532
+ };
70533
+ function fmtEth(wei) {
70534
+ return `${import_ethers33.ethers.formatEther(wei)} ETH`;
70535
+ }
70536
+ function fmtGwei(wei) {
70537
+ return `${import_ethers33.ethers.formatUnits(wei, "gwei")} gwei`;
70538
+ }
70539
+ function worstCaseFeeWei(gasLimit, maxFeePerGas) {
70540
+ if (gasLimit == null || maxFeePerGas == null)
70541
+ return null;
70542
+ return gasLimit * maxFeePerGas;
70543
+ }
70544
+ function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
70545
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
70546
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
70547
+ }
70548
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
70549
+ raise(
70550
+ `maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
70551
+ );
70552
+ }
70553
+ const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
70554
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
70555
+ raise(
70556
+ `worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
70557
+ );
70558
+ }
70559
+ }
70560
+ function eqAddr2(a, b) {
70561
+ if (!a || !b)
70562
+ return false;
70563
+ try {
70564
+ return import_ethers32.ethers.getAddress(a) === import_ethers32.ethers.getAddress(b);
70565
+ } catch {
70566
+ return false;
70567
+ }
70568
+ }
70569
+ function readToAddress2(tx2) {
70570
+ const to = tx2["to"];
70571
+ if (typeof to !== "string") {
70572
+ throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
70573
+ }
70574
+ return to;
70575
+ }
70576
+ function readData2(tx2) {
70577
+ const data = tx2["data"];
70578
+ if (typeof data !== "string" || !data.startsWith("0x")) {
70579
+ throw new TxValidationError2(`unsignedTx.data missing or malformed`);
70580
+ }
70581
+ return data;
70582
+ }
70583
+ function readChainId2(tx2) {
70584
+ const c = tx2["chainId"];
70585
+ if (c == null)
70586
+ return null;
70587
+ if (typeof c === "number")
70588
+ return c;
70589
+ if (typeof c === "string")
70590
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
70591
+ if (typeof c === "bigint")
70592
+ return Number(c);
70593
+ return null;
70594
+ }
70595
+ function readOptionalBigInt(tx2, key) {
70596
+ const v = tx2[key];
70597
+ if (v == null)
70598
+ return null;
70599
+ try {
70600
+ if (typeof v === "bigint")
70601
+ return v;
70602
+ if (typeof v === "number")
70603
+ return BigInt(v);
70604
+ if (typeof v === "string")
70605
+ return BigInt(v);
70606
+ return BigInt(v.toString());
70607
+ } catch {
70608
+ throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
70609
+ }
70610
+ }
70611
+ function readValue2(tx2) {
70612
+ const v = tx2["value"];
70613
+ if (v == null)
70614
+ return 0n;
70615
+ if (typeof v === "string")
70616
+ return BigInt(v);
70617
+ if (typeof v === "number")
70618
+ return BigInt(v);
70619
+ if (typeof v === "bigint")
70620
+ return v;
70621
+ const maybe = v;
70622
+ if (typeof maybe.toBigInt === "function")
70623
+ return maybe.toBigInt();
70624
+ if (typeof maybe.toString === "function")
70625
+ return BigInt(maybe.toString());
70626
+ throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
70627
+ }
70628
+ function normalizePositionId2(id) {
70629
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
70630
+ return import_ethers32.ethers.zeroPadValue(hex, 32).toLowerCase();
70631
+ }
70632
+ function requirePositionId(actual, expected) {
70633
+ const txPositionId = String(actual).toLowerCase();
70634
+ if (txPositionId !== normalizePositionId2(expected)) {
70635
+ throw new TxValidationError2(
70636
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
70637
+ );
70638
+ }
70639
+ }
70640
+ function validateUnsignedTx2(unsignedTx, expected, vctx) {
70641
+ const txChainId = readChainId2(unsignedTx);
70642
+ if (txChainId == null) {
70643
+ throw new TxValidationError2(
70644
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
70645
+ );
70646
+ }
70647
+ if (txChainId !== vctx.chainId) {
70648
+ throw new TxValidationError2(
70649
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
70650
+ );
70651
+ }
70652
+ const value = readValue2(unsignedTx);
70653
+ if (value !== 0n) {
70654
+ throw new TxValidationError2(
70655
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
70656
+ );
70657
+ }
70658
+ assertFeeCeiling(
70659
+ readOptionalBigInt(unsignedTx, "gasLimit"),
70660
+ readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
70661
+ (msg) => {
70662
+ throw new TxValidationError2(msg);
70663
+ },
70664
+ vctx.feeCeiling
70665
+ );
70666
+ const to = readToAddress2(unsignedTx);
70667
+ const data = readData2(unsignedTx);
70668
+ const { name, args } = decodeSignable2(data);
70669
+ const pm = vctx.contracts.PositionManager;
70670
+ switch (expected.kind) {
70671
+ case "mint": {
70672
+ if (name !== "mintUCD") {
70673
+ throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
70674
+ }
70675
+ if (!eqAddr2(to, pm)) {
70676
+ throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
70677
+ }
70678
+ requirePositionId(args[0], expected.positionId);
70679
+ const txMintAmount = BigInt(String(args[1]));
70680
+ if (txMintAmount.toString() !== expected.amountWei) {
70681
+ throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
70682
+ }
70683
+ const txMintFee = BigInt(String(args[2]));
70684
+ if (txMintFee.toString() !== expected.mintFeeWei) {
70685
+ throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
70686
+ }
70687
+ break;
70688
+ }
70689
+ case "repay": {
70690
+ if (name !== "makePayment") {
70691
+ throw new TxValidationError2(`expected makePayment, server returned ${name}`);
70692
+ }
70693
+ if (!eqAddr2(to, pm)) {
70694
+ throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
70695
+ }
70696
+ requirePositionId(args[0], expected.positionId);
70697
+ const txAmount = BigInt(String(args[1]));
70698
+ if (txAmount.toString() !== expected.amountWei) {
70699
+ throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
70700
+ }
70701
+ break;
70702
+ }
70703
+ case "extend": {
70704
+ if (name !== "extendPosition") {
70705
+ throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
70706
+ }
70707
+ if (!eqAddr2(to, pm)) {
70708
+ throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
70709
+ }
70710
+ requirePositionId(args[0], expected.positionId);
70711
+ const txTerm = Number(args[1]);
70712
+ if (txTerm !== expected.selectedTerm) {
70713
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
70714
+ }
70715
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
70716
+ const txFee = BigInt(String(args[5]));
70717
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
70718
+ if (txFee > upper) {
70719
+ throw new TxValidationError2(
70720
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
70721
+ );
70722
+ }
70723
+ }
70724
+ break;
70725
+ }
70726
+ case "withdraw-btc": {
70727
+ if (name !== "withdrawBTC") {
70728
+ throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
70729
+ }
70730
+ if (!eqAddr2(to, pm)) {
70731
+ throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
70732
+ }
70733
+ const paramsTuple = args[0];
70734
+ requirePositionId(paramsTuple[0], expected.positionId);
70735
+ const txWithdrawalAddress = String(paramsTuple[5]);
70736
+ if (txWithdrawalAddress !== expected.btcAddress) {
70737
+ throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
70738
+ }
70739
+ if (expected.upperBoundTotalDeduction != null) {
70740
+ const txDeduction = BigInt(String(paramsTuple[6]));
70741
+ const upper = BigInt(expected.upperBoundTotalDeduction);
70742
+ if (txDeduction > upper) {
70743
+ throw new TxValidationError2(
70744
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
70745
+ );
70746
+ }
70747
+ }
70748
+ break;
70749
+ }
70750
+ case "ucd-approve": {
70751
+ if (name !== "approve") {
70752
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
70753
+ }
70754
+ const ucd = vctx.contracts.UCDToken;
70755
+ if (!eqAddr2(to, ucd)) {
70756
+ throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
70757
+ }
70758
+ const spender = String(args[0]);
70759
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
70760
+ if (!ok2) {
70761
+ throw new TxValidationError2(
70762
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
70763
+ );
70764
+ }
70765
+ const amt = BigInt(String(args[1]));
70766
+ const min = BigInt(expected.minAmountWei);
70767
+ if (amt < min) {
70768
+ throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
70769
+ }
70770
+ const SANITY_MAX = min * 1000n;
70771
+ if (amt > SANITY_MAX) {
70772
+ throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
70773
+ }
70774
+ break;
70775
+ }
70776
+ case "create-position": {
70777
+ if (name !== "createPosition") {
70778
+ throw new TxValidationError2(`expected createPosition, server returned ${name}`);
70779
+ }
70780
+ if (!eqAddr2(to, pm)) {
70781
+ throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
70782
+ }
70783
+ const txTerm = BigInt(String(args[4]));
70784
+ if (txTerm !== BigInt(expected.selectedTerm)) {
70785
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
70786
+ }
70787
+ break;
70788
+ }
70789
+ case "set-position-delegate": {
70790
+ if (name !== "setPositionDelegate") {
70791
+ throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
70792
+ }
70793
+ if (!eqAddr2(to, expected.registryAddress)) {
70794
+ throw new TxValidationError2(
70795
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
70796
+ );
70797
+ }
70798
+ requirePositionId(args[0], expected.positionId);
70799
+ const txDelegate = String(args[1]);
70800
+ if (!eqAddr2(txDelegate, expected.delegate)) {
70801
+ throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
70802
+ }
70803
+ break;
70804
+ }
70805
+ case "bwar-add-address": {
70806
+ if (name !== "addAddress") {
70807
+ throw new TxValidationError2(`expected addAddress, decoded ${name}`);
70808
+ }
70809
+ if (!eqAddr2(to, expected.registryAddress)) {
70810
+ throw new TxValidationError2(
70811
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
70812
+ );
70813
+ }
70814
+ if (String(args[0]) !== expected.btcAddress) {
70815
+ throw new TxValidationError2(
70816
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
70817
+ );
70818
+ }
70819
+ break;
70820
+ }
70821
+ case "stablecoin-approve": {
70822
+ if (name !== "approve") {
70823
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
70824
+ }
70825
+ if (!eqAddr2(to, expected.tokenAddress)) {
70826
+ throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
70827
+ }
70828
+ if (!eqAddr2(String(args[0]), expected.spender)) {
70829
+ throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
70830
+ }
70831
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
70832
+ throw new TxValidationError2(
70833
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
70834
+ );
70835
+ }
70836
+ break;
70837
+ }
70838
+ case "ucd-approve-controller": {
70839
+ if (name !== "approve") {
70840
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
70841
+ }
70842
+ if (!eqAddr2(to, expected.ucdTokenAddress)) {
70843
+ throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
70844
+ }
70845
+ if (!eqAddr2(String(args[0]), expected.spender)) {
70846
+ throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
70847
+ }
70848
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
70849
+ throw new TxValidationError2(
70850
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
70851
+ );
70852
+ }
70853
+ break;
70854
+ }
70855
+ case "psm-swap": {
70856
+ if (name !== "swap")
70857
+ throw new TxValidationError2(`expected swap, server returned ${name}`);
70858
+ if (!eqAddr2(to, expected.psmAddress)) {
70859
+ throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
70860
+ }
70861
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
70862
+ throw new TxValidationError2(`swap stablecoin mismatch`);
70863
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
70864
+ throw new TxValidationError2(`swap amountIn mismatch`);
70865
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
70866
+ throw new TxValidationError2(`swap minUcdOut mismatch`);
70867
+ if (BigInt(expected.minOut) === 0n) {
70868
+ throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
70869
+ }
70870
+ break;
70871
+ }
70872
+ case "psm-redeem": {
70873
+ if (name !== "redeem")
70874
+ throw new TxValidationError2(`expected redeem, server returned ${name}`);
70875
+ if (!eqAddr2(to, expected.psmAddress)) {
70876
+ throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
70877
+ }
70878
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
70879
+ throw new TxValidationError2(`redeem stablecoin mismatch`);
70880
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
70881
+ throw new TxValidationError2(`redeem ucdAmount mismatch`);
70882
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
70883
+ throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
70884
+ if (BigInt(expected.minOut) === 0n) {
70885
+ throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
70886
+ }
70887
+ break;
70888
+ }
70889
+ default: {
70890
+ const _exhaustive = expected;
70891
+ throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
70892
+ }
70893
+ }
70894
+ }
70895
+ function buildPsmApproveTx(p) {
70896
+ return {
70897
+ to: p.token,
70898
+ data: encodeSignable2("approve", [p.spender, p.amount]),
70899
+ value: "0x0",
70900
+ chainId: p.chainId
70901
+ };
70902
+ }
70903
+ function buildPsmSwapTx2(p) {
70904
+ return {
70905
+ to: p.psm,
70906
+ data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
70907
+ value: "0x0",
70908
+ chainId: p.chainId
70909
+ };
70910
+ }
70911
+ function buildPsmRedeemTx2(p) {
70912
+ return {
70913
+ to: p.psm,
70914
+ data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
70915
+ value: "0x0",
70916
+ chainId: p.chainId
70917
+ };
70918
+ }
70919
+ var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
70920
+ var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
70921
+ function psmExchangeReadsFromProvider(provider, psmAddress) {
70922
+ const psm = new import_ethers30.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
70923
+ return {
70924
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
70925
+ allowance: async (token, owner, spender) => await new import_ethers30.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
70926
+ };
70927
+ }
70928
+ var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
70929
+ function requireAddress(direction, label, value) {
70930
+ if (!value || !import_ethers30.ethers.isAddress(value)) {
70931
+ throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
70932
+ }
70933
+ return import_ethers30.ethers.getAddress(value);
70934
+ }
70935
+ async function planPsmExchange(params) {
70936
+ const { direction, amountIn, minOut, vctx, reads } = params;
70937
+ const chainId = vctx.chainId;
70938
+ if (amountIn <= 0n) {
70939
+ throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
70940
+ }
70941
+ if (minOut <= 0n) {
70942
+ throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
70943
+ }
70944
+ const owner = requireAddress(direction, "owner", params.owner);
70945
+ const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
70946
+ const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
70947
+ const isSwap = direction === "swap";
70948
+ const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
70949
+ const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
70950
+ if (!await reads.isStablecoinSupported(stablecoin)) {
70951
+ throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
70952
+ }
70953
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
70954
+ const allowanceBefore = await reads.allowance(token, owner, spender);
70955
+ const approvals = [];
70956
+ if (allowanceBefore < amountIn) {
70957
+ if (allowanceBefore > 0n) {
70958
+ approvals.push({
70959
+ step: "reset-approve",
70960
+ tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
70961
+ expected: approveExpected(0n)
70962
+ });
70963
+ }
70964
+ approvals.push({
70965
+ step: "approve",
70966
+ tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
70967
+ expected: approveExpected(amountIn)
70968
+ });
70969
+ }
70970
+ const exec = isSwap ? {
70971
+ step: "swap",
70972
+ tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
70973
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
70974
+ } : {
70975
+ step: "redeem",
70976
+ tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
70977
+ expected: {
70978
+ kind: "psm-redeem",
70979
+ psmAddress: psm,
70980
+ stablecoin,
70981
+ amountUcdWei: amountIn.toString(),
70982
+ minOut: minOut.toString()
70983
+ }
70984
+ };
70985
+ for (const leg of [...approvals, exec]) {
70986
+ validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
70987
+ }
70988
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
70989
+ }
70990
+ async function executePsmPlan(plan, signer, vctx) {
70991
+ const approvalHashes = [];
70992
+ const residual = () => approvalHashes.length === 0 ? "" : ` An approval already landed (tx ${approvalHashes[approvalHashes.length - 1]}): an allowance of exactly ${plan.amountIn} to ${plan.spender} stands. It authorizes only that amount; the next exchange uses or replaces it.`;
70993
+ const sendLeg = async (leg) => {
70994
+ const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
70995
+ validateUnsignedTx2({ ...request }, leg.expected, vctx);
70996
+ const sent = await signer.sendTransaction(request);
70997
+ const receipt = await sent.wait();
70998
+ if (!receipt)
70999
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
71000
+ if (receipt.status !== 1)
71001
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
71002
+ return { hash: sent.hash, blockNumber: receipt.blockNumber };
71003
+ };
71004
+ for (const leg of plan.approvals) {
71005
+ const landed = await sendLeg(leg).catch((e) => {
71006
+ throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71007
+ });
71008
+ approvalHashes.push(landed.hash);
71009
+ }
71010
+ const exec = await sendLeg(plan.exec).catch((e) => {
71011
+ throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71012
+ });
71013
+ return { ...exec, approvalHashes };
71014
+ }
71015
+ var LIT_ACTION_CHAIN_NAMES = Object.freeze({
71016
+ 1: "ethereum",
71017
+ 11155111: "sepolia",
71018
+ 1337: "hardhat",
71019
+ 31337: "hardhat"
71020
+ });
71021
+ function litActionChainNameForChainId(chainId) {
71022
+ const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
71023
+ if (!name) {
71024
+ throw new Error(
71025
+ `Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
71026
+ );
71027
+ }
71028
+ return name;
71029
+ }
70145
71030
  var MockTokenManager = class {
70146
71031
  config;
70147
71032
  constructor(config) {
@@ -71115,6 +72000,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
71115
72000
  */
71116
72001
  static async create(config) {
71117
72002
  const userProvidedServiceEndpoint = config.serviceEndpoint;
72003
+ if (typeof config.chainId === "number" && config.provider) {
72004
+ const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
72005
+ if (mismatch) {
72006
+ return failure(
72007
+ new SDKError({
72008
+ message: mismatch,
72009
+ category: "CONFIGURATION",
72010
+ severity: "HIGH"
72011
+ /* HIGH */
72012
+ })
72013
+ );
72014
+ }
72015
+ }
71118
72016
  const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
71119
72017
  if (userProvidedServiceEndpoint) {
71120
72018
  enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
@@ -71765,6 +72663,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
71765
72663
  if (this.config.debug) {
71766
72664
  log.info(` Position PKP ID: ${position2.pkpId}`);
71767
72665
  }
72666
+ const termsResult = await this.getTermsWithFees();
72667
+ if (!termsResult.success) {
72668
+ return {
72669
+ success: false,
72670
+ error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
72671
+ };
72672
+ }
72673
+ const positionTermMonths = Number(position2.selectedTerm);
72674
+ const positionTerm = termsResult.value.terms.find(
72675
+ (term) => term.termMonths === positionTermMonths
72676
+ );
72677
+ if (!positionTerm) {
72678
+ return {
72679
+ success: false,
72680
+ error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
72681
+ };
72682
+ }
72683
+ const currentDebtWei = BigInt(position2.ucdDebt);
72684
+ const baseFeeWei = baseMintFeeWei(
72685
+ requestAmountWei,
72686
+ positionTerm.originationFeeBps
72687
+ );
72688
+ if (debtAfterMintExceedsLoanCap({
72689
+ currentDebtWei,
72690
+ mintAmountWei: requestAmountWei,
72691
+ mintFeeWei: baseFeeWei,
72692
+ maxLoanWei: maxLoanValueWei
72693
+ })) {
72694
+ const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
72695
+ const maxPrincipalUcd = Number(
72696
+ maxPrincipalWithinLoanCap({
72697
+ maxLoanWei: maxLoanValueWei,
72698
+ currentDebtWei,
72699
+ originationFeeBps: positionTerm.originationFeeBps
72700
+ }) / BigInt(10 ** 18)
72701
+ );
72702
+ return {
72703
+ success: false,
72704
+ error: `Amount ${request.amount} UCD plus the ${positionTerm.originationFeeBps / 100}% origination fee (${(0, import_ethers13.formatEther)(baseFeeWei)} UCD) would take this loan's debt to ${(0, import_ethers13.formatEther)(debtAfterWei)} UCD, above the protocol maximum of ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD. The largest amount you can mint now is ${maxPrincipalUcd} UCD.`
72705
+ };
72706
+ }
72707
+ if (this.config.debug) {
72708
+ log.info(
72709
+ `\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers13.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD`,
72710
+ {}
72711
+ );
72712
+ }
71768
72713
  let pkpPublicKey;
71769
72714
  let pkpEthAddress;
71770
72715
  const pkpCache = this.cacheManager.getCache("pkp-data", {
@@ -71854,7 +72799,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
71854
72799
  ` UCDController: ${contracts?.UCDController || "MISSING"}`
71855
72800
  );
71856
72801
  }
71857
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
72802
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
71858
72803
  const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
71859
72804
  if (this.config.debug) {
71860
72805
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -72454,6 +73399,25 @@ Error data: none`
72454
73399
  }
72455
73400
  const selector = simError.selector;
72456
73401
  const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
73402
+ const MINT_GUARD_CODES = {
73403
+ "1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
73404
+ "2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
73405
+ "3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
73406
+ };
73407
+ let loanCapDiagnostics = "";
73408
+ if (selector === "0xe6dd4d41") {
73409
+ const guardCode = BigInt(
73410
+ "0x" + String(simError.data).slice(10).padStart(64, "0")
73411
+ ).toString();
73412
+ const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
73413
+ loanCapDiagnostics = `
73414
+
73415
+ MintGuardFailed(${guardCode}): ${guardMeaning}
73416
+ Lit mintAmount: ${validationResponse.mintAmount}
73417
+ Lit mintFee: ${validationResponse.mintFee}
73418
+ Lit newDebt: ${validationResponse.newDebt}
73419
+ Protocol maximum: ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
73420
+ }
72457
73421
  const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
72458
73422
  selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
72459
73423
  selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
@@ -72499,7 +73463,7 @@ Quantum Timing Analysis:
72499
73463
  Error selector: ${selector}
72500
73464
  Error data: ${simError.data}
72501
73465
  Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
72502
- Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
73466
+ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
72503
73467
  );
72504
73468
  }
72505
73469
  const tx2 = await sendEip1559Transaction({
@@ -75107,7 +76071,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
75107
76071
  ` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
75108
76072
  );
75109
76073
  }
75110
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
76074
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
75111
76075
  const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
75112
76076
  if (this.config.debug) {
75113
76077
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -75662,13 +76626,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
75662
76626
  return { success: false, error: "Failed to resolve PKP public key" };
75663
76627
  }
75664
76628
  const chipotlePkpAddress = (0, import_ethers13.computeAddress)(publicKey);
75665
- const STANDALONE_CHAIN_NAMES = {
75666
- 1: "ethereum",
75667
- 11155111: "sepolia",
75668
- 1337: "hardhat",
75669
- 31337: "hardhat"
75670
- };
75671
- const chainName = STANDALONE_CHAIN_NAMES[chainId];
76629
+ const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
75672
76630
  if (!chainName) {
75673
76631
  return {
75674
76632
  success: false,
@@ -76890,6 +77848,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76890
77848
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
76891
77849
  return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
76892
77850
  }
77851
+ /**
77852
+ * Combined UCD debt (canonical wei string + display string) and by-status loan
77853
+ * counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
77854
+ * an INDEXED, informational figure that lags writes; never size a transaction
77855
+ * from it (repayments read the chain via `getPositionDetailsView`).
77856
+ *
77857
+ * Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
77858
+ * failure or past 10,000 positions; never returns a partial total.
77859
+ */
77860
+ async getBorrowerUcdDebtSummary(borrower) {
77861
+ return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
77862
+ }
76893
77863
  /**
76894
77864
  * Get all active loans
76895
77865
  *
@@ -77015,11 +77985,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77015
77985
  }
77016
77986
  /**
77017
77987
  * Execute a PSM stablecoin → UCD swap.
77018
- * Handles stablecoin approval to the PSM contract if the current allowance is insufficient.
77988
+ * Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
77989
+ * partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
77019
77990
  *
77020
77991
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
77021
77992
  * @param params.amountWei - Stablecoin amount in native decimals (bigint)
77022
- * @param params.minUcdOutWei - Minimum UCD to receive; reverts if below this (1% slippage guard)
77993
+ * @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
77023
77994
  * @param params.signer - Connected signer for the approval and swap transactions
77024
77995
  */
77025
77996
  async psmSwap(params) {
@@ -77029,32 +78000,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77029
78000
  "SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
77030
78001
  );
77031
78002
  }
77032
- const signerAddress = await params.signer.getAddress();
77033
- const erc20Abi = [
77034
- "function allowance(address owner, address spender) view returns (uint256)",
77035
- "function approve(address spender, uint256 amount) returns (bool)"
77036
- ];
77037
- const stablecoin = new import_ethers13.Contract(params.stablecoinAddress, erc20Abi, params.signer);
77038
- const allowance = await stablecoin.allowance(signerAddress, psmAddress);
77039
- if (allowance < params.amountWei) {
77040
- const approveTx = await stablecoin.approve(psmAddress, import_ethers13.MaxUint256);
77041
- await approveTx.wait();
77042
- }
77043
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77044
- const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
77045
- const receipt = await tx2.wait();
77046
- if (!receipt)
77047
- throw new Error("PSM swap transaction receipt unavailable");
77048
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78003
+ return this.runPsmExchange({
78004
+ direction: "swap",
78005
+ signer: params.signer,
78006
+ addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
78007
+ amountIn: params.amountWei,
78008
+ minOut: params.minUcdOutWei
78009
+ });
77049
78010
  }
77050
78011
  /**
77051
78012
  * Execute a PSM UCD → stablecoin redeem.
77052
- * Handles UCD approval to UCDController (not PSM) to satisfy the M-4 burn allowance guard:
77053
- * UCDToken.burn(from, amount) calls _spendAllowance(from, msg.sender=ucdController, amount).
78013
+ * Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
78014
+ * M-4 burn allowance guard: UCDToken.burn(from, amount) calls
78015
+ * _spendAllowance(from, msg.sender=ucdController, amount).
77054
78016
  *
77055
78017
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
77056
78018
  * @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
77057
- * @param params.minStablecoinOutWei - Minimum stablecoin to receive (slippage guard)
78019
+ * @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
77058
78020
  * @param params.signer - Connected signer
77059
78021
  */
77060
78022
  async psmRedeem(params) {
@@ -77067,23 +78029,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77067
78029
  throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
77068
78030
  if (!ucdControllerAddress)
77069
78031
  throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
77070
- const signerAddress = await params.signer.getAddress();
77071
- const erc20Abi = [
77072
- "function allowance(address owner, address spender) view returns (uint256)",
77073
- "function approve(address spender, uint256 amount) returns (bool)"
77074
- ];
77075
- const ucdToken = new import_ethers13.Contract(ucdAddress, erc20Abi, params.signer);
77076
- const allowance = await ucdToken.allowance(signerAddress, ucdControllerAddress);
77077
- if (allowance < params.ucdAmountWei) {
77078
- const approveTx = await ucdToken.approve(ucdControllerAddress, import_ethers13.MaxUint256);
77079
- await approveTx.wait();
77080
- }
77081
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77082
- const tx2 = await psm.redeem(params.stablecoinAddress, params.ucdAmountWei, params.minStablecoinOutWei);
77083
- const receipt = await tx2.wait();
77084
- if (!receipt)
77085
- throw new Error("PSM redeem transaction receipt unavailable");
77086
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78032
+ return this.runPsmExchange({
78033
+ direction: "redeem",
78034
+ signer: params.signer,
78035
+ addresses: {
78036
+ psm: psmAddress,
78037
+ stablecoin: params.stablecoinAddress,
78038
+ ucdToken: ucdAddress,
78039
+ ucdController: ucdControllerAddress
78040
+ },
78041
+ amountIn: params.ucdAmountWei,
78042
+ minOut: params.minStablecoinOutWei
78043
+ });
78044
+ }
78045
+ /**
78046
+ * Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
78047
+ * The signer's chain must match the SDK's configured chain — the addresses came from it.
78048
+ */
78049
+ async runPsmExchange(params) {
78050
+ const provider = params.signer.provider;
78051
+ if (!provider) {
78052
+ throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
78053
+ }
78054
+ const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
78055
+ if (typeof configuredChainId !== "number") {
78056
+ throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
78057
+ }
78058
+ const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
78059
+ if (mismatch)
78060
+ throw new Error(mismatch);
78061
+ const vctx = {
78062
+ chainId: configuredChainId,
78063
+ network: String(configuredChainId),
78064
+ contracts: {}
78065
+ };
78066
+ const plan = await planPsmExchange({
78067
+ direction: params.direction,
78068
+ owner: await params.signer.getAddress(),
78069
+ addresses: params.addresses,
78070
+ amountIn: params.amountIn,
78071
+ minOut: params.minOut,
78072
+ vctx,
78073
+ reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
78074
+ });
78075
+ const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
78076
+ return { hash, blockNumber };
77087
78077
  }
77088
78078
  /**
77089
78079
  * Wait for the subgraph to index up to (and including) the given block number.
@@ -77264,18 +78254,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77264
78254
  const user = await signer.getAddress();
77265
78255
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
77266
78256
  let agentAddress;
77267
- const hasActiveAgent = await registry.isAgentActive(user);
77268
- if (hasActiveAgent) {
77269
- agentAddress = (await registry.agentOf(user)).agent;
78257
+ const [isActive, record, latestBlock] = await Promise.all([
78258
+ registry.isAgentActive(user),
78259
+ registry.agentOf(user),
78260
+ this.getProviderOrThrow().getBlock("latest")
78261
+ ]);
78262
+ if (!latestBlock) {
78263
+ throw new SDKError({
78264
+ message: "Could not read the latest block to check the agent registration's expiry",
78265
+ category: "NETWORK",
78266
+ severity: "HIGH"
78267
+ /* HIGH */
78268
+ });
78269
+ }
78270
+ const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
78271
+ if (plan.kind === "reuse") {
78272
+ agentAddress = plan.agent;
77270
78273
  } else {
77271
78274
  agentAddress = await mintAgentPkp({
77272
78275
  serviceEndpoint: this.config.serviceEndpoint,
77273
78276
  authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
77274
78277
  });
77275
78278
  const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
77276
- const validUntil = Math.floor(Date.now() / 1e3) + validitySeconds;
77277
- const regTx = await registry.registerAgent(user, agentAddress, validUntil);
77278
- await regTx.wait();
78279
+ const validUntil = latestBlock.timestamp + validitySeconds;
78280
+ const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
78281
+ await bindTx.wait();
77279
78282
  }
77280
78283
  const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
77281
78284
  () => null
@@ -78659,21 +79662,560 @@ function listPositionsQuery(f) {
78659
79662
  return { document: LIST_POSITIONS, variables: { first, skip } };
78660
79663
  }
78661
79664
  var SUPPORTED_STABLECOINS = `
78662
- query SupportedStablecoins {
79665
+ query GetSupportedStablecoins {
78663
79666
  supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
78664
- id
78665
- address
78666
- isSupported
78667
- decimals
78668
- entryFee
78669
- exitFee
78670
- reserves
79667
+ id address isSupported exchangeRate entryFee exitFee reserves decimals
79668
+ totalSwapVolume totalRedeemVolume swapCount redeemCount addedAt lastUpdated
78671
79669
  }
79670
+ }`;
79671
+
79672
+ // src/boundary/upstream/real/psm-calls.ts
79673
+ var import_ethers41 = require("ethers");
79674
+
79675
+ // node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
79676
+ var import_ethers35 = require("ethers");
79677
+ var import_ethers36 = require("ethers");
79678
+ var import_ethers37 = require("ethers");
79679
+ var import_ethers38 = require("ethers");
79680
+ var import_ethers39 = require("ethers");
79681
+ var import_ethers40 = require("ethers");
79682
+ var TxValidationError3 = class extends Error {
79683
+ /**
79684
+ * @param subject What is being refused. Defaults to the server-returned transaction the
79685
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
79686
+ */
79687
+ constructor(msg, subject = "server-returned transaction") {
79688
+ super(`Refusing to sign ${subject}: ${msg}`);
79689
+ this.name = "TxValidationError";
78672
79690
  }
78673
- `;
79691
+ };
79692
+ var SIGNABLE_FUNCTIONS3 = [
79693
+ "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)",
79694
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
79695
+ // used to sit here; it is not a function on any deployed contract — the
79696
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
79697
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
79698
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
79699
+ // it. A signable-function whitelist should not carry calldata shapes the
79700
+ // protocol cannot execute.
79701
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
79702
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
79703
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
79704
+ // Struct-version: matches the actual on-chain function signature and the
79705
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
79706
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
79707
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
79708
+ "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)",
79709
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
79710
+ // function reverts permanently. The trustless replacement
79711
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
79712
+ // entry when its LIT Action ships.
79713
+ "function approve(address spender, uint256 amount) external returns (bool)",
79714
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
79715
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
79716
+ // without an entry here it decoded as "<unparseable>" and the CLI's
79717
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
79718
+ // collateral had no client-side pin at all.
79719
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
79720
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
79721
+ // AgentModule; the parity test documents them as client-only.
79722
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
79723
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
79724
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
79725
+ // this too is client-only and never module-whitelisted.
79726
+ "function addAddress(string btcAddress) external"
79727
+ ];
79728
+ var IFACE3 = new import_ethers35.ethers.Interface(SIGNABLE_FUNCTIONS3);
79729
+ function encodeSignable3(fn, args) {
79730
+ return IFACE3.encodeFunctionData(fn, args);
79731
+ }
79732
+ function decodeSignable3(data) {
79733
+ try {
79734
+ const parsed = IFACE3.parseTransaction({ data });
79735
+ if (!parsed) {
79736
+ throw new TxValidationError3(
79737
+ `unsignedTx.data does not decode against the signable-function whitelist`
79738
+ );
79739
+ }
79740
+ return { name: parsed.name, args: parsed.args };
79741
+ } catch (e) {
79742
+ if (e instanceof TxValidationError3)
79743
+ throw e;
79744
+ throw new TxValidationError3(
79745
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
79746
+ );
79747
+ }
79748
+ }
79749
+ var MAX_GAS_LIMIT2 = 5000000n;
79750
+ var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
79751
+ var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
79752
+ var DEFAULT_FEE_CEILING2 = {
79753
+ maxGasLimit: MAX_GAS_LIMIT2,
79754
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
79755
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
79756
+ };
79757
+ function fmtEth2(wei) {
79758
+ return `${import_ethers36.ethers.formatEther(wei)} ETH`;
79759
+ }
79760
+ function fmtGwei2(wei) {
79761
+ return `${import_ethers36.ethers.formatUnits(wei, "gwei")} gwei`;
79762
+ }
79763
+ function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
79764
+ if (gasLimit == null || maxFeePerGas == null)
79765
+ return null;
79766
+ return gasLimit * maxFeePerGas;
79767
+ }
79768
+ function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
79769
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
79770
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
79771
+ }
79772
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
79773
+ raise(
79774
+ `maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
79775
+ );
79776
+ }
79777
+ const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
79778
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
79779
+ raise(
79780
+ `worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
79781
+ );
79782
+ }
79783
+ }
79784
+ function eqAddr3(a, b) {
79785
+ if (!a || !b)
79786
+ return false;
79787
+ try {
79788
+ return import_ethers37.ethers.getAddress(a) === import_ethers37.ethers.getAddress(b);
79789
+ } catch {
79790
+ return false;
79791
+ }
79792
+ }
79793
+ function readToAddress3(tx2) {
79794
+ const to = tx2["to"];
79795
+ if (typeof to !== "string") {
79796
+ throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
79797
+ }
79798
+ return to;
79799
+ }
79800
+ function readData3(tx2) {
79801
+ const data = tx2["data"];
79802
+ if (typeof data !== "string" || !data.startsWith("0x")) {
79803
+ throw new TxValidationError3(`unsignedTx.data missing or malformed`);
79804
+ }
79805
+ return data;
79806
+ }
79807
+ function readChainId3(tx2) {
79808
+ const c = tx2["chainId"];
79809
+ if (c == null)
79810
+ return null;
79811
+ if (typeof c === "number")
79812
+ return c;
79813
+ if (typeof c === "string")
79814
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
79815
+ if (typeof c === "bigint")
79816
+ return Number(c);
79817
+ return null;
79818
+ }
79819
+ function readOptionalBigInt2(tx2, key) {
79820
+ const v = tx2[key];
79821
+ if (v == null)
79822
+ return null;
79823
+ try {
79824
+ if (typeof v === "bigint")
79825
+ return v;
79826
+ if (typeof v === "number")
79827
+ return BigInt(v);
79828
+ if (typeof v === "string")
79829
+ return BigInt(v);
79830
+ return BigInt(v.toString());
79831
+ } catch {
79832
+ throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
79833
+ }
79834
+ }
79835
+ function readValue3(tx2) {
79836
+ const v = tx2["value"];
79837
+ if (v == null)
79838
+ return 0n;
79839
+ if (typeof v === "string")
79840
+ return BigInt(v);
79841
+ if (typeof v === "number")
79842
+ return BigInt(v);
79843
+ if (typeof v === "bigint")
79844
+ return v;
79845
+ const maybe = v;
79846
+ if (typeof maybe.toBigInt === "function")
79847
+ return maybe.toBigInt();
79848
+ if (typeof maybe.toString === "function")
79849
+ return BigInt(maybe.toString());
79850
+ throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
79851
+ }
79852
+ function normalizePositionId3(id) {
79853
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
79854
+ return import_ethers37.ethers.zeroPadValue(hex, 32).toLowerCase();
79855
+ }
79856
+ function requirePositionId2(actual, expected) {
79857
+ const txPositionId = String(actual).toLowerCase();
79858
+ if (txPositionId !== normalizePositionId3(expected)) {
79859
+ throw new TxValidationError3(
79860
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
79861
+ );
79862
+ }
79863
+ }
79864
+ function validateUnsignedTx3(unsignedTx, expected, vctx) {
79865
+ const txChainId = readChainId3(unsignedTx);
79866
+ if (txChainId == null) {
79867
+ throw new TxValidationError3(
79868
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
79869
+ );
79870
+ }
79871
+ if (txChainId !== vctx.chainId) {
79872
+ throw new TxValidationError3(
79873
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
79874
+ );
79875
+ }
79876
+ const value = readValue3(unsignedTx);
79877
+ if (value !== 0n) {
79878
+ throw new TxValidationError3(
79879
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
79880
+ );
79881
+ }
79882
+ assertFeeCeiling2(
79883
+ readOptionalBigInt2(unsignedTx, "gasLimit"),
79884
+ readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
79885
+ (msg) => {
79886
+ throw new TxValidationError3(msg);
79887
+ },
79888
+ vctx.feeCeiling
79889
+ );
79890
+ const to = readToAddress3(unsignedTx);
79891
+ const data = readData3(unsignedTx);
79892
+ const { name, args } = decodeSignable3(data);
79893
+ const pm = vctx.contracts.PositionManager;
79894
+ switch (expected.kind) {
79895
+ case "mint": {
79896
+ if (name !== "mintUCD") {
79897
+ throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
79898
+ }
79899
+ if (!eqAddr3(to, pm)) {
79900
+ throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
79901
+ }
79902
+ requirePositionId2(args[0], expected.positionId);
79903
+ const txMintAmount = BigInt(String(args[1]));
79904
+ if (txMintAmount.toString() !== expected.amountWei) {
79905
+ throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
79906
+ }
79907
+ const txMintFee = BigInt(String(args[2]));
79908
+ if (txMintFee.toString() !== expected.mintFeeWei) {
79909
+ throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
79910
+ }
79911
+ break;
79912
+ }
79913
+ case "repay": {
79914
+ if (name !== "makePayment") {
79915
+ throw new TxValidationError3(`expected makePayment, server returned ${name}`);
79916
+ }
79917
+ if (!eqAddr3(to, pm)) {
79918
+ throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
79919
+ }
79920
+ requirePositionId2(args[0], expected.positionId);
79921
+ const txAmount = BigInt(String(args[1]));
79922
+ if (txAmount.toString() !== expected.amountWei) {
79923
+ throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
79924
+ }
79925
+ break;
79926
+ }
79927
+ case "extend": {
79928
+ if (name !== "extendPosition") {
79929
+ throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
79930
+ }
79931
+ if (!eqAddr3(to, pm)) {
79932
+ throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
79933
+ }
79934
+ requirePositionId2(args[0], expected.positionId);
79935
+ const txTerm = Number(args[1]);
79936
+ if (txTerm !== expected.selectedTerm) {
79937
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
79938
+ }
79939
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
79940
+ const txFee = BigInt(String(args[5]));
79941
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
79942
+ if (txFee > upper) {
79943
+ throw new TxValidationError3(
79944
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
79945
+ );
79946
+ }
79947
+ }
79948
+ break;
79949
+ }
79950
+ case "withdraw-btc": {
79951
+ if (name !== "withdrawBTC") {
79952
+ throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
79953
+ }
79954
+ if (!eqAddr3(to, pm)) {
79955
+ throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
79956
+ }
79957
+ const paramsTuple = args[0];
79958
+ requirePositionId2(paramsTuple[0], expected.positionId);
79959
+ const txWithdrawalAddress = String(paramsTuple[5]);
79960
+ if (txWithdrawalAddress !== expected.btcAddress) {
79961
+ throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
79962
+ }
79963
+ if (expected.upperBoundTotalDeduction != null) {
79964
+ const txDeduction = BigInt(String(paramsTuple[6]));
79965
+ const upper = BigInt(expected.upperBoundTotalDeduction);
79966
+ if (txDeduction > upper) {
79967
+ throw new TxValidationError3(
79968
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
79969
+ );
79970
+ }
79971
+ }
79972
+ break;
79973
+ }
79974
+ case "ucd-approve": {
79975
+ if (name !== "approve") {
79976
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
79977
+ }
79978
+ const ucd = vctx.contracts.UCDToken;
79979
+ if (!eqAddr3(to, ucd)) {
79980
+ throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
79981
+ }
79982
+ const spender = String(args[0]);
79983
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
79984
+ if (!ok2) {
79985
+ throw new TxValidationError3(
79986
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
79987
+ );
79988
+ }
79989
+ const amt = BigInt(String(args[1]));
79990
+ const min = BigInt(expected.minAmountWei);
79991
+ if (amt < min) {
79992
+ throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
79993
+ }
79994
+ const SANITY_MAX = min * 1000n;
79995
+ if (amt > SANITY_MAX) {
79996
+ throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
79997
+ }
79998
+ break;
79999
+ }
80000
+ case "create-position": {
80001
+ if (name !== "createPosition") {
80002
+ throw new TxValidationError3(`expected createPosition, server returned ${name}`);
80003
+ }
80004
+ if (!eqAddr3(to, pm)) {
80005
+ throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
80006
+ }
80007
+ const txTerm = BigInt(String(args[4]));
80008
+ if (txTerm !== BigInt(expected.selectedTerm)) {
80009
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80010
+ }
80011
+ break;
80012
+ }
80013
+ case "set-position-delegate": {
80014
+ if (name !== "setPositionDelegate") {
80015
+ throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
80016
+ }
80017
+ if (!eqAddr3(to, expected.registryAddress)) {
80018
+ throw new TxValidationError3(
80019
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
80020
+ );
80021
+ }
80022
+ requirePositionId2(args[0], expected.positionId);
80023
+ const txDelegate = String(args[1]);
80024
+ if (!eqAddr3(txDelegate, expected.delegate)) {
80025
+ throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
80026
+ }
80027
+ break;
80028
+ }
80029
+ case "bwar-add-address": {
80030
+ if (name !== "addAddress") {
80031
+ throw new TxValidationError3(`expected addAddress, decoded ${name}`);
80032
+ }
80033
+ if (!eqAddr3(to, expected.registryAddress)) {
80034
+ throw new TxValidationError3(
80035
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
80036
+ );
80037
+ }
80038
+ if (String(args[0]) !== expected.btcAddress) {
80039
+ throw new TxValidationError3(
80040
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
80041
+ );
80042
+ }
80043
+ break;
80044
+ }
80045
+ case "stablecoin-approve": {
80046
+ if (name !== "approve") {
80047
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80048
+ }
80049
+ if (!eqAddr3(to, expected.tokenAddress)) {
80050
+ throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
80051
+ }
80052
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80053
+ throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
80054
+ }
80055
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
80056
+ throw new TxValidationError3(
80057
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
80058
+ );
80059
+ }
80060
+ break;
80061
+ }
80062
+ case "ucd-approve-controller": {
80063
+ if (name !== "approve") {
80064
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80065
+ }
80066
+ if (!eqAddr3(to, expected.ucdTokenAddress)) {
80067
+ throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
80068
+ }
80069
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80070
+ throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
80071
+ }
80072
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
80073
+ throw new TxValidationError3(
80074
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
80075
+ );
80076
+ }
80077
+ break;
80078
+ }
80079
+ case "psm-swap": {
80080
+ if (name !== "swap")
80081
+ throw new TxValidationError3(`expected swap, server returned ${name}`);
80082
+ if (!eqAddr3(to, expected.psmAddress)) {
80083
+ throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
80084
+ }
80085
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80086
+ throw new TxValidationError3(`swap stablecoin mismatch`);
80087
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
80088
+ throw new TxValidationError3(`swap amountIn mismatch`);
80089
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
80090
+ throw new TxValidationError3(`swap minUcdOut mismatch`);
80091
+ if (BigInt(expected.minOut) === 0n) {
80092
+ throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
80093
+ }
80094
+ break;
80095
+ }
80096
+ case "psm-redeem": {
80097
+ if (name !== "redeem")
80098
+ throw new TxValidationError3(`expected redeem, server returned ${name}`);
80099
+ if (!eqAddr3(to, expected.psmAddress)) {
80100
+ throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
80101
+ }
80102
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80103
+ throw new TxValidationError3(`redeem stablecoin mismatch`);
80104
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
80105
+ throw new TxValidationError3(`redeem ucdAmount mismatch`);
80106
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
80107
+ throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
80108
+ if (BigInt(expected.minOut) === 0n) {
80109
+ throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
80110
+ }
80111
+ break;
80112
+ }
80113
+ default: {
80114
+ const _exhaustive = expected;
80115
+ throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
80116
+ }
80117
+ }
80118
+ }
80119
+ var SLOT_SECONDS2 = 12;
80120
+ var INCLUSION_SLOT_TOLERANCE2 = 3;
80121
+ var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
80122
+ function buildPsmApproveTx2(p) {
80123
+ return {
80124
+ to: p.token,
80125
+ data: encodeSignable3("approve", [p.spender, p.amount]),
80126
+ value: "0x0",
80127
+ chainId: p.chainId
80128
+ };
80129
+ }
80130
+ function buildPsmSwapTx3(p) {
80131
+ return {
80132
+ to: p.psm,
80133
+ data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
80134
+ value: "0x0",
80135
+ chainId: p.chainId
80136
+ };
80137
+ }
80138
+ function buildPsmRedeemTx3(p) {
80139
+ return {
80140
+ to: p.psm,
80141
+ data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
80142
+ value: "0x0",
80143
+ chainId: p.chainId
80144
+ };
80145
+ }
80146
+ var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
80147
+ var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
80148
+ function psmExchangeReadsFromProvider2(provider, psmAddress) {
80149
+ const psm = new import_ethers40.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
80150
+ return {
80151
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
80152
+ allowance: async (token, owner, spender) => await new import_ethers40.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
80153
+ };
80154
+ }
80155
+ var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
80156
+ function requireAddress2(direction, label, value) {
80157
+ if (!value || !import_ethers40.ethers.isAddress(value)) {
80158
+ throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
80159
+ }
80160
+ return import_ethers40.ethers.getAddress(value);
80161
+ }
80162
+ async function planPsmExchange2(params) {
80163
+ const { direction, amountIn, minOut, vctx, reads } = params;
80164
+ const chainId = vctx.chainId;
80165
+ if (amountIn <= 0n) {
80166
+ throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
80167
+ }
80168
+ if (minOut <= 0n) {
80169
+ throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
80170
+ }
80171
+ const owner = requireAddress2(direction, "owner", params.owner);
80172
+ const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
80173
+ const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
80174
+ const isSwap = direction === "swap";
80175
+ const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
80176
+ const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
80177
+ if (!await reads.isStablecoinSupported(stablecoin)) {
80178
+ throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
80179
+ }
80180
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
80181
+ const allowanceBefore = await reads.allowance(token, owner, spender);
80182
+ const approvals = [];
80183
+ if (allowanceBefore < amountIn) {
80184
+ if (allowanceBefore > 0n) {
80185
+ approvals.push({
80186
+ step: "reset-approve",
80187
+ tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
80188
+ expected: approveExpected(0n)
80189
+ });
80190
+ }
80191
+ approvals.push({
80192
+ step: "approve",
80193
+ tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
80194
+ expected: approveExpected(amountIn)
80195
+ });
80196
+ }
80197
+ const exec = isSwap ? {
80198
+ step: "swap",
80199
+ tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
80200
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
80201
+ } : {
80202
+ step: "redeem",
80203
+ tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
80204
+ expected: {
80205
+ kind: "psm-redeem",
80206
+ psmAddress: psm,
80207
+ stablecoin,
80208
+ amountUcdWei: amountIn.toString(),
80209
+ minOut: minOut.toString()
80210
+ }
80211
+ };
80212
+ for (const leg of [...approvals, exec]) {
80213
+ validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
80214
+ }
80215
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
80216
+ }
78674
80217
 
78675
80218
  // src/boundary/upstream/real/psm-calls.ts
78676
- var import_ethers31 = require("ethers");
78677
80219
  var PSM_VIEW_FRAGMENTS = [
78678
80220
  "function VERSION() view returns (string)",
78679
80221
  "function supportedStablecoins(address) view returns (bool)",
@@ -78693,15 +80235,7 @@ var PSM_VIEW_FRAGMENTS = [
78693
80235
  "function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
78694
80236
  "function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
78695
80237
  ];
78696
- var PSM_WRITE_FRAGMENTS = [
78697
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
78698
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
78699
- ];
78700
- var ERC20_FRAGMENTS = [
78701
- "function approve(address spender, uint256 amount) returns (bool)",
78702
- "function balanceOf(address holder) view returns (uint256)"
78703
- ];
78704
- var ERC20_IFACE = new import_ethers31.ethers.Interface(ERC20_FRAGMENTS);
80238
+ var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
78705
80239
  var PSM_ERROR_FRAGMENTS = [
78706
80240
  "error StablecoinNotSupported(address stablecoin)",
78707
80241
  "error InvalidAmount()",
@@ -78749,9 +80283,9 @@ var RENDERERS = {
78749
80283
  var PsmCalls = class {
78750
80284
  constructor(deps) {
78751
80285
  this.deps = deps;
78752
- const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_WRITE_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
78753
- this.iface = new import_ethers31.ethers.Interface(abi);
78754
- this.psm = new import_ethers31.ethers.Contract(deps.psmAddress, abi, deps.provider);
80286
+ const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
80287
+ this.iface = new import_ethers41.ethers.Interface(abi);
80288
+ this.psm = new import_ethers41.ethers.Contract(deps.psmAddress, abi, deps.provider);
78755
80289
  }
78756
80290
  psm;
78757
80291
  iface;
@@ -78764,34 +80298,10 @@ var PsmCalls = class {
78764
80298
  ...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
78765
80299
  };
78766
80300
  }
78767
- // ---- unsigned-tx builders (plan 08 W1): EXACT-amount approvals only; floors pinned ----
78768
- /** Step 1: exact-amount ERC-20 approve. Caller names the direction's REAL spender
78769
- * (swap: stablecoin → the PSM; redeem: UCD → the UCDController). */
78770
- buildApprove(p) {
78771
- return {
78772
- to: p.token,
78773
- data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
78774
- value: "0x0",
78775
- chainId: p.chainId
78776
- };
78777
- }
78778
- /** Step 2, stablecoin → UCD (contract `swap`). */
78779
- buildSwap(p) {
78780
- return {
78781
- to: this.deps.psmAddress,
78782
- data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
78783
- value: "0x0",
78784
- chainId: p.chainId
78785
- };
78786
- }
78787
- /** Step 2, UCD → stablecoin (contract `redeem`). */
78788
- buildRedeem(p) {
78789
- return {
78790
- to: this.deps.psmAddress,
78791
- data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
78792
- value: "0x0",
78793
- chainId: p.chainId
78794
- };
80301
+ /** The two live reads the SDK's exchange planner depends on (supported set + allowance),
80302
+ * over this wrapper's provider and PSM. */
80303
+ exchangeReads() {
80304
+ return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
78795
80305
  }
78796
80306
  /** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
78797
80307
  async balances(holder) {
@@ -78804,8 +80314,8 @@ var PsmCalls = class {
78804
80314
  });
78805
80315
  }
78806
80316
  return this.call(async () => {
78807
- const ucd = new import_ethers31.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
78808
- const stable = new import_ethers31.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
80317
+ const ucd = new import_ethers41.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
80318
+ const stable = new import_ethers41.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
78809
80319
  const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
78810
80320
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
78811
80321
  });
@@ -78923,7 +80433,7 @@ var PsmCalls = class {
78923
80433
  };
78924
80434
 
78925
80435
  // src/boundary/upstream/real/session.ts
78926
- var import_ethers32 = require("ethers");
80436
+ var import_ethers42 = require("ethers");
78927
80437
  var REFRESH_LEEWAY_SEC = 30;
78928
80438
  var LOGIN_TYPES_WITH_AUDIENCE3 = {
78929
80439
  DiamondHands: [
@@ -78971,7 +80481,7 @@ var LitOpsSession = class {
78971
80481
  const message = {
78972
80482
  address: this.wallet.address,
78973
80483
  issuedAt: Math.floor(Date.now() / 1e3),
78974
- nonce: "0x" + Buffer.from(import_ethers32.ethers.randomBytes(32)).toString("hex"),
80484
+ nonce: "0x" + Buffer.from(import_ethers42.ethers.randomBytes(32)).toString("hex"),
78975
80485
  audience: this.serviceEndpoint
78976
80486
  };
78977
80487
  const signature = await this.wallet.signTypedData(
@@ -79013,7 +80523,7 @@ function decodeJwtExp(token) {
79013
80523
  }
79014
80524
 
79015
80525
  // src/boundary/upstream/real/write-ops.ts
79016
- var import_ethers34 = require("ethers");
80526
+ var import_ethers44 = require("ethers");
79017
80527
 
79018
80528
  // src/signer/types.ts
79019
80529
  var OperationDeclined = class extends Error {
@@ -79023,7 +80533,7 @@ var OperationDeclined = class extends Error {
79023
80533
  init_tx_validator();
79024
80534
 
79025
80535
  // src/boundary/upstream/shared/external-bridge/page-crypto.ts
79026
- var import_ethers33 = require("ethers");
80536
+ var import_ethers43 = require("ethers");
79027
80537
  var PERSONAL_SIGN_LAYOUTS = {
79028
80538
  "dh-op-envelope-v1": {
79029
80539
  types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
@@ -79044,9 +80554,9 @@ function hashForLayout(layout, fields) {
79044
80554
  const values = def.fieldOrder.map((name) => {
79045
80555
  const raw = fields[name];
79046
80556
  if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
79047
- return hashUtf8.has(name) ? import_ethers33.ethers.keccak256(import_ethers33.ethers.toUtf8Bytes(raw)) : raw;
80557
+ return hashUtf8.has(name) ? import_ethers43.ethers.keccak256(import_ethers43.ethers.toUtf8Bytes(raw)) : raw;
79048
80558
  });
79049
- return import_ethers33.ethers.solidityPackedKeccak256(def.types, values);
80559
+ return import_ethers43.ethers.solidityPackedKeccak256(def.types, values);
79050
80560
  }
79051
80561
  var PAGE_CRYPTO_JS = `"use strict";
79052
80562
  (function () {
@@ -79275,9 +80785,21 @@ function buildValidationContext(network, chainId) {
79275
80785
 
79276
80786
  // src/boundary/upstream/real/write-ops.ts
79277
80787
  var SOURCE5 = "real-ops";
80788
+ function mcpExpected(leg) {
80789
+ const e = leg.expected;
80790
+ switch (e.kind) {
80791
+ case "stablecoin-approve":
80792
+ case "ucd-approve-controller":
80793
+ case "psm-swap":
80794
+ case "psm-redeem":
80795
+ return e;
80796
+ default:
80797
+ throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
80798
+ }
80799
+ }
79278
80800
  var OP_LAYOUT = "dh-op-envelope-v1";
79279
80801
  function randomNonceHex() {
79280
- return "0x" + Buffer.from(import_ethers34.ethers.randomBytes(16)).toString("hex");
80802
+ return "0x" + Buffer.from(import_ethers44.ethers.randomBytes(16)).toString("hex");
79281
80803
  }
79282
80804
  async function postJson(url2, body, headers) {
79283
80805
  const res = await fetch(url2, {
@@ -79338,7 +80860,7 @@ function buildWriteOps(deps) {
79338
80860
  return {
79339
80861
  to: String(tx2["to"] ?? ""),
79340
80862
  data: String(tx2["data"] ?? "0x"),
79341
- value: tx2["value"] != null ? import_ethers34.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
80863
+ value: tx2["value"] != null ? import_ethers44.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
79342
80864
  chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
79343
80865
  };
79344
80866
  }
@@ -79423,8 +80945,9 @@ function buildWriteOps(deps) {
79423
80945
  }
79424
80946
  return {
79425
80947
  createPosition: async (p) => {
79426
- const sdk = deps.getWriteSdk();
79427
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
80948
+ const built = await deps.getWriteSdk();
80949
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
80950
+ const sdk = built.sdk;
79428
80951
  try {
79429
80952
  await deps.assertValidatorConfigured();
79430
80953
  } catch (e) {
@@ -79503,7 +81026,7 @@ function buildWriteOps(deps) {
79503
81026
  mintedUcdWei: minted,
79504
81027
  feeUcdWei: mintFee,
79505
81028
  echoedAmountUcdWei: minted,
79506
- authorization: auth(action, `mint ${import_ethers34.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
81029
+ authorization: auth(action, `mint ${import_ethers44.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
79507
81030
  },
79508
81031
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
79509
81032
  );
@@ -79544,7 +81067,7 @@ function buildWriteOps(deps) {
79544
81067
  txRef: { kind: "eth-tx", id: r.value.txHash },
79545
81068
  paidUcdWei: paid,
79546
81069
  echoedAmountUcdWei: paid,
79547
- authorization: auth(action, `repay ${import_ethers34.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
81070
+ authorization: auth(action, `repay ${import_ethers44.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
79548
81071
  },
79549
81072
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
79550
81073
  );
@@ -79584,8 +81107,9 @@ function buildWriteOps(deps) {
79584
81107
  );
79585
81108
  },
79586
81109
  withdraw: async (p) => {
79587
- const sdk = deps.getWriteSdk();
79588
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81110
+ const built = await deps.getWriteSdk();
81111
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81112
+ const sdk = built.sdk;
79589
81113
  const amountSats = Number(p.amountSats);
79590
81114
  const feeSats = Number(p.networkFeeSats);
79591
81115
  let result;
@@ -79614,12 +81138,13 @@ function buildWriteOps(deps) {
79614
81138
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
79615
81139
  );
79616
81140
  },
79617
- /** PSM exchange pair (plan 08 W1): pure on-chain calls — no LIT action, no server
79618
- * orchestration. MCP-built txs over the pinned wrapper (the SDK's psmSwap/psmRedeem
79619
- * hardcode MaxUint256 approvals and are FORBIDDEN); exact-amount approve, then the
79620
- * swap/redeem with its mandatory floor, each validated against the M8-11 whitelist,
79621
- * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
79622
- * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
81141
+ /** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
81142
+ * orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
81143
+ * builder every client shares (it replaced this file's own builders and the SDK's old
81144
+ * MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
81145
+ * allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
81146
+ * validated again here by the MCP's own whitelist (the one the approval card decodes
81147
+ * with), then signed through the session signer and broadcast — one at a time. */
79623
81148
  psmSwap: async (p) => {
79624
81149
  const pr = await deps.psm(p.stablecoin);
79625
81150
  if (!pr.ok) return upFail(pr.failure);
@@ -79633,13 +81158,9 @@ function buildWriteOps(deps) {
79633
81158
  message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
79634
81159
  });
79635
81160
  }
79636
- const amountIn = BigInt(p.amountIn);
79637
- const minOut = BigInt(p.minOut);
79638
81161
  const vctx = buildValidationContext(config.network, chainId);
79639
- const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
79640
- const spenderAddress = isSwap ? addr.psm : addr.ucdController;
79641
81162
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
79642
- const tokenSymbol = isSwap ? "USDC" : "UCD";
81163
+ const tokenSymbol = isSwap ? calls.symbol() : "UCD";
79643
81164
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
79644
81165
  if (!quoteR.ok) return upFail(quoteR.failure);
79645
81166
  const broadcast = async (leg, action, tx2) => {
@@ -79654,49 +81175,66 @@ function buildWriteOps(deps) {
79654
81175
  return submitFailure(leg, e);
79655
81176
  }
79656
81177
  };
79657
- const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
81178
+ let plan;
79658
81179
  try {
79659
- validateUnsignedTx(
79660
- { ...approveTx },
79661
- isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn },
79662
- vctx
79663
- );
79664
- } catch (e) {
79665
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
79666
- }
79667
- const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
79668
- const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
79669
- if (!approveHashR.ok) return approveHashR;
79670
- const approveHash = approveHashR.value;
79671
- 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`;
79672
- const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
79673
- try {
79674
- validateUnsignedTx(
79675
- { ...execTx },
79676
- isSwap ? { kind: "psm-swap", psmAddress: addr.psm, stablecoin: addr.stablecoin, amountIn: p.amountIn, minOut: p.minOut } : { kind: "psm-redeem", psmAddress: addr.psm, stablecoin: addr.stablecoin, amountUcdWei: p.amountIn, minOut: p.minOut },
79677
- vctx
79678
- );
81180
+ plan = await planPsmExchange2({
81181
+ direction: p.direction,
81182
+ owner: p.borrower,
81183
+ addresses: addr,
81184
+ amountIn: BigInt(p.amountIn),
81185
+ minOut: BigInt(p.minOut),
81186
+ vctx,
81187
+ reads: calls.exchangeReads()
81188
+ });
79679
81189
  } catch (e) {
79680
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
81190
+ return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
81191
+ kind: "unavailable",
81192
+ source: SOURCE5,
81193
+ message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
81194
+ raw: String(e)
81195
+ });
79681
81196
  }
79682
- 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}`;
79683
- const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
79684
- if (!execHashR.ok) {
79685
- const f = execHashR.failure;
79686
- return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
81197
+ const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
81198
+ const unit = `${tokenSymbol} smallest units`;
81199
+ const landed = [];
81200
+ const residualNote = () => {
81201
+ const last = landed[landed.length - 1];
81202
+ const standing = !last ? `no approve ran \u2014 the pre-existing allowance of ${allowanceBefore} ${unit} to ${spenderContract} is unchanged` : last.step === "reset-approve" ? `the reset ALREADY broadcast (tx ${last.hash}) \u2014 the allowance to ${spenderContract} is now 0; nothing is authorized` : `the approve ALREADY broadcast (tx ${last.hash}) \u2014 an exact-amount allowance of ${p.amountIn} ${unit} to ${spenderContract} stands; it authorizes only that amount and nothing else`;
81203
+ return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
81204
+ };
81205
+ const runLeg = async (leg) => {
81206
+ const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
81207
+ try {
81208
+ validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
81209
+ } catch (e) {
81210
+ return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
81211
+ }
81212
+ const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
81213
+ const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
81214
+ return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
81215
+ };
81216
+ const approvals = [];
81217
+ for (const leg of plan.approvals) {
81218
+ const card = leg.step === "reset-approve" ? `reset the standing allowance of ${allowanceBefore} ${unit} to ${spenderContract} (${spenderAddress}) to 0 \u2014 required before an exact-amount approve` : `approve exactly ${p.amountIn} ${unit} to ${spenderContract} (${spenderAddress})`;
81219
+ const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
81220
+ const r = await runLeg(leg);
81221
+ if (!r.ok) return r;
81222
+ landed.push({ step, hash: r.value });
81223
+ approvals.push({
81224
+ step,
81225
+ txRef: { kind: "eth-tx", id: r.value },
81226
+ amount: leg.step === "reset-approve" ? "0" : p.amountIn,
81227
+ authorization: auth("psm-approve", card, r.value)
81228
+ });
79687
81229
  }
81230
+ const execCard = `${p.direction} ${p.amountIn} ${isSwap ? unit : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
81231
+ const execHashR = await runLeg(plan.exec);
81232
+ if (!execHashR.ok) return execHashR;
79688
81233
  const execHash = execHashR.value;
79689
81234
  const balancesR = await calls.balances(p.borrower);
79690
81235
  const row = {
79691
- approve: {
79692
- txRef: { kind: "eth-tx", id: approveHash },
79693
- tokenSymbol,
79694
- tokenAddress,
79695
- spenderAddress,
79696
- spenderContract,
79697
- amount: p.amountIn,
79698
- authorization: auth("psm-approve", approveCard, approveHash)
79699
- },
81236
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
81237
+ approvals,
79700
81238
  execute: {
79701
81239
  txRef: { kind: "eth-tx", id: execHash },
79702
81240
  amountIn: p.amountIn,
@@ -79713,8 +81251,9 @@ function buildWriteOps(deps) {
79713
81251
  // registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
79714
81252
  // msg.sender, so their path is a SafeTx — never this keystore leg.
79715
81253
  allowlistWithdrawalAddress: async (p) => {
79716
- const sdk = deps.getWriteSdk();
79717
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81254
+ const built = await deps.getWriteSdk();
81255
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81256
+ const sdk = built.sdk;
79718
81257
  let result;
79719
81258
  try {
79720
81259
  result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
@@ -79761,8 +81300,9 @@ function buildWriteOps(deps) {
79761
81300
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
79762
81301
  }),
79763
81302
  retryWithdrawExecute: async (p) => {
79764
- const sdk = deps.getWriteSdk();
79765
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81303
+ const built = await deps.getWriteSdk();
81304
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81305
+ const sdk = built.sdk;
79766
81306
  let rows;
79767
81307
  try {
79768
81308
  rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
@@ -79790,7 +81330,7 @@ function buildWriteOps(deps) {
79790
81330
  }
79791
81331
 
79792
81332
  // src/signer/eoa-dh.ts
79793
- var import_ethers35 = require("ethers");
81333
+ var import_ethers45 = require("ethers");
79794
81334
  var EoaDHSigner = class {
79795
81335
  constructor(wallet, broadcast, clock = Date.now) {
79796
81336
  this.wallet = wallet;
@@ -79807,7 +81347,7 @@ var EoaDHSigner = class {
79807
81347
  async signAuthorization(spec) {
79808
81348
  const quantumTs = nextQuantumTimestamp(this.clock());
79809
81349
  const { fields, hashHex } = spec.stamp(quantumTs);
79810
- const signature = await this.wallet.signMessage(import_ethers35.ethers.getBytes(hashHex));
81350
+ const signature = await this.wallet.signMessage(import_ethers45.ethers.getBytes(hashHex));
79811
81351
  return { signature, quantumTs, fields };
79812
81352
  }
79813
81353
  async wrapInnerTx(innerTx) {
@@ -79825,10 +81365,10 @@ var EoaDHSigner = class {
79825
81365
 
79826
81366
  // src/signer/external-eoa.ts
79827
81367
  var import_node_crypto5 = require("crypto");
79828
- var import_ethers37 = require("ethers");
81368
+ var import_ethers47 = require("ethers");
79829
81369
 
79830
81370
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
79831
- var import_ethers36 = require("ethers");
81371
+ var import_ethers46 = require("ethers");
79832
81372
  function eq2(a, b) {
79833
81373
  return a.toLowerCase() === b.toLowerCase();
79834
81374
  }
@@ -79851,7 +81391,7 @@ function compareLandedTx(landed, approved, borrower) {
79851
81391
  return { status: "verified", from: landed.from, hash: landed.hash };
79852
81392
  }
79853
81393
  function verifyRawSignedTx(rawSignedTx, approved, borrower) {
79854
- const parsed = import_ethers36.ethers.Transaction.from(rawSignedTx);
81394
+ const parsed = import_ethers46.ethers.Transaction.from(rawSignedTx);
79855
81395
  if (!parsed.from || !parsed.to || !parsed.hash) {
79856
81396
  return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
79857
81397
  }
@@ -79889,7 +81429,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
79889
81429
  for (let attempt = 0; attempt < 4; attempt++) {
79890
81430
  try {
79891
81431
  const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
79892
- return import_ethers37.ethers.toBeHex(est * 15n / 10n);
81432
+ return import_ethers47.ethers.toBeHex(est * 15n / 10n);
79893
81433
  } catch (e) {
79894
81434
  lastErr = e;
79895
81435
  await new Promise((r) => setTimeout(r, 13e3));
@@ -79939,7 +81479,7 @@ var ExternalEoaDHSigner = class {
79939
81479
  throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
79940
81480
  }
79941
81481
  const finalHash = spec.stamp(used.quantumTs).hashHex;
79942
- const recovered = import_ethers37.ethers.verifyMessage(import_ethers37.ethers.getBytes(finalHash), outcome.signature);
81482
+ const recovered = import_ethers47.ethers.verifyMessage(import_ethers47.ethers.getBytes(finalHash), outcome.signature);
79943
81483
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
79944
81484
  throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
79945
81485
  }
@@ -79950,7 +81490,7 @@ var ExternalEoaDHSigner = class {
79950
81490
  }
79951
81491
  async submitValidatedTx(outerTx, ctx) {
79952
81492
  const approved = toApprovedTx(outerTx, this.deps.chainId);
79953
- const gas = outerTx.gasLimit != null ? import_ethers37.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
81493
+ const gas = outerTx.gasLimit != null ? import_ethers47.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
79954
81494
  const outcome = await this.deps.bridge.requestSignature({
79955
81495
  id: (0, import_node_crypto5.randomUUID)(),
79956
81496
  kind: "transaction",
@@ -79984,7 +81524,7 @@ var ExternalEoaDHSigner = class {
79984
81524
  return new BridgeEthersSigner(this.deps);
79985
81525
  }
79986
81526
  };
79987
- var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ethers.AbstractSigner {
81527
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers47.ethers.AbstractSigner {
79988
81528
  constructor(deps) {
79989
81529
  super(deps.provider);
79990
81530
  this.deps = deps;
@@ -79995,13 +81535,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79995
81535
  return this.deps.borrower;
79996
81536
  }
79997
81537
  async signMessage(message) {
79998
- const bytes = typeof message === "string" ? import_ethers37.ethers.toUtf8Bytes(message) : message;
81538
+ const bytes = typeof message === "string" ? import_ethers47.ethers.toUtf8Bytes(message) : message;
79999
81539
  if (bytes.length !== 32) {
80000
81540
  throw new Error(
80001
81541
  `external-wallet signMessage accepts only the SDK's bare 32-byte auth hashes (got ${bytes.length} bytes) \u2014 no other raw-message signing rides this path.`
80002
81542
  );
80003
81543
  }
80004
- const hashHex = import_ethers37.ethers.hexlify(bytes).toLowerCase();
81544
+ const hashHex = import_ethers47.ethers.hexlify(bytes).toLowerCase();
80005
81545
  const nowMs = (this.deps.clock ?? Date.now)();
80006
81546
  const expiresAtSec = nextQuantumTimestamp(nowMs);
80007
81547
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
@@ -80031,7 +81571,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
80031
81571
  if (outcome.status !== "approved" || !outcome.signature) {
80032
81572
  throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
80033
81573
  }
80034
- const recovered = import_ethers37.ethers.verifyMessage(bytes, outcome.signature);
81574
+ const recovered = import_ethers47.ethers.verifyMessage(bytes, outcome.signature);
80035
81575
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80036
81576
  throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80037
81577
  }
@@ -80065,11 +81605,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
80065
81605
  const approved = {
80066
81606
  to: tx2.to,
80067
81607
  data: tx2.data,
80068
- value: tx2.value != null ? import_ethers37.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
81608
+ value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
80069
81609
  chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
80070
81610
  };
80071
81611
  const card = cardForTx(approved);
80072
- const gas = tx2.gasLimit != null ? import_ethers37.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
81612
+ const gas = tx2.gasLimit != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
80073
81613
  const outcome = await this.deps.bridge.requestSignature({
80074
81614
  id: (0, import_node_crypto5.randomUUID)(),
80075
81615
  kind: "transaction",
@@ -80111,14 +81651,14 @@ function toApprovedTx(tx2, fallbackChainId) {
80111
81651
  return {
80112
81652
  to: tx2.to,
80113
81653
  data: tx2.data,
80114
- value: tx2.value != null ? import_ethers37.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
81654
+ value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
80115
81655
  chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
80116
81656
  };
80117
81657
  }
80118
81658
  function describeFn(data) {
80119
81659
  try {
80120
- const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
80121
- return decodeSignable2(data).name;
81660
+ const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
81661
+ return decodeSignable4(data).name;
80122
81662
  } catch {
80123
81663
  return "operation";
80124
81664
  }
@@ -80155,7 +81695,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
80155
81695
  var RealUpstreamPlugin = class {
80156
81696
  constructor(config, wallet, runtime) {
80157
81697
  this.config = config;
80158
- this.provider = new import_ethers38.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
81698
+ this.provider = new import_ethers48.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
80159
81699
  this.wallet = wallet ?? null;
80160
81700
  this.runtime = runtime ?? null;
80161
81701
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
@@ -80230,25 +81770,16 @@ var RealUpstreamPlugin = class {
80230
81770
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
80231
81771
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
80232
81772
  listPsmStablecoins: async () => {
80233
- const listed = await this.listSupportedStablecoins();
80234
- if (!listed.ok) return listed;
80235
- const rows = await Promise.all(
80236
- listed.rows.map(async (row) => {
80237
- const built = await this.psmCallsFor(row.address);
80238
- return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
80239
- })
80240
- );
80241
- return upOk(
80242
- rows.filter((r) => r !== null),
80243
- this.src("subgraph")
80244
- );
81773
+ const verified = await this.verifiedStablecoins();
81774
+ if (!verified.ok) return upFail(verified.failure);
81775
+ return upOk(verified.rows, this.src("subgraph"));
80245
81776
  },
80246
81777
  getPsmStatus: async (p) => {
80247
- const r = await this.psmCallsFor(p.stablecoin);
81778
+ const r = await this.psmCallsForChoice(p.stablecoin);
80248
81779
  return r.ok ? r.calls.status() : upFail(r.failure);
80249
81780
  },
80250
81781
  getPsmQuote: async (p) => {
80251
- const r = await this.psmCallsFor(p.stablecoin);
81782
+ const r = await this.psmCallsForChoice(p.stablecoin);
80252
81783
  if (!r.ok) return upFail(r.failure);
80253
81784
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
80254
81785
  }
@@ -80357,18 +81888,24 @@ var RealUpstreamPlugin = class {
80357
81888
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
80358
81889
  * and the service-mode SDK routes its own subgraph reads through the same proxy — so
80359
81890
  * writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
80360
- * Safe to call repeatedly; failures leave the write plane honestly unavailable
80361
- * (createPosition/withdraw report the uninitialized SDK). */
81891
+ * Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
81892
+ * first write builds again (see ensureSdk). */
80362
81893
  async initWriteSdk() {
80363
81894
  if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
80364
81895
  const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
80365
81896
  if (!wallet) return;
80366
81897
  await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
80367
81898
  }
80368
- /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
80369
- * the write gateways report the uninitialized SDK honestly, never fake readiness. */
81899
+ /** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
81900
+ *
81901
+ * A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
81902
+ * life of the process and drop the error, which was survivable only while `create` never
81903
+ * touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
81904
+ * RPC blip at boot would have disabled every later write with no reason given. Now each write
81905
+ * retries, and a persistent failure says what it is. Concurrent callers share one build. */
80370
81906
  async ensureSdk(key, signer) {
80371
- if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
81907
+ const cached = this.sdkCache.get(key);
81908
+ if (cached) return { ok: true, sdk: cached };
80372
81909
  const inFlight = this.sdkInFlight.get(key);
80373
81910
  if (inFlight) return inFlight;
80374
81911
  const build = (async () => {
@@ -80388,17 +81925,23 @@ var RealUpstreamPlugin = class {
80388
81925
  // nesting writes under indexer discovery (the M8B-4 coupling this removes).
80389
81926
  ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
80390
81927
  });
80391
- return isSuccess(builtWrite) ? builtWrite.value : null;
80392
- } catch {
80393
- return null;
81928
+ if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
81929
+ return { ok: false, reason: builtWrite.error.message };
81930
+ } catch (e) {
81931
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
80394
81932
  }
80395
81933
  })();
80396
81934
  this.sdkInFlight.set(key, build);
80397
81935
  const built = await build;
80398
81936
  this.sdkInFlight.delete(key);
80399
- this.sdkCache.set(key, built);
81937
+ if (built.ok) this.sdkCache.set(key, built.sdk);
80400
81938
  return built;
80401
81939
  }
81940
+ /** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
81941
+ async writeSdkFor(key, signer) {
81942
+ const built = await this.ensureSdk(key, signer);
81943
+ return built.ok ? { ok: true, sdk: built.sdk } : built;
81944
+ }
80402
81945
  wallet;
80403
81946
  // ---- per-call signer resolution (plan 10 A3) ----
80404
81947
  /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
@@ -80438,9 +81981,9 @@ var RealUpstreamPlugin = class {
80438
81981
  chainId: this.config.chainId,
80439
81982
  dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
80440
81983
  session,
80441
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
81984
+ getWriteSdk: () => this.writeSdkFor(key, wallet),
80442
81985
  readDetails: (id) => this.readPositionDetails(id),
80443
- psm: (stablecoin) => this.psmCallsFor(stablecoin),
81986
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
80444
81987
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80445
81988
  });
80446
81989
  }
@@ -80454,14 +81997,14 @@ var RealUpstreamPlugin = class {
80454
81997
  if (!pkpValidation) {
80455
81998
  throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
80456
81999
  }
80457
- const registry = new import_ethers38.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
82000
+ const registry = new import_ethers48.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
80458
82001
  let validator;
80459
82002
  try {
80460
82003
  validator = await registry.validatorForVersion(version2);
80461
82004
  } catch (e) {
80462
82005
  throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
80463
82006
  }
80464
- if (validator === import_ethers38.ethers.ZeroAddress) {
82007
+ if (validator === import_ethers48.ethers.ZeroAddress) {
80465
82008
  throw new Error(
80466
82009
  `validator version ${version2} is NOT registered on ${this.config.network} (PKPValidation ${pkpValidation} returns the zero address) \u2014 the transaction would revert ValidatorNotConfigured. Set DH_VALIDATOR_VERSION to the network's registered generation.`
80467
82010
  );
@@ -80535,7 +82078,6 @@ var RealUpstreamPlugin = class {
80535
82078
  gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
80536
82079
  this.opsGatewayCache.set(key, gateway);
80537
82080
  }
80538
- await this.ensureSdk(key, wallet.connect(this.provider));
80539
82081
  return { ok: true, gateway };
80540
82082
  }
80541
82083
  if (mode === "external") {
@@ -80572,14 +82114,13 @@ var RealUpstreamPlugin = class {
80572
82114
  chainId: this.config.chainId,
80573
82115
  dhSigner: new ExternalEoaDHSigner(deps),
80574
82116
  session,
80575
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82117
+ getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
80576
82118
  readDetails: (id) => this.readPositionDetails(id),
80577
- psm: (stablecoin) => this.psmCallsFor(stablecoin),
82119
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
80578
82120
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80579
82121
  });
80580
82122
  this.opsGatewayCache.set(key, gateway);
80581
82123
  }
80582
- await this.ensureSdk(key, this.externalSigners.get(key));
80583
82124
  return { ok: true, gateway };
80584
82125
  }
80585
82126
  return {
@@ -80738,12 +82279,118 @@ var RealUpstreamPlugin = class {
80738
82279
  {}
80739
82280
  );
80740
82281
  if (!r.ok) return r;
80741
- const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
82282
+ const raw = r.value.data.supportedStablecoins ?? [];
82283
+ const bad = raw.find((x) => !import_ethers48.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
82284
+ if (bad) {
82285
+ return {
82286
+ ok: false,
82287
+ failure: {
82288
+ kind: "malformed",
82289
+ source: "subgraph",
82290
+ message: `the indexer returned a PSM stablecoin row this build cannot read (address '${String(bad.address)}', decimals '${String(bad.decimals)}')`
82291
+ }
82292
+ };
82293
+ }
82294
+ const rows = raw.map((x) => ({
80742
82295
  address: String(x.address).toLowerCase(),
80743
82296
  decimals: Number(x.decimals)
80744
82297
  }));
82298
+ if (rows.length === 0) {
82299
+ return {
82300
+ ok: false,
82301
+ failure: {
82302
+ kind: "unavailable",
82303
+ source: "subgraph",
82304
+ message: `the indexer lists NO supported stablecoins for the PSM on ${this.config.network}. Either the subgraph has not indexed the StablecoinAdded events yet (check its start block against the block the coins were added at), or governance has removed every coin. PSM exchange is unavailable here until one of those is resolved \u2014 this is NOT "the PSM supports nothing".`
82305
+ }
82306
+ };
82307
+ }
80745
82308
  return { ok: true, rows };
80746
82309
  }
82310
+ /**
82311
+ * The supported set, verified — index rows each re-checked on-chain, carrying the symbol
82312
+ * read from the token itself. This is what `protocol://psm` lists and what a caller's
82313
+ * SYMBOL is resolved against.
82314
+ *
82315
+ * Rows are dropped ONLY for the one reason a drop is honest: the index still lists a coin
82316
+ * the chain no longer supports (index lag behind a governance removal). Any OTHER failure
82317
+ * — an RPC outage mid-loop — propagates, because a list that silently shrinks when the
82318
+ * chain is unreachable is the same silent-failure shape as the empty list above. If
82319
+ * nothing survives verification, that is a refusal too, and it says which side disagreed.
82320
+ */
82321
+ async verifiedStablecoins() {
82322
+ const listed = await this.listSupportedStablecoins();
82323
+ if (!listed.ok) return listed;
82324
+ const checked = await Promise.all(
82325
+ listed.rows.map(async (row) => ({ row, built: await this.psmCallsFor(row.address) }))
82326
+ );
82327
+ const transport = checked.find((c) => !c.built.ok && c.built.failure.kind !== "rejected");
82328
+ if (transport && !transport.built.ok) return { ok: false, failure: transport.built.failure };
82329
+ const rows = checked.flatMap(
82330
+ ({ row, built }) => built.ok ? [{ address: row.address, symbol: built.calls.symbol(), decimals: row.decimals }] : []
82331
+ );
82332
+ if (rows.length === 0) {
82333
+ return {
82334
+ ok: false,
82335
+ failure: {
82336
+ kind: "unavailable",
82337
+ source: "chain-rpc",
82338
+ message: `the indexer lists ${listed.rows.length} PSM stablecoin(s) on ${this.config.network}, and the PSM contract confirms none of them. The index is behind a governance removal, or it is indexing a different PSM than the one in this build's deployment table \u2014 verify before exchanging anything.`
82339
+ }
82340
+ };
82341
+ }
82342
+ return { ok: true, rows };
82343
+ }
82344
+ /**
82345
+ * Resolve what the CALLER named — a symbol or a 0x address — to a verified address.
82346
+ *
82347
+ * The tool schemas have always said "by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address",
82348
+ * and the mock world accepts exactly that. The real adapter accepted only the address:
82349
+ * a symbol went straight into an address-typed `ethers.Contract`, which threw, and the
82350
+ * throw was caught as `kind: "unavailable"` → `UPSTREAM_UNAVAILABLE` — a code the guide
82351
+ * tells the model is "usually transient; retry once". So the documented input produced a
82352
+ * retry loop on the one deployment that moves real money, and a developer practising
82353
+ * against the mock never met it. Both halves are fixed here: the symbol resolves, and a
82354
+ * name that cannot resolve is `rejected` (the caller's input) rather than `unavailable`
82355
+ * (our upstream).
82356
+ */
82357
+ async psmCallsForChoice(chosen) {
82358
+ const raw = chosen.trim();
82359
+ if (raw.length === 0) {
82360
+ return {
82361
+ ok: false,
82362
+ failure: { kind: "rejected", source: "chain-rpc", message: "no stablecoin named \u2014 name one by symbol (e.g. 'USDC') or by 0x address; there is no default coin." }
82363
+ };
82364
+ }
82365
+ const symbol = raw.toLowerCase();
82366
+ if (import_ethers48.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
82367
+ const verified = await this.verifiedStablecoins();
82368
+ if (!verified.ok) return { ok: false, failure: verified.failure };
82369
+ const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
82370
+ if (hits.length > 1) {
82371
+ return {
82372
+ ok: false,
82373
+ failure: {
82374
+ kind: "rejected",
82375
+ source: "chain-rpc",
82376
+ message: `'${raw}' names ${hits.length} different coins this PSM supports \u2014 ${hits.map((r) => r.address).join(", ")}. Symbols are self-declared and not unique, so this one cannot be resolved for you: name the 0x address of the one you mean.`
82377
+ }
82378
+ };
82379
+ }
82380
+ const hit = hits[0];
82381
+ if (!hit) {
82382
+ const names = verified.rows.map((r) => `${r.symbol} (${r.address})`).join(", ");
82383
+ return {
82384
+ ok: false,
82385
+ failure: {
82386
+ kind: "rejected",
82387
+ source: "chain-rpc",
82388
+ message: `'${raw}' is not a coin this PSM supports on ${this.config.network} \u2014 it supports ${names}. Name one of those by symbol or address. \`protocol://psm\` carries each one's fees, limits and reserves.`
82389
+ }
82390
+ };
82391
+ }
82392
+ return this.psmCallsFor(hit.address);
82393
+ }
80747
82394
  /**
80748
82395
  * Build the PSM wrapper for ONE caller-chosen stablecoin.
80749
82396
  *
@@ -80754,6 +82401,9 @@ var RealUpstreamPlugin = class {
80754
82401
  * chain, then sign.
80755
82402
  */
80756
82403
  async psmCallsFor(stablecoinAddress) {
82404
+ if (!import_ethers48.ethers.isAddress(stablecoinAddress)) {
82405
+ throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
82406
+ }
80757
82407
  const key = stablecoinAddress.toLowerCase();
80758
82408
  const cached = this.psmWrappers.get(key);
80759
82409
  if (cached) return { ok: true, calls: cached };
@@ -80771,9 +82421,9 @@ var RealUpstreamPlugin = class {
80771
82421
  let supported;
80772
82422
  let symbol;
80773
82423
  try {
80774
- const psm = new import_ethers38.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
82424
+ const psm = new import_ethers48.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
80775
82425
  supported = await psm["supportedStablecoins"](key);
80776
- const erc20 = new import_ethers38.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
82426
+ const erc20 = new import_ethers48.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
80777
82427
  symbol = await erc20["symbol"]();
80778
82428
  } catch (e) {
80779
82429
  return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
@@ -80986,7 +82636,7 @@ var RealUpstreamPlugin = class {
80986
82636
  const pm = this.contracts["PositionManager"];
80987
82637
  if (!pm) return false;
80988
82638
  try {
80989
- const c = new import_ethers38.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
82639
+ const c = new import_ethers48.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
80990
82640
  return Boolean(await c["paused"]());
80991
82641
  } catch {
80992
82642
  return false;
@@ -80995,16 +82645,16 @@ var RealUpstreamPlugin = class {
80995
82645
  async readPositionDetails(id) {
80996
82646
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
80997
82647
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
80998
- const c = new import_ethers38.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
82648
+ const c = new import_ethers48.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
80999
82649
  let d;
81000
82650
  try {
81001
- d = await c["getPositionDetails"](import_ethers38.ethers.zeroPadValue(id, 32));
82651
+ d = await c["getPositionDetails"](import_ethers48.ethers.zeroPadValue(id, 32));
81002
82652
  } catch (e) {
81003
82653
  if (e.code === "CALL_EXCEPTION") return null;
81004
82654
  throw e;
81005
82655
  }
81006
82656
  const borrower = String(d["borrower"]);
81007
- if (borrower === import_ethers38.ethers.ZeroAddress) return null;
82657
+ if (borrower === import_ethers48.ethers.ZeroAddress) return null;
81008
82658
  return {
81009
82659
  positionId: String(d["positionId"]),
81010
82660
  pkpId: String(d["pkpId"]),
@@ -82634,8 +84284,8 @@ async function buildBoundary(configResult, overrides) {
82634
84284
  );
82635
84285
  }
82636
84286
  try {
82637
- const decrypted = await import_ethers39.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
82638
- if (!(decrypted instanceof import_ethers39.ethers.Wallet)) {
84287
+ const decrypted = await import_ethers49.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
84288
+ if (!(decrypted instanceof import_ethers49.ethers.Wallet)) {
82639
84289
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
82640
84290
  }
82641
84291
  wallet = decrypted;
@@ -82804,6 +84454,17 @@ function signerModeSourceClause(d) {
82804
84454
  function phoneWalletOffer(d) {
82805
84455
  return d.walletConnect ? "or scan the WalletConnect QR (or paste the pairing code) to approve on a phone wallet" : "This deployment does NOT offer the WalletConnect phone-wallet leg \u2014 there is no QR to scan and `/wc-pairing` answers 404; a browser-extension wallet is the only path here";
82806
84456
  }
84457
+ function worldAxes(d) {
84458
+ const axes = [];
84459
+ axes.push(
84460
+ offers(d, "mock-simulated") ? "practice (mock) or real adapter" : "the REAL adapter \u2014 there is no practice (mock) world on this deployment"
84461
+ );
84462
+ axes.push(
84463
+ d.networks.length > 1 ? "sepolia (practice money) or mainnet (real money)" : d.networks.includes("mainnet") ? "MAINNET only, so every fund movement here is real money" : "sepolia only, so the ceremonies are real and the money is practice"
84464
+ );
84465
+ axes.push("that writes are enabled, and what actually gates one is whether a signing identity is connected");
84466
+ return axes.join("; ");
84467
+ }
82807
84468
  function moneyTruth(d) {
82808
84469
  const practice = offers(d, "mock-simulated");
82809
84470
  const sepolia = d.networks.includes("sepolia");
@@ -82986,8 +84647,7 @@ have to guess whether the money is real.`;
82986
84647
  function authorizationModeBullets(d) {
82987
84648
  const bullets = [];
82988
84649
  if (offers(d, "external")) {
82989
- bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
82990
- mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
84650
+ bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup${d.walletConnect ? ", or WalletConnect\n mobile via QR/paste-code" : " \u2014 this build has no WalletConnect\n mobile leg"}). Real adapter and mock. For TRANSACTIONS the approval card
82991
84651
  is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
82992
84652
  The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
82993
84653
  approval page states plainly it CANNOT decode. Never extend the card promise over
@@ -83050,8 +84710,7 @@ install matrix. ${connectorInstallNote(d)}
83050
84710
  Nothing needs a config file. Three steps:
83051
84711
 
83052
84712
  **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83053
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83054
- (practice money) or mainnet (real money); whether writes are enabled here and which
84713
+ \`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
83055
84714
  signer modes exist; current terms (\`protocol_terms\`).
83056
84715
 
83057
84716
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
@@ -83118,7 +84777,7 @@ on the real adapter and the mock.
83118
84777
  | extend | 1 personal-sign + 1 tx |
83119
84778
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
83120
84779
  | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
83121
- | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
84780
+ | PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
83122
84781
 
83123
84782
  **Honesty notes (say these plainly):**
83124
84783
  - **Reads never pop the wallet.** If a read needs a login the user does not have, the
@@ -83160,8 +84819,7 @@ on the real adapter and the mock.
83160
84819
  10 UCD.
83161
84820
 
83162
84821
  **Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
83163
- \`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
83164
- WalletConnect session (pending approvals are cancelled loudly), discards the login
84822
+ \`disconnect\`):** the FULL wallet flush. It ends every approval-page session${d.walletConnect ? " and any\nWalletConnect session" : ""} (pending approvals are cancelled loudly), discards the login
83165
84823
  token from server memory AND revokes it at the service, and unbinds the borrower
83166
84824
  identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
83167
84825
  a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
@@ -83263,16 +84921,19 @@ rather than silently deliver less than quoted.
83263
84921
 
83264
84922
  ${psmStablecoinRealityNote(d)}
83265
84923
 
83266
- **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83267
- result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
84924
+ **Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
84925
+ the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
84926
+ planned against the allowance already standing: none when it covers the amount, one when it
84927
+ is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
83268
84928
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
83269
84929
  the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
83270
84930
  you approve UCD to the **UCDController** (the PSM burns your UCD through the
83271
84931
  controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83272
84932
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
83273
84933
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83274
- own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83275
- standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
84934
+ own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
84935
+ standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
84936
+ the next exchange that it covers uses it without asking for another approval.
83276
84937
  PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
83277
84938
  REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
83278
84939
  wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
@@ -83619,7 +85280,7 @@ function renderGuideIndex(deployment) {
83619
85280
 
83620
85281
  - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
83621
85282
  - first-setup \u2014 zero to ready by conversation (authorization choice included)
83622
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
85283
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, ${deployment.walletConnect ? "extension or WalletConnect QR" : "browser extension (no WalletConnect leg here)"}, popup cadence, login honesty, disconnect/log-out
83623
85284
  - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
83624
85285
  - fees \u2014 the two fee models, plainly
83625
85286
  - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
@@ -83745,7 +85406,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
83745
85406
 
83746
85407
  // src/tools/loan.ts
83747
85408
  var import_zod = require("zod");
83748
- var import_ethers40 = require("ethers");
85409
+ var import_ethers50 = require("ethers");
83749
85410
 
83750
85411
  // src/util/format.ts
83751
85412
  function bigintReplacer(_key, value) {
@@ -83933,7 +85594,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
83933
85594
  const b = getB();
83934
85595
  if (!b.ok) return renderError(b.error);
83935
85596
  return renderEnvelope(
83936
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers40.parseEther)(amountUcd.toString()).toString() })
85597
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers50.parseEther)(amountUcd.toString()).toString() })
83937
85598
  );
83938
85599
  })
83939
85600
  );
@@ -83971,7 +85632,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
83971
85632
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
83972
85633
  amountUcdWei = detail.data.debtUcdWei;
83973
85634
  } else {
83974
- amountUcdWei = (0, import_ethers40.parseEther)(amountUcd.toString()).toString();
85635
+ amountUcdWei = (0, import_ethers50.parseEther)(amountUcd.toString()).toString();
83975
85636
  }
83976
85637
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
83977
85638
  })
@@ -84372,7 +86033,7 @@ function registerPsmTools(server, getB) {
84372
86033
  "psm_swap",
84373
86034
  {
84374
86035
  title: "Exchange UCD \u2194 a stablecoin through the PSM",
84375
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
86036
+ description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as explicit on-chain ceremonies, each signed by the session signer and all reported in the result: (1) the approvals the input token NEEDS, planned against its standing allowance \u2014 none when the allowance already covers the amount; one EXACT-AMOUNT approval when it is 0; a reset to 0 followed by the exact approval when a partial allowance stands. to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
84376
86037
  inputSchema: {
84377
86038
  stablecoin: import_zod4.z.string().min(1).describe(
84378
86039
  "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
@@ -84388,7 +86049,7 @@ function registerPsmTools(server, getB) {
84388
86049
  const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84389
86050
  const gate = requireConfirmation(
84390
86051
  confirmed,
84391
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
86052
+ `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (exact-amount approval if the standing allowance does not cover it, then ${direction === "to-ucd" ? "swap" : "redeem"})`
84392
86053
  );
84393
86054
  if (gate) return gate;
84394
86055
  const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
@@ -84574,7 +86235,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
84574
86235
 
84575
86236
  // src/tools/signer.ts
84576
86237
  var import_zod6 = require("zod");
84577
- var import_ethers41 = require("ethers");
86238
+ var import_ethers51 = require("ethers");
84578
86239
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
84579
86240
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
84580
86241
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -84616,7 +86277,7 @@ function registerSignerTool(server, getRuntime, opts) {
84616
86277
  if (mode !== void 0 && !offeredModes.includes(mode)) {
84617
86278
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
84618
86279
  }
84619
- if (safeAddress !== void 0 && !import_ethers41.ethers.isAddress(safeAddress)) {
86280
+ if (safeAddress !== void 0 && !import_ethers51.ethers.isAddress(safeAddress)) {
84620
86281
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
84621
86282
  }
84622
86283
  if (action === "status") {
@@ -85027,7 +86688,7 @@ function registerBoundaryInfoResource(server, getB) {
85027
86688
  }
85028
86689
 
85029
86690
  // src/version.ts
85030
- var SERVER_VERSION = "0.5.15";
86691
+ var SERVER_VERSION = "0.5.17";
85031
86692
 
85032
86693
  // src/server.ts
85033
86694
  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. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";