@gvnrdao/dh-mcp 0.5.15 → 0.5.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
@@ -41038,7 +41072,7 @@ function htmlPageSecurityHeaders(extra) {
41038
41072
  }
41039
41073
 
41040
41074
  // src/version.ts
41041
- var SERVER_VERSION = "0.5.15";
41075
+ var SERVER_VERSION = "0.5.17";
41042
41076
 
41043
41077
  // src/connector/siwe-oauth.ts
41044
41078
  var import_node_crypto2 = require("crypto");
@@ -41756,7 +41790,7 @@ function resolveRealConfig(env) {
41756
41790
 
41757
41791
  // src/boot.ts
41758
41792
  var fs6 = __toESM(require("fs"));
41759
- var import_ethers40 = require("ethers");
41793
+ var import_ethers50 = require("ethers");
41760
41794
 
41761
41795
  // src/boundary/index.ts
41762
41796
  var import_node_crypto9 = require("crypto");
@@ -42173,7 +42207,7 @@ var BoundaryCore = class {
42173
42207
  const inToken = toUcd ? s.stablecoinSymbol : "UCD";
42174
42208
  const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
42175
42209
  const amountIn = parseDecimalUnits(p.amount, inDecimals);
42176
- const refuse = (refusal, message, details) => ({
42210
+ const refuse3 = (refusal, message, details) => ({
42177
42211
  env: errEnvelope(
42178
42212
  boundaryError("UPSTREAM_REJECTED", message, {
42179
42213
  source: statusR.source.id,
@@ -42184,13 +42218,13 @@ var BoundaryCore = class {
42184
42218
  });
42185
42219
  const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
42186
42220
  if (s.paused) {
42187
- return refuse(
42221
+ return refuse3(
42188
42222
  "psm-paused",
42189
42223
  "the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
42190
42224
  );
42191
42225
  }
42192
42226
  if (!toUcd && !s.redeemEnabled) {
42193
- return refuse(
42227
+ return refuse3(
42194
42228
  "redeem-disabled",
42195
42229
  `redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
42196
42230
  );
@@ -42201,20 +42235,20 @@ var BoundaryCore = class {
42201
42235
  const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
42202
42236
  const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
42203
42237
  if (amountIn < min) {
42204
- return refuse(
42238
+ return refuse3(
42205
42239
  "below-min",
42206
42240
  `${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
42207
42241
  { amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
42208
42242
  );
42209
42243
  }
42210
42244
  if (max === 0n) {
42211
- return refuse(
42245
+ return refuse3(
42212
42246
  "direction-disabled",
42213
42247
  `the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
42214
42248
  );
42215
42249
  }
42216
42250
  if (amountIn > max) {
42217
- return refuse(
42251
+ return refuse3(
42218
42252
  "above-max",
42219
42253
  `${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
42220
42254
  { amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
@@ -42234,7 +42268,7 @@ var BoundaryCore = class {
42234
42268
  if (!toUcd) {
42235
42269
  const available = BigInt(s.availableReserves);
42236
42270
  if (available < amountOut) {
42237
- return refuse(
42271
+ return refuse3(
42238
42272
  "insufficient-reserves",
42239
42273
  `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).`,
42240
42274
  { available: available.toString(), required: amountOut.toString(), unit: outUnit }
@@ -42310,20 +42344,31 @@ var BoundaryCore = class {
42310
42344
  const inDecimals = toUcd ? s.stablecoinDecimals : 18;
42311
42345
  const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
42312
42346
  const viaSafe = this.deps.signer?.mode() === "safe";
42347
+ const a = v.allowance;
42348
+ const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
42349
+ 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(
42350
+ (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}`
42351
+ ).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
42313
42352
  const data = {
42314
42353
  direction: p.direction,
42315
42354
  contractCall: q.contractCall,
42316
- approve: {
42317
- txRef: v.approve.txRef,
42318
- token: v.approve.tokenSymbol,
42319
- tokenAddress: v.approve.tokenAddress,
42320
- spenderAddress: v.approve.spenderAddress,
42321
- spenderContract: v.approve.spenderContract,
42322
- 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",
42323
- amount: v.approve.amount,
42355
+ allowance: {
42356
+ token: a.tokenSymbol,
42357
+ tokenAddress: a.tokenAddress,
42358
+ spenderAddress: a.spenderAddress,
42359
+ spenderContract: a.spenderContract,
42360
+ 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",
42361
+ before: a.before,
42324
42362
  amountUnit: q.amountInUnit,
42325
- authorization: v.approve.authorization
42363
+ 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."
42326
42364
  },
42365
+ approvals: v.approvals.map((leg) => ({
42366
+ step: leg.step,
42367
+ txRef: leg.txRef,
42368
+ amount: leg.amount,
42369
+ amountUnit: q.amountInUnit,
42370
+ authorization: leg.authorization
42371
+ })),
42327
42372
  execute: {
42328
42373
  txRef: v.execute.txRef,
42329
42374
  amountIn: v.execute.amountIn,
@@ -42345,7 +42390,7 @@ var BoundaryCore = class {
42345
42390
  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"
42346
42391
  },
42347
42392
  balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
42348
- 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}.`)
42393
+ 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}.`)
42349
42394
  };
42350
42395
  return okEnvelope(data, r.source, warnings);
42351
42396
  }
@@ -44204,6 +44249,16 @@ function buildExtendTx(ctx, p) {
44204
44249
  );
44205
44250
  }
44206
44251
 
44252
+ // src/boundary/upstream/shared/psm-approval-steps.ts
44253
+ function psmApprovalSteps(allowanceBefore, amountIn) {
44254
+ if (allowanceBefore >= amountIn) return [];
44255
+ if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
44256
+ return [
44257
+ { step: "reset-approve", amount: 0n },
44258
+ { step: "approve", amount: amountIn }
44259
+ ];
44260
+ }
44261
+
44207
44262
  // src/boundary/upstream/mock/sink-contracts.ts
44208
44263
  var import_ethers6 = require("ethers");
44209
44264
  function sinkAddress(label) {
@@ -45039,8 +45094,9 @@ var MockUpstreamPlugin = class {
45039
45094
  return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
45040
45095
  });
45041
45096
  }
45042
- /** PSM exchange pair (plan 08 W1): TWO ceremonies in ONE ops call — the exact-amount
45043
- * approve (spender asymmetric by direction, contract truth), then the swap/redeem with
45097
+ /** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
45098
+ * or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
45099
+ * asymmetric by direction, contract truth), then the swap/redeem with
45044
45100
  * its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
45045
45101
  * AFTER the approve reports the step that declined AND the residual exact-amount
45046
45102
  * allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
@@ -45059,55 +45115,75 @@ var MockUpstreamPlugin = class {
45059
45115
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
45060
45116
  const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
45061
45117
  const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
45062
- 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`;
45063
- const approveCard = `approve exactly ${p.amountIn} ${tokenUnit} to ${spenderContract} (${spenderReason})`;
45118
+ const standing = this.world.psmAllowancesOf(p.borrower);
45119
+ const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
45120
+ const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
45121
+ const landed = [];
45122
+ const residualNote = () => {
45123
+ const last = landed[landed.length - 1];
45124
+ 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`;
45125
+ return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
45126
+ };
45064
45127
  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}`;
45065
45128
  const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
45066
45129
  const cer = this.ceremonyNow();
45067
- let approveAuth = null;
45068
- if (cer) {
45069
- const chainId = cer.txContext().chainId;
45070
- const approveTx = buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount: p.amountIn });
45071
- const r = await cer.authorizeTx({
45072
- action: "psm-approve",
45073
- borrower: p.borrower,
45074
- tx: approveTx,
45075
- expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn }
45076
- });
45077
- if (!r.ok) {
45078
- return upFail({
45079
- kind: "rejected",
45080
- source: "mock-ops",
45081
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(r.failure)} \u2014 no allowance was granted and no funds moved`
45130
+ const approvals = [];
45131
+ for (const s of steps) {
45132
+ const amount = s.amount.toString();
45133
+ const isReset = s.step === "reset-approve";
45134
+ const label = isReset ? "RESET-APPROVE" : "APPROVE";
45135
+ 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";
45136
+ 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})`;
45137
+ let legAuth = null;
45138
+ if (cer) {
45139
+ const chainId = cer.txContext().chainId;
45140
+ const r = await cer.authorizeTx({
45141
+ action: "psm-approve",
45142
+ borrower: p.borrower,
45143
+ tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
45144
+ expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
45082
45145
  });
45146
+ if (!r.ok) {
45147
+ return upFail({
45148
+ kind: "rejected",
45149
+ source: "mock-ops",
45150
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
45151
+ });
45152
+ }
45153
+ this.bindIfDiscovering(r.authorization);
45154
+ legAuth = r.authorization;
45083
45155
  }
45084
- this.bindIfDiscovering(r.authorization);
45085
- approveAuth = r.authorization;
45086
- }
45087
- const step1 = await this.write("psmSwap", () => {
45088
- const sig = approveAuth ? { ok: true, authorization: approveAuth } : this.sign("psm-approve", p.borrower, approveCard);
45089
- if (!sig.ok) {
45090
- return upFail({
45091
- kind: "rejected",
45092
- source: "mock-ops",
45093
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(sig.failure)} \u2014 no allowance was granted and no funds moved`
45156
+ const leg = await this.write("psmSwap", () => {
45157
+ const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
45158
+ if (!sig.ok) {
45159
+ return upFail({
45160
+ kind: "rejected",
45161
+ source: "mock-ops",
45162
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
45163
+ });
45164
+ }
45165
+ const applied = this.applyAuthorized(sig.authorization, () => {
45166
+ this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
45167
+ return { ok: true, value: void 0 };
45094
45168
  });
45095
- }
45096
- const applied = this.applyAuthorized(sig.authorization, () => {
45097
- this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount: p.amountIn });
45098
- return { ok: true, value: void 0 };
45169
+ if (!applied.ok) {
45170
+ return upFail({
45171
+ kind: "rejected",
45172
+ source: "mock-ops",
45173
+ message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
45174
+ });
45175
+ }
45176
+ return upOk(sig.authorization, this.src("mock-ops"));
45099
45177
  });
45100
- if (!applied.ok) {
45101
- return upFail({
45102
- kind: "rejected",
45103
- source: "mock-ops",
45104
- message: `psmSwap failed at the APPROVE step: ${applied.reason} \u2014 no allowance was granted and no funds moved`
45105
- });
45106
- }
45107
- return upOk(sig.authorization, this.src("mock-ops"));
45108
- });
45109
- if (!step1.ok) return step1;
45110
- const aAuth = step1.value;
45178
+ if (!leg.ok) return leg;
45179
+ landed.push(s.step);
45180
+ approvals.push({
45181
+ step: s.step,
45182
+ txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
45183
+ amount,
45184
+ authorization: leg.value
45185
+ });
45186
+ }
45111
45187
  let executeAuth = null;
45112
45188
  if (cer) {
45113
45189
  const chainId = cer.txContext().chainId;
@@ -45122,7 +45198,7 @@ var MockUpstreamPlugin = class {
45122
45198
  return upFail({
45123
45199
  kind: "rejected",
45124
45200
  source: "mock-ops",
45125
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
45201
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
45126
45202
  });
45127
45203
  }
45128
45204
  executeAuth = r.authorization;
@@ -45133,23 +45209,16 @@ var MockUpstreamPlugin = class {
45133
45209
  return upFail({
45134
45210
  kind: "rejected",
45135
45211
  source: "mock-ops",
45136
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
45212
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
45137
45213
  });
45138
45214
  }
45139
45215
  const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
45140
- if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
45216
+ if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
45141
45217
  const bal = this.world.balancesOf(p.borrower);
45142
45218
  return upOk(
45143
45219
  {
45144
- approve: {
45145
- txRef: approveAuth ? { kind: "eth-tx", id: aAuth.digest } : this.world.nextTxRef(),
45146
- tokenSymbol,
45147
- tokenAddress,
45148
- spenderAddress,
45149
- spenderContract,
45150
- amount: p.amountIn,
45151
- authorization: aAuth
45152
- },
45220
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
45221
+ approvals,
45153
45222
  execute: {
45154
45223
  txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
45155
45224
  amountIn: p.amountIn,
@@ -46330,7 +46399,7 @@ var SafeModuleCeremony = class {
46330
46399
  };
46331
46400
 
46332
46401
  // src/boundary/upstream/real/plugin.ts
46333
- var import_ethers39 = require("ethers");
46402
+ var import_ethers49 = require("ethers");
46334
46403
 
46335
46404
  // node_modules/@gvnrdao/dh-sdk/dist/index.mjs
46336
46405
  var import_ethers14 = require("ethers");
@@ -52421,8 +52490,12 @@ var {
52421
52490
  var import_ethers28 = require("ethers");
52422
52491
  var import_ethers29 = require("ethers");
52423
52492
  var import_ethers30 = require("ethers");
52424
- var import_dh_lit_ops = __toESM(require_dist3(), 1);
52425
52493
  var import_ethers31 = require("ethers");
52494
+ var import_ethers32 = require("ethers");
52495
+ var import_ethers33 = require("ethers");
52496
+ var import_ethers34 = require("ethers");
52497
+ var import_dh_lit_ops = __toESM(require_dist3(), 1);
52498
+ var import_ethers35 = require("ethers");
52426
52499
  var __create2 = Object.create;
52427
52500
  var __defProp2 = Object.defineProperty;
52428
52501
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -54785,7 +54858,7 @@ ${errorReport}`);
54785
54858
  }
54786
54859
  init_debug_logger();
54787
54860
  init_session_signature_cache();
54788
- var import_ethers192 = __require("ethers");
54861
+ var import_ethers232 = __require("ethers");
54789
54862
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
54790
54863
  var GRACE_PERIOD_DAYS = 30;
54791
54864
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -57713,12 +57786,12 @@ ${auth.clientId}`;
57713
57786
  }
57714
57787
  async function executeVaultSnapshot(params) {
57715
57788
  global.ethers = {
57716
- ...import_ethers192.ethers,
57789
+ ...import_ethers232.ethers,
57717
57790
  providers: {
57718
- StaticJsonRpcProvider: import_ethers192.ethers.JsonRpcProvider
57791
+ StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
57719
57792
  },
57720
- Contract: import_ethers192.ethers.Contract,
57721
- utils: import_ethers192.ethers
57793
+ Contract: import_ethers232.ethers.Contract,
57794
+ utils: import_ethers232.ethers
57722
57795
  // v6 moved utils to top level
57723
57796
  };
57724
57797
  global.Lit = {
@@ -57972,8 +58045,8 @@ function getSepoliaConfig() {
57972
58045
  positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
57973
58046
  positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
57974
58047
  simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
57975
- mockUsdcToken: SEPOLIA_CONTRACTS["MockUSDC"] || "",
57976
- mockUsdtToken: SEPOLIA_CONTRACTS["MockUSDT"] || "",
58048
+ mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
58049
+ mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
57977
58050
  loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
57978
58051
  termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
57979
58052
  circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
@@ -58049,14 +58122,17 @@ function getMainnetConfig() {
58049
58122
  agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
58050
58123
  },
58051
58124
  subgraphs: {
58052
- // KNOWN-WRONG placeholder (see GOAL-PLAN step 2 / dogfood F-CLI-4): this is a
58053
- // SEPOLIA subgraph id in a mainnet (chainId 1) config, and this gateway host
58054
- // needs an Authorization key the SDK does not (and must not) hold — so the
58055
- // URL is doubly unusable. The `CCTPsd…` path segment is the subgraph's
58056
- // PUBLIC ID, not a credential. The fix is a chain-correct SERVER-side proxy
58057
- // (see mcp/docs/SUBGRAPH-PROXY-PLAN.md) — same rule as rpcUrls above:
58058
- // never ship an API-keyed URL in a client config.
58059
- diamondHandsUrl: "https://gateway-arbitrum.network.thegraph.com/api/subgraphs/id/CCTPsdYqco2jChDLLBQTbdJWwoukVoMt1cXeR9ti6r9A"
58125
+ // The MAINNET subgraph on The Graph's decentralized network — the same id
58126
+ // lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
58127
+ // the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
58128
+ // chainId-1 config: unusable as shipped, but a caller who added their own key would have
58129
+ // read Sepolia data as mainnet.
58130
+ //
58131
+ // The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
58132
+ // not) hold, so this URL only works for a standalone caller supplying their own key.
58133
+ // Service mode never uses it — queries go through the lit-ops-server proxy, which adds
58134
+ // the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
58135
+ diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
58060
58136
  },
58061
58137
  litNetwork: "chipotle",
58062
58138
  debug: false
@@ -59077,6 +59153,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
59077
59153
  }
59078
59154
  return { timestamp: result.timestamp, signature: result.signature };
59079
59155
  }
59156
+ function baseMintFeeWei(mintAmountWei, originationFeeBps) {
59157
+ if (mintAmountWei < 0n)
59158
+ throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
59159
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59160
+ throw new Error(
59161
+ `baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59162
+ );
59163
+ }
59164
+ return mintAmountWei * BigInt(originationFeeBps) / 10000n;
59165
+ }
59166
+ function debtAfterMintExceedsLoanCap(params) {
59167
+ const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
59168
+ for (const [name, v] of Object.entries(params)) {
59169
+ if (v < 0n)
59170
+ throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
59171
+ }
59172
+ return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
59173
+ }
59174
+ function maxPrincipalWithinLoanCap(params) {
59175
+ const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
59176
+ if (maxLoanWei < 0n || currentDebtWei < 0n) {
59177
+ throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
59178
+ }
59179
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59180
+ throw new Error(
59181
+ `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59182
+ );
59183
+ }
59184
+ const room = maxLoanWei - currentDebtWei;
59185
+ if (room <= 0n)
59186
+ return 0n;
59187
+ return room * 10000n / (10000n + BigInt(originationFeeBps));
59188
+ }
59080
59189
  function buildLoginDomain(chainId) {
59081
59190
  return {
59082
59191
  name: "Diamond Hands",
@@ -60486,23 +60595,37 @@ var BitcoinUtils = class {
60486
60595
  return getBitcoinAddressesFromPkp(pkpPublicKey);
60487
60596
  }
60488
60597
  };
60489
- function safeValidateBitcoinAddress(address, network = "regtest") {
60598
+ function networksOfValidAddress(address) {
60599
+ const lower2 = address.toLowerCase();
60600
+ if (lower2.startsWith("bcrt1"))
60601
+ return ["regtest"];
60602
+ if (lower2.startsWith("bc1"))
60603
+ return ["mainnet"];
60604
+ if (lower2.startsWith("tb1"))
60605
+ return ["testnet"];
60606
+ if (address.startsWith("1") || address.startsWith("3"))
60607
+ return ["mainnet"];
60608
+ return ["testnet", "regtest"];
60609
+ }
60610
+ function safeValidateBitcoinAddress(address, network) {
60490
60611
  if (!address || typeof address !== "string") {
60491
60612
  throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
60492
60613
  }
60493
- const base58Pattern = /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/;
60494
- const bech32Pattern = /^(bc1|tb1|bcrt1)[a-z0-9]+$/;
60495
- if (!base58Pattern.test(address) && !bech32Pattern.test(address)) {
60496
- throw new Error(`Invalid Bitcoin address format: ${address}`);
60614
+ if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
60615
+ throw new Error(
60616
+ `Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
60617
+ );
60618
+ }
60619
+ if (!BitcoinUtils.validateAddress(address)) {
60620
+ throw new Error(
60621
+ `Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
60622
+ );
60497
60623
  }
60498
- if (network === "regtest" || network === "testnet") {
60499
- if (!address.startsWith("m") && !address.startsWith("n") && !address.startsWith("2") && !address.startsWith("tb1") && !address.startsWith("bcrt1")) {
60500
- throw new Error(`Invalid ${network} Bitcoin address: ${address} (must start with m, n, 2, tb1, or bcrt1)`);
60501
- }
60502
- } else if (network === "mainnet") {
60503
- if (!address.startsWith("1") && !address.startsWith("3") && !address.startsWith("bc1")) {
60504
- throw new Error(`Invalid mainnet Bitcoin address: ${address} (must start with 1, 3, or bc1)`);
60505
- }
60624
+ const belongsTo = networksOfValidAddress(address);
60625
+ if (!belongsTo.includes(network)) {
60626
+ throw new Error(
60627
+ `Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
60628
+ );
60506
60629
  }
60507
60630
  return address;
60508
60631
  }
@@ -62611,6 +62734,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
62611
62734
  LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
62612
62735
  return LoanStatus2;
62613
62736
  })(LoanStatus || {});
62737
+ var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
62738
+ var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
62739
+ var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
62740
+ async function collectBorrowerDebtRows(fetchPage) {
62741
+ const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
62742
+ const rows = [];
62743
+ for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
62744
+ const batch = await fetchPage(page * pageSize, pageSize);
62745
+ if (batch.length > pageSize) {
62746
+ throw new Error(
62747
+ `Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
62748
+ );
62749
+ }
62750
+ rows.push(...batch);
62751
+ if (batch.length < pageSize) {
62752
+ return rows;
62753
+ }
62754
+ }
62755
+ throw new Error(
62756
+ `Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
62757
+ );
62758
+ }
62759
+ function parseSubgraphLoanStatus(label) {
62760
+ if (typeof label !== "string") {
62761
+ throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
62762
+ }
62763
+ const value = LoanStatus[label];
62764
+ if (typeof value !== "number") {
62765
+ throw new Error(`Unknown subgraph loan status label: "${label}"`);
62766
+ }
62767
+ return value;
62768
+ }
62769
+ function parseSubgraphWei(row) {
62770
+ const raw = row.ucdDebt || "0";
62771
+ if (typeof raw !== "string") {
62772
+ throw new Error(
62773
+ `ucdDebt on position ${row.id} is not a string: ${String(raw)}`
62774
+ );
62775
+ }
62776
+ let wei;
62777
+ try {
62778
+ wei = BigInt(raw);
62779
+ } catch (error) {
62780
+ throw new Error(
62781
+ `ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
62782
+ { cause: error }
62783
+ );
62784
+ }
62785
+ if (wei < 0n) {
62786
+ throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
62787
+ }
62788
+ return wei;
62789
+ }
62790
+ var WEI_PER_UCD = 10n ** 18n;
62791
+ function weiToHumanUcdString(wei) {
62792
+ if (wei < 0n) {
62793
+ throw new Error(`Cannot render negative wei: ${wei}`);
62794
+ }
62795
+ const whole = wei / WEI_PER_UCD;
62796
+ const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
62797
+ return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
62798
+ }
62799
+ var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
62800
+ function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
62801
+ let totalWei = 0n;
62802
+ const counts = /* @__PURE__ */ new Map();
62803
+ for (const row of rows) {
62804
+ totalWei += parseSubgraphWei(row);
62805
+ const status = parseSubgraphLoanStatus(row.status);
62806
+ counts.set(status, (counts.get(status) ?? 0) + 1);
62807
+ }
62808
+ const byStatus = [];
62809
+ for (const status of STATUS_ORDINALS) {
62810
+ const count = counts.get(status);
62811
+ if (count === void 0) {
62812
+ continue;
62813
+ }
62814
+ byStatus.push({ status, statusLabel: LoanStatus[status], count });
62815
+ }
62816
+ return {
62817
+ borrower: borrower.toLowerCase(),
62818
+ loanCount: rows.length,
62819
+ totalUcdDebt: totalWei.toString(),
62820
+ totalUcdDebtHuman: weiToHumanUcdString(totalWei),
62821
+ byStatus,
62822
+ source: "subgraph",
62823
+ fetchedAt
62824
+ };
62825
+ }
62614
62826
  var POSITION_CORE_ABI = [
62615
62827
  "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))"
62616
62828
  ];
@@ -63003,6 +63215,43 @@ var LoanQuery = class {
63003
63215
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
63004
63216
  return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
63005
63217
  }
63218
+ /**
63219
+ * Combined UCD debt + by-status counts for a borrower from ONE pass over the
63220
+ * subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
63221
+ * status labels, `source: "subgraph"`.
63222
+ *
63223
+ * INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
63224
+ * sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
63225
+ * failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
63226
+ * is no partial total.
63227
+ */
63228
+ async getBorrowerUcdDebtSummary(borrower) {
63229
+ const trimmed = typeof borrower === "string" ? borrower.trim() : "";
63230
+ if (!(0, import_ethers26.isAddress)(trimmed)) {
63231
+ return failure(
63232
+ new SDKError({
63233
+ message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
63234
+ category: "VALIDATION",
63235
+ severity: "LOW",
63236
+ context: { borrower: trimmed }
63237
+ })
63238
+ );
63239
+ }
63240
+ return tryCatchAsync(
63241
+ async () => {
63242
+ const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
63243
+ return buildBorrowerUcdDebtSummary(trimmed, rows);
63244
+ },
63245
+ (error) => error instanceof SDKError ? error : new SDKError({
63246
+ message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
63247
+ category: "SUBGRAPH",
63248
+ severity: "MEDIUM",
63249
+ originalError: error instanceof Error ? error : void 0,
63250
+ cause: error,
63251
+ context: { borrower: trimmed }
63252
+ })
63253
+ );
63254
+ }
63006
63255
  /**
63007
63256
  * Get active loans (status = ACTIVE)
63008
63257
  *
@@ -64528,7 +64777,35 @@ var GraphClient = class {
64528
64777
  await new Promise((r) => setTimeout(r, ms));
64529
64778
  }
64530
64779
  };
64531
- var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
64780
+ var GET_USER_POSITIONS_DOCUMENT = `
64781
+ query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64782
+ user(id: $borrower) {
64783
+ id
64784
+ positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64785
+ id
64786
+ pkpId
64787
+ borrower {
64788
+ createdAt
64789
+ id
64790
+ }
64791
+ # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64792
+ ucdMinted
64793
+ ucdPaid
64794
+ ucdDebt
64795
+ collateralRatio
64796
+ requestedCollateralRatio
64797
+ selectedTerm
64798
+ status
64799
+ createdAt
64800
+ createdAtBlock
64801
+ lastUpdated
64802
+ originalTerm
64803
+ remainingDebt
64804
+ expiryAt
64805
+ }
64806
+ }
64807
+ }
64808
+ `;
64532
64809
  function normalizePkpId2(pkpId) {
64533
64810
  const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
64534
64811
  if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
@@ -64846,35 +65123,7 @@ var DiamondHandsGraph = class {
64846
65123
  * Get user positions from subgraph
64847
65124
  */
64848
65125
  async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
64849
- const query = `
64850
- query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64851
- user(id: $borrower) {
64852
- id
64853
- positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64854
- id
64855
- pkpId
64856
- borrower {
64857
- createdAt
64858
- id
64859
- }
64860
- # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64861
- ucdMinted
64862
- ucdPaid
64863
- ucdDebt
64864
- collateralRatio
64865
- requestedCollateralRatio
64866
- selectedTerm
64867
- status
64868
- createdAt
64869
- createdAtBlock
64870
- lastUpdated
64871
- originalTerm
64872
- remainingDebt
64873
- expiryAt
64874
- }
64875
- }
64876
- }
64877
- `;
65126
+ const query = GET_USER_POSITIONS_DOCUMENT;
64878
65127
  const variables = {
64879
65128
  borrower: userAddress.toLowerCase(),
64880
65129
  first: first || void 0,
@@ -64892,6 +65141,45 @@ var DiamondHandsGraph = class {
64892
65141
  }
64893
65142
  return positions;
64894
65143
  }
65144
+ /**
65145
+ * Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
65146
+ * 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
65147
+ * coerces wei to a float and leaves `status` a string cast to the numeric enum).
65148
+ *
65149
+ * Deliberately issues the `GetUserPositions` document rather than a leaner one: the
65150
+ * lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
65151
+ * and that one is already listed, so this needs no server change. The extra fields
65152
+ * cost bytes, not round trips.
65153
+ *
65154
+ * Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
65155
+ */
65156
+ async getBorrowerDebtRows(borrower) {
65157
+ const borrowerId = borrower.toLowerCase();
65158
+ return collectBorrowerDebtRows(async (skip, first) => {
65159
+ const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
65160
+ borrower: borrowerId,
65161
+ first,
65162
+ skip,
65163
+ orderBy: "id",
65164
+ orderDirection: "asc"
65165
+ });
65166
+ if (result?.user == null) {
65167
+ if (skip > 0) {
65168
+ throw new Error(
65169
+ `getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
65170
+ );
65171
+ }
65172
+ return [];
65173
+ }
65174
+ const positions = result.user.positions;
65175
+ if (!Array.isArray(positions)) {
65176
+ throw new Error(
65177
+ `getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
65178
+ );
65179
+ }
65180
+ return positions.filter((p) => p != null);
65181
+ });
65182
+ }
64895
65183
  /**
64896
65184
  * Get user positions, plus an accurate total count.
64897
65185
  *
@@ -71060,6 +71348,603 @@ async function mintAgentPkp(params) {
71060
71348
  clearTimeout(timeout);
71061
71349
  }
71062
71350
  }
71351
+ var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
71352
+ function planAgentBinding(params) {
71353
+ const { isActive, record, nowSeconds } = params;
71354
+ if (isActive)
71355
+ return { kind: "reuse", agent: record.agent };
71356
+ const status = Number(record.status);
71357
+ if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
71358
+ return { kind: "register" };
71359
+ }
71360
+ if (status !== AGENT_STATUS.Active) {
71361
+ throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
71362
+ }
71363
+ if (Number(record.validUntil) > nowSeconds) {
71364
+ throw new Error(
71365
+ "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
71366
+ );
71367
+ }
71368
+ return { kind: "rotate" };
71369
+ }
71370
+ async function describeProviderChainMismatch(provider, chainId) {
71371
+ const actual = Number((await provider.getNetwork()).chainId);
71372
+ if (actual === chainId)
71373
+ return null;
71374
+ 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.`;
71375
+ }
71376
+ var TxValidationError2 = class extends Error {
71377
+ /**
71378
+ * @param subject What is being refused. Defaults to the server-returned transaction the
71379
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
71380
+ */
71381
+ constructor(msg, subject = "server-returned transaction") {
71382
+ super(`Refusing to sign ${subject}: ${msg}`);
71383
+ this.name = "TxValidationError";
71384
+ }
71385
+ };
71386
+ var SIGNABLE_FUNCTIONS2 = [
71387
+ "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)",
71388
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
71389
+ // used to sit here; it is not a function on any deployed contract — the
71390
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
71391
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
71392
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
71393
+ // it. A signable-function whitelist should not carry calldata shapes the
71394
+ // protocol cannot execute.
71395
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
71396
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
71397
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
71398
+ // Struct-version: matches the actual on-chain function signature and the
71399
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
71400
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
71401
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
71402
+ "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)",
71403
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
71404
+ // function reverts permanently. The trustless replacement
71405
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
71406
+ // entry when its LIT Action ships.
71407
+ "function approve(address spender, uint256 amount) external returns (bool)",
71408
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
71409
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
71410
+ // without an entry here it decoded as "<unparseable>" and the CLI's
71411
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
71412
+ // collateral had no client-side pin at all.
71413
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
71414
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
71415
+ // AgentModule; the parity test documents them as client-only.
71416
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
71417
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
71418
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
71419
+ // this too is client-only and never module-whitelisted.
71420
+ "function addAddress(string btcAddress) external"
71421
+ ];
71422
+ var IFACE2 = new import_ethers32.ethers.Interface(SIGNABLE_FUNCTIONS2);
71423
+ function encodeSignable2(fn, args) {
71424
+ return IFACE2.encodeFunctionData(fn, args);
71425
+ }
71426
+ function decodeSignable2(data) {
71427
+ try {
71428
+ const parsed = IFACE2.parseTransaction({ data });
71429
+ if (!parsed) {
71430
+ throw new TxValidationError2(
71431
+ `unsignedTx.data does not decode against the signable-function whitelist`
71432
+ );
71433
+ }
71434
+ return { name: parsed.name, args: parsed.args };
71435
+ } catch (e) {
71436
+ if (e instanceof TxValidationError2)
71437
+ throw e;
71438
+ throw new TxValidationError2(
71439
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
71440
+ );
71441
+ }
71442
+ }
71443
+ var MAX_GAS_LIMIT = 5000000n;
71444
+ var MAX_FEE_PER_GAS_WEI = 2000000000000n;
71445
+ var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
71446
+ var DEFAULT_FEE_CEILING = {
71447
+ maxGasLimit: MAX_GAS_LIMIT,
71448
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
71449
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
71450
+ };
71451
+ function fmtEth(wei) {
71452
+ return `${import_ethers34.ethers.formatEther(wei)} ETH`;
71453
+ }
71454
+ function fmtGwei(wei) {
71455
+ return `${import_ethers34.ethers.formatUnits(wei, "gwei")} gwei`;
71456
+ }
71457
+ function worstCaseFeeWei(gasLimit, maxFeePerGas) {
71458
+ if (gasLimit == null || maxFeePerGas == null)
71459
+ return null;
71460
+ return gasLimit * maxFeePerGas;
71461
+ }
71462
+ function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
71463
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
71464
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
71465
+ }
71466
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
71467
+ raise(
71468
+ `maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
71469
+ );
71470
+ }
71471
+ const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
71472
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
71473
+ raise(
71474
+ `worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
71475
+ );
71476
+ }
71477
+ }
71478
+ function eqAddr2(a, b) {
71479
+ if (!a || !b)
71480
+ return false;
71481
+ try {
71482
+ return import_ethers33.ethers.getAddress(a) === import_ethers33.ethers.getAddress(b);
71483
+ } catch {
71484
+ return false;
71485
+ }
71486
+ }
71487
+ function readToAddress2(tx2) {
71488
+ const to = tx2["to"];
71489
+ if (typeof to !== "string") {
71490
+ throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
71491
+ }
71492
+ return to;
71493
+ }
71494
+ function readData2(tx2) {
71495
+ const data = tx2["data"];
71496
+ if (typeof data !== "string" || !data.startsWith("0x")) {
71497
+ throw new TxValidationError2(`unsignedTx.data missing or malformed`);
71498
+ }
71499
+ return data;
71500
+ }
71501
+ function readChainId2(tx2) {
71502
+ const c = tx2["chainId"];
71503
+ if (c == null)
71504
+ return null;
71505
+ if (typeof c === "number")
71506
+ return c;
71507
+ if (typeof c === "string")
71508
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
71509
+ if (typeof c === "bigint")
71510
+ return Number(c);
71511
+ return null;
71512
+ }
71513
+ function readOptionalBigInt(tx2, key) {
71514
+ const v = tx2[key];
71515
+ if (v == null)
71516
+ return null;
71517
+ try {
71518
+ if (typeof v === "bigint")
71519
+ return v;
71520
+ if (typeof v === "number")
71521
+ return BigInt(v);
71522
+ if (typeof v === "string")
71523
+ return BigInt(v);
71524
+ return BigInt(v.toString());
71525
+ } catch {
71526
+ throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
71527
+ }
71528
+ }
71529
+ function readValue2(tx2) {
71530
+ const v = tx2["value"];
71531
+ if (v == null)
71532
+ return 0n;
71533
+ if (typeof v === "string")
71534
+ return BigInt(v);
71535
+ if (typeof v === "number")
71536
+ return BigInt(v);
71537
+ if (typeof v === "bigint")
71538
+ return v;
71539
+ const maybe = v;
71540
+ if (typeof maybe.toBigInt === "function")
71541
+ return maybe.toBigInt();
71542
+ if (typeof maybe.toString === "function")
71543
+ return BigInt(maybe.toString());
71544
+ throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
71545
+ }
71546
+ function normalizePositionId2(id) {
71547
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
71548
+ return import_ethers33.ethers.zeroPadValue(hex, 32).toLowerCase();
71549
+ }
71550
+ function requirePositionId(actual, expected) {
71551
+ const txPositionId = String(actual).toLowerCase();
71552
+ if (txPositionId !== normalizePositionId2(expected)) {
71553
+ throw new TxValidationError2(
71554
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
71555
+ );
71556
+ }
71557
+ }
71558
+ function validateUnsignedTx2(unsignedTx, expected, vctx) {
71559
+ const txChainId = readChainId2(unsignedTx);
71560
+ if (txChainId == null) {
71561
+ throw new TxValidationError2(
71562
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
71563
+ );
71564
+ }
71565
+ if (txChainId !== vctx.chainId) {
71566
+ throw new TxValidationError2(
71567
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
71568
+ );
71569
+ }
71570
+ const value = readValue2(unsignedTx);
71571
+ if (value !== 0n) {
71572
+ throw new TxValidationError2(
71573
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
71574
+ );
71575
+ }
71576
+ assertFeeCeiling(
71577
+ readOptionalBigInt(unsignedTx, "gasLimit"),
71578
+ readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
71579
+ (msg) => {
71580
+ throw new TxValidationError2(msg);
71581
+ },
71582
+ vctx.feeCeiling
71583
+ );
71584
+ const to = readToAddress2(unsignedTx);
71585
+ const data = readData2(unsignedTx);
71586
+ const { name, args } = decodeSignable2(data);
71587
+ const pm = vctx.contracts.PositionManager;
71588
+ switch (expected.kind) {
71589
+ case "mint": {
71590
+ if (name !== "mintUCD") {
71591
+ throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
71592
+ }
71593
+ if (!eqAddr2(to, pm)) {
71594
+ throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
71595
+ }
71596
+ requirePositionId(args[0], expected.positionId);
71597
+ const txMintAmount = BigInt(String(args[1]));
71598
+ if (txMintAmount.toString() !== expected.amountWei) {
71599
+ throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
71600
+ }
71601
+ const txMintFee = BigInt(String(args[2]));
71602
+ if (txMintFee.toString() !== expected.mintFeeWei) {
71603
+ throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
71604
+ }
71605
+ break;
71606
+ }
71607
+ case "repay": {
71608
+ if (name !== "makePayment") {
71609
+ throw new TxValidationError2(`expected makePayment, server returned ${name}`);
71610
+ }
71611
+ if (!eqAddr2(to, pm)) {
71612
+ throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
71613
+ }
71614
+ requirePositionId(args[0], expected.positionId);
71615
+ const txAmount = BigInt(String(args[1]));
71616
+ if (txAmount.toString() !== expected.amountWei) {
71617
+ throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
71618
+ }
71619
+ break;
71620
+ }
71621
+ case "extend": {
71622
+ if (name !== "extendPosition") {
71623
+ throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
71624
+ }
71625
+ if (!eqAddr2(to, pm)) {
71626
+ throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
71627
+ }
71628
+ requirePositionId(args[0], expected.positionId);
71629
+ const txTerm = Number(args[1]);
71630
+ if (txTerm !== expected.selectedTerm) {
71631
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71632
+ }
71633
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
71634
+ const txFee = BigInt(String(args[5]));
71635
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
71636
+ if (txFee > upper) {
71637
+ throw new TxValidationError2(
71638
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
71639
+ );
71640
+ }
71641
+ }
71642
+ break;
71643
+ }
71644
+ case "withdraw-btc": {
71645
+ if (name !== "withdrawBTC") {
71646
+ throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
71647
+ }
71648
+ if (!eqAddr2(to, pm)) {
71649
+ throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
71650
+ }
71651
+ const paramsTuple = args[0];
71652
+ requirePositionId(paramsTuple[0], expected.positionId);
71653
+ const txWithdrawalAddress = String(paramsTuple[5]);
71654
+ if (txWithdrawalAddress !== expected.btcAddress) {
71655
+ throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
71656
+ }
71657
+ if (expected.upperBoundTotalDeduction != null) {
71658
+ const txDeduction = BigInt(String(paramsTuple[6]));
71659
+ const upper = BigInt(expected.upperBoundTotalDeduction);
71660
+ if (txDeduction > upper) {
71661
+ throw new TxValidationError2(
71662
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
71663
+ );
71664
+ }
71665
+ }
71666
+ break;
71667
+ }
71668
+ case "ucd-approve": {
71669
+ if (name !== "approve") {
71670
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71671
+ }
71672
+ const ucd = vctx.contracts.UCDToken;
71673
+ if (!eqAddr2(to, ucd)) {
71674
+ throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
71675
+ }
71676
+ const spender = String(args[0]);
71677
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
71678
+ if (!ok2) {
71679
+ throw new TxValidationError2(
71680
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
71681
+ );
71682
+ }
71683
+ const amt = BigInt(String(args[1]));
71684
+ const min = BigInt(expected.minAmountWei);
71685
+ if (amt < min) {
71686
+ throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
71687
+ }
71688
+ const SANITY_MAX = min * 1000n;
71689
+ if (amt > SANITY_MAX) {
71690
+ throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
71691
+ }
71692
+ break;
71693
+ }
71694
+ case "create-position": {
71695
+ if (name !== "createPosition") {
71696
+ throw new TxValidationError2(`expected createPosition, server returned ${name}`);
71697
+ }
71698
+ if (!eqAddr2(to, pm)) {
71699
+ throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
71700
+ }
71701
+ const txTerm = BigInt(String(args[4]));
71702
+ if (txTerm !== BigInt(expected.selectedTerm)) {
71703
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71704
+ }
71705
+ break;
71706
+ }
71707
+ case "set-position-delegate": {
71708
+ if (name !== "setPositionDelegate") {
71709
+ throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
71710
+ }
71711
+ if (!eqAddr2(to, expected.registryAddress)) {
71712
+ throw new TxValidationError2(
71713
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
71714
+ );
71715
+ }
71716
+ requirePositionId(args[0], expected.positionId);
71717
+ const txDelegate = String(args[1]);
71718
+ if (!eqAddr2(txDelegate, expected.delegate)) {
71719
+ throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
71720
+ }
71721
+ break;
71722
+ }
71723
+ case "bwar-add-address": {
71724
+ if (name !== "addAddress") {
71725
+ throw new TxValidationError2(`expected addAddress, decoded ${name}`);
71726
+ }
71727
+ if (!eqAddr2(to, expected.registryAddress)) {
71728
+ throw new TxValidationError2(
71729
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
71730
+ );
71731
+ }
71732
+ if (String(args[0]) !== expected.btcAddress) {
71733
+ throw new TxValidationError2(
71734
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
71735
+ );
71736
+ }
71737
+ break;
71738
+ }
71739
+ case "stablecoin-approve": {
71740
+ if (name !== "approve") {
71741
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71742
+ }
71743
+ if (!eqAddr2(to, expected.tokenAddress)) {
71744
+ throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
71745
+ }
71746
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71747
+ throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
71748
+ }
71749
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
71750
+ throw new TxValidationError2(
71751
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
71752
+ );
71753
+ }
71754
+ break;
71755
+ }
71756
+ case "ucd-approve-controller": {
71757
+ if (name !== "approve") {
71758
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71759
+ }
71760
+ if (!eqAddr2(to, expected.ucdTokenAddress)) {
71761
+ throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
71762
+ }
71763
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71764
+ throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
71765
+ }
71766
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
71767
+ throw new TxValidationError2(
71768
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
71769
+ );
71770
+ }
71771
+ break;
71772
+ }
71773
+ case "psm-swap": {
71774
+ if (name !== "swap")
71775
+ throw new TxValidationError2(`expected swap, server returned ${name}`);
71776
+ if (!eqAddr2(to, expected.psmAddress)) {
71777
+ throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
71778
+ }
71779
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71780
+ throw new TxValidationError2(`swap stablecoin mismatch`);
71781
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
71782
+ throw new TxValidationError2(`swap amountIn mismatch`);
71783
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71784
+ throw new TxValidationError2(`swap minUcdOut mismatch`);
71785
+ if (BigInt(expected.minOut) === 0n) {
71786
+ throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71787
+ }
71788
+ break;
71789
+ }
71790
+ case "psm-redeem": {
71791
+ if (name !== "redeem")
71792
+ throw new TxValidationError2(`expected redeem, server returned ${name}`);
71793
+ if (!eqAddr2(to, expected.psmAddress)) {
71794
+ throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
71795
+ }
71796
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71797
+ throw new TxValidationError2(`redeem stablecoin mismatch`);
71798
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
71799
+ throw new TxValidationError2(`redeem ucdAmount mismatch`);
71800
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71801
+ throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
71802
+ if (BigInt(expected.minOut) === 0n) {
71803
+ throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71804
+ }
71805
+ break;
71806
+ }
71807
+ default: {
71808
+ const _exhaustive = expected;
71809
+ throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
71810
+ }
71811
+ }
71812
+ }
71813
+ function buildPsmApproveTx(p) {
71814
+ return {
71815
+ to: p.token,
71816
+ data: encodeSignable2("approve", [p.spender, p.amount]),
71817
+ value: "0x0",
71818
+ chainId: p.chainId
71819
+ };
71820
+ }
71821
+ function buildPsmSwapTx2(p) {
71822
+ return {
71823
+ to: p.psm,
71824
+ data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
71825
+ value: "0x0",
71826
+ chainId: p.chainId
71827
+ };
71828
+ }
71829
+ function buildPsmRedeemTx2(p) {
71830
+ return {
71831
+ to: p.psm,
71832
+ data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
71833
+ value: "0x0",
71834
+ chainId: p.chainId
71835
+ };
71836
+ }
71837
+ var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
71838
+ var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
71839
+ function psmExchangeReadsFromProvider(provider, psmAddress) {
71840
+ const psm = new import_ethers31.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
71841
+ return {
71842
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
71843
+ allowance: async (token, owner, spender) => await new import_ethers31.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
71844
+ };
71845
+ }
71846
+ var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
71847
+ function requireAddress(direction, label, value) {
71848
+ if (!value || !import_ethers31.ethers.isAddress(value)) {
71849
+ throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
71850
+ }
71851
+ return import_ethers31.ethers.getAddress(value);
71852
+ }
71853
+ async function planPsmExchange(params) {
71854
+ const { direction, amountIn, minOut, vctx, reads } = params;
71855
+ const chainId = vctx.chainId;
71856
+ if (amountIn <= 0n) {
71857
+ throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
71858
+ }
71859
+ if (minOut <= 0n) {
71860
+ throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
71861
+ }
71862
+ const owner = requireAddress(direction, "owner", params.owner);
71863
+ const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
71864
+ const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
71865
+ const isSwap = direction === "swap";
71866
+ const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
71867
+ const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
71868
+ if (!await reads.isStablecoinSupported(stablecoin)) {
71869
+ throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
71870
+ }
71871
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
71872
+ const allowanceBefore = await reads.allowance(token, owner, spender);
71873
+ const approvals = [];
71874
+ if (allowanceBefore < amountIn) {
71875
+ if (allowanceBefore > 0n) {
71876
+ approvals.push({
71877
+ step: "reset-approve",
71878
+ tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
71879
+ expected: approveExpected(0n)
71880
+ });
71881
+ }
71882
+ approvals.push({
71883
+ step: "approve",
71884
+ tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
71885
+ expected: approveExpected(amountIn)
71886
+ });
71887
+ }
71888
+ const exec = isSwap ? {
71889
+ step: "swap",
71890
+ tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
71891
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
71892
+ } : {
71893
+ step: "redeem",
71894
+ tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
71895
+ expected: {
71896
+ kind: "psm-redeem",
71897
+ psmAddress: psm,
71898
+ stablecoin,
71899
+ amountUcdWei: amountIn.toString(),
71900
+ minOut: minOut.toString()
71901
+ }
71902
+ };
71903
+ for (const leg of [...approvals, exec]) {
71904
+ validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
71905
+ }
71906
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
71907
+ }
71908
+ async function executePsmPlan(plan, signer, vctx) {
71909
+ const approvalHashes = [];
71910
+ 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.`;
71911
+ const sendLeg = async (leg) => {
71912
+ const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
71913
+ validateUnsignedTx2({ ...request }, leg.expected, vctx);
71914
+ const sent = await signer.sendTransaction(request);
71915
+ const receipt = await sent.wait();
71916
+ if (!receipt)
71917
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
71918
+ if (receipt.status !== 1)
71919
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
71920
+ return { hash: sent.hash, blockNumber: receipt.blockNumber };
71921
+ };
71922
+ for (const leg of plan.approvals) {
71923
+ const landed = await sendLeg(leg).catch((e) => {
71924
+ throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71925
+ });
71926
+ approvalHashes.push(landed.hash);
71927
+ }
71928
+ const exec = await sendLeg(plan.exec).catch((e) => {
71929
+ throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71930
+ });
71931
+ return { ...exec, approvalHashes };
71932
+ }
71933
+ var LIT_ACTION_CHAIN_NAMES = Object.freeze({
71934
+ 1: "ethereum",
71935
+ 11155111: "sepolia",
71936
+ 1337: "hardhat",
71937
+ 31337: "hardhat"
71938
+ });
71939
+ function litActionChainNameForChainId(chainId) {
71940
+ const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
71941
+ if (!name) {
71942
+ throw new Error(
71943
+ `Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
71944
+ );
71945
+ }
71946
+ return name;
71947
+ }
71063
71948
  var MockTokenManager = class {
71064
71949
  config;
71065
71950
  constructor(config) {
@@ -72033,6 +72918,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72033
72918
  */
72034
72919
  static async create(config) {
72035
72920
  const userProvidedServiceEndpoint = config.serviceEndpoint;
72921
+ if (typeof config.chainId === "number" && config.provider) {
72922
+ const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
72923
+ if (mismatch) {
72924
+ return failure(
72925
+ new SDKError({
72926
+ message: mismatch,
72927
+ category: "CONFIGURATION",
72928
+ severity: "HIGH"
72929
+ /* HIGH */
72930
+ })
72931
+ );
72932
+ }
72933
+ }
72036
72934
  const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
72037
72935
  if (userProvidedServiceEndpoint) {
72038
72936
  enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
@@ -72683,6 +73581,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72683
73581
  if (this.config.debug) {
72684
73582
  log.info(` Position PKP ID: ${position2.pkpId}`);
72685
73583
  }
73584
+ const termsResult = await this.getTermsWithFees();
73585
+ if (!termsResult.success) {
73586
+ return {
73587
+ success: false,
73588
+ error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
73589
+ };
73590
+ }
73591
+ const positionTermMonths = Number(position2.selectedTerm);
73592
+ const positionTerm = termsResult.value.terms.find(
73593
+ (term) => term.termMonths === positionTermMonths
73594
+ );
73595
+ if (!positionTerm) {
73596
+ return {
73597
+ success: false,
73598
+ error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
73599
+ };
73600
+ }
73601
+ const currentDebtWei = BigInt(position2.ucdDebt);
73602
+ const baseFeeWei = baseMintFeeWei(
73603
+ requestAmountWei,
73604
+ positionTerm.originationFeeBps
73605
+ );
73606
+ if (debtAfterMintExceedsLoanCap({
73607
+ currentDebtWei,
73608
+ mintAmountWei: requestAmountWei,
73609
+ mintFeeWei: baseFeeWei,
73610
+ maxLoanWei: maxLoanValueWei
73611
+ })) {
73612
+ const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
73613
+ const maxPrincipalUcd = Number(
73614
+ maxPrincipalWithinLoanCap({
73615
+ maxLoanWei: maxLoanValueWei,
73616
+ currentDebtWei,
73617
+ originationFeeBps: positionTerm.originationFeeBps
73618
+ }) / BigInt(10 ** 18)
73619
+ );
73620
+ return {
73621
+ success: false,
73622
+ 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.`
73623
+ };
73624
+ }
73625
+ if (this.config.debug) {
73626
+ log.info(
73627
+ `\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers14.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD`,
73628
+ {}
73629
+ );
73630
+ }
72686
73631
  let pkpPublicKey;
72687
73632
  let pkpEthAddress;
72688
73633
  const pkpCache = this.cacheManager.getCache("pkp-data", {
@@ -72772,7 +73717,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72772
73717
  ` UCDController: ${contracts?.UCDController || "MISSING"}`
72773
73718
  );
72774
73719
  }
72775
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
73720
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
72776
73721
  const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
72777
73722
  if (this.config.debug) {
72778
73723
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -73372,6 +74317,25 @@ Error data: none`
73372
74317
  }
73373
74318
  const selector = simError.selector;
73374
74319
  const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
74320
+ const MINT_GUARD_CODES = {
74321
+ "1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
74322
+ "2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
74323
+ "3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
74324
+ };
74325
+ let loanCapDiagnostics = "";
74326
+ if (selector === "0xe6dd4d41") {
74327
+ const guardCode = BigInt(
74328
+ "0x" + String(simError.data).slice(10).padStart(64, "0")
74329
+ ).toString();
74330
+ const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
74331
+ loanCapDiagnostics = `
74332
+
74333
+ MintGuardFailed(${guardCode}): ${guardMeaning}
74334
+ Lit mintAmount: ${validationResponse.mintAmount}
74335
+ Lit mintFee: ${validationResponse.mintFee}
74336
+ Lit newDebt: ${validationResponse.newDebt}
74337
+ Protocol maximum: ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
74338
+ }
73375
74339
  const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
73376
74340
  selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
73377
74341
  selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
@@ -73417,7 +74381,7 @@ Quantum Timing Analysis:
73417
74381
  Error selector: ${selector}
73418
74382
  Error data: ${simError.data}
73419
74383
  Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
73420
- Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
74384
+ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
73421
74385
  );
73422
74386
  }
73423
74387
  const tx2 = await sendEip1559Transaction({
@@ -76025,7 +76989,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76025
76989
  ` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
76026
76990
  );
76027
76991
  }
76028
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
76992
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
76029
76993
  const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
76030
76994
  if (this.config.debug) {
76031
76995
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -76580,13 +77544,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76580
77544
  return { success: false, error: "Failed to resolve PKP public key" };
76581
77545
  }
76582
77546
  const chipotlePkpAddress = (0, import_ethers14.computeAddress)(publicKey);
76583
- const STANDALONE_CHAIN_NAMES = {
76584
- 1: "ethereum",
76585
- 11155111: "sepolia",
76586
- 1337: "hardhat",
76587
- 31337: "hardhat"
76588
- };
76589
- const chainName = STANDALONE_CHAIN_NAMES[chainId];
77547
+ const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
76590
77548
  if (!chainName) {
76591
77549
  return {
76592
77550
  success: false,
@@ -77808,6 +78766,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77808
78766
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
77809
78767
  return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
77810
78768
  }
78769
+ /**
78770
+ * Combined UCD debt (canonical wei string + display string) and by-status loan
78771
+ * counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
78772
+ * an INDEXED, informational figure that lags writes; never size a transaction
78773
+ * from it (repayments read the chain via `getPositionDetailsView`).
78774
+ *
78775
+ * Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
78776
+ * failure or past 10,000 positions; never returns a partial total.
78777
+ */
78778
+ async getBorrowerUcdDebtSummary(borrower) {
78779
+ return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
78780
+ }
77811
78781
  /**
77812
78782
  * Get all active loans
77813
78783
  *
@@ -77933,11 +78903,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77933
78903
  }
77934
78904
  /**
77935
78905
  * Execute a PSM stablecoin → UCD swap.
77936
- * Handles stablecoin approval to the PSM contract if the current allowance is insufficient.
78906
+ * Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
78907
+ * partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
77937
78908
  *
77938
78909
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
77939
78910
  * @param params.amountWei - Stablecoin amount in native decimals (bigint)
77940
- * @param params.minUcdOutWei - Minimum UCD to receive; reverts if below this (1% slippage guard)
78911
+ * @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
77941
78912
  * @param params.signer - Connected signer for the approval and swap transactions
77942
78913
  */
77943
78914
  async psmSwap(params) {
@@ -77947,32 +78918,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77947
78918
  "SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
77948
78919
  );
77949
78920
  }
77950
- const signerAddress = await params.signer.getAddress();
77951
- const erc20Abi = [
77952
- "function allowance(address owner, address spender) view returns (uint256)",
77953
- "function approve(address spender, uint256 amount) returns (bool)"
77954
- ];
77955
- const stablecoin = new import_ethers14.Contract(params.stablecoinAddress, erc20Abi, params.signer);
77956
- const allowance = await stablecoin.allowance(signerAddress, psmAddress);
77957
- if (allowance < params.amountWei) {
77958
- const approveTx = await stablecoin.approve(psmAddress, import_ethers14.MaxUint256);
77959
- await approveTx.wait();
77960
- }
77961
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77962
- const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
77963
- const receipt = await tx2.wait();
77964
- if (!receipt)
77965
- throw new Error("PSM swap transaction receipt unavailable");
77966
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78921
+ return this.runPsmExchange({
78922
+ direction: "swap",
78923
+ signer: params.signer,
78924
+ addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
78925
+ amountIn: params.amountWei,
78926
+ minOut: params.minUcdOutWei
78927
+ });
77967
78928
  }
77968
78929
  /**
77969
78930
  * Execute a PSM UCD → stablecoin redeem.
77970
- * Handles UCD approval to UCDController (not PSM) to satisfy the M-4 burn allowance guard:
77971
- * UCDToken.burn(from, amount) calls _spendAllowance(from, msg.sender=ucdController, amount).
78931
+ * Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
78932
+ * M-4 burn allowance guard: UCDToken.burn(from, amount) calls
78933
+ * _spendAllowance(from, msg.sender=ucdController, amount).
77972
78934
  *
77973
78935
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
77974
78936
  * @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
77975
- * @param params.minStablecoinOutWei - Minimum stablecoin to receive (slippage guard)
78937
+ * @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
77976
78938
  * @param params.signer - Connected signer
77977
78939
  */
77978
78940
  async psmRedeem(params) {
@@ -77985,23 +78947,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77985
78947
  throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
77986
78948
  if (!ucdControllerAddress)
77987
78949
  throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
77988
- const signerAddress = await params.signer.getAddress();
77989
- const erc20Abi = [
77990
- "function allowance(address owner, address spender) view returns (uint256)",
77991
- "function approve(address spender, uint256 amount) returns (bool)"
77992
- ];
77993
- const ucdToken = new import_ethers14.Contract(ucdAddress, erc20Abi, params.signer);
77994
- const allowance = await ucdToken.allowance(signerAddress, ucdControllerAddress);
77995
- if (allowance < params.ucdAmountWei) {
77996
- const approveTx = await ucdToken.approve(ucdControllerAddress, import_ethers14.MaxUint256);
77997
- await approveTx.wait();
77998
- }
77999
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
78000
- const tx2 = await psm.redeem(params.stablecoinAddress, params.ucdAmountWei, params.minStablecoinOutWei);
78001
- const receipt = await tx2.wait();
78002
- if (!receipt)
78003
- throw new Error("PSM redeem transaction receipt unavailable");
78004
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78950
+ return this.runPsmExchange({
78951
+ direction: "redeem",
78952
+ signer: params.signer,
78953
+ addresses: {
78954
+ psm: psmAddress,
78955
+ stablecoin: params.stablecoinAddress,
78956
+ ucdToken: ucdAddress,
78957
+ ucdController: ucdControllerAddress
78958
+ },
78959
+ amountIn: params.ucdAmountWei,
78960
+ minOut: params.minStablecoinOutWei
78961
+ });
78962
+ }
78963
+ /**
78964
+ * Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
78965
+ * The signer's chain must match the SDK's configured chain — the addresses came from it.
78966
+ */
78967
+ async runPsmExchange(params) {
78968
+ const provider = params.signer.provider;
78969
+ if (!provider) {
78970
+ throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
78971
+ }
78972
+ const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
78973
+ if (typeof configuredChainId !== "number") {
78974
+ throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
78975
+ }
78976
+ const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
78977
+ if (mismatch)
78978
+ throw new Error(mismatch);
78979
+ const vctx = {
78980
+ chainId: configuredChainId,
78981
+ network: String(configuredChainId),
78982
+ contracts: {}
78983
+ };
78984
+ const plan = await planPsmExchange({
78985
+ direction: params.direction,
78986
+ owner: await params.signer.getAddress(),
78987
+ addresses: params.addresses,
78988
+ amountIn: params.amountIn,
78989
+ minOut: params.minOut,
78990
+ vctx,
78991
+ reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
78992
+ });
78993
+ const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
78994
+ return { hash, blockNumber };
78005
78995
  }
78006
78996
  /**
78007
78997
  * Wait for the subgraph to index up to (and including) the given block number.
@@ -78182,18 +79172,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
78182
79172
  const user = await signer.getAddress();
78183
79173
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
78184
79174
  let agentAddress;
78185
- const hasActiveAgent = await registry.isAgentActive(user);
78186
- if (hasActiveAgent) {
78187
- agentAddress = (await registry.agentOf(user)).agent;
79175
+ const [isActive, record, latestBlock] = await Promise.all([
79176
+ registry.isAgentActive(user),
79177
+ registry.agentOf(user),
79178
+ this.getProviderOrThrow().getBlock("latest")
79179
+ ]);
79180
+ if (!latestBlock) {
79181
+ throw new SDKError({
79182
+ message: "Could not read the latest block to check the agent registration's expiry",
79183
+ category: "NETWORK",
79184
+ severity: "HIGH"
79185
+ /* HIGH */
79186
+ });
79187
+ }
79188
+ const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
79189
+ if (plan.kind === "reuse") {
79190
+ agentAddress = plan.agent;
78188
79191
  } else {
78189
79192
  agentAddress = await mintAgentPkp({
78190
79193
  serviceEndpoint: this.config.serviceEndpoint,
78191
79194
  authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
78192
79195
  });
78193
79196
  const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
78194
- const validUntil = Math.floor(Date.now() / 1e3) + validitySeconds;
78195
- const regTx = await registry.registerAgent(user, agentAddress, validUntil);
78196
- await regTx.wait();
79197
+ const validUntil = latestBlock.timestamp + validitySeconds;
79198
+ const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
79199
+ await bindTx.wait();
78197
79200
  }
78198
79201
  const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
78199
79202
  () => null
@@ -79577,21 +80580,560 @@ function listPositionsQuery(f) {
79577
80580
  return { document: LIST_POSITIONS, variables: { first, skip } };
79578
80581
  }
79579
80582
  var SUPPORTED_STABLECOINS = `
79580
- query SupportedStablecoins {
80583
+ query GetSupportedStablecoins {
79581
80584
  supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
79582
- id
79583
- address
79584
- isSupported
79585
- decimals
79586
- entryFee
79587
- exitFee
79588
- reserves
80585
+ id address isSupported exchangeRate entryFee exitFee reserves decimals
80586
+ totalSwapVolume totalRedeemVolume swapCount redeemCount addedAt lastUpdated
79589
80587
  }
80588
+ }`;
80589
+
80590
+ // src/boundary/upstream/real/psm-calls.ts
80591
+ var import_ethers42 = require("ethers");
80592
+
80593
+ // node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
80594
+ var import_ethers36 = require("ethers");
80595
+ var import_ethers37 = require("ethers");
80596
+ var import_ethers38 = require("ethers");
80597
+ var import_ethers39 = require("ethers");
80598
+ var import_ethers40 = require("ethers");
80599
+ var import_ethers41 = require("ethers");
80600
+ var TxValidationError3 = class extends Error {
80601
+ /**
80602
+ * @param subject What is being refused. Defaults to the server-returned transaction the
80603
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
80604
+ */
80605
+ constructor(msg, subject = "server-returned transaction") {
80606
+ super(`Refusing to sign ${subject}: ${msg}`);
80607
+ this.name = "TxValidationError";
79590
80608
  }
79591
- `;
80609
+ };
80610
+ var SIGNABLE_FUNCTIONS3 = [
80611
+ "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)",
80612
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
80613
+ // used to sit here; it is not a function on any deployed contract — the
80614
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
80615
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
80616
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
80617
+ // it. A signable-function whitelist should not carry calldata shapes the
80618
+ // protocol cannot execute.
80619
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
80620
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
80621
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
80622
+ // Struct-version: matches the actual on-chain function signature and the
80623
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
80624
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
80625
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
80626
+ "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)",
80627
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
80628
+ // function reverts permanently. The trustless replacement
80629
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
80630
+ // entry when its LIT Action ships.
80631
+ "function approve(address spender, uint256 amount) external returns (bool)",
80632
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
80633
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
80634
+ // without an entry here it decoded as "<unparseable>" and the CLI's
80635
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
80636
+ // collateral had no client-side pin at all.
80637
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
80638
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
80639
+ // AgentModule; the parity test documents them as client-only.
80640
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
80641
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
80642
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
80643
+ // this too is client-only and never module-whitelisted.
80644
+ "function addAddress(string btcAddress) external"
80645
+ ];
80646
+ var IFACE3 = new import_ethers36.ethers.Interface(SIGNABLE_FUNCTIONS3);
80647
+ function encodeSignable3(fn, args) {
80648
+ return IFACE3.encodeFunctionData(fn, args);
80649
+ }
80650
+ function decodeSignable3(data) {
80651
+ try {
80652
+ const parsed = IFACE3.parseTransaction({ data });
80653
+ if (!parsed) {
80654
+ throw new TxValidationError3(
80655
+ `unsignedTx.data does not decode against the signable-function whitelist`
80656
+ );
80657
+ }
80658
+ return { name: parsed.name, args: parsed.args };
80659
+ } catch (e) {
80660
+ if (e instanceof TxValidationError3)
80661
+ throw e;
80662
+ throw new TxValidationError3(
80663
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
80664
+ );
80665
+ }
80666
+ }
80667
+ var MAX_GAS_LIMIT2 = 5000000n;
80668
+ var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
80669
+ var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
80670
+ var DEFAULT_FEE_CEILING2 = {
80671
+ maxGasLimit: MAX_GAS_LIMIT2,
80672
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
80673
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
80674
+ };
80675
+ function fmtEth2(wei) {
80676
+ return `${import_ethers37.ethers.formatEther(wei)} ETH`;
80677
+ }
80678
+ function fmtGwei2(wei) {
80679
+ return `${import_ethers37.ethers.formatUnits(wei, "gwei")} gwei`;
80680
+ }
80681
+ function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
80682
+ if (gasLimit == null || maxFeePerGas == null)
80683
+ return null;
80684
+ return gasLimit * maxFeePerGas;
80685
+ }
80686
+ function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
80687
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
80688
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
80689
+ }
80690
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
80691
+ raise(
80692
+ `maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
80693
+ );
80694
+ }
80695
+ const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
80696
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
80697
+ raise(
80698
+ `worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
80699
+ );
80700
+ }
80701
+ }
80702
+ function eqAddr3(a, b) {
80703
+ if (!a || !b)
80704
+ return false;
80705
+ try {
80706
+ return import_ethers38.ethers.getAddress(a) === import_ethers38.ethers.getAddress(b);
80707
+ } catch {
80708
+ return false;
80709
+ }
80710
+ }
80711
+ function readToAddress3(tx2) {
80712
+ const to = tx2["to"];
80713
+ if (typeof to !== "string") {
80714
+ throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
80715
+ }
80716
+ return to;
80717
+ }
80718
+ function readData3(tx2) {
80719
+ const data = tx2["data"];
80720
+ if (typeof data !== "string" || !data.startsWith("0x")) {
80721
+ throw new TxValidationError3(`unsignedTx.data missing or malformed`);
80722
+ }
80723
+ return data;
80724
+ }
80725
+ function readChainId3(tx2) {
80726
+ const c = tx2["chainId"];
80727
+ if (c == null)
80728
+ return null;
80729
+ if (typeof c === "number")
80730
+ return c;
80731
+ if (typeof c === "string")
80732
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
80733
+ if (typeof c === "bigint")
80734
+ return Number(c);
80735
+ return null;
80736
+ }
80737
+ function readOptionalBigInt2(tx2, key) {
80738
+ const v = tx2[key];
80739
+ if (v == null)
80740
+ return null;
80741
+ try {
80742
+ if (typeof v === "bigint")
80743
+ return v;
80744
+ if (typeof v === "number")
80745
+ return BigInt(v);
80746
+ if (typeof v === "string")
80747
+ return BigInt(v);
80748
+ return BigInt(v.toString());
80749
+ } catch {
80750
+ throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
80751
+ }
80752
+ }
80753
+ function readValue3(tx2) {
80754
+ const v = tx2["value"];
80755
+ if (v == null)
80756
+ return 0n;
80757
+ if (typeof v === "string")
80758
+ return BigInt(v);
80759
+ if (typeof v === "number")
80760
+ return BigInt(v);
80761
+ if (typeof v === "bigint")
80762
+ return v;
80763
+ const maybe = v;
80764
+ if (typeof maybe.toBigInt === "function")
80765
+ return maybe.toBigInt();
80766
+ if (typeof maybe.toString === "function")
80767
+ return BigInt(maybe.toString());
80768
+ throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
80769
+ }
80770
+ function normalizePositionId3(id) {
80771
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
80772
+ return import_ethers38.ethers.zeroPadValue(hex, 32).toLowerCase();
80773
+ }
80774
+ function requirePositionId2(actual, expected) {
80775
+ const txPositionId = String(actual).toLowerCase();
80776
+ if (txPositionId !== normalizePositionId3(expected)) {
80777
+ throw new TxValidationError3(
80778
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
80779
+ );
80780
+ }
80781
+ }
80782
+ function validateUnsignedTx3(unsignedTx, expected, vctx) {
80783
+ const txChainId = readChainId3(unsignedTx);
80784
+ if (txChainId == null) {
80785
+ throw new TxValidationError3(
80786
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
80787
+ );
80788
+ }
80789
+ if (txChainId !== vctx.chainId) {
80790
+ throw new TxValidationError3(
80791
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
80792
+ );
80793
+ }
80794
+ const value = readValue3(unsignedTx);
80795
+ if (value !== 0n) {
80796
+ throw new TxValidationError3(
80797
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
80798
+ );
80799
+ }
80800
+ assertFeeCeiling2(
80801
+ readOptionalBigInt2(unsignedTx, "gasLimit"),
80802
+ readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
80803
+ (msg) => {
80804
+ throw new TxValidationError3(msg);
80805
+ },
80806
+ vctx.feeCeiling
80807
+ );
80808
+ const to = readToAddress3(unsignedTx);
80809
+ const data = readData3(unsignedTx);
80810
+ const { name, args } = decodeSignable3(data);
80811
+ const pm = vctx.contracts.PositionManager;
80812
+ switch (expected.kind) {
80813
+ case "mint": {
80814
+ if (name !== "mintUCD") {
80815
+ throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
80816
+ }
80817
+ if (!eqAddr3(to, pm)) {
80818
+ throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
80819
+ }
80820
+ requirePositionId2(args[0], expected.positionId);
80821
+ const txMintAmount = BigInt(String(args[1]));
80822
+ if (txMintAmount.toString() !== expected.amountWei) {
80823
+ throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
80824
+ }
80825
+ const txMintFee = BigInt(String(args[2]));
80826
+ if (txMintFee.toString() !== expected.mintFeeWei) {
80827
+ throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
80828
+ }
80829
+ break;
80830
+ }
80831
+ case "repay": {
80832
+ if (name !== "makePayment") {
80833
+ throw new TxValidationError3(`expected makePayment, server returned ${name}`);
80834
+ }
80835
+ if (!eqAddr3(to, pm)) {
80836
+ throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
80837
+ }
80838
+ requirePositionId2(args[0], expected.positionId);
80839
+ const txAmount = BigInt(String(args[1]));
80840
+ if (txAmount.toString() !== expected.amountWei) {
80841
+ throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
80842
+ }
80843
+ break;
80844
+ }
80845
+ case "extend": {
80846
+ if (name !== "extendPosition") {
80847
+ throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
80848
+ }
80849
+ if (!eqAddr3(to, pm)) {
80850
+ throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
80851
+ }
80852
+ requirePositionId2(args[0], expected.positionId);
80853
+ const txTerm = Number(args[1]);
80854
+ if (txTerm !== expected.selectedTerm) {
80855
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80856
+ }
80857
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
80858
+ const txFee = BigInt(String(args[5]));
80859
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
80860
+ if (txFee > upper) {
80861
+ throw new TxValidationError3(
80862
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
80863
+ );
80864
+ }
80865
+ }
80866
+ break;
80867
+ }
80868
+ case "withdraw-btc": {
80869
+ if (name !== "withdrawBTC") {
80870
+ throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
80871
+ }
80872
+ if (!eqAddr3(to, pm)) {
80873
+ throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
80874
+ }
80875
+ const paramsTuple = args[0];
80876
+ requirePositionId2(paramsTuple[0], expected.positionId);
80877
+ const txWithdrawalAddress = String(paramsTuple[5]);
80878
+ if (txWithdrawalAddress !== expected.btcAddress) {
80879
+ throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
80880
+ }
80881
+ if (expected.upperBoundTotalDeduction != null) {
80882
+ const txDeduction = BigInt(String(paramsTuple[6]));
80883
+ const upper = BigInt(expected.upperBoundTotalDeduction);
80884
+ if (txDeduction > upper) {
80885
+ throw new TxValidationError3(
80886
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
80887
+ );
80888
+ }
80889
+ }
80890
+ break;
80891
+ }
80892
+ case "ucd-approve": {
80893
+ if (name !== "approve") {
80894
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80895
+ }
80896
+ const ucd = vctx.contracts.UCDToken;
80897
+ if (!eqAddr3(to, ucd)) {
80898
+ throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
80899
+ }
80900
+ const spender = String(args[0]);
80901
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
80902
+ if (!ok2) {
80903
+ throw new TxValidationError3(
80904
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
80905
+ );
80906
+ }
80907
+ const amt = BigInt(String(args[1]));
80908
+ const min = BigInt(expected.minAmountWei);
80909
+ if (amt < min) {
80910
+ throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
80911
+ }
80912
+ const SANITY_MAX = min * 1000n;
80913
+ if (amt > SANITY_MAX) {
80914
+ throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
80915
+ }
80916
+ break;
80917
+ }
80918
+ case "create-position": {
80919
+ if (name !== "createPosition") {
80920
+ throw new TxValidationError3(`expected createPosition, server returned ${name}`);
80921
+ }
80922
+ if (!eqAddr3(to, pm)) {
80923
+ throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
80924
+ }
80925
+ const txTerm = BigInt(String(args[4]));
80926
+ if (txTerm !== BigInt(expected.selectedTerm)) {
80927
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80928
+ }
80929
+ break;
80930
+ }
80931
+ case "set-position-delegate": {
80932
+ if (name !== "setPositionDelegate") {
80933
+ throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
80934
+ }
80935
+ if (!eqAddr3(to, expected.registryAddress)) {
80936
+ throw new TxValidationError3(
80937
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
80938
+ );
80939
+ }
80940
+ requirePositionId2(args[0], expected.positionId);
80941
+ const txDelegate = String(args[1]);
80942
+ if (!eqAddr3(txDelegate, expected.delegate)) {
80943
+ throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
80944
+ }
80945
+ break;
80946
+ }
80947
+ case "bwar-add-address": {
80948
+ if (name !== "addAddress") {
80949
+ throw new TxValidationError3(`expected addAddress, decoded ${name}`);
80950
+ }
80951
+ if (!eqAddr3(to, expected.registryAddress)) {
80952
+ throw new TxValidationError3(
80953
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
80954
+ );
80955
+ }
80956
+ if (String(args[0]) !== expected.btcAddress) {
80957
+ throw new TxValidationError3(
80958
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
80959
+ );
80960
+ }
80961
+ break;
80962
+ }
80963
+ case "stablecoin-approve": {
80964
+ if (name !== "approve") {
80965
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80966
+ }
80967
+ if (!eqAddr3(to, expected.tokenAddress)) {
80968
+ throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
80969
+ }
80970
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80971
+ throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
80972
+ }
80973
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
80974
+ throw new TxValidationError3(
80975
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
80976
+ );
80977
+ }
80978
+ break;
80979
+ }
80980
+ case "ucd-approve-controller": {
80981
+ if (name !== "approve") {
80982
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80983
+ }
80984
+ if (!eqAddr3(to, expected.ucdTokenAddress)) {
80985
+ throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
80986
+ }
80987
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80988
+ throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
80989
+ }
80990
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
80991
+ throw new TxValidationError3(
80992
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
80993
+ );
80994
+ }
80995
+ break;
80996
+ }
80997
+ case "psm-swap": {
80998
+ if (name !== "swap")
80999
+ throw new TxValidationError3(`expected swap, server returned ${name}`);
81000
+ if (!eqAddr3(to, expected.psmAddress)) {
81001
+ throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
81002
+ }
81003
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
81004
+ throw new TxValidationError3(`swap stablecoin mismatch`);
81005
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
81006
+ throw new TxValidationError3(`swap amountIn mismatch`);
81007
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
81008
+ throw new TxValidationError3(`swap minUcdOut mismatch`);
81009
+ if (BigInt(expected.minOut) === 0n) {
81010
+ throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
81011
+ }
81012
+ break;
81013
+ }
81014
+ case "psm-redeem": {
81015
+ if (name !== "redeem")
81016
+ throw new TxValidationError3(`expected redeem, server returned ${name}`);
81017
+ if (!eqAddr3(to, expected.psmAddress)) {
81018
+ throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
81019
+ }
81020
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
81021
+ throw new TxValidationError3(`redeem stablecoin mismatch`);
81022
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
81023
+ throw new TxValidationError3(`redeem ucdAmount mismatch`);
81024
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
81025
+ throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
81026
+ if (BigInt(expected.minOut) === 0n) {
81027
+ throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
81028
+ }
81029
+ break;
81030
+ }
81031
+ default: {
81032
+ const _exhaustive = expected;
81033
+ throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
81034
+ }
81035
+ }
81036
+ }
81037
+ var SLOT_SECONDS2 = 12;
81038
+ var INCLUSION_SLOT_TOLERANCE2 = 3;
81039
+ var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
81040
+ function buildPsmApproveTx2(p) {
81041
+ return {
81042
+ to: p.token,
81043
+ data: encodeSignable3("approve", [p.spender, p.amount]),
81044
+ value: "0x0",
81045
+ chainId: p.chainId
81046
+ };
81047
+ }
81048
+ function buildPsmSwapTx3(p) {
81049
+ return {
81050
+ to: p.psm,
81051
+ data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
81052
+ value: "0x0",
81053
+ chainId: p.chainId
81054
+ };
81055
+ }
81056
+ function buildPsmRedeemTx3(p) {
81057
+ return {
81058
+ to: p.psm,
81059
+ data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
81060
+ value: "0x0",
81061
+ chainId: p.chainId
81062
+ };
81063
+ }
81064
+ var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
81065
+ var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
81066
+ function psmExchangeReadsFromProvider2(provider, psmAddress) {
81067
+ const psm = new import_ethers41.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
81068
+ return {
81069
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
81070
+ allowance: async (token, owner, spender) => await new import_ethers41.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
81071
+ };
81072
+ }
81073
+ var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
81074
+ function requireAddress2(direction, label, value) {
81075
+ if (!value || !import_ethers41.ethers.isAddress(value)) {
81076
+ throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
81077
+ }
81078
+ return import_ethers41.ethers.getAddress(value);
81079
+ }
81080
+ async function planPsmExchange2(params) {
81081
+ const { direction, amountIn, minOut, vctx, reads } = params;
81082
+ const chainId = vctx.chainId;
81083
+ if (amountIn <= 0n) {
81084
+ throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
81085
+ }
81086
+ if (minOut <= 0n) {
81087
+ throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
81088
+ }
81089
+ const owner = requireAddress2(direction, "owner", params.owner);
81090
+ const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
81091
+ const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
81092
+ const isSwap = direction === "swap";
81093
+ const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
81094
+ const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
81095
+ if (!await reads.isStablecoinSupported(stablecoin)) {
81096
+ throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
81097
+ }
81098
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
81099
+ const allowanceBefore = await reads.allowance(token, owner, spender);
81100
+ const approvals = [];
81101
+ if (allowanceBefore < amountIn) {
81102
+ if (allowanceBefore > 0n) {
81103
+ approvals.push({
81104
+ step: "reset-approve",
81105
+ tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
81106
+ expected: approveExpected(0n)
81107
+ });
81108
+ }
81109
+ approvals.push({
81110
+ step: "approve",
81111
+ tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
81112
+ expected: approveExpected(amountIn)
81113
+ });
81114
+ }
81115
+ const exec = isSwap ? {
81116
+ step: "swap",
81117
+ tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
81118
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
81119
+ } : {
81120
+ step: "redeem",
81121
+ tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
81122
+ expected: {
81123
+ kind: "psm-redeem",
81124
+ psmAddress: psm,
81125
+ stablecoin,
81126
+ amountUcdWei: amountIn.toString(),
81127
+ minOut: minOut.toString()
81128
+ }
81129
+ };
81130
+ for (const leg of [...approvals, exec]) {
81131
+ validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
81132
+ }
81133
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
81134
+ }
79592
81135
 
79593
81136
  // src/boundary/upstream/real/psm-calls.ts
79594
- var import_ethers32 = require("ethers");
79595
81137
  var PSM_VIEW_FRAGMENTS = [
79596
81138
  "function VERSION() view returns (string)",
79597
81139
  "function supportedStablecoins(address) view returns (bool)",
@@ -79611,15 +81153,7 @@ var PSM_VIEW_FRAGMENTS = [
79611
81153
  "function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
79612
81154
  "function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
79613
81155
  ];
79614
- var PSM_WRITE_FRAGMENTS = [
79615
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
79616
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
79617
- ];
79618
- var ERC20_FRAGMENTS = [
79619
- "function approve(address spender, uint256 amount) returns (bool)",
79620
- "function balanceOf(address holder) view returns (uint256)"
79621
- ];
79622
- var ERC20_IFACE = new import_ethers32.ethers.Interface(ERC20_FRAGMENTS);
81156
+ var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
79623
81157
  var PSM_ERROR_FRAGMENTS = [
79624
81158
  "error StablecoinNotSupported(address stablecoin)",
79625
81159
  "error InvalidAmount()",
@@ -79667,9 +81201,9 @@ var RENDERERS = {
79667
81201
  var PsmCalls = class {
79668
81202
  constructor(deps) {
79669
81203
  this.deps = deps;
79670
- const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_WRITE_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
79671
- this.iface = new import_ethers32.ethers.Interface(abi);
79672
- this.psm = new import_ethers32.ethers.Contract(deps.psmAddress, abi, deps.provider);
81204
+ const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
81205
+ this.iface = new import_ethers42.ethers.Interface(abi);
81206
+ this.psm = new import_ethers42.ethers.Contract(deps.psmAddress, abi, deps.provider);
79673
81207
  }
79674
81208
  psm;
79675
81209
  iface;
@@ -79682,34 +81216,10 @@ var PsmCalls = class {
79682
81216
  ...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
79683
81217
  };
79684
81218
  }
79685
- // ---- unsigned-tx builders (plan 08 W1): EXACT-amount approvals only; floors pinned ----
79686
- /** Step 1: exact-amount ERC-20 approve. Caller names the direction's REAL spender
79687
- * (swap: stablecoin → the PSM; redeem: UCD → the UCDController). */
79688
- buildApprove(p) {
79689
- return {
79690
- to: p.token,
79691
- data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
79692
- value: "0x0",
79693
- chainId: p.chainId
79694
- };
79695
- }
79696
- /** Step 2, stablecoin → UCD (contract `swap`). */
79697
- buildSwap(p) {
79698
- return {
79699
- to: this.deps.psmAddress,
79700
- data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
79701
- value: "0x0",
79702
- chainId: p.chainId
79703
- };
79704
- }
79705
- /** Step 2, UCD → stablecoin (contract `redeem`). */
79706
- buildRedeem(p) {
79707
- return {
79708
- to: this.deps.psmAddress,
79709
- data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
79710
- value: "0x0",
79711
- chainId: p.chainId
79712
- };
81219
+ /** The two live reads the SDK's exchange planner depends on (supported set + allowance),
81220
+ * over this wrapper's provider and PSM. */
81221
+ exchangeReads() {
81222
+ return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
79713
81223
  }
79714
81224
  /** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
79715
81225
  async balances(holder) {
@@ -79722,8 +81232,8 @@ var PsmCalls = class {
79722
81232
  });
79723
81233
  }
79724
81234
  return this.call(async () => {
79725
- const ucd = new import_ethers32.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
79726
- const stable = new import_ethers32.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
81235
+ const ucd = new import_ethers42.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
81236
+ const stable = new import_ethers42.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
79727
81237
  const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
79728
81238
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79729
81239
  });
@@ -79841,7 +81351,7 @@ var PsmCalls = class {
79841
81351
  };
79842
81352
 
79843
81353
  // src/boundary/upstream/real/session.ts
79844
- var import_ethers33 = require("ethers");
81354
+ var import_ethers43 = require("ethers");
79845
81355
  var REFRESH_LEEWAY_SEC = 30;
79846
81356
  var LOGIN_TYPES_WITH_AUDIENCE3 = {
79847
81357
  DiamondHands: [
@@ -79889,7 +81399,7 @@ var LitOpsSession = class {
79889
81399
  const message = {
79890
81400
  address: this.wallet.address,
79891
81401
  issuedAt: Math.floor(Date.now() / 1e3),
79892
- nonce: "0x" + Buffer.from(import_ethers33.ethers.randomBytes(32)).toString("hex"),
81402
+ nonce: "0x" + Buffer.from(import_ethers43.ethers.randomBytes(32)).toString("hex"),
79893
81403
  audience: this.serviceEndpoint
79894
81404
  };
79895
81405
  const signature = await this.wallet.signTypedData(
@@ -79931,7 +81441,7 @@ function decodeJwtExp(token) {
79931
81441
  }
79932
81442
 
79933
81443
  // src/boundary/upstream/real/write-ops.ts
79934
- var import_ethers35 = require("ethers");
81444
+ var import_ethers45 = require("ethers");
79935
81445
 
79936
81446
  // src/signer/types.ts
79937
81447
  var OperationDeclined = class extends Error {
@@ -79941,7 +81451,7 @@ var OperationDeclined = class extends Error {
79941
81451
  init_tx_validator();
79942
81452
 
79943
81453
  // src/boundary/upstream/shared/external-bridge/page-crypto.ts
79944
- var import_ethers34 = require("ethers");
81454
+ var import_ethers44 = require("ethers");
79945
81455
  var PERSONAL_SIGN_LAYOUTS = {
79946
81456
  "dh-op-envelope-v1": {
79947
81457
  types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
@@ -79962,9 +81472,9 @@ function hashForLayout(layout, fields) {
79962
81472
  const values = def.fieldOrder.map((name) => {
79963
81473
  const raw = fields[name];
79964
81474
  if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
79965
- return hashUtf8.has(name) ? import_ethers34.ethers.keccak256(import_ethers34.ethers.toUtf8Bytes(raw)) : raw;
81475
+ return hashUtf8.has(name) ? import_ethers44.ethers.keccak256(import_ethers44.ethers.toUtf8Bytes(raw)) : raw;
79966
81476
  });
79967
- return import_ethers34.ethers.solidityPackedKeccak256(def.types, values);
81477
+ return import_ethers44.ethers.solidityPackedKeccak256(def.types, values);
79968
81478
  }
79969
81479
  var PAGE_CRYPTO_JS = `"use strict";
79970
81480
  (function () {
@@ -80193,9 +81703,21 @@ function buildValidationContext(network, chainId) {
80193
81703
 
80194
81704
  // src/boundary/upstream/real/write-ops.ts
80195
81705
  var SOURCE5 = "real-ops";
81706
+ function mcpExpected(leg) {
81707
+ const e = leg.expected;
81708
+ switch (e.kind) {
81709
+ case "stablecoin-approve":
81710
+ case "ucd-approve-controller":
81711
+ case "psm-swap":
81712
+ case "psm-redeem":
81713
+ return e;
81714
+ default:
81715
+ throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
81716
+ }
81717
+ }
80196
81718
  var OP_LAYOUT = "dh-op-envelope-v1";
80197
81719
  function randomNonceHex() {
80198
- return "0x" + Buffer.from(import_ethers35.ethers.randomBytes(16)).toString("hex");
81720
+ return "0x" + Buffer.from(import_ethers45.ethers.randomBytes(16)).toString("hex");
80199
81721
  }
80200
81722
  async function postJson(url2, body, headers) {
80201
81723
  const res = await fetch(url2, {
@@ -80256,7 +81778,7 @@ function buildWriteOps(deps) {
80256
81778
  return {
80257
81779
  to: String(tx2["to"] ?? ""),
80258
81780
  data: String(tx2["data"] ?? "0x"),
80259
- value: tx2["value"] != null ? import_ethers35.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
81781
+ value: tx2["value"] != null ? import_ethers45.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
80260
81782
  chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
80261
81783
  };
80262
81784
  }
@@ -80341,8 +81863,9 @@ function buildWriteOps(deps) {
80341
81863
  }
80342
81864
  return {
80343
81865
  createPosition: async (p) => {
80344
- const sdk = deps.getWriteSdk();
80345
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81866
+ const built = await deps.getWriteSdk();
81867
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81868
+ const sdk = built.sdk;
80346
81869
  try {
80347
81870
  await deps.assertValidatorConfigured();
80348
81871
  } catch (e) {
@@ -80421,7 +81944,7 @@ function buildWriteOps(deps) {
80421
81944
  mintedUcdWei: minted,
80422
81945
  feeUcdWei: mintFee,
80423
81946
  echoedAmountUcdWei: minted,
80424
- authorization: auth(action, `mint ${import_ethers35.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
81947
+ authorization: auth(action, `mint ${import_ethers45.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
80425
81948
  },
80426
81949
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80427
81950
  );
@@ -80462,7 +81985,7 @@ function buildWriteOps(deps) {
80462
81985
  txRef: { kind: "eth-tx", id: r.value.txHash },
80463
81986
  paidUcdWei: paid,
80464
81987
  echoedAmountUcdWei: paid,
80465
- authorization: auth(action, `repay ${import_ethers35.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
81988
+ authorization: auth(action, `repay ${import_ethers45.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
80466
81989
  },
80467
81990
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80468
81991
  );
@@ -80502,8 +82025,9 @@ function buildWriteOps(deps) {
80502
82025
  );
80503
82026
  },
80504
82027
  withdraw: async (p) => {
80505
- const sdk = deps.getWriteSdk();
80506
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82028
+ const built = await deps.getWriteSdk();
82029
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82030
+ const sdk = built.sdk;
80507
82031
  const amountSats = Number(p.amountSats);
80508
82032
  const feeSats = Number(p.networkFeeSats);
80509
82033
  let result;
@@ -80532,12 +82056,13 @@ function buildWriteOps(deps) {
80532
82056
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80533
82057
  );
80534
82058
  },
80535
- /** PSM exchange pair (plan 08 W1): pure on-chain calls — no LIT action, no server
80536
- * orchestration. MCP-built txs over the pinned wrapper (the SDK's psmSwap/psmRedeem
80537
- * hardcode MaxUint256 approvals and are FORBIDDEN); exact-amount approve, then the
80538
- * swap/redeem with its mandatory floor, each validated against the M8-11 whitelist,
80539
- * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80540
- * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
82059
+ /** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
82060
+ * orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
82061
+ * builder every client shares (it replaced this file's own builders and the SDK's old
82062
+ * MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
82063
+ * allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
82064
+ * validated again here by the MCP's own whitelist (the one the approval card decodes
82065
+ * with), then signed through the session signer and broadcast — one at a time. */
80541
82066
  psmSwap: async (p) => {
80542
82067
  const pr = await deps.psm(p.stablecoin);
80543
82068
  if (!pr.ok) return upFail(pr.failure);
@@ -80551,13 +82076,9 @@ function buildWriteOps(deps) {
80551
82076
  message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
80552
82077
  });
80553
82078
  }
80554
- const amountIn = BigInt(p.amountIn);
80555
- const minOut = BigInt(p.minOut);
80556
82079
  const vctx = buildValidationContext(config.network, chainId);
80557
- const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
80558
- const spenderAddress = isSwap ? addr.psm : addr.ucdController;
80559
82080
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
80560
- const tokenSymbol = isSwap ? "USDC" : "UCD";
82081
+ const tokenSymbol = isSwap ? calls.symbol() : "UCD";
80561
82082
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
80562
82083
  if (!quoteR.ok) return upFail(quoteR.failure);
80563
82084
  const broadcast = async (leg, action, tx2) => {
@@ -80572,49 +82093,66 @@ function buildWriteOps(deps) {
80572
82093
  return submitFailure(leg, e);
80573
82094
  }
80574
82095
  };
80575
- const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
82096
+ let plan;
80576
82097
  try {
80577
- validateUnsignedTx(
80578
- { ...approveTx },
80579
- isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn },
80580
- vctx
80581
- );
80582
- } catch (e) {
80583
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
80584
- }
80585
- const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
80586
- const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
80587
- if (!approveHashR.ok) return approveHashR;
80588
- const approveHash = approveHashR.value;
80589
- 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`;
80590
- const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
80591
- try {
80592
- validateUnsignedTx(
80593
- { ...execTx },
80594
- 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 },
80595
- vctx
80596
- );
82098
+ plan = await planPsmExchange2({
82099
+ direction: p.direction,
82100
+ owner: p.borrower,
82101
+ addresses: addr,
82102
+ amountIn: BigInt(p.amountIn),
82103
+ minOut: BigInt(p.minOut),
82104
+ vctx,
82105
+ reads: calls.exchangeReads()
82106
+ });
80597
82107
  } catch (e) {
80598
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
82108
+ return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
82109
+ kind: "unavailable",
82110
+ source: SOURCE5,
82111
+ message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
82112
+ raw: String(e)
82113
+ });
80599
82114
  }
80600
- const execCard = `${p.direction} ${p.amountIn} ${isSwap ? "USDC smallest units" : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
80601
- const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
80602
- if (!execHashR.ok) {
80603
- const f = execHashR.failure;
80604
- return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
82115
+ const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
82116
+ const unit = `${tokenSymbol} smallest units`;
82117
+ const landed = [];
82118
+ const residualNote = () => {
82119
+ const last = landed[landed.length - 1];
82120
+ 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`;
82121
+ return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
82122
+ };
82123
+ const runLeg = async (leg) => {
82124
+ const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
82125
+ try {
82126
+ validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
82127
+ } catch (e) {
82128
+ return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
82129
+ }
82130
+ const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
82131
+ const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
82132
+ return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
82133
+ };
82134
+ const approvals = [];
82135
+ for (const leg of plan.approvals) {
82136
+ 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})`;
82137
+ const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
82138
+ const r = await runLeg(leg);
82139
+ if (!r.ok) return r;
82140
+ landed.push({ step, hash: r.value });
82141
+ approvals.push({
82142
+ step,
82143
+ txRef: { kind: "eth-tx", id: r.value },
82144
+ amount: leg.step === "reset-approve" ? "0" : p.amountIn,
82145
+ authorization: auth("psm-approve", card, r.value)
82146
+ });
80605
82147
  }
82148
+ 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}`;
82149
+ const execHashR = await runLeg(plan.exec);
82150
+ if (!execHashR.ok) return execHashR;
80606
82151
  const execHash = execHashR.value;
80607
82152
  const balancesR = await calls.balances(p.borrower);
80608
82153
  const row = {
80609
- approve: {
80610
- txRef: { kind: "eth-tx", id: approveHash },
80611
- tokenSymbol,
80612
- tokenAddress,
80613
- spenderAddress,
80614
- spenderContract,
80615
- amount: p.amountIn,
80616
- authorization: auth("psm-approve", approveCard, approveHash)
80617
- },
82154
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
82155
+ approvals,
80618
82156
  execute: {
80619
82157
  txRef: { kind: "eth-tx", id: execHash },
80620
82158
  amountIn: p.amountIn,
@@ -80631,8 +82169,9 @@ function buildWriteOps(deps) {
80631
82169
  // registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
80632
82170
  // msg.sender, so their path is a SafeTx — never this keystore leg.
80633
82171
  allowlistWithdrawalAddress: async (p) => {
80634
- const sdk = deps.getWriteSdk();
80635
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82172
+ const built = await deps.getWriteSdk();
82173
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82174
+ const sdk = built.sdk;
80636
82175
  let result;
80637
82176
  try {
80638
82177
  result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
@@ -80679,8 +82218,9 @@ function buildWriteOps(deps) {
80679
82218
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
80680
82219
  }),
80681
82220
  retryWithdrawExecute: async (p) => {
80682
- const sdk = deps.getWriteSdk();
80683
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82221
+ const built = await deps.getWriteSdk();
82222
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82223
+ const sdk = built.sdk;
80684
82224
  let rows;
80685
82225
  try {
80686
82226
  rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
@@ -80708,7 +82248,7 @@ function buildWriteOps(deps) {
80708
82248
  }
80709
82249
 
80710
82250
  // src/signer/eoa-dh.ts
80711
- var import_ethers36 = require("ethers");
82251
+ var import_ethers46 = require("ethers");
80712
82252
  var EoaDHSigner = class {
80713
82253
  constructor(wallet, broadcast, clock = Date.now) {
80714
82254
  this.wallet = wallet;
@@ -80725,7 +82265,7 @@ var EoaDHSigner = class {
80725
82265
  async signAuthorization(spec) {
80726
82266
  const quantumTs = nextQuantumTimestamp(this.clock());
80727
82267
  const { fields, hashHex } = spec.stamp(quantumTs);
80728
- const signature = await this.wallet.signMessage(import_ethers36.ethers.getBytes(hashHex));
82268
+ const signature = await this.wallet.signMessage(import_ethers46.ethers.getBytes(hashHex));
80729
82269
  return { signature, quantumTs, fields };
80730
82270
  }
80731
82271
  async wrapInnerTx(innerTx) {
@@ -80743,10 +82283,10 @@ var EoaDHSigner = class {
80743
82283
 
80744
82284
  // src/signer/external-eoa.ts
80745
82285
  var import_node_crypto7 = require("crypto");
80746
- var import_ethers38 = require("ethers");
82286
+ var import_ethers48 = require("ethers");
80747
82287
 
80748
82288
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
80749
- var import_ethers37 = require("ethers");
82289
+ var import_ethers47 = require("ethers");
80750
82290
  function eq2(a, b) {
80751
82291
  return a.toLowerCase() === b.toLowerCase();
80752
82292
  }
@@ -80769,7 +82309,7 @@ function compareLandedTx(landed, approved, borrower) {
80769
82309
  return { status: "verified", from: landed.from, hash: landed.hash };
80770
82310
  }
80771
82311
  function verifyRawSignedTx(rawSignedTx, approved, borrower) {
80772
- const parsed = import_ethers37.ethers.Transaction.from(rawSignedTx);
82312
+ const parsed = import_ethers47.ethers.Transaction.from(rawSignedTx);
80773
82313
  if (!parsed.from || !parsed.to || !parsed.hash) {
80774
82314
  return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
80775
82315
  }
@@ -80807,7 +82347,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
80807
82347
  for (let attempt = 0; attempt < 4; attempt++) {
80808
82348
  try {
80809
82349
  const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
80810
- return import_ethers38.ethers.toBeHex(est * 15n / 10n);
82350
+ return import_ethers48.ethers.toBeHex(est * 15n / 10n);
80811
82351
  } catch (e) {
80812
82352
  lastErr = e;
80813
82353
  await new Promise((r) => setTimeout(r, 13e3));
@@ -80857,7 +82397,7 @@ var ExternalEoaDHSigner = class {
80857
82397
  throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
80858
82398
  }
80859
82399
  const finalHash = spec.stamp(used.quantumTs).hashHex;
80860
- const recovered = import_ethers38.ethers.verifyMessage(import_ethers38.ethers.getBytes(finalHash), outcome.signature);
82400
+ const recovered = import_ethers48.ethers.verifyMessage(import_ethers48.ethers.getBytes(finalHash), outcome.signature);
80861
82401
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80862
82402
  throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80863
82403
  }
@@ -80868,7 +82408,7 @@ var ExternalEoaDHSigner = class {
80868
82408
  }
80869
82409
  async submitValidatedTx(outerTx, ctx) {
80870
82410
  const approved = toApprovedTx(outerTx, this.deps.chainId);
80871
- const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
82411
+ const gas = outerTx.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
80872
82412
  const outcome = await this.deps.bridge.requestSignature({
80873
82413
  id: (0, import_node_crypto7.randomUUID)(),
80874
82414
  kind: "transaction",
@@ -80902,7 +82442,7 @@ var ExternalEoaDHSigner = class {
80902
82442
  return new BridgeEthersSigner(this.deps);
80903
82443
  }
80904
82444
  };
80905
- var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ethers.AbstractSigner {
82445
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers48.ethers.AbstractSigner {
80906
82446
  constructor(deps) {
80907
82447
  super(deps.provider);
80908
82448
  this.deps = deps;
@@ -80913,13 +82453,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80913
82453
  return this.deps.borrower;
80914
82454
  }
80915
82455
  async signMessage(message) {
80916
- const bytes = typeof message === "string" ? import_ethers38.ethers.toUtf8Bytes(message) : message;
82456
+ const bytes = typeof message === "string" ? import_ethers48.ethers.toUtf8Bytes(message) : message;
80917
82457
  if (bytes.length !== 32) {
80918
82458
  throw new Error(
80919
82459
  `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.`
80920
82460
  );
80921
82461
  }
80922
- const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
82462
+ const hashHex = import_ethers48.ethers.hexlify(bytes).toLowerCase();
80923
82463
  const nowMs = (this.deps.clock ?? Date.now)();
80924
82464
  const expiresAtSec = nextQuantumTimestamp(nowMs);
80925
82465
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
@@ -80949,7 +82489,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80949
82489
  if (outcome.status !== "approved" || !outcome.signature) {
80950
82490
  throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
80951
82491
  }
80952
- const recovered = import_ethers38.ethers.verifyMessage(bytes, outcome.signature);
82492
+ const recovered = import_ethers48.ethers.verifyMessage(bytes, outcome.signature);
80953
82493
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80954
82494
  throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80955
82495
  }
@@ -80983,11 +82523,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80983
82523
  const approved = {
80984
82524
  to: tx2.to,
80985
82525
  data: tx2.data,
80986
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82526
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
80987
82527
  chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
80988
82528
  };
80989
82529
  const card = cardForTx(approved);
80990
- 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));
82530
+ 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));
80991
82531
  const outcome = await this.deps.bridge.requestSignature({
80992
82532
  id: (0, import_node_crypto7.randomUUID)(),
80993
82533
  kind: "transaction",
@@ -81029,14 +82569,14 @@ function toApprovedTx(tx2, fallbackChainId) {
81029
82569
  return {
81030
82570
  to: tx2.to,
81031
82571
  data: tx2.data,
81032
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82572
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
81033
82573
  chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
81034
82574
  };
81035
82575
  }
81036
82576
  function describeFn(data) {
81037
82577
  try {
81038
- const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
81039
- return decodeSignable2(data).name;
82578
+ const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
82579
+ return decodeSignable4(data).name;
81040
82580
  } catch {
81041
82581
  return "operation";
81042
82582
  }
@@ -81073,7 +82613,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
81073
82613
  var RealUpstreamPlugin = class {
81074
82614
  constructor(config, wallet, runtime) {
81075
82615
  this.config = config;
81076
- this.provider = new import_ethers39.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
82616
+ this.provider = new import_ethers49.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
81077
82617
  this.wallet = wallet ?? null;
81078
82618
  this.runtime = runtime ?? null;
81079
82619
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
@@ -81148,25 +82688,16 @@ var RealUpstreamPlugin = class {
81148
82688
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
81149
82689
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
81150
82690
  listPsmStablecoins: async () => {
81151
- const listed = await this.listSupportedStablecoins();
81152
- if (!listed.ok) return listed;
81153
- const rows = await Promise.all(
81154
- listed.rows.map(async (row) => {
81155
- const built = await this.psmCallsFor(row.address);
81156
- return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
81157
- })
81158
- );
81159
- return upOk(
81160
- rows.filter((r) => r !== null),
81161
- this.src("subgraph")
81162
- );
82691
+ const verified = await this.verifiedStablecoins();
82692
+ if (!verified.ok) return upFail(verified.failure);
82693
+ return upOk(verified.rows, this.src("subgraph"));
81163
82694
  },
81164
82695
  getPsmStatus: async (p) => {
81165
- const r = await this.psmCallsFor(p.stablecoin);
82696
+ const r = await this.psmCallsForChoice(p.stablecoin);
81166
82697
  return r.ok ? r.calls.status() : upFail(r.failure);
81167
82698
  },
81168
82699
  getPsmQuote: async (p) => {
81169
- const r = await this.psmCallsFor(p.stablecoin);
82700
+ const r = await this.psmCallsForChoice(p.stablecoin);
81170
82701
  if (!r.ok) return upFail(r.failure);
81171
82702
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
81172
82703
  }
@@ -81275,18 +82806,24 @@ var RealUpstreamPlugin = class {
81275
82806
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
81276
82807
  * and the service-mode SDK routes its own subgraph reads through the same proxy — so
81277
82808
  * writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
81278
- * Safe to call repeatedly; failures leave the write plane honestly unavailable
81279
- * (createPosition/withdraw report the uninitialized SDK). */
82809
+ * Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
82810
+ * first write builds again (see ensureSdk). */
81280
82811
  async initWriteSdk() {
81281
82812
  if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
81282
82813
  const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
81283
82814
  if (!wallet) return;
81284
82815
  await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
81285
82816
  }
81286
- /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
81287
- * the write gateways report the uninitialized SDK honestly, never fake readiness. */
82817
+ /** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
82818
+ *
82819
+ * A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
82820
+ * life of the process and drop the error, which was survivable only while `create` never
82821
+ * touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
82822
+ * RPC blip at boot would have disabled every later write with no reason given. Now each write
82823
+ * retries, and a persistent failure says what it is. Concurrent callers share one build. */
81288
82824
  async ensureSdk(key, signer) {
81289
- if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
82825
+ const cached = this.sdkCache.get(key);
82826
+ if (cached) return { ok: true, sdk: cached };
81290
82827
  const inFlight = this.sdkInFlight.get(key);
81291
82828
  if (inFlight) return inFlight;
81292
82829
  const build = (async () => {
@@ -81306,17 +82843,23 @@ var RealUpstreamPlugin = class {
81306
82843
  // nesting writes under indexer discovery (the M8B-4 coupling this removes).
81307
82844
  ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
81308
82845
  });
81309
- return isSuccess(builtWrite) ? builtWrite.value : null;
81310
- } catch {
81311
- return null;
82846
+ if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
82847
+ return { ok: false, reason: builtWrite.error.message };
82848
+ } catch (e) {
82849
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
81312
82850
  }
81313
82851
  })();
81314
82852
  this.sdkInFlight.set(key, build);
81315
82853
  const built = await build;
81316
82854
  this.sdkInFlight.delete(key);
81317
- this.sdkCache.set(key, built);
82855
+ if (built.ok) this.sdkCache.set(key, built.sdk);
81318
82856
  return built;
81319
82857
  }
82858
+ /** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
82859
+ async writeSdkFor(key, signer) {
82860
+ const built = await this.ensureSdk(key, signer);
82861
+ return built.ok ? { ok: true, sdk: built.sdk } : built;
82862
+ }
81320
82863
  wallet;
81321
82864
  // ---- per-call signer resolution (plan 10 A3) ----
81322
82865
  /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
@@ -81356,9 +82899,9 @@ var RealUpstreamPlugin = class {
81356
82899
  chainId: this.config.chainId,
81357
82900
  dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
81358
82901
  session,
81359
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82902
+ getWriteSdk: () => this.writeSdkFor(key, wallet),
81360
82903
  readDetails: (id) => this.readPositionDetails(id),
81361
- psm: (stablecoin) => this.psmCallsFor(stablecoin),
82904
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81362
82905
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81363
82906
  });
81364
82907
  }
@@ -81372,14 +82915,14 @@ var RealUpstreamPlugin = class {
81372
82915
  if (!pkpValidation) {
81373
82916
  throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
81374
82917
  }
81375
- const registry = new import_ethers39.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
82918
+ const registry = new import_ethers49.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
81376
82919
  let validator;
81377
82920
  try {
81378
82921
  validator = await registry.validatorForVersion(version2);
81379
82922
  } catch (e) {
81380
82923
  throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
81381
82924
  }
81382
- if (validator === import_ethers39.ethers.ZeroAddress) {
82925
+ if (validator === import_ethers49.ethers.ZeroAddress) {
81383
82926
  throw new Error(
81384
82927
  `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.`
81385
82928
  );
@@ -81453,7 +82996,6 @@ var RealUpstreamPlugin = class {
81453
82996
  gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
81454
82997
  this.opsGatewayCache.set(key, gateway);
81455
82998
  }
81456
- await this.ensureSdk(key, wallet.connect(this.provider));
81457
82999
  return { ok: true, gateway };
81458
83000
  }
81459
83001
  if (mode === "external") {
@@ -81490,14 +83032,13 @@ var RealUpstreamPlugin = class {
81490
83032
  chainId: this.config.chainId,
81491
83033
  dhSigner: new ExternalEoaDHSigner(deps),
81492
83034
  session,
81493
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
83035
+ getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
81494
83036
  readDetails: (id) => this.readPositionDetails(id),
81495
- psm: (stablecoin) => this.psmCallsFor(stablecoin),
83037
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81496
83038
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81497
83039
  });
81498
83040
  this.opsGatewayCache.set(key, gateway);
81499
83041
  }
81500
- await this.ensureSdk(key, this.externalSigners.get(key));
81501
83042
  return { ok: true, gateway };
81502
83043
  }
81503
83044
  return {
@@ -81656,12 +83197,118 @@ var RealUpstreamPlugin = class {
81656
83197
  {}
81657
83198
  );
81658
83199
  if (!r.ok) return r;
81659
- const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
83200
+ const raw = r.value.data.supportedStablecoins ?? [];
83201
+ const bad = raw.find((x) => !import_ethers49.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
83202
+ if (bad) {
83203
+ return {
83204
+ ok: false,
83205
+ failure: {
83206
+ kind: "malformed",
83207
+ source: "subgraph",
83208
+ message: `the indexer returned a PSM stablecoin row this build cannot read (address '${String(bad.address)}', decimals '${String(bad.decimals)}')`
83209
+ }
83210
+ };
83211
+ }
83212
+ const rows = raw.map((x) => ({
81660
83213
  address: String(x.address).toLowerCase(),
81661
83214
  decimals: Number(x.decimals)
81662
83215
  }));
83216
+ if (rows.length === 0) {
83217
+ return {
83218
+ ok: false,
83219
+ failure: {
83220
+ kind: "unavailable",
83221
+ source: "subgraph",
83222
+ message: `the indexer lists NO supported stablecoins for the PSM on ${this.config.network}. Either the subgraph has not indexed the StablecoinAdded events yet (check its start block against the block the coins were added at), or governance has removed every coin. PSM exchange is unavailable here until one of those is resolved \u2014 this is NOT "the PSM supports nothing".`
83223
+ }
83224
+ };
83225
+ }
81663
83226
  return { ok: true, rows };
81664
83227
  }
83228
+ /**
83229
+ * The supported set, verified — index rows each re-checked on-chain, carrying the symbol
83230
+ * read from the token itself. This is what `protocol://psm` lists and what a caller's
83231
+ * SYMBOL is resolved against.
83232
+ *
83233
+ * Rows are dropped ONLY for the one reason a drop is honest: the index still lists a coin
83234
+ * the chain no longer supports (index lag behind a governance removal). Any OTHER failure
83235
+ * — an RPC outage mid-loop — propagates, because a list that silently shrinks when the
83236
+ * chain is unreachable is the same silent-failure shape as the empty list above. If
83237
+ * nothing survives verification, that is a refusal too, and it says which side disagreed.
83238
+ */
83239
+ async verifiedStablecoins() {
83240
+ const listed = await this.listSupportedStablecoins();
83241
+ if (!listed.ok) return listed;
83242
+ const checked = await Promise.all(
83243
+ listed.rows.map(async (row) => ({ row, built: await this.psmCallsFor(row.address) }))
83244
+ );
83245
+ const transport = checked.find((c) => !c.built.ok && c.built.failure.kind !== "rejected");
83246
+ if (transport && !transport.built.ok) return { ok: false, failure: transport.built.failure };
83247
+ const rows = checked.flatMap(
83248
+ ({ row, built }) => built.ok ? [{ address: row.address, symbol: built.calls.symbol(), decimals: row.decimals }] : []
83249
+ );
83250
+ if (rows.length === 0) {
83251
+ return {
83252
+ ok: false,
83253
+ failure: {
83254
+ kind: "unavailable",
83255
+ source: "chain-rpc",
83256
+ message: `the indexer lists ${listed.rows.length} PSM stablecoin(s) on ${this.config.network}, and the PSM contract confirms none of them. The index is behind a governance removal, or it is indexing a different PSM than the one in this build's deployment table \u2014 verify before exchanging anything.`
83257
+ }
83258
+ };
83259
+ }
83260
+ return { ok: true, rows };
83261
+ }
83262
+ /**
83263
+ * Resolve what the CALLER named — a symbol or a 0x address — to a verified address.
83264
+ *
83265
+ * The tool schemas have always said "by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address",
83266
+ * and the mock world accepts exactly that. The real adapter accepted only the address:
83267
+ * a symbol went straight into an address-typed `ethers.Contract`, which threw, and the
83268
+ * throw was caught as `kind: "unavailable"` → `UPSTREAM_UNAVAILABLE` — a code the guide
83269
+ * tells the model is "usually transient; retry once". So the documented input produced a
83270
+ * retry loop on the one deployment that moves real money, and a developer practising
83271
+ * against the mock never met it. Both halves are fixed here: the symbol resolves, and a
83272
+ * name that cannot resolve is `rejected` (the caller's input) rather than `unavailable`
83273
+ * (our upstream).
83274
+ */
83275
+ async psmCallsForChoice(chosen) {
83276
+ const raw = chosen.trim();
83277
+ if (raw.length === 0) {
83278
+ return {
83279
+ ok: false,
83280
+ failure: { kind: "rejected", source: "chain-rpc", message: "no stablecoin named \u2014 name one by symbol (e.g. 'USDC') or by 0x address; there is no default coin." }
83281
+ };
83282
+ }
83283
+ const symbol = raw.toLowerCase();
83284
+ if (import_ethers49.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
83285
+ const verified = await this.verifiedStablecoins();
83286
+ if (!verified.ok) return { ok: false, failure: verified.failure };
83287
+ const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
83288
+ if (hits.length > 1) {
83289
+ return {
83290
+ ok: false,
83291
+ failure: {
83292
+ kind: "rejected",
83293
+ source: "chain-rpc",
83294
+ message: `'${raw}' names ${hits.length} different coins this PSM supports \u2014 ${hits.map((r) => r.address).join(", ")}. Symbols are self-declared and not unique, so this one cannot be resolved for you: name the 0x address of the one you mean.`
83295
+ }
83296
+ };
83297
+ }
83298
+ const hit = hits[0];
83299
+ if (!hit) {
83300
+ const names = verified.rows.map((r) => `${r.symbol} (${r.address})`).join(", ");
83301
+ return {
83302
+ ok: false,
83303
+ failure: {
83304
+ kind: "rejected",
83305
+ source: "chain-rpc",
83306
+ message: `'${raw}' is not a coin this PSM supports on ${this.config.network} \u2014 it supports ${names}. Name one of those by symbol or address. \`protocol://psm\` carries each one's fees, limits and reserves.`
83307
+ }
83308
+ };
83309
+ }
83310
+ return this.psmCallsFor(hit.address);
83311
+ }
81665
83312
  /**
81666
83313
  * Build the PSM wrapper for ONE caller-chosen stablecoin.
81667
83314
  *
@@ -81672,6 +83319,9 @@ var RealUpstreamPlugin = class {
81672
83319
  * chain, then sign.
81673
83320
  */
81674
83321
  async psmCallsFor(stablecoinAddress) {
83322
+ if (!import_ethers49.ethers.isAddress(stablecoinAddress)) {
83323
+ throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
83324
+ }
81675
83325
  const key = stablecoinAddress.toLowerCase();
81676
83326
  const cached = this.psmWrappers.get(key);
81677
83327
  if (cached) return { ok: true, calls: cached };
@@ -81689,9 +83339,9 @@ var RealUpstreamPlugin = class {
81689
83339
  let supported;
81690
83340
  let symbol;
81691
83341
  try {
81692
- const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
83342
+ const psm = new import_ethers49.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81693
83343
  supported = await psm["supportedStablecoins"](key);
81694
- const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
83344
+ const erc20 = new import_ethers49.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81695
83345
  symbol = await erc20["symbol"]();
81696
83346
  } catch (e) {
81697
83347
  return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
@@ -81904,7 +83554,7 @@ var RealUpstreamPlugin = class {
81904
83554
  const pm = this.contracts["PositionManager"];
81905
83555
  if (!pm) return false;
81906
83556
  try {
81907
- const c = new import_ethers39.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
83557
+ const c = new import_ethers49.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
81908
83558
  return Boolean(await c["paused"]());
81909
83559
  } catch {
81910
83560
  return false;
@@ -81913,16 +83563,16 @@ var RealUpstreamPlugin = class {
81913
83563
  async readPositionDetails(id) {
81914
83564
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
81915
83565
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
81916
- const c = new import_ethers39.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
83566
+ const c = new import_ethers49.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
81917
83567
  let d;
81918
83568
  try {
81919
- d = await c["getPositionDetails"](import_ethers39.ethers.zeroPadValue(id, 32));
83569
+ d = await c["getPositionDetails"](import_ethers49.ethers.zeroPadValue(id, 32));
81920
83570
  } catch (e) {
81921
83571
  if (e.code === "CALL_EXCEPTION") return null;
81922
83572
  throw e;
81923
83573
  }
81924
83574
  const borrower = String(d["borrower"]);
81925
- if (borrower === import_ethers39.ethers.ZeroAddress) return null;
83575
+ if (borrower === import_ethers49.ethers.ZeroAddress) return null;
81926
83576
  return {
81927
83577
  positionId: String(d["positionId"]),
81928
83578
  pkpId: String(d["pkpId"]),
@@ -83524,8 +85174,8 @@ async function buildBoundary(configResult, overrides) {
83524
85174
  );
83525
85175
  }
83526
85176
  try {
83527
- const decrypted = await import_ethers40.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
83528
- if (!(decrypted instanceof import_ethers40.ethers.Wallet)) {
85177
+ const decrypted = await import_ethers50.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85178
+ if (!(decrypted instanceof import_ethers50.ethers.Wallet)) {
83529
85179
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
83530
85180
  }
83531
85181
  wallet = decrypted;
@@ -83694,6 +85344,17 @@ function signerModeSourceClause(d) {
83694
85344
  function phoneWalletOffer(d) {
83695
85345
  return d.walletConnect ? "or scan the WalletConnect QR (or paste the pairing code) to approve on a phone wallet" : "This deployment does NOT offer the WalletConnect phone-wallet leg \u2014 there is no QR to scan and `/wc-pairing` answers 404; a browser-extension wallet is the only path here";
83696
85346
  }
85347
+ function worldAxes(d) {
85348
+ const axes = [];
85349
+ axes.push(
85350
+ offers(d, "mock-simulated") ? "practice (mock) or real adapter" : "the REAL adapter \u2014 there is no practice (mock) world on this deployment"
85351
+ );
85352
+ axes.push(
85353
+ d.networks.length > 1 ? "sepolia (practice money) or mainnet (real money)" : d.networks.includes("mainnet") ? "MAINNET only, so every fund movement here is real money" : "sepolia only, so the ceremonies are real and the money is practice"
85354
+ );
85355
+ axes.push("that writes are enabled, and what actually gates one is whether a signing identity is connected");
85356
+ return axes.join("; ");
85357
+ }
83697
85358
  function moneyTruth(d) {
83698
85359
  const practice = offers(d, "mock-simulated");
83699
85360
  const sepolia = d.networks.includes("sepolia");
@@ -83876,8 +85537,7 @@ have to guess whether the money is real.`;
83876
85537
  function authorizationModeBullets(d) {
83877
85538
  const bullets = [];
83878
85539
  if (offers(d, "external")) {
83879
- bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
83880
- mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
85540
+ bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup${d.walletConnect ? ", or WalletConnect\n mobile via QR/paste-code" : " \u2014 this build has no WalletConnect\n mobile leg"}). Real adapter and mock. For TRANSACTIONS the approval card
83881
85541
  is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
83882
85542
  The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
83883
85543
  approval page states plainly it CANNOT decode. Never extend the card promise over
@@ -83940,8 +85600,7 @@ install matrix. ${connectorInstallNote(d)}
83940
85600
  Nothing needs a config file. Three steps:
83941
85601
 
83942
85602
  **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83943
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83944
- (practice money) or mainnet (real money); whether writes are enabled here and which
85603
+ \`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
83945
85604
  signer modes exist; current terms (\`protocol_terms\`).
83946
85605
 
83947
85606
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
@@ -84008,7 +85667,7 @@ on the real adapter and the mock.
84008
85667
  | extend | 1 personal-sign + 1 tx |
84009
85668
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
84010
85669
  | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
84011
- | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
85670
+ | PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
84012
85671
 
84013
85672
  **Honesty notes (say these plainly):**
84014
85673
  - **Reads never pop the wallet.** If a read needs a login the user does not have, the
@@ -84050,8 +85709,7 @@ on the real adapter and the mock.
84050
85709
  10 UCD.
84051
85710
 
84052
85711
  **Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
84053
- \`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
84054
- WalletConnect session (pending approvals are cancelled loudly), discards the login
85712
+ \`disconnect\`):** the FULL wallet flush. It ends every approval-page session${d.walletConnect ? " and any\nWalletConnect session" : ""} (pending approvals are cancelled loudly), discards the login
84055
85713
  token from server memory AND revokes it at the service, and unbinds the borrower
84056
85714
  identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
84057
85715
  a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
@@ -84153,16 +85811,19 @@ rather than silently deliver less than quoted.
84153
85811
 
84154
85812
  ${psmStablecoinRealityNote(d)}
84155
85813
 
84156
- **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
84157
- result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
85814
+ **Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
85815
+ the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
85816
+ planned against the allowance already standing: none when it covers the amount, one when it
85817
+ is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
84158
85818
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
84159
85819
  the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84160
85820
  you approve UCD to the **UCDController** (the PSM burns your UCD through the
84161
85821
  controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84162
85822
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
84163
85823
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
84164
- own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
84165
- standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
85824
+ own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
85825
+ standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
85826
+ the next exchange that it covers uses it without asking for another approval.
84166
85827
  PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84167
85828
  REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84168
85829
  wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
@@ -84509,7 +86170,7 @@ function renderGuideIndex(deployment) {
84509
86170
 
84510
86171
  - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
84511
86172
  - first-setup \u2014 zero to ready by conversation (authorization choice included)
84512
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
86173
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, ${deployment.walletConnect ? "extension or WalletConnect QR" : "browser extension (no WalletConnect leg here)"}, popup cadence, login honesty, disconnect/log-out
84513
86174
  - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
84514
86175
  - fees \u2014 the two fee models, plainly
84515
86176
  - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
@@ -84635,7 +86296,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
84635
86296
 
84636
86297
  // src/tools/loan.ts
84637
86298
  var import_zod = require("zod");
84638
- var import_ethers41 = require("ethers");
86299
+ var import_ethers51 = require("ethers");
84639
86300
 
84640
86301
  // src/util/format.ts
84641
86302
  function bigintReplacer(_key, value) {
@@ -84823,7 +86484,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84823
86484
  const b = getB();
84824
86485
  if (!b.ok) return renderError(b.error);
84825
86486
  return renderEnvelope(
84826
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
86487
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers51.parseEther)(amountUcd.toString()).toString() })
84827
86488
  );
84828
86489
  })
84829
86490
  );
@@ -84861,7 +86522,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84861
86522
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
84862
86523
  amountUcdWei = detail.data.debtUcdWei;
84863
86524
  } else {
84864
- amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
86525
+ amountUcdWei = (0, import_ethers51.parseEther)(amountUcd.toString()).toString();
84865
86526
  }
84866
86527
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
84867
86528
  })
@@ -85262,7 +86923,7 @@ function registerPsmTools(server, getB) {
85262
86923
  "psm_swap",
85263
86924
  {
85264
86925
  title: "Exchange UCD \u2194 a stablecoin through the PSM",
85265
- 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).",
86926
+ 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).",
85266
86927
  inputSchema: {
85267
86928
  stablecoin: import_zod4.z.string().min(1).describe(
85268
86929
  "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."
@@ -85278,7 +86939,7 @@ function registerPsmTools(server, getB) {
85278
86939
  const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
85279
86940
  const gate = requireConfirmation(
85280
86941
  confirmed,
85281
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
86942
+ `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"})`
85282
86943
  );
85283
86944
  if (gate) return gate;
85284
86945
  const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
@@ -85464,7 +87125,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
85464
87125
 
85465
87126
  // src/tools/signer.ts
85466
87127
  var import_zod6 = require("zod");
85467
- var import_ethers42 = require("ethers");
87128
+ var import_ethers52 = require("ethers");
85468
87129
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
85469
87130
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
85470
87131
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -85506,7 +87167,7 @@ function registerSignerTool(server, getRuntime, opts) {
85506
87167
  if (mode !== void 0 && !offeredModes.includes(mode)) {
85507
87168
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
85508
87169
  }
85509
- if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
87170
+ if (safeAddress !== void 0 && !import_ethers52.ethers.isAddress(safeAddress)) {
85510
87171
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
85511
87172
  }
85512
87173
  if (action === "status") {