@gvnrdao/dh-mcp 0.5.16 → 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/connector.js CHANGED
@@ -15552,7 +15552,7 @@ ${errorReport}`);
15552
15552
  }
15553
15553
  init_debug_logger();
15554
15554
  init_session_signature_cache();
15555
- var import_ethers43 = require("ethers");
15555
+ var import_ethers53 = require("ethers");
15556
15556
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15557
15557
  var GRACE_PERIOD_DAYS = 30;
15558
15558
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -18468,12 +18468,12 @@ ${auth.clientId}`;
18468
18468
  }
18469
18469
  async function executeVaultSnapshot(params) {
18470
18470
  global.ethers = {
18471
- ...import_ethers43.ethers,
18471
+ ...import_ethers53.ethers,
18472
18472
  providers: {
18473
- StaticJsonRpcProvider: import_ethers43.ethers.JsonRpcProvider
18473
+ StaticJsonRpcProvider: import_ethers53.ethers.JsonRpcProvider
18474
18474
  },
18475
- Contract: import_ethers43.ethers.Contract,
18476
- utils: import_ethers43.ethers
18475
+ Contract: import_ethers53.ethers.Contract,
18476
+ utils: import_ethers53.ethers
18477
18477
  // v6 moved utils to top level
18478
18478
  };
18479
18479
  global.Lit = {
@@ -25682,7 +25682,10 @@ var require_lit_core_lit_action_client = __commonJS({
25682
25682
  "node_modules/@gvnrdao/dh-lit-ops/dist/utils/lit-core-lit-action-client.js"(exports2) {
25683
25683
  "use strict";
25684
25684
  Object.defineProperty(exports2, "__esModule", { value: true });
25685
+ exports2.CORE_API_TRANSPORT_FAILURE_MARKER = void 0;
25685
25686
  exports2.normalizeCoreLitActionResult = normalizeCoreLitActionResult;
25687
+ exports2.describeErrorWithCause = describeErrorWithCause;
25688
+ exports2.isCoreApiTransportError = isCoreApiTransportError;
25686
25689
  exports2.executeLitActionViaCoreApi = executeLitActionViaCoreApi;
25687
25690
  var fetch_lit_action_from_ipfs_1 = require_fetch_lit_action_from_ipfs();
25688
25691
  function parseResponsePayload(raw) {
@@ -25733,6 +25736,27 @@ var require_lit_core_lit_action_client = __commonJS({
25733
25736
  const fromEnv = process.env.LIT_CORE_API_BASE_URL;
25734
25737
  return (explicit || fromEnv || "https://api.chipotle.litprotocol.com").replace(/\/$/, "");
25735
25738
  }
25739
+ exports2.CORE_API_TRANSPORT_FAILURE_MARKER = "Lit Core lit_action transport failure";
25740
+ function describeErrorWithCause(e) {
25741
+ const parts = [];
25742
+ let current = e;
25743
+ const seen = /* @__PURE__ */ new Set();
25744
+ while (current != null && !seen.has(current) && parts.length < 5) {
25745
+ seen.add(current);
25746
+ if (current instanceof Error) {
25747
+ const code = current.code;
25748
+ parts.push(typeof code === "string" && !current.message.includes(code) ? `${code}: ${current.message}` : current.message);
25749
+ current = current.cause;
25750
+ } else {
25751
+ parts.push(String(current));
25752
+ break;
25753
+ }
25754
+ }
25755
+ return parts.length === 0 ? String(e) : parts.join(" <- ");
25756
+ }
25757
+ function isCoreApiTransportError(message) {
25758
+ return message.includes(exports2.CORE_API_TRANSPORT_FAILURE_MARKER);
25759
+ }
25736
25760
  async function executeLitActionViaCoreApi(options) {
25737
25761
  let resolvedCode = options.code || "";
25738
25762
  if (!resolvedCode.trim()) {
@@ -25794,13 +25818,11 @@ var require_lit_core_lit_action_client = __commonJS({
25794
25818
  return normalizeCoreLitActionResult(body);
25795
25819
  } catch (e) {
25796
25820
  const msg = e instanceof Error ? e.message : String(e);
25821
+ const error = msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : `${exports2.CORE_API_TRANSPORT_FAILURE_MARKER}: ${describeErrorWithCause(e)}`;
25797
25822
  if (options.debug) {
25798
- console.error("\u274C [executeLitActionViaCoreApi]", msg);
25823
+ console.error("\u274C [executeLitActionViaCoreApi]", error);
25799
25824
  }
25800
- return {
25801
- success: false,
25802
- error: msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : msg
25803
- };
25825
+ return { success: false, error };
25804
25826
  } finally {
25805
25827
  clearTimeout(timer);
25806
25828
  }
@@ -26782,7 +26804,8 @@ var require_lit_ops_module = __commonJS({
26782
26804
  const borrowerAddress = borrowerOverride ?? this.config.serverAddress ?? await this.config.signer.getAddress();
26783
26805
  const pkpValidatorInfo = DH_LIT_ACTIONS_CHIPOTLE.pkpValidator;
26784
26806
  const validatorWalletAddress = process.env.LIT_PKP_VALIDATOR_WALLET_OVERRIDE || pkpValidatorInfo?.validatorWalletAddress;
26785
- const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(e instanceof Error ? e.message : String(e));
26807
+ const errorMessage = (e) => e instanceof Error ? e.message : String(e);
26808
+ const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(errorMessage(e));
26786
26809
  const propagationRetries = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_RETRIES) || 8;
26787
26810
  const propagationDelayMs = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_DELAY_MS) || 15e3;
26788
26811
  let coreResponse;
@@ -26803,10 +26826,12 @@ var require_lit_ops_module = __commonJS({
26803
26826
  coreResponse = exec.response;
26804
26827
  break;
26805
26828
  } catch (e) {
26806
- if (!isWalletPropagationError(e) || attempt === propagationRetries) {
26829
+ const propagating = isWalletPropagationError(e);
26830
+ const transport = (0, lit_core_lit_action_client_1.isCoreApiTransportError)(errorMessage(e));
26831
+ if (!propagating && !transport || attempt === propagationRetries) {
26807
26832
  throw e;
26808
26833
  }
26809
- console.log(`[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
26834
+ 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`);
26810
26835
  await new Promise((r) => setTimeout(r, propagationDelayMs));
26811
26836
  }
26812
26837
  }
@@ -40531,7 +40556,7 @@ var require_dist3 = __commonJS({
40531
40556
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
40532
40557
  };
40533
40558
  Object.defineProperty(exports2, "__esModule", { value: true });
40534
- 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;
40559
+ 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;
40535
40560
  __exportStar(require_interfaces(), exports2);
40536
40561
  var dh_lit_actions_1 = require_pkg_src();
40537
40562
  Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
@@ -40601,6 +40626,15 @@ var require_dist3 = __commonJS({
40601
40626
  Object.defineProperty(exports2, "normalizeCoreLitActionResult", { enumerable: true, get: function() {
40602
40627
  return lit_core_lit_action_client_1.normalizeCoreLitActionResult;
40603
40628
  } });
40629
+ Object.defineProperty(exports2, "describeErrorWithCause", { enumerable: true, get: function() {
40630
+ return lit_core_lit_action_client_1.describeErrorWithCause;
40631
+ } });
40632
+ Object.defineProperty(exports2, "isCoreApiTransportError", { enumerable: true, get: function() {
40633
+ return lit_core_lit_action_client_1.isCoreApiTransportError;
40634
+ } });
40635
+ Object.defineProperty(exports2, "CORE_API_TRANSPORT_FAILURE_MARKER", { enumerable: true, get: function() {
40636
+ return lit_core_lit_action_client_1.CORE_API_TRANSPORT_FAILURE_MARKER;
40637
+ } });
40604
40638
  var bitcoin_signature_1 = require_bitcoin_signature();
40605
40639
  Object.defineProperty(exports2, "convertEthereumSignatureToBitcoinDER", { enumerable: true, get: function() {
40606
40640
  return bitcoin_signature_1.convertEthereumSignatureToBitcoinDER;
@@ -41032,7 +41066,7 @@ function htmlPageSecurityHeaders(extra) {
41032
41066
  }
41033
41067
 
41034
41068
  // src/version.ts
41035
- var SERVER_VERSION = "0.5.16";
41069
+ var SERVER_VERSION = "0.5.17";
41036
41070
 
41037
41071
  // src/connector/siwe-oauth.ts
41038
41072
  var import_node_crypto2 = require("crypto");
@@ -41750,7 +41784,7 @@ function resolveRealConfig(env) {
41750
41784
 
41751
41785
  // src/boot.ts
41752
41786
  var fs6 = __toESM(require("fs"));
41753
- var import_ethers40 = require("ethers");
41787
+ var import_ethers50 = require("ethers");
41754
41788
 
41755
41789
  // src/boundary/index.ts
41756
41790
  var import_node_crypto9 = require("crypto");
@@ -42167,7 +42201,7 @@ var BoundaryCore = class {
42167
42201
  const inToken = toUcd ? s.stablecoinSymbol : "UCD";
42168
42202
  const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
42169
42203
  const amountIn = parseDecimalUnits(p.amount, inDecimals);
42170
- const refuse = (refusal, message, details) => ({
42204
+ const refuse3 = (refusal, message, details) => ({
42171
42205
  env: errEnvelope(
42172
42206
  boundaryError("UPSTREAM_REJECTED", message, {
42173
42207
  source: statusR.source.id,
@@ -42178,13 +42212,13 @@ var BoundaryCore = class {
42178
42212
  });
42179
42213
  const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
42180
42214
  if (s.paused) {
42181
- return refuse(
42215
+ return refuse3(
42182
42216
  "psm-paused",
42183
42217
  "the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
42184
42218
  );
42185
42219
  }
42186
42220
  if (!toUcd && !s.redeemEnabled) {
42187
- return refuse(
42221
+ return refuse3(
42188
42222
  "redeem-disabled",
42189
42223
  `redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
42190
42224
  );
@@ -42195,20 +42229,20 @@ var BoundaryCore = class {
42195
42229
  const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
42196
42230
  const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
42197
42231
  if (amountIn < min) {
42198
- return refuse(
42232
+ return refuse3(
42199
42233
  "below-min",
42200
42234
  `${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
42201
42235
  { amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
42202
42236
  );
42203
42237
  }
42204
42238
  if (max === 0n) {
42205
- return refuse(
42239
+ return refuse3(
42206
42240
  "direction-disabled",
42207
42241
  `the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
42208
42242
  );
42209
42243
  }
42210
42244
  if (amountIn > max) {
42211
- return refuse(
42245
+ return refuse3(
42212
42246
  "above-max",
42213
42247
  `${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
42214
42248
  { amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
@@ -42228,7 +42262,7 @@ var BoundaryCore = class {
42228
42262
  if (!toUcd) {
42229
42263
  const available = BigInt(s.availableReserves);
42230
42264
  if (available < amountOut) {
42231
- return refuse(
42265
+ return refuse3(
42232
42266
  "insufficient-reserves",
42233
42267
  `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).`,
42234
42268
  { available: available.toString(), required: amountOut.toString(), unit: outUnit }
@@ -42304,20 +42338,31 @@ var BoundaryCore = class {
42304
42338
  const inDecimals = toUcd ? s.stablecoinDecimals : 18;
42305
42339
  const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
42306
42340
  const viaSafe = this.deps.signer?.mode() === "safe";
42341
+ const a = v.allowance;
42342
+ const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
42343
+ 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(
42344
+ (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}`
42345
+ ).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
42307
42346
  const data = {
42308
42347
  direction: p.direction,
42309
42348
  contractCall: q.contractCall,
42310
- approve: {
42311
- txRef: v.approve.txRef,
42312
- token: v.approve.tokenSymbol,
42313
- tokenAddress: v.approve.tokenAddress,
42314
- spenderAddress: v.approve.spenderAddress,
42315
- spenderContract: v.approve.spenderContract,
42316
- 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",
42317
- amount: v.approve.amount,
42349
+ allowance: {
42350
+ token: a.tokenSymbol,
42351
+ tokenAddress: a.tokenAddress,
42352
+ spenderAddress: a.spenderAddress,
42353
+ spenderContract: a.spenderContract,
42354
+ 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",
42355
+ before: a.before,
42318
42356
  amountUnit: q.amountInUnit,
42319
- authorization: v.approve.authorization
42357
+ 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."
42320
42358
  },
42359
+ approvals: v.approvals.map((leg) => ({
42360
+ step: leg.step,
42361
+ txRef: leg.txRef,
42362
+ amount: leg.amount,
42363
+ amountUnit: q.amountInUnit,
42364
+ authorization: leg.authorization
42365
+ })),
42321
42366
  execute: {
42322
42367
  txRef: v.execute.txRef,
42323
42368
  amountIn: v.execute.amountIn,
@@ -42339,7 +42384,7 @@ var BoundaryCore = class {
42339
42384
  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"
42340
42385
  },
42341
42386
  balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
42342
- 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}.`)
42387
+ 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}.`)
42343
42388
  };
42344
42389
  return okEnvelope(data, r.source, warnings);
42345
42390
  }
@@ -44198,6 +44243,16 @@ function buildExtendTx(ctx, p) {
44198
44243
  );
44199
44244
  }
44200
44245
 
44246
+ // src/boundary/upstream/shared/psm-approval-steps.ts
44247
+ function psmApprovalSteps(allowanceBefore, amountIn) {
44248
+ if (allowanceBefore >= amountIn) return [];
44249
+ if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
44250
+ return [
44251
+ { step: "reset-approve", amount: 0n },
44252
+ { step: "approve", amount: amountIn }
44253
+ ];
44254
+ }
44255
+
44201
44256
  // src/boundary/upstream/mock/sink-contracts.ts
44202
44257
  var import_ethers6 = require("ethers");
44203
44258
  function sinkAddress(label) {
@@ -45033,8 +45088,9 @@ var MockUpstreamPlugin = class {
45033
45088
  return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
45034
45089
  });
45035
45090
  }
45036
- /** PSM exchange pair (plan 08 W1): TWO ceremonies in ONE ops call — the exact-amount
45037
- * approve (spender asymmetric by direction, contract truth), then the swap/redeem with
45091
+ /** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
45092
+ * or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
45093
+ * asymmetric by direction, contract truth), then the swap/redeem with
45038
45094
  * its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
45039
45095
  * AFTER the approve reports the step that declined AND the residual exact-amount
45040
45096
  * allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
@@ -45053,55 +45109,75 @@ var MockUpstreamPlugin = class {
45053
45109
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
45054
45110
  const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
45055
45111
  const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
45056
- 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`;
45057
- const approveCard = `approve exactly ${p.amountIn} ${tokenUnit} to ${spenderContract} (${spenderReason})`;
45112
+ const standing = this.world.psmAllowancesOf(p.borrower);
45113
+ const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
45114
+ const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
45115
+ const landed = [];
45116
+ const residualNote = () => {
45117
+ const last = landed[landed.length - 1];
45118
+ 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`;
45119
+ return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
45120
+ };
45058
45121
  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}`;
45059
45122
  const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
45060
45123
  const cer = this.ceremonyNow();
45061
- let approveAuth = null;
45062
- if (cer) {
45063
- const chainId = cer.txContext().chainId;
45064
- const approveTx = buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount: p.amountIn });
45065
- const r = await cer.authorizeTx({
45066
- action: "psm-approve",
45067
- borrower: p.borrower,
45068
- tx: approveTx,
45069
- expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn }
45070
- });
45071
- if (!r.ok) {
45072
- return upFail({
45073
- kind: "rejected",
45074
- source: "mock-ops",
45075
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(r.failure)} \u2014 no allowance was granted and no funds moved`
45124
+ const approvals = [];
45125
+ for (const s of steps) {
45126
+ const amount = s.amount.toString();
45127
+ const isReset = s.step === "reset-approve";
45128
+ const label = isReset ? "RESET-APPROVE" : "APPROVE";
45129
+ 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";
45130
+ 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})`;
45131
+ let legAuth = null;
45132
+ if (cer) {
45133
+ const chainId = cer.txContext().chainId;
45134
+ const r = await cer.authorizeTx({
45135
+ action: "psm-approve",
45136
+ borrower: p.borrower,
45137
+ tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
45138
+ expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
45076
45139
  });
45140
+ if (!r.ok) {
45141
+ return upFail({
45142
+ kind: "rejected",
45143
+ source: "mock-ops",
45144
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
45145
+ });
45146
+ }
45147
+ this.bindIfDiscovering(r.authorization);
45148
+ legAuth = r.authorization;
45077
45149
  }
45078
- this.bindIfDiscovering(r.authorization);
45079
- approveAuth = r.authorization;
45080
- }
45081
- const step1 = await this.write("psmSwap", () => {
45082
- const sig = approveAuth ? { ok: true, authorization: approveAuth } : this.sign("psm-approve", p.borrower, approveCard);
45083
- if (!sig.ok) {
45084
- return upFail({
45085
- kind: "rejected",
45086
- source: "mock-ops",
45087
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(sig.failure)} \u2014 no allowance was granted and no funds moved`
45150
+ const leg = await this.write("psmSwap", () => {
45151
+ const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
45152
+ if (!sig.ok) {
45153
+ return upFail({
45154
+ kind: "rejected",
45155
+ source: "mock-ops",
45156
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
45157
+ });
45158
+ }
45159
+ const applied = this.applyAuthorized(sig.authorization, () => {
45160
+ this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
45161
+ return { ok: true, value: void 0 };
45088
45162
  });
45089
- }
45090
- const applied = this.applyAuthorized(sig.authorization, () => {
45091
- this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount: p.amountIn });
45092
- return { ok: true, value: void 0 };
45163
+ if (!applied.ok) {
45164
+ return upFail({
45165
+ kind: "rejected",
45166
+ source: "mock-ops",
45167
+ message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
45168
+ });
45169
+ }
45170
+ return upOk(sig.authorization, this.src("mock-ops"));
45093
45171
  });
45094
- if (!applied.ok) {
45095
- return upFail({
45096
- kind: "rejected",
45097
- source: "mock-ops",
45098
- message: `psmSwap failed at the APPROVE step: ${applied.reason} \u2014 no allowance was granted and no funds moved`
45099
- });
45100
- }
45101
- return upOk(sig.authorization, this.src("mock-ops"));
45102
- });
45103
- if (!step1.ok) return step1;
45104
- const aAuth = step1.value;
45172
+ if (!leg.ok) return leg;
45173
+ landed.push(s.step);
45174
+ approvals.push({
45175
+ step: s.step,
45176
+ txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
45177
+ amount,
45178
+ authorization: leg.value
45179
+ });
45180
+ }
45105
45181
  let executeAuth = null;
45106
45182
  if (cer) {
45107
45183
  const chainId = cer.txContext().chainId;
@@ -45116,7 +45192,7 @@ var MockUpstreamPlugin = class {
45116
45192
  return upFail({
45117
45193
  kind: "rejected",
45118
45194
  source: "mock-ops",
45119
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
45195
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
45120
45196
  });
45121
45197
  }
45122
45198
  executeAuth = r.authorization;
@@ -45127,23 +45203,16 @@ var MockUpstreamPlugin = class {
45127
45203
  return upFail({
45128
45204
  kind: "rejected",
45129
45205
  source: "mock-ops",
45130
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
45206
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
45131
45207
  });
45132
45208
  }
45133
45209
  const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
45134
- if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
45210
+ if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
45135
45211
  const bal = this.world.balancesOf(p.borrower);
45136
45212
  return upOk(
45137
45213
  {
45138
- approve: {
45139
- txRef: approveAuth ? { kind: "eth-tx", id: aAuth.digest } : this.world.nextTxRef(),
45140
- tokenSymbol,
45141
- tokenAddress,
45142
- spenderAddress,
45143
- spenderContract,
45144
- amount: p.amountIn,
45145
- authorization: aAuth
45146
- },
45214
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
45215
+ approvals,
45147
45216
  execute: {
45148
45217
  txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
45149
45218
  amountIn: p.amountIn,
@@ -46324,7 +46393,7 @@ var SafeModuleCeremony = class {
46324
46393
  };
46325
46394
 
46326
46395
  // src/boundary/upstream/real/plugin.ts
46327
- var import_ethers39 = require("ethers");
46396
+ var import_ethers49 = require("ethers");
46328
46397
 
46329
46398
  // node_modules/@gvnrdao/dh-sdk/dist/index.mjs
46330
46399
  var import_ethers14 = require("ethers");
@@ -52415,8 +52484,12 @@ var {
52415
52484
  var import_ethers28 = require("ethers");
52416
52485
  var import_ethers29 = require("ethers");
52417
52486
  var import_ethers30 = require("ethers");
52418
- var import_dh_lit_ops = __toESM(require_dist3(), 1);
52419
52487
  var import_ethers31 = require("ethers");
52488
+ var import_ethers32 = require("ethers");
52489
+ var import_ethers33 = require("ethers");
52490
+ var import_ethers34 = require("ethers");
52491
+ var import_dh_lit_ops = __toESM(require_dist3(), 1);
52492
+ var import_ethers35 = require("ethers");
52420
52493
  var __create2 = Object.create;
52421
52494
  var __defProp2 = Object.defineProperty;
52422
52495
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -54779,7 +54852,7 @@ ${errorReport}`);
54779
54852
  }
54780
54853
  init_debug_logger();
54781
54854
  init_session_signature_cache();
54782
- var import_ethers192 = __require("ethers");
54855
+ var import_ethers232 = __require("ethers");
54783
54856
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
54784
54857
  var GRACE_PERIOD_DAYS = 30;
54785
54858
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -57707,12 +57780,12 @@ ${auth.clientId}`;
57707
57780
  }
57708
57781
  async function executeVaultSnapshot(params) {
57709
57782
  global.ethers = {
57710
- ...import_ethers192.ethers,
57783
+ ...import_ethers232.ethers,
57711
57784
  providers: {
57712
- StaticJsonRpcProvider: import_ethers192.ethers.JsonRpcProvider
57785
+ StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
57713
57786
  },
57714
- Contract: import_ethers192.ethers.Contract,
57715
- utils: import_ethers192.ethers
57787
+ Contract: import_ethers232.ethers.Contract,
57788
+ utils: import_ethers232.ethers
57716
57789
  // v6 moved utils to top level
57717
57790
  };
57718
57791
  global.Lit = {
@@ -57966,8 +58039,8 @@ function getSepoliaConfig() {
57966
58039
  positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
57967
58040
  positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
57968
58041
  simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
57969
- mockUsdcToken: SEPOLIA_CONTRACTS["MockUSDC"] || "",
57970
- mockUsdtToken: SEPOLIA_CONTRACTS["MockUSDT"] || "",
58042
+ mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
58043
+ mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
57971
58044
  loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
57972
58045
  termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
57973
58046
  circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
@@ -58043,14 +58116,17 @@ function getMainnetConfig() {
58043
58116
  agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
58044
58117
  },
58045
58118
  subgraphs: {
58046
- // KNOWN-WRONG placeholder (see GOAL-PLAN step 2 / dogfood F-CLI-4): this is a
58047
- // SEPOLIA subgraph id in a mainnet (chainId 1) config, and this gateway host
58048
- // needs an Authorization key the SDK does not (and must not) hold — so the
58049
- // URL is doubly unusable. The `CCTPsd…` path segment is the subgraph's
58050
- // PUBLIC ID, not a credential. The fix is a chain-correct SERVER-side proxy
58051
- // (see mcp/docs/SUBGRAPH-PROXY-PLAN.md) — same rule as rpcUrls above:
58052
- // never ship an API-keyed URL in a client config.
58053
- diamondHandsUrl: "https://gateway-arbitrum.network.thegraph.com/api/subgraphs/id/CCTPsdYqco2jChDLLBQTbdJWwoukVoMt1cXeR9ti6r9A"
58119
+ // The MAINNET subgraph on The Graph's decentralized network — the same id
58120
+ // lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
58121
+ // the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
58122
+ // chainId-1 config: unusable as shipped, but a caller who added their own key would have
58123
+ // read Sepolia data as mainnet.
58124
+ //
58125
+ // The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
58126
+ // not) hold, so this URL only works for a standalone caller supplying their own key.
58127
+ // Service mode never uses it — queries go through the lit-ops-server proxy, which adds
58128
+ // the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
58129
+ diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
58054
58130
  },
58055
58131
  litNetwork: "chipotle",
58056
58132
  debug: false
@@ -59071,6 +59147,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
59071
59147
  }
59072
59148
  return { timestamp: result.timestamp, signature: result.signature };
59073
59149
  }
59150
+ function baseMintFeeWei(mintAmountWei, originationFeeBps) {
59151
+ if (mintAmountWei < 0n)
59152
+ throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
59153
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59154
+ throw new Error(
59155
+ `baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59156
+ );
59157
+ }
59158
+ return mintAmountWei * BigInt(originationFeeBps) / 10000n;
59159
+ }
59160
+ function debtAfterMintExceedsLoanCap(params) {
59161
+ const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
59162
+ for (const [name, v] of Object.entries(params)) {
59163
+ if (v < 0n)
59164
+ throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
59165
+ }
59166
+ return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
59167
+ }
59168
+ function maxPrincipalWithinLoanCap(params) {
59169
+ const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
59170
+ if (maxLoanWei < 0n || currentDebtWei < 0n) {
59171
+ throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
59172
+ }
59173
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59174
+ throw new Error(
59175
+ `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59176
+ );
59177
+ }
59178
+ const room = maxLoanWei - currentDebtWei;
59179
+ if (room <= 0n)
59180
+ return 0n;
59181
+ return room * 10000n / (10000n + BigInt(originationFeeBps));
59182
+ }
59074
59183
  function buildLoginDomain(chainId) {
59075
59184
  return {
59076
59185
  name: "Diamond Hands",
@@ -60480,23 +60589,37 @@ var BitcoinUtils = class {
60480
60589
  return getBitcoinAddressesFromPkp(pkpPublicKey);
60481
60590
  }
60482
60591
  };
60483
- function safeValidateBitcoinAddress(address, network = "regtest") {
60592
+ function networksOfValidAddress(address) {
60593
+ const lower2 = address.toLowerCase();
60594
+ if (lower2.startsWith("bcrt1"))
60595
+ return ["regtest"];
60596
+ if (lower2.startsWith("bc1"))
60597
+ return ["mainnet"];
60598
+ if (lower2.startsWith("tb1"))
60599
+ return ["testnet"];
60600
+ if (address.startsWith("1") || address.startsWith("3"))
60601
+ return ["mainnet"];
60602
+ return ["testnet", "regtest"];
60603
+ }
60604
+ function safeValidateBitcoinAddress(address, network) {
60484
60605
  if (!address || typeof address !== "string") {
60485
60606
  throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
60486
60607
  }
60487
- const base58Pattern = /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/;
60488
- const bech32Pattern = /^(bc1|tb1|bcrt1)[a-z0-9]+$/;
60489
- if (!base58Pattern.test(address) && !bech32Pattern.test(address)) {
60490
- throw new Error(`Invalid Bitcoin address format: ${address}`);
60608
+ if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
60609
+ throw new Error(
60610
+ `Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
60611
+ );
60491
60612
  }
60492
- if (network === "regtest" || network === "testnet") {
60493
- if (!address.startsWith("m") && !address.startsWith("n") && !address.startsWith("2") && !address.startsWith("tb1") && !address.startsWith("bcrt1")) {
60494
- throw new Error(`Invalid ${network} Bitcoin address: ${address} (must start with m, n, 2, tb1, or bcrt1)`);
60495
- }
60496
- } else if (network === "mainnet") {
60497
- if (!address.startsWith("1") && !address.startsWith("3") && !address.startsWith("bc1")) {
60498
- throw new Error(`Invalid mainnet Bitcoin address: ${address} (must start with 1, 3, or bc1)`);
60499
- }
60613
+ if (!BitcoinUtils.validateAddress(address)) {
60614
+ throw new Error(
60615
+ `Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
60616
+ );
60617
+ }
60618
+ const belongsTo = networksOfValidAddress(address);
60619
+ if (!belongsTo.includes(network)) {
60620
+ throw new Error(
60621
+ `Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
60622
+ );
60500
60623
  }
60501
60624
  return address;
60502
60625
  }
@@ -62605,6 +62728,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
62605
62728
  LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
62606
62729
  return LoanStatus2;
62607
62730
  })(LoanStatus || {});
62731
+ var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
62732
+ var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
62733
+ var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
62734
+ async function collectBorrowerDebtRows(fetchPage) {
62735
+ const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
62736
+ const rows = [];
62737
+ for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
62738
+ const batch = await fetchPage(page * pageSize, pageSize);
62739
+ if (batch.length > pageSize) {
62740
+ throw new Error(
62741
+ `Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
62742
+ );
62743
+ }
62744
+ rows.push(...batch);
62745
+ if (batch.length < pageSize) {
62746
+ return rows;
62747
+ }
62748
+ }
62749
+ throw new Error(
62750
+ `Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
62751
+ );
62752
+ }
62753
+ function parseSubgraphLoanStatus(label) {
62754
+ if (typeof label !== "string") {
62755
+ throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
62756
+ }
62757
+ const value = LoanStatus[label];
62758
+ if (typeof value !== "number") {
62759
+ throw new Error(`Unknown subgraph loan status label: "${label}"`);
62760
+ }
62761
+ return value;
62762
+ }
62763
+ function parseSubgraphWei(row) {
62764
+ const raw = row.ucdDebt || "0";
62765
+ if (typeof raw !== "string") {
62766
+ throw new Error(
62767
+ `ucdDebt on position ${row.id} is not a string: ${String(raw)}`
62768
+ );
62769
+ }
62770
+ let wei;
62771
+ try {
62772
+ wei = BigInt(raw);
62773
+ } catch (error) {
62774
+ throw new Error(
62775
+ `ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
62776
+ { cause: error }
62777
+ );
62778
+ }
62779
+ if (wei < 0n) {
62780
+ throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
62781
+ }
62782
+ return wei;
62783
+ }
62784
+ var WEI_PER_UCD = 10n ** 18n;
62785
+ function weiToHumanUcdString(wei) {
62786
+ if (wei < 0n) {
62787
+ throw new Error(`Cannot render negative wei: ${wei}`);
62788
+ }
62789
+ const whole = wei / WEI_PER_UCD;
62790
+ const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
62791
+ return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
62792
+ }
62793
+ var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
62794
+ function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
62795
+ let totalWei = 0n;
62796
+ const counts = /* @__PURE__ */ new Map();
62797
+ for (const row of rows) {
62798
+ totalWei += parseSubgraphWei(row);
62799
+ const status = parseSubgraphLoanStatus(row.status);
62800
+ counts.set(status, (counts.get(status) ?? 0) + 1);
62801
+ }
62802
+ const byStatus = [];
62803
+ for (const status of STATUS_ORDINALS) {
62804
+ const count = counts.get(status);
62805
+ if (count === void 0) {
62806
+ continue;
62807
+ }
62808
+ byStatus.push({ status, statusLabel: LoanStatus[status], count });
62809
+ }
62810
+ return {
62811
+ borrower: borrower.toLowerCase(),
62812
+ loanCount: rows.length,
62813
+ totalUcdDebt: totalWei.toString(),
62814
+ totalUcdDebtHuman: weiToHumanUcdString(totalWei),
62815
+ byStatus,
62816
+ source: "subgraph",
62817
+ fetchedAt
62818
+ };
62819
+ }
62608
62820
  var POSITION_CORE_ABI = [
62609
62821
  "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))"
62610
62822
  ];
@@ -62997,6 +63209,43 @@ var LoanQuery = class {
62997
63209
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
62998
63210
  return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
62999
63211
  }
63212
+ /**
63213
+ * Combined UCD debt + by-status counts for a borrower from ONE pass over the
63214
+ * subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
63215
+ * status labels, `source: "subgraph"`.
63216
+ *
63217
+ * INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
63218
+ * sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
63219
+ * failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
63220
+ * is no partial total.
63221
+ */
63222
+ async getBorrowerUcdDebtSummary(borrower) {
63223
+ const trimmed = typeof borrower === "string" ? borrower.trim() : "";
63224
+ if (!(0, import_ethers26.isAddress)(trimmed)) {
63225
+ return failure(
63226
+ new SDKError({
63227
+ message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
63228
+ category: "VALIDATION",
63229
+ severity: "LOW",
63230
+ context: { borrower: trimmed }
63231
+ })
63232
+ );
63233
+ }
63234
+ return tryCatchAsync(
63235
+ async () => {
63236
+ const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
63237
+ return buildBorrowerUcdDebtSummary(trimmed, rows);
63238
+ },
63239
+ (error) => error instanceof SDKError ? error : new SDKError({
63240
+ message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
63241
+ category: "SUBGRAPH",
63242
+ severity: "MEDIUM",
63243
+ originalError: error instanceof Error ? error : void 0,
63244
+ cause: error,
63245
+ context: { borrower: trimmed }
63246
+ })
63247
+ );
63248
+ }
63000
63249
  /**
63001
63250
  * Get active loans (status = ACTIVE)
63002
63251
  *
@@ -64522,7 +64771,35 @@ var GraphClient = class {
64522
64771
  await new Promise((r) => setTimeout(r, ms));
64523
64772
  }
64524
64773
  };
64525
- var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
64774
+ var GET_USER_POSITIONS_DOCUMENT = `
64775
+ query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64776
+ user(id: $borrower) {
64777
+ id
64778
+ positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64779
+ id
64780
+ pkpId
64781
+ borrower {
64782
+ createdAt
64783
+ id
64784
+ }
64785
+ # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64786
+ ucdMinted
64787
+ ucdPaid
64788
+ ucdDebt
64789
+ collateralRatio
64790
+ requestedCollateralRatio
64791
+ selectedTerm
64792
+ status
64793
+ createdAt
64794
+ createdAtBlock
64795
+ lastUpdated
64796
+ originalTerm
64797
+ remainingDebt
64798
+ expiryAt
64799
+ }
64800
+ }
64801
+ }
64802
+ `;
64526
64803
  function normalizePkpId2(pkpId) {
64527
64804
  const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
64528
64805
  if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
@@ -64840,35 +65117,7 @@ var DiamondHandsGraph = class {
64840
65117
  * Get user positions from subgraph
64841
65118
  */
64842
65119
  async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
64843
- const query = `
64844
- query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64845
- user(id: $borrower) {
64846
- id
64847
- positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64848
- id
64849
- pkpId
64850
- borrower {
64851
- createdAt
64852
- id
64853
- }
64854
- # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64855
- ucdMinted
64856
- ucdPaid
64857
- ucdDebt
64858
- collateralRatio
64859
- requestedCollateralRatio
64860
- selectedTerm
64861
- status
64862
- createdAt
64863
- createdAtBlock
64864
- lastUpdated
64865
- originalTerm
64866
- remainingDebt
64867
- expiryAt
64868
- }
64869
- }
64870
- }
64871
- `;
65120
+ const query = GET_USER_POSITIONS_DOCUMENT;
64872
65121
  const variables = {
64873
65122
  borrower: userAddress.toLowerCase(),
64874
65123
  first: first || void 0,
@@ -64886,6 +65135,45 @@ var DiamondHandsGraph = class {
64886
65135
  }
64887
65136
  return positions;
64888
65137
  }
65138
+ /**
65139
+ * Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
65140
+ * 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
65141
+ * coerces wei to a float and leaves `status` a string cast to the numeric enum).
65142
+ *
65143
+ * Deliberately issues the `GetUserPositions` document rather than a leaner one: the
65144
+ * lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
65145
+ * and that one is already listed, so this needs no server change. The extra fields
65146
+ * cost bytes, not round trips.
65147
+ *
65148
+ * Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
65149
+ */
65150
+ async getBorrowerDebtRows(borrower) {
65151
+ const borrowerId = borrower.toLowerCase();
65152
+ return collectBorrowerDebtRows(async (skip, first) => {
65153
+ const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
65154
+ borrower: borrowerId,
65155
+ first,
65156
+ skip,
65157
+ orderBy: "id",
65158
+ orderDirection: "asc"
65159
+ });
65160
+ if (result?.user == null) {
65161
+ if (skip > 0) {
65162
+ throw new Error(
65163
+ `getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
65164
+ );
65165
+ }
65166
+ return [];
65167
+ }
65168
+ const positions = result.user.positions;
65169
+ if (!Array.isArray(positions)) {
65170
+ throw new Error(
65171
+ `getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
65172
+ );
65173
+ }
65174
+ return positions.filter((p) => p != null);
65175
+ });
65176
+ }
64889
65177
  /**
64890
65178
  * Get user positions, plus an accurate total count.
64891
65179
  *
@@ -71054,6 +71342,603 @@ async function mintAgentPkp(params) {
71054
71342
  clearTimeout(timeout);
71055
71343
  }
71056
71344
  }
71345
+ var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
71346
+ function planAgentBinding(params) {
71347
+ const { isActive, record, nowSeconds } = params;
71348
+ if (isActive)
71349
+ return { kind: "reuse", agent: record.agent };
71350
+ const status = Number(record.status);
71351
+ if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
71352
+ return { kind: "register" };
71353
+ }
71354
+ if (status !== AGENT_STATUS.Active) {
71355
+ throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
71356
+ }
71357
+ if (Number(record.validUntil) > nowSeconds) {
71358
+ throw new Error(
71359
+ "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
71360
+ );
71361
+ }
71362
+ return { kind: "rotate" };
71363
+ }
71364
+ async function describeProviderChainMismatch(provider, chainId) {
71365
+ const actual = Number((await provider.getNetwork()).chainId);
71366
+ if (actual === chainId)
71367
+ return null;
71368
+ 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.`;
71369
+ }
71370
+ var TxValidationError2 = class extends Error {
71371
+ /**
71372
+ * @param subject What is being refused. Defaults to the server-returned transaction the
71373
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
71374
+ */
71375
+ constructor(msg, subject = "server-returned transaction") {
71376
+ super(`Refusing to sign ${subject}: ${msg}`);
71377
+ this.name = "TxValidationError";
71378
+ }
71379
+ };
71380
+ var SIGNABLE_FUNCTIONS2 = [
71381
+ "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)",
71382
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
71383
+ // used to sit here; it is not a function on any deployed contract — the
71384
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
71385
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
71386
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
71387
+ // it. A signable-function whitelist should not carry calldata shapes the
71388
+ // protocol cannot execute.
71389
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
71390
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
71391
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
71392
+ // Struct-version: matches the actual on-chain function signature and the
71393
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
71394
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
71395
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
71396
+ "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)",
71397
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
71398
+ // function reverts permanently. The trustless replacement
71399
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
71400
+ // entry when its LIT Action ships.
71401
+ "function approve(address spender, uint256 amount) external returns (bool)",
71402
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
71403
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
71404
+ // without an entry here it decoded as "<unparseable>" and the CLI's
71405
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
71406
+ // collateral had no client-side pin at all.
71407
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
71408
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
71409
+ // AgentModule; the parity test documents them as client-only.
71410
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
71411
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
71412
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
71413
+ // this too is client-only and never module-whitelisted.
71414
+ "function addAddress(string btcAddress) external"
71415
+ ];
71416
+ var IFACE2 = new import_ethers32.ethers.Interface(SIGNABLE_FUNCTIONS2);
71417
+ function encodeSignable2(fn, args) {
71418
+ return IFACE2.encodeFunctionData(fn, args);
71419
+ }
71420
+ function decodeSignable2(data) {
71421
+ try {
71422
+ const parsed = IFACE2.parseTransaction({ data });
71423
+ if (!parsed) {
71424
+ throw new TxValidationError2(
71425
+ `unsignedTx.data does not decode against the signable-function whitelist`
71426
+ );
71427
+ }
71428
+ return { name: parsed.name, args: parsed.args };
71429
+ } catch (e) {
71430
+ if (e instanceof TxValidationError2)
71431
+ throw e;
71432
+ throw new TxValidationError2(
71433
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
71434
+ );
71435
+ }
71436
+ }
71437
+ var MAX_GAS_LIMIT = 5000000n;
71438
+ var MAX_FEE_PER_GAS_WEI = 2000000000000n;
71439
+ var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
71440
+ var DEFAULT_FEE_CEILING = {
71441
+ maxGasLimit: MAX_GAS_LIMIT,
71442
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
71443
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
71444
+ };
71445
+ function fmtEth(wei) {
71446
+ return `${import_ethers34.ethers.formatEther(wei)} ETH`;
71447
+ }
71448
+ function fmtGwei(wei) {
71449
+ return `${import_ethers34.ethers.formatUnits(wei, "gwei")} gwei`;
71450
+ }
71451
+ function worstCaseFeeWei(gasLimit, maxFeePerGas) {
71452
+ if (gasLimit == null || maxFeePerGas == null)
71453
+ return null;
71454
+ return gasLimit * maxFeePerGas;
71455
+ }
71456
+ function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
71457
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
71458
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
71459
+ }
71460
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
71461
+ raise(
71462
+ `maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
71463
+ );
71464
+ }
71465
+ const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
71466
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
71467
+ raise(
71468
+ `worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
71469
+ );
71470
+ }
71471
+ }
71472
+ function eqAddr2(a, b) {
71473
+ if (!a || !b)
71474
+ return false;
71475
+ try {
71476
+ return import_ethers33.ethers.getAddress(a) === import_ethers33.ethers.getAddress(b);
71477
+ } catch {
71478
+ return false;
71479
+ }
71480
+ }
71481
+ function readToAddress2(tx2) {
71482
+ const to = tx2["to"];
71483
+ if (typeof to !== "string") {
71484
+ throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
71485
+ }
71486
+ return to;
71487
+ }
71488
+ function readData2(tx2) {
71489
+ const data = tx2["data"];
71490
+ if (typeof data !== "string" || !data.startsWith("0x")) {
71491
+ throw new TxValidationError2(`unsignedTx.data missing or malformed`);
71492
+ }
71493
+ return data;
71494
+ }
71495
+ function readChainId2(tx2) {
71496
+ const c = tx2["chainId"];
71497
+ if (c == null)
71498
+ return null;
71499
+ if (typeof c === "number")
71500
+ return c;
71501
+ if (typeof c === "string")
71502
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
71503
+ if (typeof c === "bigint")
71504
+ return Number(c);
71505
+ return null;
71506
+ }
71507
+ function readOptionalBigInt(tx2, key) {
71508
+ const v = tx2[key];
71509
+ if (v == null)
71510
+ return null;
71511
+ try {
71512
+ if (typeof v === "bigint")
71513
+ return v;
71514
+ if (typeof v === "number")
71515
+ return BigInt(v);
71516
+ if (typeof v === "string")
71517
+ return BigInt(v);
71518
+ return BigInt(v.toString());
71519
+ } catch {
71520
+ throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
71521
+ }
71522
+ }
71523
+ function readValue2(tx2) {
71524
+ const v = tx2["value"];
71525
+ if (v == null)
71526
+ return 0n;
71527
+ if (typeof v === "string")
71528
+ return BigInt(v);
71529
+ if (typeof v === "number")
71530
+ return BigInt(v);
71531
+ if (typeof v === "bigint")
71532
+ return v;
71533
+ const maybe = v;
71534
+ if (typeof maybe.toBigInt === "function")
71535
+ return maybe.toBigInt();
71536
+ if (typeof maybe.toString === "function")
71537
+ return BigInt(maybe.toString());
71538
+ throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
71539
+ }
71540
+ function normalizePositionId2(id) {
71541
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
71542
+ return import_ethers33.ethers.zeroPadValue(hex, 32).toLowerCase();
71543
+ }
71544
+ function requirePositionId(actual, expected) {
71545
+ const txPositionId = String(actual).toLowerCase();
71546
+ if (txPositionId !== normalizePositionId2(expected)) {
71547
+ throw new TxValidationError2(
71548
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
71549
+ );
71550
+ }
71551
+ }
71552
+ function validateUnsignedTx2(unsignedTx, expected, vctx) {
71553
+ const txChainId = readChainId2(unsignedTx);
71554
+ if (txChainId == null) {
71555
+ throw new TxValidationError2(
71556
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
71557
+ );
71558
+ }
71559
+ if (txChainId !== vctx.chainId) {
71560
+ throw new TxValidationError2(
71561
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
71562
+ );
71563
+ }
71564
+ const value = readValue2(unsignedTx);
71565
+ if (value !== 0n) {
71566
+ throw new TxValidationError2(
71567
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
71568
+ );
71569
+ }
71570
+ assertFeeCeiling(
71571
+ readOptionalBigInt(unsignedTx, "gasLimit"),
71572
+ readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
71573
+ (msg) => {
71574
+ throw new TxValidationError2(msg);
71575
+ },
71576
+ vctx.feeCeiling
71577
+ );
71578
+ const to = readToAddress2(unsignedTx);
71579
+ const data = readData2(unsignedTx);
71580
+ const { name, args } = decodeSignable2(data);
71581
+ const pm = vctx.contracts.PositionManager;
71582
+ switch (expected.kind) {
71583
+ case "mint": {
71584
+ if (name !== "mintUCD") {
71585
+ throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
71586
+ }
71587
+ if (!eqAddr2(to, pm)) {
71588
+ throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
71589
+ }
71590
+ requirePositionId(args[0], expected.positionId);
71591
+ const txMintAmount = BigInt(String(args[1]));
71592
+ if (txMintAmount.toString() !== expected.amountWei) {
71593
+ throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
71594
+ }
71595
+ const txMintFee = BigInt(String(args[2]));
71596
+ if (txMintFee.toString() !== expected.mintFeeWei) {
71597
+ throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
71598
+ }
71599
+ break;
71600
+ }
71601
+ case "repay": {
71602
+ if (name !== "makePayment") {
71603
+ throw new TxValidationError2(`expected makePayment, server returned ${name}`);
71604
+ }
71605
+ if (!eqAddr2(to, pm)) {
71606
+ throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
71607
+ }
71608
+ requirePositionId(args[0], expected.positionId);
71609
+ const txAmount = BigInt(String(args[1]));
71610
+ if (txAmount.toString() !== expected.amountWei) {
71611
+ throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
71612
+ }
71613
+ break;
71614
+ }
71615
+ case "extend": {
71616
+ if (name !== "extendPosition") {
71617
+ throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
71618
+ }
71619
+ if (!eqAddr2(to, pm)) {
71620
+ throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
71621
+ }
71622
+ requirePositionId(args[0], expected.positionId);
71623
+ const txTerm = Number(args[1]);
71624
+ if (txTerm !== expected.selectedTerm) {
71625
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71626
+ }
71627
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
71628
+ const txFee = BigInt(String(args[5]));
71629
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
71630
+ if (txFee > upper) {
71631
+ throw new TxValidationError2(
71632
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
71633
+ );
71634
+ }
71635
+ }
71636
+ break;
71637
+ }
71638
+ case "withdraw-btc": {
71639
+ if (name !== "withdrawBTC") {
71640
+ throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
71641
+ }
71642
+ if (!eqAddr2(to, pm)) {
71643
+ throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
71644
+ }
71645
+ const paramsTuple = args[0];
71646
+ requirePositionId(paramsTuple[0], expected.positionId);
71647
+ const txWithdrawalAddress = String(paramsTuple[5]);
71648
+ if (txWithdrawalAddress !== expected.btcAddress) {
71649
+ throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
71650
+ }
71651
+ if (expected.upperBoundTotalDeduction != null) {
71652
+ const txDeduction = BigInt(String(paramsTuple[6]));
71653
+ const upper = BigInt(expected.upperBoundTotalDeduction);
71654
+ if (txDeduction > upper) {
71655
+ throw new TxValidationError2(
71656
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
71657
+ );
71658
+ }
71659
+ }
71660
+ break;
71661
+ }
71662
+ case "ucd-approve": {
71663
+ if (name !== "approve") {
71664
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71665
+ }
71666
+ const ucd = vctx.contracts.UCDToken;
71667
+ if (!eqAddr2(to, ucd)) {
71668
+ throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
71669
+ }
71670
+ const spender = String(args[0]);
71671
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
71672
+ if (!ok2) {
71673
+ throw new TxValidationError2(
71674
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
71675
+ );
71676
+ }
71677
+ const amt = BigInt(String(args[1]));
71678
+ const min = BigInt(expected.minAmountWei);
71679
+ if (amt < min) {
71680
+ throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
71681
+ }
71682
+ const SANITY_MAX = min * 1000n;
71683
+ if (amt > SANITY_MAX) {
71684
+ throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
71685
+ }
71686
+ break;
71687
+ }
71688
+ case "create-position": {
71689
+ if (name !== "createPosition") {
71690
+ throw new TxValidationError2(`expected createPosition, server returned ${name}`);
71691
+ }
71692
+ if (!eqAddr2(to, pm)) {
71693
+ throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
71694
+ }
71695
+ const txTerm = BigInt(String(args[4]));
71696
+ if (txTerm !== BigInt(expected.selectedTerm)) {
71697
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71698
+ }
71699
+ break;
71700
+ }
71701
+ case "set-position-delegate": {
71702
+ if (name !== "setPositionDelegate") {
71703
+ throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
71704
+ }
71705
+ if (!eqAddr2(to, expected.registryAddress)) {
71706
+ throw new TxValidationError2(
71707
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
71708
+ );
71709
+ }
71710
+ requirePositionId(args[0], expected.positionId);
71711
+ const txDelegate = String(args[1]);
71712
+ if (!eqAddr2(txDelegate, expected.delegate)) {
71713
+ throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
71714
+ }
71715
+ break;
71716
+ }
71717
+ case "bwar-add-address": {
71718
+ if (name !== "addAddress") {
71719
+ throw new TxValidationError2(`expected addAddress, decoded ${name}`);
71720
+ }
71721
+ if (!eqAddr2(to, expected.registryAddress)) {
71722
+ throw new TxValidationError2(
71723
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
71724
+ );
71725
+ }
71726
+ if (String(args[0]) !== expected.btcAddress) {
71727
+ throw new TxValidationError2(
71728
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
71729
+ );
71730
+ }
71731
+ break;
71732
+ }
71733
+ case "stablecoin-approve": {
71734
+ if (name !== "approve") {
71735
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71736
+ }
71737
+ if (!eqAddr2(to, expected.tokenAddress)) {
71738
+ throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
71739
+ }
71740
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71741
+ throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
71742
+ }
71743
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
71744
+ throw new TxValidationError2(
71745
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
71746
+ );
71747
+ }
71748
+ break;
71749
+ }
71750
+ case "ucd-approve-controller": {
71751
+ if (name !== "approve") {
71752
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71753
+ }
71754
+ if (!eqAddr2(to, expected.ucdTokenAddress)) {
71755
+ throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
71756
+ }
71757
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71758
+ throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
71759
+ }
71760
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
71761
+ throw new TxValidationError2(
71762
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
71763
+ );
71764
+ }
71765
+ break;
71766
+ }
71767
+ case "psm-swap": {
71768
+ if (name !== "swap")
71769
+ throw new TxValidationError2(`expected swap, server returned ${name}`);
71770
+ if (!eqAddr2(to, expected.psmAddress)) {
71771
+ throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
71772
+ }
71773
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71774
+ throw new TxValidationError2(`swap stablecoin mismatch`);
71775
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
71776
+ throw new TxValidationError2(`swap amountIn mismatch`);
71777
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71778
+ throw new TxValidationError2(`swap minUcdOut mismatch`);
71779
+ if (BigInt(expected.minOut) === 0n) {
71780
+ throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71781
+ }
71782
+ break;
71783
+ }
71784
+ case "psm-redeem": {
71785
+ if (name !== "redeem")
71786
+ throw new TxValidationError2(`expected redeem, server returned ${name}`);
71787
+ if (!eqAddr2(to, expected.psmAddress)) {
71788
+ throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
71789
+ }
71790
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71791
+ throw new TxValidationError2(`redeem stablecoin mismatch`);
71792
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
71793
+ throw new TxValidationError2(`redeem ucdAmount mismatch`);
71794
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71795
+ throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
71796
+ if (BigInt(expected.minOut) === 0n) {
71797
+ throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71798
+ }
71799
+ break;
71800
+ }
71801
+ default: {
71802
+ const _exhaustive = expected;
71803
+ throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
71804
+ }
71805
+ }
71806
+ }
71807
+ function buildPsmApproveTx(p) {
71808
+ return {
71809
+ to: p.token,
71810
+ data: encodeSignable2("approve", [p.spender, p.amount]),
71811
+ value: "0x0",
71812
+ chainId: p.chainId
71813
+ };
71814
+ }
71815
+ function buildPsmSwapTx2(p) {
71816
+ return {
71817
+ to: p.psm,
71818
+ data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
71819
+ value: "0x0",
71820
+ chainId: p.chainId
71821
+ };
71822
+ }
71823
+ function buildPsmRedeemTx2(p) {
71824
+ return {
71825
+ to: p.psm,
71826
+ data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
71827
+ value: "0x0",
71828
+ chainId: p.chainId
71829
+ };
71830
+ }
71831
+ var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
71832
+ var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
71833
+ function psmExchangeReadsFromProvider(provider, psmAddress) {
71834
+ const psm = new import_ethers31.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
71835
+ return {
71836
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
71837
+ allowance: async (token, owner, spender) => await new import_ethers31.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
71838
+ };
71839
+ }
71840
+ var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
71841
+ function requireAddress(direction, label, value) {
71842
+ if (!value || !import_ethers31.ethers.isAddress(value)) {
71843
+ throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
71844
+ }
71845
+ return import_ethers31.ethers.getAddress(value);
71846
+ }
71847
+ async function planPsmExchange(params) {
71848
+ const { direction, amountIn, minOut, vctx, reads } = params;
71849
+ const chainId = vctx.chainId;
71850
+ if (amountIn <= 0n) {
71851
+ throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
71852
+ }
71853
+ if (minOut <= 0n) {
71854
+ throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
71855
+ }
71856
+ const owner = requireAddress(direction, "owner", params.owner);
71857
+ const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
71858
+ const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
71859
+ const isSwap = direction === "swap";
71860
+ const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
71861
+ const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
71862
+ if (!await reads.isStablecoinSupported(stablecoin)) {
71863
+ throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
71864
+ }
71865
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
71866
+ const allowanceBefore = await reads.allowance(token, owner, spender);
71867
+ const approvals = [];
71868
+ if (allowanceBefore < amountIn) {
71869
+ if (allowanceBefore > 0n) {
71870
+ approvals.push({
71871
+ step: "reset-approve",
71872
+ tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
71873
+ expected: approveExpected(0n)
71874
+ });
71875
+ }
71876
+ approvals.push({
71877
+ step: "approve",
71878
+ tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
71879
+ expected: approveExpected(amountIn)
71880
+ });
71881
+ }
71882
+ const exec = isSwap ? {
71883
+ step: "swap",
71884
+ tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
71885
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
71886
+ } : {
71887
+ step: "redeem",
71888
+ tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
71889
+ expected: {
71890
+ kind: "psm-redeem",
71891
+ psmAddress: psm,
71892
+ stablecoin,
71893
+ amountUcdWei: amountIn.toString(),
71894
+ minOut: minOut.toString()
71895
+ }
71896
+ };
71897
+ for (const leg of [...approvals, exec]) {
71898
+ validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
71899
+ }
71900
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
71901
+ }
71902
+ async function executePsmPlan(plan, signer, vctx) {
71903
+ const approvalHashes = [];
71904
+ 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.`;
71905
+ const sendLeg = async (leg) => {
71906
+ const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
71907
+ validateUnsignedTx2({ ...request }, leg.expected, vctx);
71908
+ const sent = await signer.sendTransaction(request);
71909
+ const receipt = await sent.wait();
71910
+ if (!receipt)
71911
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
71912
+ if (receipt.status !== 1)
71913
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
71914
+ return { hash: sent.hash, blockNumber: receipt.blockNumber };
71915
+ };
71916
+ for (const leg of plan.approvals) {
71917
+ const landed = await sendLeg(leg).catch((e) => {
71918
+ throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71919
+ });
71920
+ approvalHashes.push(landed.hash);
71921
+ }
71922
+ const exec = await sendLeg(plan.exec).catch((e) => {
71923
+ throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71924
+ });
71925
+ return { ...exec, approvalHashes };
71926
+ }
71927
+ var LIT_ACTION_CHAIN_NAMES = Object.freeze({
71928
+ 1: "ethereum",
71929
+ 11155111: "sepolia",
71930
+ 1337: "hardhat",
71931
+ 31337: "hardhat"
71932
+ });
71933
+ function litActionChainNameForChainId(chainId) {
71934
+ const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
71935
+ if (!name) {
71936
+ throw new Error(
71937
+ `Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
71938
+ );
71939
+ }
71940
+ return name;
71941
+ }
71057
71942
  var MockTokenManager = class {
71058
71943
  config;
71059
71944
  constructor(config) {
@@ -72027,6 +72912,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72027
72912
  */
72028
72913
  static async create(config) {
72029
72914
  const userProvidedServiceEndpoint = config.serviceEndpoint;
72915
+ if (typeof config.chainId === "number" && config.provider) {
72916
+ const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
72917
+ if (mismatch) {
72918
+ return failure(
72919
+ new SDKError({
72920
+ message: mismatch,
72921
+ category: "CONFIGURATION",
72922
+ severity: "HIGH"
72923
+ /* HIGH */
72924
+ })
72925
+ );
72926
+ }
72927
+ }
72030
72928
  const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
72031
72929
  if (userProvidedServiceEndpoint) {
72032
72930
  enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
@@ -72677,6 +73575,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72677
73575
  if (this.config.debug) {
72678
73576
  log.info(` Position PKP ID: ${position2.pkpId}`);
72679
73577
  }
73578
+ const termsResult = await this.getTermsWithFees();
73579
+ if (!termsResult.success) {
73580
+ return {
73581
+ success: false,
73582
+ error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
73583
+ };
73584
+ }
73585
+ const positionTermMonths = Number(position2.selectedTerm);
73586
+ const positionTerm = termsResult.value.terms.find(
73587
+ (term) => term.termMonths === positionTermMonths
73588
+ );
73589
+ if (!positionTerm) {
73590
+ return {
73591
+ success: false,
73592
+ error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
73593
+ };
73594
+ }
73595
+ const currentDebtWei = BigInt(position2.ucdDebt);
73596
+ const baseFeeWei = baseMintFeeWei(
73597
+ requestAmountWei,
73598
+ positionTerm.originationFeeBps
73599
+ );
73600
+ if (debtAfterMintExceedsLoanCap({
73601
+ currentDebtWei,
73602
+ mintAmountWei: requestAmountWei,
73603
+ mintFeeWei: baseFeeWei,
73604
+ maxLoanWei: maxLoanValueWei
73605
+ })) {
73606
+ const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
73607
+ const maxPrincipalUcd = Number(
73608
+ maxPrincipalWithinLoanCap({
73609
+ maxLoanWei: maxLoanValueWei,
73610
+ currentDebtWei,
73611
+ originationFeeBps: positionTerm.originationFeeBps
73612
+ }) / BigInt(10 ** 18)
73613
+ );
73614
+ return {
73615
+ success: false,
73616
+ error: `Amount ${request.amount} UCD plus the ${positionTerm.originationFeeBps / 100}% origination fee (${(0, import_ethers14.formatEther)(baseFeeWei)} UCD) would take this loan's debt to ${(0, import_ethers14.formatEther)(debtAfterWei)} UCD, above the protocol maximum of ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD. The largest amount you can mint now is ${maxPrincipalUcd} UCD.`
73617
+ };
73618
+ }
73619
+ if (this.config.debug) {
73620
+ log.info(
73621
+ `\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers14.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD`,
73622
+ {}
73623
+ );
73624
+ }
72680
73625
  let pkpPublicKey;
72681
73626
  let pkpEthAddress;
72682
73627
  const pkpCache = this.cacheManager.getCache("pkp-data", {
@@ -72766,7 +73711,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72766
73711
  ` UCDController: ${contracts?.UCDController || "MISSING"}`
72767
73712
  );
72768
73713
  }
72769
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
73714
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
72770
73715
  const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
72771
73716
  if (this.config.debug) {
72772
73717
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -73366,6 +74311,25 @@ Error data: none`
73366
74311
  }
73367
74312
  const selector = simError.selector;
73368
74313
  const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
74314
+ const MINT_GUARD_CODES = {
74315
+ "1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
74316
+ "2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
74317
+ "3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
74318
+ };
74319
+ let loanCapDiagnostics = "";
74320
+ if (selector === "0xe6dd4d41") {
74321
+ const guardCode = BigInt(
74322
+ "0x" + String(simError.data).slice(10).padStart(64, "0")
74323
+ ).toString();
74324
+ const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
74325
+ loanCapDiagnostics = `
74326
+
74327
+ MintGuardFailed(${guardCode}): ${guardMeaning}
74328
+ Lit mintAmount: ${validationResponse.mintAmount}
74329
+ Lit mintFee: ${validationResponse.mintFee}
74330
+ Lit newDebt: ${validationResponse.newDebt}
74331
+ Protocol maximum: ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
74332
+ }
73369
74333
  const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
73370
74334
  selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
73371
74335
  selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
@@ -73411,7 +74375,7 @@ Quantum Timing Analysis:
73411
74375
  Error selector: ${selector}
73412
74376
  Error data: ${simError.data}
73413
74377
  Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
73414
- Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
74378
+ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
73415
74379
  );
73416
74380
  }
73417
74381
  const tx2 = await sendEip1559Transaction({
@@ -76019,7 +76983,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76019
76983
  ` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
76020
76984
  );
76021
76985
  }
76022
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
76986
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
76023
76987
  const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
76024
76988
  if (this.config.debug) {
76025
76989
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -76574,13 +77538,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76574
77538
  return { success: false, error: "Failed to resolve PKP public key" };
76575
77539
  }
76576
77540
  const chipotlePkpAddress = (0, import_ethers14.computeAddress)(publicKey);
76577
- const STANDALONE_CHAIN_NAMES = {
76578
- 1: "ethereum",
76579
- 11155111: "sepolia",
76580
- 1337: "hardhat",
76581
- 31337: "hardhat"
76582
- };
76583
- const chainName = STANDALONE_CHAIN_NAMES[chainId];
77541
+ const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
76584
77542
  if (!chainName) {
76585
77543
  return {
76586
77544
  success: false,
@@ -77802,6 +78760,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77802
78760
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
77803
78761
  return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
77804
78762
  }
78763
+ /**
78764
+ * Combined UCD debt (canonical wei string + display string) and by-status loan
78765
+ * counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
78766
+ * an INDEXED, informational figure that lags writes; never size a transaction
78767
+ * from it (repayments read the chain via `getPositionDetailsView`).
78768
+ *
78769
+ * Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
78770
+ * failure or past 10,000 positions; never returns a partial total.
78771
+ */
78772
+ async getBorrowerUcdDebtSummary(borrower) {
78773
+ return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
78774
+ }
77805
78775
  /**
77806
78776
  * Get all active loans
77807
78777
  *
@@ -77927,11 +78897,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77927
78897
  }
77928
78898
  /**
77929
78899
  * Execute a PSM stablecoin → UCD swap.
77930
- * Handles stablecoin approval to the PSM contract if the current allowance is insufficient.
78900
+ * Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
78901
+ * partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
77931
78902
  *
77932
78903
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
77933
78904
  * @param params.amountWei - Stablecoin amount in native decimals (bigint)
77934
- * @param params.minUcdOutWei - Minimum UCD to receive; reverts if below this (1% slippage guard)
78905
+ * @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
77935
78906
  * @param params.signer - Connected signer for the approval and swap transactions
77936
78907
  */
77937
78908
  async psmSwap(params) {
@@ -77941,32 +78912,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77941
78912
  "SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
77942
78913
  );
77943
78914
  }
77944
- const signerAddress = await params.signer.getAddress();
77945
- const erc20Abi = [
77946
- "function allowance(address owner, address spender) view returns (uint256)",
77947
- "function approve(address spender, uint256 amount) returns (bool)"
77948
- ];
77949
- const stablecoin = new import_ethers14.Contract(params.stablecoinAddress, erc20Abi, params.signer);
77950
- const allowance = await stablecoin.allowance(signerAddress, psmAddress);
77951
- if (allowance < params.amountWei) {
77952
- const approveTx = await stablecoin.approve(psmAddress, import_ethers14.MaxUint256);
77953
- await approveTx.wait();
77954
- }
77955
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77956
- const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
77957
- const receipt = await tx2.wait();
77958
- if (!receipt)
77959
- throw new Error("PSM swap transaction receipt unavailable");
77960
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78915
+ return this.runPsmExchange({
78916
+ direction: "swap",
78917
+ signer: params.signer,
78918
+ addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
78919
+ amountIn: params.amountWei,
78920
+ minOut: params.minUcdOutWei
78921
+ });
77961
78922
  }
77962
78923
  /**
77963
78924
  * Execute a PSM UCD → stablecoin redeem.
77964
- * Handles UCD approval to UCDController (not PSM) to satisfy the M-4 burn allowance guard:
77965
- * UCDToken.burn(from, amount) calls _spendAllowance(from, msg.sender=ucdController, amount).
78925
+ * Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
78926
+ * M-4 burn allowance guard: UCDToken.burn(from, amount) calls
78927
+ * _spendAllowance(from, msg.sender=ucdController, amount).
77966
78928
  *
77967
78929
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
77968
78930
  * @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
77969
- * @param params.minStablecoinOutWei - Minimum stablecoin to receive (slippage guard)
78931
+ * @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
77970
78932
  * @param params.signer - Connected signer
77971
78933
  */
77972
78934
  async psmRedeem(params) {
@@ -77979,23 +78941,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77979
78941
  throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
77980
78942
  if (!ucdControllerAddress)
77981
78943
  throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
77982
- const signerAddress = await params.signer.getAddress();
77983
- const erc20Abi = [
77984
- "function allowance(address owner, address spender) view returns (uint256)",
77985
- "function approve(address spender, uint256 amount) returns (bool)"
77986
- ];
77987
- const ucdToken = new import_ethers14.Contract(ucdAddress, erc20Abi, params.signer);
77988
- const allowance = await ucdToken.allowance(signerAddress, ucdControllerAddress);
77989
- if (allowance < params.ucdAmountWei) {
77990
- const approveTx = await ucdToken.approve(ucdControllerAddress, import_ethers14.MaxUint256);
77991
- await approveTx.wait();
77992
- }
77993
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77994
- const tx2 = await psm.redeem(params.stablecoinAddress, params.ucdAmountWei, params.minStablecoinOutWei);
77995
- const receipt = await tx2.wait();
77996
- if (!receipt)
77997
- throw new Error("PSM redeem transaction receipt unavailable");
77998
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78944
+ return this.runPsmExchange({
78945
+ direction: "redeem",
78946
+ signer: params.signer,
78947
+ addresses: {
78948
+ psm: psmAddress,
78949
+ stablecoin: params.stablecoinAddress,
78950
+ ucdToken: ucdAddress,
78951
+ ucdController: ucdControllerAddress
78952
+ },
78953
+ amountIn: params.ucdAmountWei,
78954
+ minOut: params.minStablecoinOutWei
78955
+ });
78956
+ }
78957
+ /**
78958
+ * Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
78959
+ * The signer's chain must match the SDK's configured chain — the addresses came from it.
78960
+ */
78961
+ async runPsmExchange(params) {
78962
+ const provider = params.signer.provider;
78963
+ if (!provider) {
78964
+ throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
78965
+ }
78966
+ const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
78967
+ if (typeof configuredChainId !== "number") {
78968
+ throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
78969
+ }
78970
+ const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
78971
+ if (mismatch)
78972
+ throw new Error(mismatch);
78973
+ const vctx = {
78974
+ chainId: configuredChainId,
78975
+ network: String(configuredChainId),
78976
+ contracts: {}
78977
+ };
78978
+ const plan = await planPsmExchange({
78979
+ direction: params.direction,
78980
+ owner: await params.signer.getAddress(),
78981
+ addresses: params.addresses,
78982
+ amountIn: params.amountIn,
78983
+ minOut: params.minOut,
78984
+ vctx,
78985
+ reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
78986
+ });
78987
+ const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
78988
+ return { hash, blockNumber };
77999
78989
  }
78000
78990
  /**
78001
78991
  * Wait for the subgraph to index up to (and including) the given block number.
@@ -78176,18 +79166,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
78176
79166
  const user = await signer.getAddress();
78177
79167
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
78178
79168
  let agentAddress;
78179
- const hasActiveAgent = await registry.isAgentActive(user);
78180
- if (hasActiveAgent) {
78181
- agentAddress = (await registry.agentOf(user)).agent;
79169
+ const [isActive, record, latestBlock] = await Promise.all([
79170
+ registry.isAgentActive(user),
79171
+ registry.agentOf(user),
79172
+ this.getProviderOrThrow().getBlock("latest")
79173
+ ]);
79174
+ if (!latestBlock) {
79175
+ throw new SDKError({
79176
+ message: "Could not read the latest block to check the agent registration's expiry",
79177
+ category: "NETWORK",
79178
+ severity: "HIGH"
79179
+ /* HIGH */
79180
+ });
79181
+ }
79182
+ const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
79183
+ if (plan.kind === "reuse") {
79184
+ agentAddress = plan.agent;
78182
79185
  } else {
78183
79186
  agentAddress = await mintAgentPkp({
78184
79187
  serviceEndpoint: this.config.serviceEndpoint,
78185
79188
  authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
78186
79189
  });
78187
79190
  const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
78188
- const validUntil = Math.floor(Date.now() / 1e3) + validitySeconds;
78189
- const regTx = await registry.registerAgent(user, agentAddress, validUntil);
78190
- await regTx.wait();
79191
+ const validUntil = latestBlock.timestamp + validitySeconds;
79192
+ const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
79193
+ await bindTx.wait();
78191
79194
  }
78192
79195
  const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
78193
79196
  () => null
@@ -79579,7 +80582,552 @@ var SUPPORTED_STABLECOINS = `
79579
80582
  }`;
79580
80583
 
79581
80584
  // src/boundary/upstream/real/psm-calls.ts
79582
- var import_ethers32 = require("ethers");
80585
+ var import_ethers42 = require("ethers");
80586
+
80587
+ // node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
80588
+ var import_ethers36 = require("ethers");
80589
+ var import_ethers37 = require("ethers");
80590
+ var import_ethers38 = require("ethers");
80591
+ var import_ethers39 = require("ethers");
80592
+ var import_ethers40 = require("ethers");
80593
+ var import_ethers41 = require("ethers");
80594
+ var TxValidationError3 = class extends Error {
80595
+ /**
80596
+ * @param subject What is being refused. Defaults to the server-returned transaction the
80597
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
80598
+ */
80599
+ constructor(msg, subject = "server-returned transaction") {
80600
+ super(`Refusing to sign ${subject}: ${msg}`);
80601
+ this.name = "TxValidationError";
80602
+ }
80603
+ };
80604
+ var SIGNABLE_FUNCTIONS3 = [
80605
+ "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)",
80606
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
80607
+ // used to sit here; it is not a function on any deployed contract — the
80608
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
80609
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
80610
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
80611
+ // it. A signable-function whitelist should not carry calldata shapes the
80612
+ // protocol cannot execute.
80613
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
80614
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
80615
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
80616
+ // Struct-version: matches the actual on-chain function signature and the
80617
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
80618
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
80619
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
80620
+ "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)",
80621
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
80622
+ // function reverts permanently. The trustless replacement
80623
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
80624
+ // entry when its LIT Action ships.
80625
+ "function approve(address spender, uint256 amount) external returns (bool)",
80626
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
80627
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
80628
+ // without an entry here it decoded as "<unparseable>" and the CLI's
80629
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
80630
+ // collateral had no client-side pin at all.
80631
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
80632
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
80633
+ // AgentModule; the parity test documents them as client-only.
80634
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
80635
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
80636
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
80637
+ // this too is client-only and never module-whitelisted.
80638
+ "function addAddress(string btcAddress) external"
80639
+ ];
80640
+ var IFACE3 = new import_ethers36.ethers.Interface(SIGNABLE_FUNCTIONS3);
80641
+ function encodeSignable3(fn, args) {
80642
+ return IFACE3.encodeFunctionData(fn, args);
80643
+ }
80644
+ function decodeSignable3(data) {
80645
+ try {
80646
+ const parsed = IFACE3.parseTransaction({ data });
80647
+ if (!parsed) {
80648
+ throw new TxValidationError3(
80649
+ `unsignedTx.data does not decode against the signable-function whitelist`
80650
+ );
80651
+ }
80652
+ return { name: parsed.name, args: parsed.args };
80653
+ } catch (e) {
80654
+ if (e instanceof TxValidationError3)
80655
+ throw e;
80656
+ throw new TxValidationError3(
80657
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
80658
+ );
80659
+ }
80660
+ }
80661
+ var MAX_GAS_LIMIT2 = 5000000n;
80662
+ var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
80663
+ var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
80664
+ var DEFAULT_FEE_CEILING2 = {
80665
+ maxGasLimit: MAX_GAS_LIMIT2,
80666
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
80667
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
80668
+ };
80669
+ function fmtEth2(wei) {
80670
+ return `${import_ethers37.ethers.formatEther(wei)} ETH`;
80671
+ }
80672
+ function fmtGwei2(wei) {
80673
+ return `${import_ethers37.ethers.formatUnits(wei, "gwei")} gwei`;
80674
+ }
80675
+ function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
80676
+ if (gasLimit == null || maxFeePerGas == null)
80677
+ return null;
80678
+ return gasLimit * maxFeePerGas;
80679
+ }
80680
+ function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
80681
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
80682
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
80683
+ }
80684
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
80685
+ raise(
80686
+ `maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
80687
+ );
80688
+ }
80689
+ const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
80690
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
80691
+ raise(
80692
+ `worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
80693
+ );
80694
+ }
80695
+ }
80696
+ function eqAddr3(a, b) {
80697
+ if (!a || !b)
80698
+ return false;
80699
+ try {
80700
+ return import_ethers38.ethers.getAddress(a) === import_ethers38.ethers.getAddress(b);
80701
+ } catch {
80702
+ return false;
80703
+ }
80704
+ }
80705
+ function readToAddress3(tx2) {
80706
+ const to = tx2["to"];
80707
+ if (typeof to !== "string") {
80708
+ throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
80709
+ }
80710
+ return to;
80711
+ }
80712
+ function readData3(tx2) {
80713
+ const data = tx2["data"];
80714
+ if (typeof data !== "string" || !data.startsWith("0x")) {
80715
+ throw new TxValidationError3(`unsignedTx.data missing or malformed`);
80716
+ }
80717
+ return data;
80718
+ }
80719
+ function readChainId3(tx2) {
80720
+ const c = tx2["chainId"];
80721
+ if (c == null)
80722
+ return null;
80723
+ if (typeof c === "number")
80724
+ return c;
80725
+ if (typeof c === "string")
80726
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
80727
+ if (typeof c === "bigint")
80728
+ return Number(c);
80729
+ return null;
80730
+ }
80731
+ function readOptionalBigInt2(tx2, key) {
80732
+ const v = tx2[key];
80733
+ if (v == null)
80734
+ return null;
80735
+ try {
80736
+ if (typeof v === "bigint")
80737
+ return v;
80738
+ if (typeof v === "number")
80739
+ return BigInt(v);
80740
+ if (typeof v === "string")
80741
+ return BigInt(v);
80742
+ return BigInt(v.toString());
80743
+ } catch {
80744
+ throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
80745
+ }
80746
+ }
80747
+ function readValue3(tx2) {
80748
+ const v = tx2["value"];
80749
+ if (v == null)
80750
+ return 0n;
80751
+ if (typeof v === "string")
80752
+ return BigInt(v);
80753
+ if (typeof v === "number")
80754
+ return BigInt(v);
80755
+ if (typeof v === "bigint")
80756
+ return v;
80757
+ const maybe = v;
80758
+ if (typeof maybe.toBigInt === "function")
80759
+ return maybe.toBigInt();
80760
+ if (typeof maybe.toString === "function")
80761
+ return BigInt(maybe.toString());
80762
+ throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
80763
+ }
80764
+ function normalizePositionId3(id) {
80765
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
80766
+ return import_ethers38.ethers.zeroPadValue(hex, 32).toLowerCase();
80767
+ }
80768
+ function requirePositionId2(actual, expected) {
80769
+ const txPositionId = String(actual).toLowerCase();
80770
+ if (txPositionId !== normalizePositionId3(expected)) {
80771
+ throw new TxValidationError3(
80772
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
80773
+ );
80774
+ }
80775
+ }
80776
+ function validateUnsignedTx3(unsignedTx, expected, vctx) {
80777
+ const txChainId = readChainId3(unsignedTx);
80778
+ if (txChainId == null) {
80779
+ throw new TxValidationError3(
80780
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
80781
+ );
80782
+ }
80783
+ if (txChainId !== vctx.chainId) {
80784
+ throw new TxValidationError3(
80785
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
80786
+ );
80787
+ }
80788
+ const value = readValue3(unsignedTx);
80789
+ if (value !== 0n) {
80790
+ throw new TxValidationError3(
80791
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
80792
+ );
80793
+ }
80794
+ assertFeeCeiling2(
80795
+ readOptionalBigInt2(unsignedTx, "gasLimit"),
80796
+ readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
80797
+ (msg) => {
80798
+ throw new TxValidationError3(msg);
80799
+ },
80800
+ vctx.feeCeiling
80801
+ );
80802
+ const to = readToAddress3(unsignedTx);
80803
+ const data = readData3(unsignedTx);
80804
+ const { name, args } = decodeSignable3(data);
80805
+ const pm = vctx.contracts.PositionManager;
80806
+ switch (expected.kind) {
80807
+ case "mint": {
80808
+ if (name !== "mintUCD") {
80809
+ throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
80810
+ }
80811
+ if (!eqAddr3(to, pm)) {
80812
+ throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
80813
+ }
80814
+ requirePositionId2(args[0], expected.positionId);
80815
+ const txMintAmount = BigInt(String(args[1]));
80816
+ if (txMintAmount.toString() !== expected.amountWei) {
80817
+ throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
80818
+ }
80819
+ const txMintFee = BigInt(String(args[2]));
80820
+ if (txMintFee.toString() !== expected.mintFeeWei) {
80821
+ throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
80822
+ }
80823
+ break;
80824
+ }
80825
+ case "repay": {
80826
+ if (name !== "makePayment") {
80827
+ throw new TxValidationError3(`expected makePayment, server returned ${name}`);
80828
+ }
80829
+ if (!eqAddr3(to, pm)) {
80830
+ throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
80831
+ }
80832
+ requirePositionId2(args[0], expected.positionId);
80833
+ const txAmount = BigInt(String(args[1]));
80834
+ if (txAmount.toString() !== expected.amountWei) {
80835
+ throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
80836
+ }
80837
+ break;
80838
+ }
80839
+ case "extend": {
80840
+ if (name !== "extendPosition") {
80841
+ throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
80842
+ }
80843
+ if (!eqAddr3(to, pm)) {
80844
+ throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
80845
+ }
80846
+ requirePositionId2(args[0], expected.positionId);
80847
+ const txTerm = Number(args[1]);
80848
+ if (txTerm !== expected.selectedTerm) {
80849
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80850
+ }
80851
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
80852
+ const txFee = BigInt(String(args[5]));
80853
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
80854
+ if (txFee > upper) {
80855
+ throw new TxValidationError3(
80856
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
80857
+ );
80858
+ }
80859
+ }
80860
+ break;
80861
+ }
80862
+ case "withdraw-btc": {
80863
+ if (name !== "withdrawBTC") {
80864
+ throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
80865
+ }
80866
+ if (!eqAddr3(to, pm)) {
80867
+ throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
80868
+ }
80869
+ const paramsTuple = args[0];
80870
+ requirePositionId2(paramsTuple[0], expected.positionId);
80871
+ const txWithdrawalAddress = String(paramsTuple[5]);
80872
+ if (txWithdrawalAddress !== expected.btcAddress) {
80873
+ throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
80874
+ }
80875
+ if (expected.upperBoundTotalDeduction != null) {
80876
+ const txDeduction = BigInt(String(paramsTuple[6]));
80877
+ const upper = BigInt(expected.upperBoundTotalDeduction);
80878
+ if (txDeduction > upper) {
80879
+ throw new TxValidationError3(
80880
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
80881
+ );
80882
+ }
80883
+ }
80884
+ break;
80885
+ }
80886
+ case "ucd-approve": {
80887
+ if (name !== "approve") {
80888
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80889
+ }
80890
+ const ucd = vctx.contracts.UCDToken;
80891
+ if (!eqAddr3(to, ucd)) {
80892
+ throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
80893
+ }
80894
+ const spender = String(args[0]);
80895
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
80896
+ if (!ok2) {
80897
+ throw new TxValidationError3(
80898
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
80899
+ );
80900
+ }
80901
+ const amt = BigInt(String(args[1]));
80902
+ const min = BigInt(expected.minAmountWei);
80903
+ if (amt < min) {
80904
+ throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
80905
+ }
80906
+ const SANITY_MAX = min * 1000n;
80907
+ if (amt > SANITY_MAX) {
80908
+ throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
80909
+ }
80910
+ break;
80911
+ }
80912
+ case "create-position": {
80913
+ if (name !== "createPosition") {
80914
+ throw new TxValidationError3(`expected createPosition, server returned ${name}`);
80915
+ }
80916
+ if (!eqAddr3(to, pm)) {
80917
+ throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
80918
+ }
80919
+ const txTerm = BigInt(String(args[4]));
80920
+ if (txTerm !== BigInt(expected.selectedTerm)) {
80921
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80922
+ }
80923
+ break;
80924
+ }
80925
+ case "set-position-delegate": {
80926
+ if (name !== "setPositionDelegate") {
80927
+ throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
80928
+ }
80929
+ if (!eqAddr3(to, expected.registryAddress)) {
80930
+ throw new TxValidationError3(
80931
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
80932
+ );
80933
+ }
80934
+ requirePositionId2(args[0], expected.positionId);
80935
+ const txDelegate = String(args[1]);
80936
+ if (!eqAddr3(txDelegate, expected.delegate)) {
80937
+ throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
80938
+ }
80939
+ break;
80940
+ }
80941
+ case "bwar-add-address": {
80942
+ if (name !== "addAddress") {
80943
+ throw new TxValidationError3(`expected addAddress, decoded ${name}`);
80944
+ }
80945
+ if (!eqAddr3(to, expected.registryAddress)) {
80946
+ throw new TxValidationError3(
80947
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
80948
+ );
80949
+ }
80950
+ if (String(args[0]) !== expected.btcAddress) {
80951
+ throw new TxValidationError3(
80952
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
80953
+ );
80954
+ }
80955
+ break;
80956
+ }
80957
+ case "stablecoin-approve": {
80958
+ if (name !== "approve") {
80959
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80960
+ }
80961
+ if (!eqAddr3(to, expected.tokenAddress)) {
80962
+ throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
80963
+ }
80964
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80965
+ throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
80966
+ }
80967
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
80968
+ throw new TxValidationError3(
80969
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
80970
+ );
80971
+ }
80972
+ break;
80973
+ }
80974
+ case "ucd-approve-controller": {
80975
+ if (name !== "approve") {
80976
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80977
+ }
80978
+ if (!eqAddr3(to, expected.ucdTokenAddress)) {
80979
+ throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
80980
+ }
80981
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80982
+ throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
80983
+ }
80984
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
80985
+ throw new TxValidationError3(
80986
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
80987
+ );
80988
+ }
80989
+ break;
80990
+ }
80991
+ case "psm-swap": {
80992
+ if (name !== "swap")
80993
+ throw new TxValidationError3(`expected swap, server returned ${name}`);
80994
+ if (!eqAddr3(to, expected.psmAddress)) {
80995
+ throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
80996
+ }
80997
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80998
+ throw new TxValidationError3(`swap stablecoin mismatch`);
80999
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
81000
+ throw new TxValidationError3(`swap amountIn mismatch`);
81001
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
81002
+ throw new TxValidationError3(`swap minUcdOut mismatch`);
81003
+ if (BigInt(expected.minOut) === 0n) {
81004
+ throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
81005
+ }
81006
+ break;
81007
+ }
81008
+ case "psm-redeem": {
81009
+ if (name !== "redeem")
81010
+ throw new TxValidationError3(`expected redeem, server returned ${name}`);
81011
+ if (!eqAddr3(to, expected.psmAddress)) {
81012
+ throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
81013
+ }
81014
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
81015
+ throw new TxValidationError3(`redeem stablecoin mismatch`);
81016
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
81017
+ throw new TxValidationError3(`redeem ucdAmount mismatch`);
81018
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
81019
+ throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
81020
+ if (BigInt(expected.minOut) === 0n) {
81021
+ throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
81022
+ }
81023
+ break;
81024
+ }
81025
+ default: {
81026
+ const _exhaustive = expected;
81027
+ throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
81028
+ }
81029
+ }
81030
+ }
81031
+ var SLOT_SECONDS2 = 12;
81032
+ var INCLUSION_SLOT_TOLERANCE2 = 3;
81033
+ var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
81034
+ function buildPsmApproveTx2(p) {
81035
+ return {
81036
+ to: p.token,
81037
+ data: encodeSignable3("approve", [p.spender, p.amount]),
81038
+ value: "0x0",
81039
+ chainId: p.chainId
81040
+ };
81041
+ }
81042
+ function buildPsmSwapTx3(p) {
81043
+ return {
81044
+ to: p.psm,
81045
+ data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
81046
+ value: "0x0",
81047
+ chainId: p.chainId
81048
+ };
81049
+ }
81050
+ function buildPsmRedeemTx3(p) {
81051
+ return {
81052
+ to: p.psm,
81053
+ data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
81054
+ value: "0x0",
81055
+ chainId: p.chainId
81056
+ };
81057
+ }
81058
+ var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
81059
+ var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
81060
+ function psmExchangeReadsFromProvider2(provider, psmAddress) {
81061
+ const psm = new import_ethers41.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
81062
+ return {
81063
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
81064
+ allowance: async (token, owner, spender) => await new import_ethers41.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
81065
+ };
81066
+ }
81067
+ var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
81068
+ function requireAddress2(direction, label, value) {
81069
+ if (!value || !import_ethers41.ethers.isAddress(value)) {
81070
+ throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
81071
+ }
81072
+ return import_ethers41.ethers.getAddress(value);
81073
+ }
81074
+ async function planPsmExchange2(params) {
81075
+ const { direction, amountIn, minOut, vctx, reads } = params;
81076
+ const chainId = vctx.chainId;
81077
+ if (amountIn <= 0n) {
81078
+ throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
81079
+ }
81080
+ if (minOut <= 0n) {
81081
+ throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
81082
+ }
81083
+ const owner = requireAddress2(direction, "owner", params.owner);
81084
+ const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
81085
+ const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
81086
+ const isSwap = direction === "swap";
81087
+ const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
81088
+ const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
81089
+ if (!await reads.isStablecoinSupported(stablecoin)) {
81090
+ throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
81091
+ }
81092
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
81093
+ const allowanceBefore = await reads.allowance(token, owner, spender);
81094
+ const approvals = [];
81095
+ if (allowanceBefore < amountIn) {
81096
+ if (allowanceBefore > 0n) {
81097
+ approvals.push({
81098
+ step: "reset-approve",
81099
+ tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
81100
+ expected: approveExpected(0n)
81101
+ });
81102
+ }
81103
+ approvals.push({
81104
+ step: "approve",
81105
+ tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
81106
+ expected: approveExpected(amountIn)
81107
+ });
81108
+ }
81109
+ const exec = isSwap ? {
81110
+ step: "swap",
81111
+ tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
81112
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
81113
+ } : {
81114
+ step: "redeem",
81115
+ tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
81116
+ expected: {
81117
+ kind: "psm-redeem",
81118
+ psmAddress: psm,
81119
+ stablecoin,
81120
+ amountUcdWei: amountIn.toString(),
81121
+ minOut: minOut.toString()
81122
+ }
81123
+ };
81124
+ for (const leg of [...approvals, exec]) {
81125
+ validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
81126
+ }
81127
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
81128
+ }
81129
+
81130
+ // src/boundary/upstream/real/psm-calls.ts
79583
81131
  var PSM_VIEW_FRAGMENTS = [
79584
81132
  "function VERSION() view returns (string)",
79585
81133
  "function supportedStablecoins(address) view returns (bool)",
@@ -79599,15 +81147,7 @@ var PSM_VIEW_FRAGMENTS = [
79599
81147
  "function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
79600
81148
  "function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
79601
81149
  ];
79602
- var PSM_WRITE_FRAGMENTS = [
79603
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
79604
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
79605
- ];
79606
- var ERC20_FRAGMENTS = [
79607
- "function approve(address spender, uint256 amount) returns (bool)",
79608
- "function balanceOf(address holder) view returns (uint256)"
79609
- ];
79610
- var ERC20_IFACE = new import_ethers32.ethers.Interface(ERC20_FRAGMENTS);
81150
+ var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
79611
81151
  var PSM_ERROR_FRAGMENTS = [
79612
81152
  "error StablecoinNotSupported(address stablecoin)",
79613
81153
  "error InvalidAmount()",
@@ -79655,9 +81195,9 @@ var RENDERERS = {
79655
81195
  var PsmCalls = class {
79656
81196
  constructor(deps) {
79657
81197
  this.deps = deps;
79658
- const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_WRITE_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
79659
- this.iface = new import_ethers32.ethers.Interface(abi);
79660
- this.psm = new import_ethers32.ethers.Contract(deps.psmAddress, abi, deps.provider);
81198
+ const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
81199
+ this.iface = new import_ethers42.ethers.Interface(abi);
81200
+ this.psm = new import_ethers42.ethers.Contract(deps.psmAddress, abi, deps.provider);
79661
81201
  }
79662
81202
  psm;
79663
81203
  iface;
@@ -79670,34 +81210,10 @@ var PsmCalls = class {
79670
81210
  ...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
79671
81211
  };
79672
81212
  }
79673
- // ---- unsigned-tx builders (plan 08 W1): EXACT-amount approvals only; floors pinned ----
79674
- /** Step 1: exact-amount ERC-20 approve. Caller names the direction's REAL spender
79675
- * (swap: stablecoin → the PSM; redeem: UCD → the UCDController). */
79676
- buildApprove(p) {
79677
- return {
79678
- to: p.token,
79679
- data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
79680
- value: "0x0",
79681
- chainId: p.chainId
79682
- };
79683
- }
79684
- /** Step 2, stablecoin → UCD (contract `swap`). */
79685
- buildSwap(p) {
79686
- return {
79687
- to: this.deps.psmAddress,
79688
- data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
79689
- value: "0x0",
79690
- chainId: p.chainId
79691
- };
79692
- }
79693
- /** Step 2, UCD → stablecoin (contract `redeem`). */
79694
- buildRedeem(p) {
79695
- return {
79696
- to: this.deps.psmAddress,
79697
- data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
79698
- value: "0x0",
79699
- chainId: p.chainId
79700
- };
81213
+ /** The two live reads the SDK's exchange planner depends on (supported set + allowance),
81214
+ * over this wrapper's provider and PSM. */
81215
+ exchangeReads() {
81216
+ return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
79701
81217
  }
79702
81218
  /** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
79703
81219
  async balances(holder) {
@@ -79710,8 +81226,8 @@ var PsmCalls = class {
79710
81226
  });
79711
81227
  }
79712
81228
  return this.call(async () => {
79713
- const ucd = new import_ethers32.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
79714
- const stable = new import_ethers32.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
81229
+ const ucd = new import_ethers42.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
81230
+ const stable = new import_ethers42.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
79715
81231
  const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
79716
81232
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79717
81233
  });
@@ -79829,7 +81345,7 @@ var PsmCalls = class {
79829
81345
  };
79830
81346
 
79831
81347
  // src/boundary/upstream/real/session.ts
79832
- var import_ethers33 = require("ethers");
81348
+ var import_ethers43 = require("ethers");
79833
81349
  var REFRESH_LEEWAY_SEC = 30;
79834
81350
  var LOGIN_TYPES_WITH_AUDIENCE3 = {
79835
81351
  DiamondHands: [
@@ -79877,7 +81393,7 @@ var LitOpsSession = class {
79877
81393
  const message = {
79878
81394
  address: this.wallet.address,
79879
81395
  issuedAt: Math.floor(Date.now() / 1e3),
79880
- nonce: "0x" + Buffer.from(import_ethers33.ethers.randomBytes(32)).toString("hex"),
81396
+ nonce: "0x" + Buffer.from(import_ethers43.ethers.randomBytes(32)).toString("hex"),
79881
81397
  audience: this.serviceEndpoint
79882
81398
  };
79883
81399
  const signature = await this.wallet.signTypedData(
@@ -79919,7 +81435,7 @@ function decodeJwtExp(token) {
79919
81435
  }
79920
81436
 
79921
81437
  // src/boundary/upstream/real/write-ops.ts
79922
- var import_ethers35 = require("ethers");
81438
+ var import_ethers45 = require("ethers");
79923
81439
 
79924
81440
  // src/signer/types.ts
79925
81441
  var OperationDeclined = class extends Error {
@@ -79929,7 +81445,7 @@ var OperationDeclined = class extends Error {
79929
81445
  init_tx_validator();
79930
81446
 
79931
81447
  // src/boundary/upstream/shared/external-bridge/page-crypto.ts
79932
- var import_ethers34 = require("ethers");
81448
+ var import_ethers44 = require("ethers");
79933
81449
  var PERSONAL_SIGN_LAYOUTS = {
79934
81450
  "dh-op-envelope-v1": {
79935
81451
  types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
@@ -79950,9 +81466,9 @@ function hashForLayout(layout, fields) {
79950
81466
  const values = def.fieldOrder.map((name) => {
79951
81467
  const raw = fields[name];
79952
81468
  if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
79953
- return hashUtf8.has(name) ? import_ethers34.ethers.keccak256(import_ethers34.ethers.toUtf8Bytes(raw)) : raw;
81469
+ return hashUtf8.has(name) ? import_ethers44.ethers.keccak256(import_ethers44.ethers.toUtf8Bytes(raw)) : raw;
79954
81470
  });
79955
- return import_ethers34.ethers.solidityPackedKeccak256(def.types, values);
81471
+ return import_ethers44.ethers.solidityPackedKeccak256(def.types, values);
79956
81472
  }
79957
81473
  var PAGE_CRYPTO_JS = `"use strict";
79958
81474
  (function () {
@@ -80181,9 +81697,21 @@ function buildValidationContext(network, chainId) {
80181
81697
 
80182
81698
  // src/boundary/upstream/real/write-ops.ts
80183
81699
  var SOURCE5 = "real-ops";
81700
+ function mcpExpected(leg) {
81701
+ const e = leg.expected;
81702
+ switch (e.kind) {
81703
+ case "stablecoin-approve":
81704
+ case "ucd-approve-controller":
81705
+ case "psm-swap":
81706
+ case "psm-redeem":
81707
+ return e;
81708
+ default:
81709
+ throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
81710
+ }
81711
+ }
80184
81712
  var OP_LAYOUT = "dh-op-envelope-v1";
80185
81713
  function randomNonceHex() {
80186
- return "0x" + Buffer.from(import_ethers35.ethers.randomBytes(16)).toString("hex");
81714
+ return "0x" + Buffer.from(import_ethers45.ethers.randomBytes(16)).toString("hex");
80187
81715
  }
80188
81716
  async function postJson(url2, body, headers) {
80189
81717
  const res = await fetch(url2, {
@@ -80244,7 +81772,7 @@ function buildWriteOps(deps) {
80244
81772
  return {
80245
81773
  to: String(tx2["to"] ?? ""),
80246
81774
  data: String(tx2["data"] ?? "0x"),
80247
- value: tx2["value"] != null ? import_ethers35.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
81775
+ value: tx2["value"] != null ? import_ethers45.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
80248
81776
  chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
80249
81777
  };
80250
81778
  }
@@ -80329,8 +81857,9 @@ function buildWriteOps(deps) {
80329
81857
  }
80330
81858
  return {
80331
81859
  createPosition: async (p) => {
80332
- const sdk = deps.getWriteSdk();
80333
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81860
+ const built = await deps.getWriteSdk();
81861
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81862
+ const sdk = built.sdk;
80334
81863
  try {
80335
81864
  await deps.assertValidatorConfigured();
80336
81865
  } catch (e) {
@@ -80409,7 +81938,7 @@ function buildWriteOps(deps) {
80409
81938
  mintedUcdWei: minted,
80410
81939
  feeUcdWei: mintFee,
80411
81940
  echoedAmountUcdWei: minted,
80412
- authorization: auth(action, `mint ${import_ethers35.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
81941
+ authorization: auth(action, `mint ${import_ethers45.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
80413
81942
  },
80414
81943
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80415
81944
  );
@@ -80450,7 +81979,7 @@ function buildWriteOps(deps) {
80450
81979
  txRef: { kind: "eth-tx", id: r.value.txHash },
80451
81980
  paidUcdWei: paid,
80452
81981
  echoedAmountUcdWei: paid,
80453
- authorization: auth(action, `repay ${import_ethers35.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
81982
+ authorization: auth(action, `repay ${import_ethers45.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
80454
81983
  },
80455
81984
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80456
81985
  );
@@ -80490,8 +82019,9 @@ function buildWriteOps(deps) {
80490
82019
  );
80491
82020
  },
80492
82021
  withdraw: async (p) => {
80493
- const sdk = deps.getWriteSdk();
80494
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82022
+ const built = await deps.getWriteSdk();
82023
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82024
+ const sdk = built.sdk;
80495
82025
  const amountSats = Number(p.amountSats);
80496
82026
  const feeSats = Number(p.networkFeeSats);
80497
82027
  let result;
@@ -80520,12 +82050,13 @@ function buildWriteOps(deps) {
80520
82050
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80521
82051
  );
80522
82052
  },
80523
- /** PSM exchange pair (plan 08 W1): pure on-chain calls — no LIT action, no server
80524
- * orchestration. MCP-built txs over the pinned wrapper (the SDK's psmSwap/psmRedeem
80525
- * hardcode MaxUint256 approvals and are FORBIDDEN); exact-amount approve, then the
80526
- * swap/redeem with its mandatory floor, each validated against the M8-11 whitelist,
80527
- * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80528
- * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
82053
+ /** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
82054
+ * orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
82055
+ * builder every client shares (it replaced this file's own builders and the SDK's old
82056
+ * MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
82057
+ * allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
82058
+ * validated again here by the MCP's own whitelist (the one the approval card decodes
82059
+ * with), then signed through the session signer and broadcast — one at a time. */
80529
82060
  psmSwap: async (p) => {
80530
82061
  const pr = await deps.psm(p.stablecoin);
80531
82062
  if (!pr.ok) return upFail(pr.failure);
@@ -80539,11 +82070,7 @@ function buildWriteOps(deps) {
80539
82070
  message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
80540
82071
  });
80541
82072
  }
80542
- const amountIn = BigInt(p.amountIn);
80543
- const minOut = BigInt(p.minOut);
80544
82073
  const vctx = buildValidationContext(config.network, chainId);
80545
- const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
80546
- const spenderAddress = isSwap ? addr.psm : addr.ucdController;
80547
82074
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
80548
82075
  const tokenSymbol = isSwap ? calls.symbol() : "UCD";
80549
82076
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
@@ -80560,49 +82087,66 @@ function buildWriteOps(deps) {
80560
82087
  return submitFailure(leg, e);
80561
82088
  }
80562
82089
  };
80563
- const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
82090
+ let plan;
80564
82091
  try {
80565
- validateUnsignedTx(
80566
- { ...approveTx },
80567
- isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn },
80568
- vctx
80569
- );
80570
- } catch (e) {
80571
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
80572
- }
80573
- const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
80574
- const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
80575
- if (!approveHashR.ok) return approveHashR;
80576
- const approveHash = approveHashR.value;
80577
- 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`;
80578
- const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
80579
- try {
80580
- validateUnsignedTx(
80581
- { ...execTx },
80582
- 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 },
80583
- vctx
80584
- );
82092
+ plan = await planPsmExchange2({
82093
+ direction: p.direction,
82094
+ owner: p.borrower,
82095
+ addresses: addr,
82096
+ amountIn: BigInt(p.amountIn),
82097
+ minOut: BigInt(p.minOut),
82098
+ vctx,
82099
+ reads: calls.exchangeReads()
82100
+ });
80585
82101
  } catch (e) {
80586
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
82102
+ return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
82103
+ kind: "unavailable",
82104
+ source: SOURCE5,
82105
+ message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
82106
+ raw: String(e)
82107
+ });
80587
82108
  }
80588
- const execCard = `${p.direction} ${p.amountIn} ${isSwap ? `${tokenSymbol} smallest units` : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
80589
- const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
80590
- if (!execHashR.ok) {
80591
- const f = execHashR.failure;
80592
- return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
82109
+ const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
82110
+ const unit = `${tokenSymbol} smallest units`;
82111
+ const landed = [];
82112
+ const residualNote = () => {
82113
+ const last = landed[landed.length - 1];
82114
+ 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`;
82115
+ return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
82116
+ };
82117
+ const runLeg = async (leg) => {
82118
+ const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
82119
+ try {
82120
+ validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
82121
+ } catch (e) {
82122
+ return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
82123
+ }
82124
+ const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
82125
+ const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
82126
+ return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
82127
+ };
82128
+ const approvals = [];
82129
+ for (const leg of plan.approvals) {
82130
+ 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})`;
82131
+ const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
82132
+ const r = await runLeg(leg);
82133
+ if (!r.ok) return r;
82134
+ landed.push({ step, hash: r.value });
82135
+ approvals.push({
82136
+ step,
82137
+ txRef: { kind: "eth-tx", id: r.value },
82138
+ amount: leg.step === "reset-approve" ? "0" : p.amountIn,
82139
+ authorization: auth("psm-approve", card, r.value)
82140
+ });
80593
82141
  }
82142
+ 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}`;
82143
+ const execHashR = await runLeg(plan.exec);
82144
+ if (!execHashR.ok) return execHashR;
80594
82145
  const execHash = execHashR.value;
80595
82146
  const balancesR = await calls.balances(p.borrower);
80596
82147
  const row = {
80597
- approve: {
80598
- txRef: { kind: "eth-tx", id: approveHash },
80599
- tokenSymbol,
80600
- tokenAddress,
80601
- spenderAddress,
80602
- spenderContract,
80603
- amount: p.amountIn,
80604
- authorization: auth("psm-approve", approveCard, approveHash)
80605
- },
82148
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
82149
+ approvals,
80606
82150
  execute: {
80607
82151
  txRef: { kind: "eth-tx", id: execHash },
80608
82152
  amountIn: p.amountIn,
@@ -80619,8 +82163,9 @@ function buildWriteOps(deps) {
80619
82163
  // registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
80620
82164
  // msg.sender, so their path is a SafeTx — never this keystore leg.
80621
82165
  allowlistWithdrawalAddress: async (p) => {
80622
- const sdk = deps.getWriteSdk();
80623
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82166
+ const built = await deps.getWriteSdk();
82167
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82168
+ const sdk = built.sdk;
80624
82169
  let result;
80625
82170
  try {
80626
82171
  result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
@@ -80667,8 +82212,9 @@ function buildWriteOps(deps) {
80667
82212
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
80668
82213
  }),
80669
82214
  retryWithdrawExecute: async (p) => {
80670
- const sdk = deps.getWriteSdk();
80671
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82215
+ const built = await deps.getWriteSdk();
82216
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82217
+ const sdk = built.sdk;
80672
82218
  let rows;
80673
82219
  try {
80674
82220
  rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
@@ -80696,7 +82242,7 @@ function buildWriteOps(deps) {
80696
82242
  }
80697
82243
 
80698
82244
  // src/signer/eoa-dh.ts
80699
- var import_ethers36 = require("ethers");
82245
+ var import_ethers46 = require("ethers");
80700
82246
  var EoaDHSigner = class {
80701
82247
  constructor(wallet, broadcast, clock = Date.now) {
80702
82248
  this.wallet = wallet;
@@ -80713,7 +82259,7 @@ var EoaDHSigner = class {
80713
82259
  async signAuthorization(spec) {
80714
82260
  const quantumTs = nextQuantumTimestamp(this.clock());
80715
82261
  const { fields, hashHex } = spec.stamp(quantumTs);
80716
- const signature = await this.wallet.signMessage(import_ethers36.ethers.getBytes(hashHex));
82262
+ const signature = await this.wallet.signMessage(import_ethers46.ethers.getBytes(hashHex));
80717
82263
  return { signature, quantumTs, fields };
80718
82264
  }
80719
82265
  async wrapInnerTx(innerTx) {
@@ -80731,10 +82277,10 @@ var EoaDHSigner = class {
80731
82277
 
80732
82278
  // src/signer/external-eoa.ts
80733
82279
  var import_node_crypto7 = require("crypto");
80734
- var import_ethers38 = require("ethers");
82280
+ var import_ethers48 = require("ethers");
80735
82281
 
80736
82282
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
80737
- var import_ethers37 = require("ethers");
82283
+ var import_ethers47 = require("ethers");
80738
82284
  function eq2(a, b) {
80739
82285
  return a.toLowerCase() === b.toLowerCase();
80740
82286
  }
@@ -80757,7 +82303,7 @@ function compareLandedTx(landed, approved, borrower) {
80757
82303
  return { status: "verified", from: landed.from, hash: landed.hash };
80758
82304
  }
80759
82305
  function verifyRawSignedTx(rawSignedTx, approved, borrower) {
80760
- const parsed = import_ethers37.ethers.Transaction.from(rawSignedTx);
82306
+ const parsed = import_ethers47.ethers.Transaction.from(rawSignedTx);
80761
82307
  if (!parsed.from || !parsed.to || !parsed.hash) {
80762
82308
  return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
80763
82309
  }
@@ -80795,7 +82341,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
80795
82341
  for (let attempt = 0; attempt < 4; attempt++) {
80796
82342
  try {
80797
82343
  const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
80798
- return import_ethers38.ethers.toBeHex(est * 15n / 10n);
82344
+ return import_ethers48.ethers.toBeHex(est * 15n / 10n);
80799
82345
  } catch (e) {
80800
82346
  lastErr = e;
80801
82347
  await new Promise((r) => setTimeout(r, 13e3));
@@ -80845,7 +82391,7 @@ var ExternalEoaDHSigner = class {
80845
82391
  throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
80846
82392
  }
80847
82393
  const finalHash = spec.stamp(used.quantumTs).hashHex;
80848
- const recovered = import_ethers38.ethers.verifyMessage(import_ethers38.ethers.getBytes(finalHash), outcome.signature);
82394
+ const recovered = import_ethers48.ethers.verifyMessage(import_ethers48.ethers.getBytes(finalHash), outcome.signature);
80849
82395
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80850
82396
  throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80851
82397
  }
@@ -80856,7 +82402,7 @@ var ExternalEoaDHSigner = class {
80856
82402
  }
80857
82403
  async submitValidatedTx(outerTx, ctx) {
80858
82404
  const approved = toApprovedTx(outerTx, this.deps.chainId);
80859
- const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
82405
+ const gas = outerTx.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
80860
82406
  const outcome = await this.deps.bridge.requestSignature({
80861
82407
  id: (0, import_node_crypto7.randomUUID)(),
80862
82408
  kind: "transaction",
@@ -80890,7 +82436,7 @@ var ExternalEoaDHSigner = class {
80890
82436
  return new BridgeEthersSigner(this.deps);
80891
82437
  }
80892
82438
  };
80893
- var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ethers.AbstractSigner {
82439
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers48.ethers.AbstractSigner {
80894
82440
  constructor(deps) {
80895
82441
  super(deps.provider);
80896
82442
  this.deps = deps;
@@ -80901,13 +82447,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80901
82447
  return this.deps.borrower;
80902
82448
  }
80903
82449
  async signMessage(message) {
80904
- const bytes = typeof message === "string" ? import_ethers38.ethers.toUtf8Bytes(message) : message;
82450
+ const bytes = typeof message === "string" ? import_ethers48.ethers.toUtf8Bytes(message) : message;
80905
82451
  if (bytes.length !== 32) {
80906
82452
  throw new Error(
80907
82453
  `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.`
80908
82454
  );
80909
82455
  }
80910
- const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
82456
+ const hashHex = import_ethers48.ethers.hexlify(bytes).toLowerCase();
80911
82457
  const nowMs = (this.deps.clock ?? Date.now)();
80912
82458
  const expiresAtSec = nextQuantumTimestamp(nowMs);
80913
82459
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
@@ -80937,7 +82483,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80937
82483
  if (outcome.status !== "approved" || !outcome.signature) {
80938
82484
  throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
80939
82485
  }
80940
- const recovered = import_ethers38.ethers.verifyMessage(bytes, outcome.signature);
82486
+ const recovered = import_ethers48.ethers.verifyMessage(bytes, outcome.signature);
80941
82487
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80942
82488
  throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80943
82489
  }
@@ -80971,11 +82517,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80971
82517
  const approved = {
80972
82518
  to: tx2.to,
80973
82519
  data: tx2.data,
80974
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82520
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
80975
82521
  chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
80976
82522
  };
80977
82523
  const card = cardForTx(approved);
80978
- const gas = tx2.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
82524
+ const gas = tx2.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
80979
82525
  const outcome = await this.deps.bridge.requestSignature({
80980
82526
  id: (0, import_node_crypto7.randomUUID)(),
80981
82527
  kind: "transaction",
@@ -81017,14 +82563,14 @@ function toApprovedTx(tx2, fallbackChainId) {
81017
82563
  return {
81018
82564
  to: tx2.to,
81019
82565
  data: tx2.data,
81020
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82566
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
81021
82567
  chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
81022
82568
  };
81023
82569
  }
81024
82570
  function describeFn(data) {
81025
82571
  try {
81026
- const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
81027
- return decodeSignable2(data).name;
82572
+ const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
82573
+ return decodeSignable4(data).name;
81028
82574
  } catch {
81029
82575
  return "operation";
81030
82576
  }
@@ -81061,7 +82607,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
81061
82607
  var RealUpstreamPlugin = class {
81062
82608
  constructor(config, wallet, runtime) {
81063
82609
  this.config = config;
81064
- this.provider = new import_ethers39.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
82610
+ this.provider = new import_ethers49.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
81065
82611
  this.wallet = wallet ?? null;
81066
82612
  this.runtime = runtime ?? null;
81067
82613
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
@@ -81254,18 +82800,24 @@ var RealUpstreamPlugin = class {
81254
82800
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
81255
82801
  * and the service-mode SDK routes its own subgraph reads through the same proxy — so
81256
82802
  * writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
81257
- * Safe to call repeatedly; failures leave the write plane honestly unavailable
81258
- * (createPosition/withdraw report the uninitialized SDK). */
82803
+ * Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
82804
+ * first write builds again (see ensureSdk). */
81259
82805
  async initWriteSdk() {
81260
82806
  if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
81261
82807
  const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
81262
82808
  if (!wallet) return;
81263
82809
  await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
81264
82810
  }
81265
- /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
81266
- * the write gateways report the uninitialized SDK honestly, never fake readiness. */
82811
+ /** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
82812
+ *
82813
+ * A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
82814
+ * life of the process and drop the error, which was survivable only while `create` never
82815
+ * touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
82816
+ * RPC blip at boot would have disabled every later write with no reason given. Now each write
82817
+ * retries, and a persistent failure says what it is. Concurrent callers share one build. */
81267
82818
  async ensureSdk(key, signer) {
81268
- if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
82819
+ const cached = this.sdkCache.get(key);
82820
+ if (cached) return { ok: true, sdk: cached };
81269
82821
  const inFlight = this.sdkInFlight.get(key);
81270
82822
  if (inFlight) return inFlight;
81271
82823
  const build = (async () => {
@@ -81285,17 +82837,23 @@ var RealUpstreamPlugin = class {
81285
82837
  // nesting writes under indexer discovery (the M8B-4 coupling this removes).
81286
82838
  ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
81287
82839
  });
81288
- return isSuccess(builtWrite) ? builtWrite.value : null;
81289
- } catch {
81290
- return null;
82840
+ if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
82841
+ return { ok: false, reason: builtWrite.error.message };
82842
+ } catch (e) {
82843
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
81291
82844
  }
81292
82845
  })();
81293
82846
  this.sdkInFlight.set(key, build);
81294
82847
  const built = await build;
81295
82848
  this.sdkInFlight.delete(key);
81296
- this.sdkCache.set(key, built);
82849
+ if (built.ok) this.sdkCache.set(key, built.sdk);
81297
82850
  return built;
81298
82851
  }
82852
+ /** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
82853
+ async writeSdkFor(key, signer) {
82854
+ const built = await this.ensureSdk(key, signer);
82855
+ return built.ok ? { ok: true, sdk: built.sdk } : built;
82856
+ }
81299
82857
  wallet;
81300
82858
  // ---- per-call signer resolution (plan 10 A3) ----
81301
82859
  /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
@@ -81335,7 +82893,7 @@ var RealUpstreamPlugin = class {
81335
82893
  chainId: this.config.chainId,
81336
82894
  dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
81337
82895
  session,
81338
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82896
+ getWriteSdk: () => this.writeSdkFor(key, wallet),
81339
82897
  readDetails: (id) => this.readPositionDetails(id),
81340
82898
  psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81341
82899
  assertValidatorConfigured: () => this.assertValidatorConfigured()
@@ -81351,14 +82909,14 @@ var RealUpstreamPlugin = class {
81351
82909
  if (!pkpValidation) {
81352
82910
  throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
81353
82911
  }
81354
- const registry = new import_ethers39.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
82912
+ const registry = new import_ethers49.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
81355
82913
  let validator;
81356
82914
  try {
81357
82915
  validator = await registry.validatorForVersion(version2);
81358
82916
  } catch (e) {
81359
82917
  throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
81360
82918
  }
81361
- if (validator === import_ethers39.ethers.ZeroAddress) {
82919
+ if (validator === import_ethers49.ethers.ZeroAddress) {
81362
82920
  throw new Error(
81363
82921
  `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.`
81364
82922
  );
@@ -81432,7 +82990,6 @@ var RealUpstreamPlugin = class {
81432
82990
  gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
81433
82991
  this.opsGatewayCache.set(key, gateway);
81434
82992
  }
81435
- await this.ensureSdk(key, wallet.connect(this.provider));
81436
82993
  return { ok: true, gateway };
81437
82994
  }
81438
82995
  if (mode === "external") {
@@ -81469,14 +83026,13 @@ var RealUpstreamPlugin = class {
81469
83026
  chainId: this.config.chainId,
81470
83027
  dhSigner: new ExternalEoaDHSigner(deps),
81471
83028
  session,
81472
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
83029
+ getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
81473
83030
  readDetails: (id) => this.readPositionDetails(id),
81474
83031
  psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81475
83032
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81476
83033
  });
81477
83034
  this.opsGatewayCache.set(key, gateway);
81478
83035
  }
81479
- await this.ensureSdk(key, this.externalSigners.get(key));
81480
83036
  return { ok: true, gateway };
81481
83037
  }
81482
83038
  return {
@@ -81636,7 +83192,7 @@ var RealUpstreamPlugin = class {
81636
83192
  );
81637
83193
  if (!r.ok) return r;
81638
83194
  const raw = r.value.data.supportedStablecoins ?? [];
81639
- const bad = raw.find((x) => !import_ethers39.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
83195
+ const bad = raw.find((x) => !import_ethers49.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
81640
83196
  if (bad) {
81641
83197
  return {
81642
83198
  ok: false,
@@ -81719,7 +83275,7 @@ var RealUpstreamPlugin = class {
81719
83275
  };
81720
83276
  }
81721
83277
  const symbol = raw.toLowerCase();
81722
- if (import_ethers39.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
83278
+ if (import_ethers49.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
81723
83279
  const verified = await this.verifiedStablecoins();
81724
83280
  if (!verified.ok) return { ok: false, failure: verified.failure };
81725
83281
  const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
@@ -81757,7 +83313,7 @@ var RealUpstreamPlugin = class {
81757
83313
  * chain, then sign.
81758
83314
  */
81759
83315
  async psmCallsFor(stablecoinAddress) {
81760
- if (!import_ethers39.ethers.isAddress(stablecoinAddress)) {
83316
+ if (!import_ethers49.ethers.isAddress(stablecoinAddress)) {
81761
83317
  throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
81762
83318
  }
81763
83319
  const key = stablecoinAddress.toLowerCase();
@@ -81777,9 +83333,9 @@ var RealUpstreamPlugin = class {
81777
83333
  let supported;
81778
83334
  let symbol;
81779
83335
  try {
81780
- const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
83336
+ const psm = new import_ethers49.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81781
83337
  supported = await psm["supportedStablecoins"](key);
81782
- const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
83338
+ const erc20 = new import_ethers49.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81783
83339
  symbol = await erc20["symbol"]();
81784
83340
  } catch (e) {
81785
83341
  return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
@@ -81992,7 +83548,7 @@ var RealUpstreamPlugin = class {
81992
83548
  const pm = this.contracts["PositionManager"];
81993
83549
  if (!pm) return false;
81994
83550
  try {
81995
- const c = new import_ethers39.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
83551
+ const c = new import_ethers49.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
81996
83552
  return Boolean(await c["paused"]());
81997
83553
  } catch {
81998
83554
  return false;
@@ -82001,16 +83557,16 @@ var RealUpstreamPlugin = class {
82001
83557
  async readPositionDetails(id) {
82002
83558
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
82003
83559
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
82004
- const c = new import_ethers39.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
83560
+ const c = new import_ethers49.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
82005
83561
  let d;
82006
83562
  try {
82007
- d = await c["getPositionDetails"](import_ethers39.ethers.zeroPadValue(id, 32));
83563
+ d = await c["getPositionDetails"](import_ethers49.ethers.zeroPadValue(id, 32));
82008
83564
  } catch (e) {
82009
83565
  if (e.code === "CALL_EXCEPTION") return null;
82010
83566
  throw e;
82011
83567
  }
82012
83568
  const borrower = String(d["borrower"]);
82013
- if (borrower === import_ethers39.ethers.ZeroAddress) return null;
83569
+ if (borrower === import_ethers49.ethers.ZeroAddress) return null;
82014
83570
  return {
82015
83571
  positionId: String(d["positionId"]),
82016
83572
  pkpId: String(d["pkpId"]),
@@ -83612,8 +85168,8 @@ async function buildBoundary(configResult, overrides) {
83612
85168
  );
83613
85169
  }
83614
85170
  try {
83615
- const decrypted = await import_ethers40.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
83616
- if (!(decrypted instanceof import_ethers40.ethers.Wallet)) {
85171
+ const decrypted = await import_ethers50.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85172
+ if (!(decrypted instanceof import_ethers50.ethers.Wallet)) {
83617
85173
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
83618
85174
  }
83619
85175
  wallet = decrypted;
@@ -84105,7 +85661,7 @@ on the real adapter and the mock.
84105
85661
  | extend | 1 personal-sign + 1 tx |
84106
85662
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
84107
85663
  | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
84108
- | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
85664
+ | PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
84109
85665
 
84110
85666
  **Honesty notes (say these plainly):**
84111
85667
  - **Reads never pop the wallet.** If a read needs a login the user does not have, the
@@ -84249,16 +85805,19 @@ rather than silently deliver less than quoted.
84249
85805
 
84250
85806
  ${psmStablecoinRealityNote(d)}
84251
85807
 
84252
- **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
84253
- result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
85808
+ **Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
85809
+ the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
85810
+ planned against the allowance already standing: none when it covers the amount, one when it
85811
+ is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
84254
85812
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
84255
85813
  the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84256
85814
  you approve UCD to the **UCDController** (the PSM burns your UCD through the
84257
85815
  controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84258
85816
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
84259
85817
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
84260
- own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
84261
- standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
85818
+ own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
85819
+ standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
85820
+ the next exchange that it covers uses it without asking for another approval.
84262
85821
  PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84263
85822
  REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84264
85823
  wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
@@ -84731,7 +86290,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
84731
86290
 
84732
86291
  // src/tools/loan.ts
84733
86292
  var import_zod = require("zod");
84734
- var import_ethers41 = require("ethers");
86293
+ var import_ethers51 = require("ethers");
84735
86294
 
84736
86295
  // src/util/format.ts
84737
86296
  function bigintReplacer(_key, value) {
@@ -84919,7 +86478,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84919
86478
  const b = getB();
84920
86479
  if (!b.ok) return renderError(b.error);
84921
86480
  return renderEnvelope(
84922
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
86481
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers51.parseEther)(amountUcd.toString()).toString() })
84923
86482
  );
84924
86483
  })
84925
86484
  );
@@ -84957,7 +86516,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84957
86516
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
84958
86517
  amountUcdWei = detail.data.debtUcdWei;
84959
86518
  } else {
84960
- amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
86519
+ amountUcdWei = (0, import_ethers51.parseEther)(amountUcd.toString()).toString();
84961
86520
  }
84962
86521
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
84963
86522
  })
@@ -85358,7 +86917,7 @@ function registerPsmTools(server, getB) {
85358
86917
  "psm_swap",
85359
86918
  {
85360
86919
  title: "Exchange UCD \u2194 a stablecoin through the PSM",
85361
- 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).",
86920
+ 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).",
85362
86921
  inputSchema: {
85363
86922
  stablecoin: import_zod4.z.string().min(1).describe(
85364
86923
  "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."
@@ -85374,7 +86933,7 @@ function registerPsmTools(server, getB) {
85374
86933
  const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
85375
86934
  const gate = requireConfirmation(
85376
86935
  confirmed,
85377
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
86936
+ `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"})`
85378
86937
  );
85379
86938
  if (gate) return gate;
85380
86939
  const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
@@ -85560,7 +87119,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
85560
87119
 
85561
87120
  // src/tools/signer.ts
85562
87121
  var import_zod6 = require("zod");
85563
- var import_ethers42 = require("ethers");
87122
+ var import_ethers52 = require("ethers");
85564
87123
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
85565
87124
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
85566
87125
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -85602,7 +87161,7 @@ function registerSignerTool(server, getRuntime, opts) {
85602
87161
  if (mode !== void 0 && !offeredModes.includes(mode)) {
85603
87162
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
85604
87163
  }
85605
- if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
87164
+ if (safeAddress !== void 0 && !import_ethers52.ethers.isAddress(safeAddress)) {
85606
87165
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
85607
87166
  }
85608
87167
  if (action === "status") {