@gvnrdao/dh-mcp 0.5.16 → 0.5.18

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;
@@ -40806,8 +40840,10 @@ An agent on the user's own machine can skip this service and talk to the protoco
40806
40840
  directly through the published MCP server, which carries the same tools:
40807
40841
 
40808
40842
  - \`npx -y @gvnrdao/dh-mcp\` (requires Node \u2265 18)
40809
- - \`curl -fsSL https://assets.gvnr.xyz/dh-mcp/install.sh | sh\` (self-contained binary)
40810
- - Claude Desktop bundle and checksums: <https://assets.gvnr.xyz/dh-mcp/>
40843
+
40844
+ That is the only self-hosted path. The downloadable binaries and Claude Desktop bundle
40845
+ that this document used to list were withdrawn on 2026-09-18; nothing is served under
40846
+ \`assets.gvnr.xyz/dh-mcp\` any more.
40811
40847
 
40812
40848
  ## Contact
40813
40849
 
@@ -40826,31 +40862,10 @@ var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).rep
40826
40862
  var BACKGROUND_IMAGE_ORIGIN = "https://images.gvnr.xyz";
40827
40863
  var BACKGROUND_IMAGE_URL = `${BACKGROUND_IMAGE_ORIGIN}/images/layout/backgroundCorleoneb.jpg`;
40828
40864
  var escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
40829
- function moneyReality(networks2) {
40830
- const mainnet = networks2.includes("mainnet");
40831
- const sepolia = networks2.includes("sepolia");
40832
- if (mainnet && sepolia) {
40833
- return {
40834
- label: "REAL MONEY on mainnet \xB7 practice funds on sepolia",
40835
- detail: "This deployment serves both networks. Mainnet moves real BTC and real UCD; sepolia is the test network and its funds are not real. Ask which network you are on before acting."
40836
- };
40837
- }
40838
- if (mainnet) {
40839
- return {
40840
- label: "REAL MONEY \u2014 Ethereum mainnet",
40841
- detail: "This deployment serves mainnet only. Every fund-moving operation moves real BTC and real UCD, and each one needs a fresh signature from your own wallet."
40842
- };
40843
- }
40844
- return {
40845
- label: "PRACTICE FUNDS \u2014 sepolia test network",
40846
- detail: "This deployment serves sepolia only. The contracts and ceremonies are real, the money is not. Nothing here can move mainnet funds."
40847
- };
40848
- }
40865
+ var CONNECT_URL = "https://app.diamondhands.credit/connect";
40849
40866
  function renderLandingPage(input) {
40850
- const { publicOrigin, networks: networks2, version: version2, nonce } = input;
40867
+ const { publicOrigin, version: version2 } = input;
40851
40868
  const origin2 = escapeHtml(publicOrigin);
40852
- const money = moneyReality(networks2);
40853
- const config = JSON.stringify({ mcpServers: { "diamond-hands": { type: "http", url: `${publicOrigin}/mcp` } } }, null, 2);
40854
40869
  return `<!doctype html>
40855
40870
  <html lang="en">
40856
40871
  <head>
@@ -40875,135 +40890,34 @@ function renderLandingPage(input) {
40875
40890
  .scroll { height:100%; overflow-y:auto; overscroll-behavior:contain; }
40876
40891
  main { max-width:41rem; margin:0 auto; padding:1.9rem 1.25rem 2rem;
40877
40892
  text-shadow:0 1px 3px rgba(0,0,0,.85); }
40878
- /* Wide viewports: the lower half goes side-by-side so the whole page fits without the
40879
- viewport scrolling \u2014 the house treatment is a full-bleed image, not a long page. */
40880
- @media (min-width: 62rem) and (min-height: 34rem) {
40881
- main { max-width:62rem; }
40882
- .cols { display:grid; grid-template-columns:1fr 1fr; gap:0 1.6rem; align-items:start; }
40883
- .cols h2:first-child { margin-top:0; }
40884
- }
40885
40893
  h1 { font-size:1.35rem; margin:0 0 .25rem; letter-spacing:-.01em; }
40886
40894
  .sub { color:#dfe3ea; margin:0 0 1.1rem; font-size:14px; }
40887
- .card { background:rgba(6,8,12,.62); border:1px solid rgba(255,255,255,.16);
40888
- border-radius:10px; padding:.75rem .95rem; margin:0 0 .8rem;
40889
- backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px); }
40890
- .money { border-left:3px solid #f59e0b; }
40891
- .money strong { display:block; margin-bottom:.15rem; }
40892
- h2 { font-size:.72rem; text-transform:uppercase; letter-spacing:.08em; color:#cbd2dc;
40893
- margin:1.1rem 0 .45rem; font-weight:600; }
40894
- pre { margin:0; padding:.7rem .9rem; background:rgba(0,0,0,.66);
40895
- border:1px solid rgba(255,255,255,.16); border-radius:8px; overflow-x:auto;
40896
- font-size:12.5px; line-height:1.45; text-shadow:none;
40897
- font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
40898
40895
  code { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:.92em; }
40899
- table { border-collapse:collapse; width:100%; font-size:13.5px; }
40900
- td { padding:.3rem .6rem .3rem 0; border-bottom:1px solid rgba(255,255,255,.12); vertical-align:top; }
40901
- td:first-child { color:#cbd2dc; white-space:nowrap; width:10.5rem; }
40902
- tr:last-child td { border-bottom:0; }
40903
40896
  a { color:inherit; text-decoration:underline; text-underline-offset:2px; }
40904
- .row { display:flex; align-items:center; gap:.6rem; margin-bottom:.4rem; font-size:13px; }
40905
- button { font:inherit; font-size:12.5px; padding:.25rem .65rem;
40906
- border:1px solid rgba(255,255,255,.24); border-radius:6px;
40907
- background:rgba(0,0,0,.55); color:#f3f4f6; cursor:pointer; text-shadow:none; }
40908
- button:hover { background:rgba(0,0,0,.75); }
40909
40897
  footer { color:#cbd2dc; font-size:12.5px; margin-top:1.1rem; padding-top:.7rem;
40910
40898
  border-top:1px solid rgba(255,255,255,.14); }
40911
- [hidden] { display:none !important; }
40912
- #reveal-wrap { margin:0 0 .4rem; }
40913
- #reveal { display:inline-block; padding:.4rem .85rem; border-radius:6px;
40914
- border:1px solid rgba(255,255,255,.26); background:rgba(6,8,12,.62);
40915
- backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px);
40916
- text-decoration:none; font-size:13.5px; text-shadow:none; cursor:pointer; }
40917
- #reveal:hover { background:rgba(6,8,12,.85); border-color:rgba(255,255,255,.4); }
40918
- #reveal::after { content:" \u2193"; opacity:.7; }
40899
+ #cta-wrap { margin:.2rem 0 0; }
40900
+ #cta { display:inline-block; padding:.4rem .85rem; border-radius:6px;
40901
+ border:1px solid rgba(255,255,255,.26); background:rgba(6,8,12,.62);
40902
+ backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px);
40903
+ text-decoration:none; font-size:13.5px; text-shadow:none; cursor:pointer; }
40904
+ #cta:hover { background:rgba(6,8,12,.85); border-color:rgba(255,255,255,.4); }
40905
+ #cta::after { content:" \u2192"; opacity:.7; }
40919
40906
  </style>
40920
40907
  </head>
40921
40908
  <body>
40922
40909
  <div class="scroll">
40923
40910
  <main>
40924
40911
  <h1>Diamond Hands \u2014 MCP endpoint</h1>
40925
- <p class="sub">This host is a <strong>Model Context Protocol</strong> server, not a website.
40926
- There is no app to use here. If you are a person, the app is at
40927
- <a href="https://app.diamondhands.credit/">app.diamondhands.credit</a>.</p>
40928
-
40929
- <!-- Revealed BY SCRIPT, hidden in the served markup \u2014 the inverse of #details below.
40930
- With no JS this stays hidden and the details stay open, so the page degrades to
40931
- everything-visible rather than to a trigger that does nothing. -->
40932
- <p id="reveal-wrap" hidden><a href="#details" id="reveal" role="button">View MCP installation details</a></p>
40933
-
40934
- <div id="details">
40935
- <div class="card money">
40936
- <strong>${escapeHtml(money.label)}</strong>
40937
- ${escapeHtml(money.detail)}
40938
- </div>
40939
-
40940
- <div class="cols">
40941
- <section>
40942
- <h2>Connect an agent</h2>
40943
- <div class="row">
40944
- <span style="color:var(--muted);font-size:13px">Add this to your MCP client configuration:</span>
40945
- <button id="copy" type="button">Copy</button>
40946
- </div>
40947
- <pre id="cfg">${escapeHtml(config)}</pre>
40948
-
40949
- <h2>How authorization works</h2>
40950
- <div class="card">
40951
- Identity is a <strong>wallet</strong>, not an account: OAuth 2.1 with dynamic client
40952
- registration (RFC 7591) and PKCE, where the login is an Ethereum signature (EIP-4361).
40953
- No passwords, no user database. The bearer token proves <em>session identity only</em> \u2014
40954
- it signs nothing and can never move funds; every fund-moving step raises its own approval
40955
- in your own wallet. Session state is in memory, so a restart means signing in again.
40956
- </div>
40957
- </section>
40958
-
40959
- <section>
40960
- <h2>Endpoints</h2>
40961
- <div class="card">
40962
- <table>
40963
- <tr><td>MCP</td><td><code>${origin2}/mcp</code> \u2014 streamable HTTP</td></tr>
40964
- <tr><td>Networks served</td><td><code>${escapeHtml(networks2.join(", "))}</code></td></tr>
40965
- <tr><td>Registration</td><td><a href="/auth.md">/auth.md</a> \u2014 how an agent registers and signs in</td></tr>
40966
- <tr><td>Resource metadata</td><td><a href="/.well-known/oauth-protected-resource">/.well-known/oauth-protected-resource</a></td></tr>
40967
- <tr><td>Auth server metadata</td><td><a href="/.well-known/oauth-authorization-server">/.well-known/oauth-authorization-server</a></td></tr>
40968
- </table>
40969
- </div>
40912
+ <p class="sub">Welcome to the Diamond Hands <strong>Model Context Protocol</strong> server.</p>
40970
40913
 
40971
- </section>
40972
- </div>
40914
+ <p id="cta-wrap"><a href="${CONNECT_URL}" id="cta" role="button">View MCP installation details</a></p>
40973
40915
 
40974
40916
  <footer>
40975
40917
  <code>@gvnrdao/dh-mcp</code> v${escapeHtml(version2)} \xB7 origin <code>${origin2}</code>
40976
40918
  </footer>
40977
- </div>
40978
40919
  </main>
40979
40920
  </div>
40980
- <script nonce="${escapeHtml(nonce)}">
40981
- // Progressive disclosure, applied by SCRIPT rather than baked into the markup: the
40982
- // details ship visible, and only a browser that can re-open them is allowed to close
40983
- // them. A page whose whole content sits behind a trigger that needs JS is a page that
40984
- // shows two sentences and nothing else when the script does not run.
40985
- (function () {
40986
- var details = document.getElementById('details');
40987
- var wrap = document.getElementById('reveal-wrap');
40988
- var link = document.getElementById('reveal');
40989
- if (!details || !wrap || !link) return;
40990
- details.hidden = true;
40991
- wrap.hidden = false;
40992
- link.addEventListener('click', function (e) {
40993
- e.preventDefault();
40994
- wrap.hidden = true;
40995
- details.hidden = false;
40996
- });
40997
- })();
40998
-
40999
- document.getElementById('copy').addEventListener('click', function () {
41000
- var t = document.getElementById('cfg').textContent;
41001
- navigator.clipboard.writeText(t).then(function () {
41002
- var b = document.getElementById('copy');
41003
- b.textContent = 'Copied'; setTimeout(function () { b.textContent = 'Copy'; }, 1400);
41004
- });
41005
- });
41006
- </script>
41007
40921
  </body>
41008
40922
  </html>
41009
40923
  `;
@@ -41038,7 +40952,7 @@ function htmlPageSecurityHeaders(extra) {
41038
40952
  }
41039
40953
 
41040
40954
  // src/version.ts
41041
- var SERVER_VERSION = "0.5.16";
40955
+ var SERVER_VERSION = "0.5.18";
41042
40956
 
41043
40957
  // src/connector/siwe-oauth.ts
41044
40958
  var import_node_crypto2 = require("crypto");
@@ -41560,16 +41474,18 @@ function resolveWcProjectId(raw, problems) {
41560
41474
  }
41561
41475
  return raw;
41562
41476
  }
41477
+ var RPC_PROXY_ORIGIN = "https://api.gvnr.xyz";
41478
+ var rpcProxy = (chainId) => `${RPC_PROXY_ORIGIN}/v1/proxy/rpc/${chainId}`;
41563
41479
  var NETWORK_DEFAULTS = {
41564
41480
  sepolia: {
41565
- rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
41481
+ rpcUrl: rpcProxy(11155111),
41566
41482
  serviceEndpoint: "https://ops-test.gvnr.xyz",
41567
41483
  litNetwork: "chipotle",
41568
41484
  validatorVersion: 3
41569
41485
  // on-chain validator generation, sepolia (2026-07-30)
41570
41486
  },
41571
41487
  mainnet: {
41572
- rpcUrl: "https://ethereum-rpc.publicnode.com",
41488
+ rpcUrl: rpcProxy(1),
41573
41489
  // Cutover 2026-09-08 — see sdk/src/constants/chunks/network-configs.ts for the full
41574
41490
  // reasoning. Widening, not a rename: ops.gvnr.xyz serves the same broker and cannot be
41575
41491
  // retired while installed copies call it. The sepolia entry above deliberately stays on
@@ -41687,11 +41603,11 @@ function resolveRealConfig(env) {
41687
41603
  problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
41688
41604
  }
41689
41605
  }
41690
- const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "sepolia" : env["DH_NETWORK"];
41606
+ const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "mainnet" : env["DH_NETWORK"];
41691
41607
  if (NETWORKS[network] === void 0) {
41692
41608
  problems.push(`DH_NETWORK='${network}' is not supported. Allowed: ${Object.keys(NETWORKS).join(" | ")}.`);
41693
41609
  }
41694
- const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.sepolia;
41610
+ const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.mainnet;
41695
41611
  const rpcUrl = env["ETH_RPC_URL"] || defaults2.rpcUrl;
41696
41612
  const serviceEndpoint = env["DH_SERVICE_ENDPOINT"] || defaults2.serviceEndpoint;
41697
41613
  if (!/^https:\/\//.test(serviceEndpoint) && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(serviceEndpoint)) {
@@ -41756,7 +41672,7 @@ function resolveRealConfig(env) {
41756
41672
 
41757
41673
  // src/boot.ts
41758
41674
  var fs6 = __toESM(require("fs"));
41759
- var import_ethers40 = require("ethers");
41675
+ var import_ethers50 = require("ethers");
41760
41676
 
41761
41677
  // src/boundary/index.ts
41762
41678
  var import_node_crypto9 = require("crypto");
@@ -42173,7 +42089,7 @@ var BoundaryCore = class {
42173
42089
  const inToken = toUcd ? s.stablecoinSymbol : "UCD";
42174
42090
  const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
42175
42091
  const amountIn = parseDecimalUnits(p.amount, inDecimals);
42176
- const refuse = (refusal, message, details) => ({
42092
+ const refuse3 = (refusal, message, details) => ({
42177
42093
  env: errEnvelope(
42178
42094
  boundaryError("UPSTREAM_REJECTED", message, {
42179
42095
  source: statusR.source.id,
@@ -42184,13 +42100,13 @@ var BoundaryCore = class {
42184
42100
  });
42185
42101
  const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
42186
42102
  if (s.paused) {
42187
- return refuse(
42103
+ return refuse3(
42188
42104
  "psm-paused",
42189
42105
  "the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
42190
42106
  );
42191
42107
  }
42192
42108
  if (!toUcd && !s.redeemEnabled) {
42193
- return refuse(
42109
+ return refuse3(
42194
42110
  "redeem-disabled",
42195
42111
  `redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
42196
42112
  );
@@ -42201,20 +42117,20 @@ var BoundaryCore = class {
42201
42117
  const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
42202
42118
  const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
42203
42119
  if (amountIn < min) {
42204
- return refuse(
42120
+ return refuse3(
42205
42121
  "below-min",
42206
42122
  `${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
42207
42123
  { amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
42208
42124
  );
42209
42125
  }
42210
42126
  if (max === 0n) {
42211
- return refuse(
42127
+ return refuse3(
42212
42128
  "direction-disabled",
42213
42129
  `the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
42214
42130
  );
42215
42131
  }
42216
42132
  if (amountIn > max) {
42217
- return refuse(
42133
+ return refuse3(
42218
42134
  "above-max",
42219
42135
  `${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
42220
42136
  { amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
@@ -42234,7 +42150,7 @@ var BoundaryCore = class {
42234
42150
  if (!toUcd) {
42235
42151
  const available = BigInt(s.availableReserves);
42236
42152
  if (available < amountOut) {
42237
- return refuse(
42153
+ return refuse3(
42238
42154
  "insufficient-reserves",
42239
42155
  `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
42156
  { available: available.toString(), required: amountOut.toString(), unit: outUnit }
@@ -42310,20 +42226,31 @@ var BoundaryCore = class {
42310
42226
  const inDecimals = toUcd ? s.stablecoinDecimals : 18;
42311
42227
  const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
42312
42228
  const viaSafe = this.deps.signer?.mode() === "safe";
42229
+ const a = v.allowance;
42230
+ const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
42231
+ 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(
42232
+ (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}`
42233
+ ).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
42313
42234
  const data = {
42314
42235
  direction: p.direction,
42315
42236
  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,
42237
+ allowance: {
42238
+ token: a.tokenSymbol,
42239
+ tokenAddress: a.tokenAddress,
42240
+ spenderAddress: a.spenderAddress,
42241
+ spenderContract: a.spenderContract,
42242
+ 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",
42243
+ before: a.before,
42324
42244
  amountUnit: q.amountInUnit,
42325
- authorization: v.approve.authorization
42245
+ 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
42246
  },
42247
+ approvals: v.approvals.map((leg) => ({
42248
+ step: leg.step,
42249
+ txRef: leg.txRef,
42250
+ amount: leg.amount,
42251
+ amountUnit: q.amountInUnit,
42252
+ authorization: leg.authorization
42253
+ })),
42327
42254
  execute: {
42328
42255
  txRef: v.execute.txRef,
42329
42256
  amountIn: v.execute.amountIn,
@@ -42345,7 +42272,7 @@ var BoundaryCore = class {
42345
42272
  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
42273
  },
42347
42274
  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}.`)
42275
+ 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
42276
  };
42350
42277
  return okEnvelope(data, r.source, warnings);
42351
42278
  }
@@ -44204,6 +44131,16 @@ function buildExtendTx(ctx, p) {
44204
44131
  );
44205
44132
  }
44206
44133
 
44134
+ // src/boundary/upstream/shared/psm-approval-steps.ts
44135
+ function psmApprovalSteps(allowanceBefore, amountIn) {
44136
+ if (allowanceBefore >= amountIn) return [];
44137
+ if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
44138
+ return [
44139
+ { step: "reset-approve", amount: 0n },
44140
+ { step: "approve", amount: amountIn }
44141
+ ];
44142
+ }
44143
+
44207
44144
  // src/boundary/upstream/mock/sink-contracts.ts
44208
44145
  var import_ethers6 = require("ethers");
44209
44146
  function sinkAddress(label) {
@@ -44360,9 +44297,25 @@ var SignerManager = class {
44360
44297
  pendingCeremonies: this.deps.pendingCeremonies()
44361
44298
  };
44362
44299
  }
44363
- /** The conversational first-run text every write answers with under mode `none`. */
44300
+ /**
44301
+ * The conversational first-run text every write answers with under mode `none`.
44302
+ *
44303
+ * It states the SCOPE of the refusal first, because the tool list does not change with
44304
+ * signer mode: an assistant that meets this on `loan_mint` still sees `loan_pay`,
44305
+ * `loan_withdraw` and `psm_swap` advertised, and its natural next move is to try one
44306
+ * rather than to run setup. Every one of them refuses identically here
44307
+ * (`BoundaryCore.requireBorrower`), so without that sentence the model rediscovers the
44308
+ * same wall N times and the user watches it flail. Naming the scope converts N refusals
44309
+ * into one instruction.
44310
+ *
44311
+ * It also says reads still work, so "no signer" is not misread as "server broken", and
44312
+ * it offers ONLY the modes this composition can actually construct — a build with no
44313
+ * keystore runtime must not suggest one (the same rule G-CONN-14 holds the guide to).
44314
+ */
44364
44315
  invitation() {
44365
- return "No authorization mode is chosen yet. Choose how to approve operations that move funds: (1) 'use my own wallet' \u2014 you approve each operation in YOUR wallet (MetaMask popup, or a mobile wallet via WalletConnect); (2) 'sign automatically' \u2014 a local keystore signs after each confirmation. Tell the agent which you prefer (it calls signer_setup), or ask for 'guide first-setup'.";
44316
+ const keystoreOffered = this.deps.keystore !== null;
44317
+ const options = keystoreOffered ? "(1) 'use my own wallet' \u2014 you approve each operation in YOUR wallet (MetaMask popup, or a mobile wallet via WalletConnect); (2) 'sign automatically' \u2014 a local keystore signs after each confirmation. " : "'use my own wallet' \u2014 you approve each operation in YOUR wallet. It is the only mode this build offers. ";
44318
+ return `No authorization mode is chosen yet, so EVERY fund-moving tool will refuse with this same message until one is \u2014 trying a different write tool will not get past it. Reading is unaffected: prices, protocol terms and position data all work right now. To move funds, choose how to approve it: ${options}Tell the agent which you prefer (it calls signer_setup), or ask for 'guide first-setup'.`;
44366
44319
  }
44367
44320
  };
44368
44321
  var KeystoreProvider = class {
@@ -45039,8 +44992,9 @@ var MockUpstreamPlugin = class {
45039
44992
  return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
45040
44993
  });
45041
44994
  }
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
44995
+ /** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
44996
+ * or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
44997
+ * asymmetric by direction, contract truth), then the swap/redeem with
45044
44998
  * its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
45045
44999
  * AFTER the approve reports the step that declined AND the residual exact-amount
45046
45000
  * allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
@@ -45059,55 +45013,75 @@ var MockUpstreamPlugin = class {
45059
45013
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
45060
45014
  const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
45061
45015
  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})`;
45016
+ const standing = this.world.psmAllowancesOf(p.borrower);
45017
+ const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
45018
+ const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
45019
+ const landed = [];
45020
+ const residualNote = () => {
45021
+ const last = landed[landed.length - 1];
45022
+ 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`;
45023
+ return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
45024
+ };
45064
45025
  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
45026
  const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
45066
45027
  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`
45028
+ const approvals = [];
45029
+ for (const s of steps) {
45030
+ const amount = s.amount.toString();
45031
+ const isReset = s.step === "reset-approve";
45032
+ const label = isReset ? "RESET-APPROVE" : "APPROVE";
45033
+ 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";
45034
+ 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})`;
45035
+ let legAuth = null;
45036
+ if (cer) {
45037
+ const chainId = cer.txContext().chainId;
45038
+ const r = await cer.authorizeTx({
45039
+ action: "psm-approve",
45040
+ borrower: p.borrower,
45041
+ tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
45042
+ expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
45082
45043
  });
45044
+ if (!r.ok) {
45045
+ return upFail({
45046
+ kind: "rejected",
45047
+ source: "mock-ops",
45048
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
45049
+ });
45050
+ }
45051
+ this.bindIfDiscovering(r.authorization);
45052
+ legAuth = r.authorization;
45083
45053
  }
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`
45054
+ const leg = await this.write("psmSwap", () => {
45055
+ const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
45056
+ if (!sig.ok) {
45057
+ return upFail({
45058
+ kind: "rejected",
45059
+ source: "mock-ops",
45060
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
45061
+ });
45062
+ }
45063
+ const applied = this.applyAuthorized(sig.authorization, () => {
45064
+ this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
45065
+ return { ok: true, value: void 0 };
45094
45066
  });
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 };
45067
+ if (!applied.ok) {
45068
+ return upFail({
45069
+ kind: "rejected",
45070
+ source: "mock-ops",
45071
+ message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
45072
+ });
45073
+ }
45074
+ return upOk(sig.authorization, this.src("mock-ops"));
45099
45075
  });
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;
45076
+ if (!leg.ok) return leg;
45077
+ landed.push(s.step);
45078
+ approvals.push({
45079
+ step: s.step,
45080
+ txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
45081
+ amount,
45082
+ authorization: leg.value
45083
+ });
45084
+ }
45111
45085
  let executeAuth = null;
45112
45086
  if (cer) {
45113
45087
  const chainId = cer.txContext().chainId;
@@ -45122,7 +45096,7 @@ var MockUpstreamPlugin = class {
45122
45096
  return upFail({
45123
45097
  kind: "rejected",
45124
45098
  source: "mock-ops",
45125
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
45099
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
45126
45100
  });
45127
45101
  }
45128
45102
  executeAuth = r.authorization;
@@ -45133,23 +45107,16 @@ var MockUpstreamPlugin = class {
45133
45107
  return upFail({
45134
45108
  kind: "rejected",
45135
45109
  source: "mock-ops",
45136
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
45110
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
45137
45111
  });
45138
45112
  }
45139
45113
  const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
45140
- if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
45114
+ if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
45141
45115
  const bal = this.world.balancesOf(p.borrower);
45142
45116
  return upOk(
45143
45117
  {
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
- },
45118
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
45119
+ approvals,
45153
45120
  execute: {
45154
45121
  txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
45155
45122
  amountIn: p.amountIn,
@@ -46330,7 +46297,7 @@ var SafeModuleCeremony = class {
46330
46297
  };
46331
46298
 
46332
46299
  // src/boundary/upstream/real/plugin.ts
46333
- var import_ethers39 = require("ethers");
46300
+ var import_ethers49 = require("ethers");
46334
46301
 
46335
46302
  // node_modules/@gvnrdao/dh-sdk/dist/index.mjs
46336
46303
  var import_ethers14 = require("ethers");
@@ -52421,8 +52388,12 @@ var {
52421
52388
  var import_ethers28 = require("ethers");
52422
52389
  var import_ethers29 = require("ethers");
52423
52390
  var import_ethers30 = require("ethers");
52424
- var import_dh_lit_ops = __toESM(require_dist3(), 1);
52425
52391
  var import_ethers31 = require("ethers");
52392
+ var import_ethers32 = require("ethers");
52393
+ var import_ethers33 = require("ethers");
52394
+ var import_ethers34 = require("ethers");
52395
+ var import_dh_lit_ops = __toESM(require_dist3(), 1);
52396
+ var import_ethers35 = require("ethers");
52426
52397
  var __create2 = Object.create;
52427
52398
  var __defProp2 = Object.defineProperty;
52428
52399
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -54785,7 +54756,7 @@ ${errorReport}`);
54785
54756
  }
54786
54757
  init_debug_logger();
54787
54758
  init_session_signature_cache();
54788
- var import_ethers192 = __require("ethers");
54759
+ var import_ethers232 = __require("ethers");
54789
54760
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
54790
54761
  var GRACE_PERIOD_DAYS = 30;
54791
54762
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -57713,12 +57684,12 @@ ${auth.clientId}`;
57713
57684
  }
57714
57685
  async function executeVaultSnapshot(params) {
57715
57686
  global.ethers = {
57716
- ...import_ethers192.ethers,
57687
+ ...import_ethers232.ethers,
57717
57688
  providers: {
57718
- StaticJsonRpcProvider: import_ethers192.ethers.JsonRpcProvider
57689
+ StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
57719
57690
  },
57720
- Contract: import_ethers192.ethers.Contract,
57721
- utils: import_ethers192.ethers
57691
+ Contract: import_ethers232.ethers.Contract,
57692
+ utils: import_ethers232.ethers
57722
57693
  // v6 moved utils to top level
57723
57694
  };
57724
57695
  global.Lit = {
@@ -57972,8 +57943,8 @@ function getSepoliaConfig() {
57972
57943
  positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
57973
57944
  positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
57974
57945
  simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
57975
- mockUsdcToken: SEPOLIA_CONTRACTS["MockUSDC"] || "",
57976
- mockUsdtToken: SEPOLIA_CONTRACTS["MockUSDT"] || "",
57946
+ mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
57947
+ mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
57977
57948
  loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
57978
57949
  termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
57979
57950
  circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
@@ -58049,14 +58020,17 @@ function getMainnetConfig() {
58049
58020
  agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
58050
58021
  },
58051
58022
  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"
58023
+ // The MAINNET subgraph on The Graph's decentralized network — the same id
58024
+ // lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
58025
+ // the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
58026
+ // chainId-1 config: unusable as shipped, but a caller who added their own key would have
58027
+ // read Sepolia data as mainnet.
58028
+ //
58029
+ // The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
58030
+ // not) hold, so this URL only works for a standalone caller supplying their own key.
58031
+ // Service mode never uses it — queries go through the lit-ops-server proxy, which adds
58032
+ // the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
58033
+ diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
58060
58034
  },
58061
58035
  litNetwork: "chipotle",
58062
58036
  debug: false
@@ -59077,6 +59051,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
59077
59051
  }
59078
59052
  return { timestamp: result.timestamp, signature: result.signature };
59079
59053
  }
59054
+ function baseMintFeeWei(mintAmountWei, originationFeeBps) {
59055
+ if (mintAmountWei < 0n)
59056
+ throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
59057
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59058
+ throw new Error(
59059
+ `baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59060
+ );
59061
+ }
59062
+ return mintAmountWei * BigInt(originationFeeBps) / 10000n;
59063
+ }
59064
+ function debtAfterMintExceedsLoanCap(params) {
59065
+ const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
59066
+ for (const [name, v] of Object.entries(params)) {
59067
+ if (v < 0n)
59068
+ throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
59069
+ }
59070
+ return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
59071
+ }
59072
+ function maxPrincipalWithinLoanCap(params) {
59073
+ const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
59074
+ if (maxLoanWei < 0n || currentDebtWei < 0n) {
59075
+ throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
59076
+ }
59077
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59078
+ throw new Error(
59079
+ `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59080
+ );
59081
+ }
59082
+ const room = maxLoanWei - currentDebtWei;
59083
+ if (room <= 0n)
59084
+ return 0n;
59085
+ return room * 10000n / (10000n + BigInt(originationFeeBps));
59086
+ }
59080
59087
  function buildLoginDomain(chainId) {
59081
59088
  return {
59082
59089
  name: "Diamond Hands",
@@ -60486,23 +60493,37 @@ var BitcoinUtils = class {
60486
60493
  return getBitcoinAddressesFromPkp(pkpPublicKey);
60487
60494
  }
60488
60495
  };
60489
- function safeValidateBitcoinAddress(address, network = "regtest") {
60496
+ function networksOfValidAddress(address) {
60497
+ const lower2 = address.toLowerCase();
60498
+ if (lower2.startsWith("bcrt1"))
60499
+ return ["regtest"];
60500
+ if (lower2.startsWith("bc1"))
60501
+ return ["mainnet"];
60502
+ if (lower2.startsWith("tb1"))
60503
+ return ["testnet"];
60504
+ if (address.startsWith("1") || address.startsWith("3"))
60505
+ return ["mainnet"];
60506
+ return ["testnet", "regtest"];
60507
+ }
60508
+ function safeValidateBitcoinAddress(address, network) {
60490
60509
  if (!address || typeof address !== "string") {
60491
60510
  throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
60492
60511
  }
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}`);
60512
+ if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
60513
+ throw new Error(
60514
+ `Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
60515
+ );
60516
+ }
60517
+ if (!BitcoinUtils.validateAddress(address)) {
60518
+ throw new Error(
60519
+ `Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
60520
+ );
60497
60521
  }
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
- }
60522
+ const belongsTo = networksOfValidAddress(address);
60523
+ if (!belongsTo.includes(network)) {
60524
+ throw new Error(
60525
+ `Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
60526
+ );
60506
60527
  }
60507
60528
  return address;
60508
60529
  }
@@ -62611,6 +62632,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
62611
62632
  LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
62612
62633
  return LoanStatus2;
62613
62634
  })(LoanStatus || {});
62635
+ var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
62636
+ var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
62637
+ var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
62638
+ async function collectBorrowerDebtRows(fetchPage) {
62639
+ const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
62640
+ const rows = [];
62641
+ for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
62642
+ const batch = await fetchPage(page * pageSize, pageSize);
62643
+ if (batch.length > pageSize) {
62644
+ throw new Error(
62645
+ `Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
62646
+ );
62647
+ }
62648
+ rows.push(...batch);
62649
+ if (batch.length < pageSize) {
62650
+ return rows;
62651
+ }
62652
+ }
62653
+ throw new Error(
62654
+ `Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
62655
+ );
62656
+ }
62657
+ function parseSubgraphLoanStatus(label) {
62658
+ if (typeof label !== "string") {
62659
+ throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
62660
+ }
62661
+ const value = LoanStatus[label];
62662
+ if (typeof value !== "number") {
62663
+ throw new Error(`Unknown subgraph loan status label: "${label}"`);
62664
+ }
62665
+ return value;
62666
+ }
62667
+ function parseSubgraphWei(row) {
62668
+ const raw = row.ucdDebt || "0";
62669
+ if (typeof raw !== "string") {
62670
+ throw new Error(
62671
+ `ucdDebt on position ${row.id} is not a string: ${String(raw)}`
62672
+ );
62673
+ }
62674
+ let wei;
62675
+ try {
62676
+ wei = BigInt(raw);
62677
+ } catch (error) {
62678
+ throw new Error(
62679
+ `ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
62680
+ { cause: error }
62681
+ );
62682
+ }
62683
+ if (wei < 0n) {
62684
+ throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
62685
+ }
62686
+ return wei;
62687
+ }
62688
+ var WEI_PER_UCD = 10n ** 18n;
62689
+ function weiToHumanUcdString(wei) {
62690
+ if (wei < 0n) {
62691
+ throw new Error(`Cannot render negative wei: ${wei}`);
62692
+ }
62693
+ const whole = wei / WEI_PER_UCD;
62694
+ const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
62695
+ return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
62696
+ }
62697
+ var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
62698
+ function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
62699
+ let totalWei = 0n;
62700
+ const counts = /* @__PURE__ */ new Map();
62701
+ for (const row of rows) {
62702
+ totalWei += parseSubgraphWei(row);
62703
+ const status = parseSubgraphLoanStatus(row.status);
62704
+ counts.set(status, (counts.get(status) ?? 0) + 1);
62705
+ }
62706
+ const byStatus = [];
62707
+ for (const status of STATUS_ORDINALS) {
62708
+ const count = counts.get(status);
62709
+ if (count === void 0) {
62710
+ continue;
62711
+ }
62712
+ byStatus.push({ status, statusLabel: LoanStatus[status], count });
62713
+ }
62714
+ return {
62715
+ borrower: borrower.toLowerCase(),
62716
+ loanCount: rows.length,
62717
+ totalUcdDebt: totalWei.toString(),
62718
+ totalUcdDebtHuman: weiToHumanUcdString(totalWei),
62719
+ byStatus,
62720
+ source: "subgraph",
62721
+ fetchedAt
62722
+ };
62723
+ }
62614
62724
  var POSITION_CORE_ABI = [
62615
62725
  "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
62726
  ];
@@ -63003,6 +63113,43 @@ var LoanQuery = class {
63003
63113
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
63004
63114
  return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
63005
63115
  }
63116
+ /**
63117
+ * Combined UCD debt + by-status counts for a borrower from ONE pass over the
63118
+ * subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
63119
+ * status labels, `source: "subgraph"`.
63120
+ *
63121
+ * INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
63122
+ * sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
63123
+ * failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
63124
+ * is no partial total.
63125
+ */
63126
+ async getBorrowerUcdDebtSummary(borrower) {
63127
+ const trimmed = typeof borrower === "string" ? borrower.trim() : "";
63128
+ if (!(0, import_ethers26.isAddress)(trimmed)) {
63129
+ return failure(
63130
+ new SDKError({
63131
+ message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
63132
+ category: "VALIDATION",
63133
+ severity: "LOW",
63134
+ context: { borrower: trimmed }
63135
+ })
63136
+ );
63137
+ }
63138
+ return tryCatchAsync(
63139
+ async () => {
63140
+ const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
63141
+ return buildBorrowerUcdDebtSummary(trimmed, rows);
63142
+ },
63143
+ (error) => error instanceof SDKError ? error : new SDKError({
63144
+ message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
63145
+ category: "SUBGRAPH",
63146
+ severity: "MEDIUM",
63147
+ originalError: error instanceof Error ? error : void 0,
63148
+ cause: error,
63149
+ context: { borrower: trimmed }
63150
+ })
63151
+ );
63152
+ }
63006
63153
  /**
63007
63154
  * Get active loans (status = ACTIVE)
63008
63155
  *
@@ -64528,7 +64675,35 @@ var GraphClient = class {
64528
64675
  await new Promise((r) => setTimeout(r, ms));
64529
64676
  }
64530
64677
  };
64531
- var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
64678
+ var GET_USER_POSITIONS_DOCUMENT = `
64679
+ query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64680
+ user(id: $borrower) {
64681
+ id
64682
+ positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64683
+ id
64684
+ pkpId
64685
+ borrower {
64686
+ createdAt
64687
+ id
64688
+ }
64689
+ # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64690
+ ucdMinted
64691
+ ucdPaid
64692
+ ucdDebt
64693
+ collateralRatio
64694
+ requestedCollateralRatio
64695
+ selectedTerm
64696
+ status
64697
+ createdAt
64698
+ createdAtBlock
64699
+ lastUpdated
64700
+ originalTerm
64701
+ remainingDebt
64702
+ expiryAt
64703
+ }
64704
+ }
64705
+ }
64706
+ `;
64532
64707
  function normalizePkpId2(pkpId) {
64533
64708
  const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
64534
64709
  if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
@@ -64846,35 +65021,7 @@ var DiamondHandsGraph = class {
64846
65021
  * Get user positions from subgraph
64847
65022
  */
64848
65023
  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
- `;
65024
+ const query = GET_USER_POSITIONS_DOCUMENT;
64878
65025
  const variables = {
64879
65026
  borrower: userAddress.toLowerCase(),
64880
65027
  first: first || void 0,
@@ -64892,6 +65039,45 @@ var DiamondHandsGraph = class {
64892
65039
  }
64893
65040
  return positions;
64894
65041
  }
65042
+ /**
65043
+ * Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
65044
+ * 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
65045
+ * coerces wei to a float and leaves `status` a string cast to the numeric enum).
65046
+ *
65047
+ * Deliberately issues the `GetUserPositions` document rather than a leaner one: the
65048
+ * lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
65049
+ * and that one is already listed, so this needs no server change. The extra fields
65050
+ * cost bytes, not round trips.
65051
+ *
65052
+ * Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
65053
+ */
65054
+ async getBorrowerDebtRows(borrower) {
65055
+ const borrowerId = borrower.toLowerCase();
65056
+ return collectBorrowerDebtRows(async (skip, first) => {
65057
+ const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
65058
+ borrower: borrowerId,
65059
+ first,
65060
+ skip,
65061
+ orderBy: "id",
65062
+ orderDirection: "asc"
65063
+ });
65064
+ if (result?.user == null) {
65065
+ if (skip > 0) {
65066
+ throw new Error(
65067
+ `getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
65068
+ );
65069
+ }
65070
+ return [];
65071
+ }
65072
+ const positions = result.user.positions;
65073
+ if (!Array.isArray(positions)) {
65074
+ throw new Error(
65075
+ `getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
65076
+ );
65077
+ }
65078
+ return positions.filter((p) => p != null);
65079
+ });
65080
+ }
64895
65081
  /**
64896
65082
  * Get user positions, plus an accurate total count.
64897
65083
  *
@@ -71060,6 +71246,603 @@ async function mintAgentPkp(params) {
71060
71246
  clearTimeout(timeout);
71061
71247
  }
71062
71248
  }
71249
+ var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
71250
+ function planAgentBinding(params) {
71251
+ const { isActive, record, nowSeconds } = params;
71252
+ if (isActive)
71253
+ return { kind: "reuse", agent: record.agent };
71254
+ const status = Number(record.status);
71255
+ if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
71256
+ return { kind: "register" };
71257
+ }
71258
+ if (status !== AGENT_STATUS.Active) {
71259
+ throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
71260
+ }
71261
+ if (Number(record.validUntil) > nowSeconds) {
71262
+ throw new Error(
71263
+ "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
71264
+ );
71265
+ }
71266
+ return { kind: "rotate" };
71267
+ }
71268
+ async function describeProviderChainMismatch(provider, chainId) {
71269
+ const actual = Number((await provider.getNetwork()).chainId);
71270
+ if (actual === chainId)
71271
+ return null;
71272
+ 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.`;
71273
+ }
71274
+ var TxValidationError2 = class extends Error {
71275
+ /**
71276
+ * @param subject What is being refused. Defaults to the server-returned transaction the
71277
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
71278
+ */
71279
+ constructor(msg, subject = "server-returned transaction") {
71280
+ super(`Refusing to sign ${subject}: ${msg}`);
71281
+ this.name = "TxValidationError";
71282
+ }
71283
+ };
71284
+ var SIGNABLE_FUNCTIONS2 = [
71285
+ "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)",
71286
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
71287
+ // used to sit here; it is not a function on any deployed contract — the
71288
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
71289
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
71290
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
71291
+ // it. A signable-function whitelist should not carry calldata shapes the
71292
+ // protocol cannot execute.
71293
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
71294
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
71295
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
71296
+ // Struct-version: matches the actual on-chain function signature and the
71297
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
71298
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
71299
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
71300
+ "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)",
71301
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
71302
+ // function reverts permanently. The trustless replacement
71303
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
71304
+ // entry when its LIT Action ships.
71305
+ "function approve(address spender, uint256 amount) external returns (bool)",
71306
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
71307
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
71308
+ // without an entry here it decoded as "<unparseable>" and the CLI's
71309
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
71310
+ // collateral had no client-side pin at all.
71311
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
71312
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
71313
+ // AgentModule; the parity test documents them as client-only.
71314
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
71315
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
71316
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
71317
+ // this too is client-only and never module-whitelisted.
71318
+ "function addAddress(string btcAddress) external"
71319
+ ];
71320
+ var IFACE2 = new import_ethers32.ethers.Interface(SIGNABLE_FUNCTIONS2);
71321
+ function encodeSignable2(fn, args) {
71322
+ return IFACE2.encodeFunctionData(fn, args);
71323
+ }
71324
+ function decodeSignable2(data) {
71325
+ try {
71326
+ const parsed = IFACE2.parseTransaction({ data });
71327
+ if (!parsed) {
71328
+ throw new TxValidationError2(
71329
+ `unsignedTx.data does not decode against the signable-function whitelist`
71330
+ );
71331
+ }
71332
+ return { name: parsed.name, args: parsed.args };
71333
+ } catch (e) {
71334
+ if (e instanceof TxValidationError2)
71335
+ throw e;
71336
+ throw new TxValidationError2(
71337
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
71338
+ );
71339
+ }
71340
+ }
71341
+ var MAX_GAS_LIMIT = 5000000n;
71342
+ var MAX_FEE_PER_GAS_WEI = 2000000000000n;
71343
+ var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
71344
+ var DEFAULT_FEE_CEILING = {
71345
+ maxGasLimit: MAX_GAS_LIMIT,
71346
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
71347
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
71348
+ };
71349
+ function fmtEth(wei) {
71350
+ return `${import_ethers34.ethers.formatEther(wei)} ETH`;
71351
+ }
71352
+ function fmtGwei(wei) {
71353
+ return `${import_ethers34.ethers.formatUnits(wei, "gwei")} gwei`;
71354
+ }
71355
+ function worstCaseFeeWei(gasLimit, maxFeePerGas) {
71356
+ if (gasLimit == null || maxFeePerGas == null)
71357
+ return null;
71358
+ return gasLimit * maxFeePerGas;
71359
+ }
71360
+ function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
71361
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
71362
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
71363
+ }
71364
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
71365
+ raise(
71366
+ `maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
71367
+ );
71368
+ }
71369
+ const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
71370
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
71371
+ raise(
71372
+ `worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
71373
+ );
71374
+ }
71375
+ }
71376
+ function eqAddr2(a, b) {
71377
+ if (!a || !b)
71378
+ return false;
71379
+ try {
71380
+ return import_ethers33.ethers.getAddress(a) === import_ethers33.ethers.getAddress(b);
71381
+ } catch {
71382
+ return false;
71383
+ }
71384
+ }
71385
+ function readToAddress2(tx2) {
71386
+ const to = tx2["to"];
71387
+ if (typeof to !== "string") {
71388
+ throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
71389
+ }
71390
+ return to;
71391
+ }
71392
+ function readData2(tx2) {
71393
+ const data = tx2["data"];
71394
+ if (typeof data !== "string" || !data.startsWith("0x")) {
71395
+ throw new TxValidationError2(`unsignedTx.data missing or malformed`);
71396
+ }
71397
+ return data;
71398
+ }
71399
+ function readChainId2(tx2) {
71400
+ const c = tx2["chainId"];
71401
+ if (c == null)
71402
+ return null;
71403
+ if (typeof c === "number")
71404
+ return c;
71405
+ if (typeof c === "string")
71406
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
71407
+ if (typeof c === "bigint")
71408
+ return Number(c);
71409
+ return null;
71410
+ }
71411
+ function readOptionalBigInt(tx2, key) {
71412
+ const v = tx2[key];
71413
+ if (v == null)
71414
+ return null;
71415
+ try {
71416
+ if (typeof v === "bigint")
71417
+ return v;
71418
+ if (typeof v === "number")
71419
+ return BigInt(v);
71420
+ if (typeof v === "string")
71421
+ return BigInt(v);
71422
+ return BigInt(v.toString());
71423
+ } catch {
71424
+ throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
71425
+ }
71426
+ }
71427
+ function readValue2(tx2) {
71428
+ const v = tx2["value"];
71429
+ if (v == null)
71430
+ return 0n;
71431
+ if (typeof v === "string")
71432
+ return BigInt(v);
71433
+ if (typeof v === "number")
71434
+ return BigInt(v);
71435
+ if (typeof v === "bigint")
71436
+ return v;
71437
+ const maybe = v;
71438
+ if (typeof maybe.toBigInt === "function")
71439
+ return maybe.toBigInt();
71440
+ if (typeof maybe.toString === "function")
71441
+ return BigInt(maybe.toString());
71442
+ throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
71443
+ }
71444
+ function normalizePositionId2(id) {
71445
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
71446
+ return import_ethers33.ethers.zeroPadValue(hex, 32).toLowerCase();
71447
+ }
71448
+ function requirePositionId(actual, expected) {
71449
+ const txPositionId = String(actual).toLowerCase();
71450
+ if (txPositionId !== normalizePositionId2(expected)) {
71451
+ throw new TxValidationError2(
71452
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
71453
+ );
71454
+ }
71455
+ }
71456
+ function validateUnsignedTx2(unsignedTx, expected, vctx) {
71457
+ const txChainId = readChainId2(unsignedTx);
71458
+ if (txChainId == null) {
71459
+ throw new TxValidationError2(
71460
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
71461
+ );
71462
+ }
71463
+ if (txChainId !== vctx.chainId) {
71464
+ throw new TxValidationError2(
71465
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
71466
+ );
71467
+ }
71468
+ const value = readValue2(unsignedTx);
71469
+ if (value !== 0n) {
71470
+ throw new TxValidationError2(
71471
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
71472
+ );
71473
+ }
71474
+ assertFeeCeiling(
71475
+ readOptionalBigInt(unsignedTx, "gasLimit"),
71476
+ readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
71477
+ (msg) => {
71478
+ throw new TxValidationError2(msg);
71479
+ },
71480
+ vctx.feeCeiling
71481
+ );
71482
+ const to = readToAddress2(unsignedTx);
71483
+ const data = readData2(unsignedTx);
71484
+ const { name, args } = decodeSignable2(data);
71485
+ const pm = vctx.contracts.PositionManager;
71486
+ switch (expected.kind) {
71487
+ case "mint": {
71488
+ if (name !== "mintUCD") {
71489
+ throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
71490
+ }
71491
+ if (!eqAddr2(to, pm)) {
71492
+ throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
71493
+ }
71494
+ requirePositionId(args[0], expected.positionId);
71495
+ const txMintAmount = BigInt(String(args[1]));
71496
+ if (txMintAmount.toString() !== expected.amountWei) {
71497
+ throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
71498
+ }
71499
+ const txMintFee = BigInt(String(args[2]));
71500
+ if (txMintFee.toString() !== expected.mintFeeWei) {
71501
+ throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
71502
+ }
71503
+ break;
71504
+ }
71505
+ case "repay": {
71506
+ if (name !== "makePayment") {
71507
+ throw new TxValidationError2(`expected makePayment, server returned ${name}`);
71508
+ }
71509
+ if (!eqAddr2(to, pm)) {
71510
+ throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
71511
+ }
71512
+ requirePositionId(args[0], expected.positionId);
71513
+ const txAmount = BigInt(String(args[1]));
71514
+ if (txAmount.toString() !== expected.amountWei) {
71515
+ throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
71516
+ }
71517
+ break;
71518
+ }
71519
+ case "extend": {
71520
+ if (name !== "extendPosition") {
71521
+ throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
71522
+ }
71523
+ if (!eqAddr2(to, pm)) {
71524
+ throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
71525
+ }
71526
+ requirePositionId(args[0], expected.positionId);
71527
+ const txTerm = Number(args[1]);
71528
+ if (txTerm !== expected.selectedTerm) {
71529
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71530
+ }
71531
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
71532
+ const txFee = BigInt(String(args[5]));
71533
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
71534
+ if (txFee > upper) {
71535
+ throw new TxValidationError2(
71536
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
71537
+ );
71538
+ }
71539
+ }
71540
+ break;
71541
+ }
71542
+ case "withdraw-btc": {
71543
+ if (name !== "withdrawBTC") {
71544
+ throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
71545
+ }
71546
+ if (!eqAddr2(to, pm)) {
71547
+ throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
71548
+ }
71549
+ const paramsTuple = args[0];
71550
+ requirePositionId(paramsTuple[0], expected.positionId);
71551
+ const txWithdrawalAddress = String(paramsTuple[5]);
71552
+ if (txWithdrawalAddress !== expected.btcAddress) {
71553
+ throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
71554
+ }
71555
+ if (expected.upperBoundTotalDeduction != null) {
71556
+ const txDeduction = BigInt(String(paramsTuple[6]));
71557
+ const upper = BigInt(expected.upperBoundTotalDeduction);
71558
+ if (txDeduction > upper) {
71559
+ throw new TxValidationError2(
71560
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
71561
+ );
71562
+ }
71563
+ }
71564
+ break;
71565
+ }
71566
+ case "ucd-approve": {
71567
+ if (name !== "approve") {
71568
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71569
+ }
71570
+ const ucd = vctx.contracts.UCDToken;
71571
+ if (!eqAddr2(to, ucd)) {
71572
+ throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
71573
+ }
71574
+ const spender = String(args[0]);
71575
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
71576
+ if (!ok2) {
71577
+ throw new TxValidationError2(
71578
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
71579
+ );
71580
+ }
71581
+ const amt = BigInt(String(args[1]));
71582
+ const min = BigInt(expected.minAmountWei);
71583
+ if (amt < min) {
71584
+ throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
71585
+ }
71586
+ const SANITY_MAX = min * 1000n;
71587
+ if (amt > SANITY_MAX) {
71588
+ throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
71589
+ }
71590
+ break;
71591
+ }
71592
+ case "create-position": {
71593
+ if (name !== "createPosition") {
71594
+ throw new TxValidationError2(`expected createPosition, server returned ${name}`);
71595
+ }
71596
+ if (!eqAddr2(to, pm)) {
71597
+ throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
71598
+ }
71599
+ const txTerm = BigInt(String(args[4]));
71600
+ if (txTerm !== BigInt(expected.selectedTerm)) {
71601
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71602
+ }
71603
+ break;
71604
+ }
71605
+ case "set-position-delegate": {
71606
+ if (name !== "setPositionDelegate") {
71607
+ throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
71608
+ }
71609
+ if (!eqAddr2(to, expected.registryAddress)) {
71610
+ throw new TxValidationError2(
71611
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
71612
+ );
71613
+ }
71614
+ requirePositionId(args[0], expected.positionId);
71615
+ const txDelegate = String(args[1]);
71616
+ if (!eqAddr2(txDelegate, expected.delegate)) {
71617
+ throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
71618
+ }
71619
+ break;
71620
+ }
71621
+ case "bwar-add-address": {
71622
+ if (name !== "addAddress") {
71623
+ throw new TxValidationError2(`expected addAddress, decoded ${name}`);
71624
+ }
71625
+ if (!eqAddr2(to, expected.registryAddress)) {
71626
+ throw new TxValidationError2(
71627
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
71628
+ );
71629
+ }
71630
+ if (String(args[0]) !== expected.btcAddress) {
71631
+ throw new TxValidationError2(
71632
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
71633
+ );
71634
+ }
71635
+ break;
71636
+ }
71637
+ case "stablecoin-approve": {
71638
+ if (name !== "approve") {
71639
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71640
+ }
71641
+ if (!eqAddr2(to, expected.tokenAddress)) {
71642
+ throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
71643
+ }
71644
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71645
+ throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
71646
+ }
71647
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
71648
+ throw new TxValidationError2(
71649
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
71650
+ );
71651
+ }
71652
+ break;
71653
+ }
71654
+ case "ucd-approve-controller": {
71655
+ if (name !== "approve") {
71656
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71657
+ }
71658
+ if (!eqAddr2(to, expected.ucdTokenAddress)) {
71659
+ throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
71660
+ }
71661
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71662
+ throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
71663
+ }
71664
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
71665
+ throw new TxValidationError2(
71666
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
71667
+ );
71668
+ }
71669
+ break;
71670
+ }
71671
+ case "psm-swap": {
71672
+ if (name !== "swap")
71673
+ throw new TxValidationError2(`expected swap, server returned ${name}`);
71674
+ if (!eqAddr2(to, expected.psmAddress)) {
71675
+ throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
71676
+ }
71677
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71678
+ throw new TxValidationError2(`swap stablecoin mismatch`);
71679
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
71680
+ throw new TxValidationError2(`swap amountIn mismatch`);
71681
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71682
+ throw new TxValidationError2(`swap minUcdOut mismatch`);
71683
+ if (BigInt(expected.minOut) === 0n) {
71684
+ throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71685
+ }
71686
+ break;
71687
+ }
71688
+ case "psm-redeem": {
71689
+ if (name !== "redeem")
71690
+ throw new TxValidationError2(`expected redeem, server returned ${name}`);
71691
+ if (!eqAddr2(to, expected.psmAddress)) {
71692
+ throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
71693
+ }
71694
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71695
+ throw new TxValidationError2(`redeem stablecoin mismatch`);
71696
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
71697
+ throw new TxValidationError2(`redeem ucdAmount mismatch`);
71698
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71699
+ throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
71700
+ if (BigInt(expected.minOut) === 0n) {
71701
+ throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71702
+ }
71703
+ break;
71704
+ }
71705
+ default: {
71706
+ const _exhaustive = expected;
71707
+ throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
71708
+ }
71709
+ }
71710
+ }
71711
+ function buildPsmApproveTx(p) {
71712
+ return {
71713
+ to: p.token,
71714
+ data: encodeSignable2("approve", [p.spender, p.amount]),
71715
+ value: "0x0",
71716
+ chainId: p.chainId
71717
+ };
71718
+ }
71719
+ function buildPsmSwapTx2(p) {
71720
+ return {
71721
+ to: p.psm,
71722
+ data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
71723
+ value: "0x0",
71724
+ chainId: p.chainId
71725
+ };
71726
+ }
71727
+ function buildPsmRedeemTx2(p) {
71728
+ return {
71729
+ to: p.psm,
71730
+ data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
71731
+ value: "0x0",
71732
+ chainId: p.chainId
71733
+ };
71734
+ }
71735
+ var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
71736
+ var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
71737
+ function psmExchangeReadsFromProvider(provider, psmAddress) {
71738
+ const psm = new import_ethers31.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
71739
+ return {
71740
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
71741
+ allowance: async (token, owner, spender) => await new import_ethers31.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
71742
+ };
71743
+ }
71744
+ var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
71745
+ function requireAddress(direction, label, value) {
71746
+ if (!value || !import_ethers31.ethers.isAddress(value)) {
71747
+ throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
71748
+ }
71749
+ return import_ethers31.ethers.getAddress(value);
71750
+ }
71751
+ async function planPsmExchange(params) {
71752
+ const { direction, amountIn, minOut, vctx, reads } = params;
71753
+ const chainId = vctx.chainId;
71754
+ if (amountIn <= 0n) {
71755
+ throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
71756
+ }
71757
+ if (minOut <= 0n) {
71758
+ throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
71759
+ }
71760
+ const owner = requireAddress(direction, "owner", params.owner);
71761
+ const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
71762
+ const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
71763
+ const isSwap = direction === "swap";
71764
+ const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
71765
+ const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
71766
+ if (!await reads.isStablecoinSupported(stablecoin)) {
71767
+ throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
71768
+ }
71769
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
71770
+ const allowanceBefore = await reads.allowance(token, owner, spender);
71771
+ const approvals = [];
71772
+ if (allowanceBefore < amountIn) {
71773
+ if (allowanceBefore > 0n) {
71774
+ approvals.push({
71775
+ step: "reset-approve",
71776
+ tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
71777
+ expected: approveExpected(0n)
71778
+ });
71779
+ }
71780
+ approvals.push({
71781
+ step: "approve",
71782
+ tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
71783
+ expected: approveExpected(amountIn)
71784
+ });
71785
+ }
71786
+ const exec = isSwap ? {
71787
+ step: "swap",
71788
+ tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
71789
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
71790
+ } : {
71791
+ step: "redeem",
71792
+ tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
71793
+ expected: {
71794
+ kind: "psm-redeem",
71795
+ psmAddress: psm,
71796
+ stablecoin,
71797
+ amountUcdWei: amountIn.toString(),
71798
+ minOut: minOut.toString()
71799
+ }
71800
+ };
71801
+ for (const leg of [...approvals, exec]) {
71802
+ validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
71803
+ }
71804
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
71805
+ }
71806
+ async function executePsmPlan(plan, signer, vctx) {
71807
+ const approvalHashes = [];
71808
+ 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.`;
71809
+ const sendLeg = async (leg) => {
71810
+ const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
71811
+ validateUnsignedTx2({ ...request }, leg.expected, vctx);
71812
+ const sent = await signer.sendTransaction(request);
71813
+ const receipt = await sent.wait();
71814
+ if (!receipt)
71815
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
71816
+ if (receipt.status !== 1)
71817
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
71818
+ return { hash: sent.hash, blockNumber: receipt.blockNumber };
71819
+ };
71820
+ for (const leg of plan.approvals) {
71821
+ const landed = await sendLeg(leg).catch((e) => {
71822
+ throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71823
+ });
71824
+ approvalHashes.push(landed.hash);
71825
+ }
71826
+ const exec = await sendLeg(plan.exec).catch((e) => {
71827
+ throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71828
+ });
71829
+ return { ...exec, approvalHashes };
71830
+ }
71831
+ var LIT_ACTION_CHAIN_NAMES = Object.freeze({
71832
+ 1: "ethereum",
71833
+ 11155111: "sepolia",
71834
+ 1337: "hardhat",
71835
+ 31337: "hardhat"
71836
+ });
71837
+ function litActionChainNameForChainId(chainId) {
71838
+ const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
71839
+ if (!name) {
71840
+ throw new Error(
71841
+ `Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
71842
+ );
71843
+ }
71844
+ return name;
71845
+ }
71063
71846
  var MockTokenManager = class {
71064
71847
  config;
71065
71848
  constructor(config) {
@@ -72033,6 +72816,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72033
72816
  */
72034
72817
  static async create(config) {
72035
72818
  const userProvidedServiceEndpoint = config.serviceEndpoint;
72819
+ if (typeof config.chainId === "number" && config.provider) {
72820
+ const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
72821
+ if (mismatch) {
72822
+ return failure(
72823
+ new SDKError({
72824
+ message: mismatch,
72825
+ category: "CONFIGURATION",
72826
+ severity: "HIGH"
72827
+ /* HIGH */
72828
+ })
72829
+ );
72830
+ }
72831
+ }
72036
72832
  const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
72037
72833
  if (userProvidedServiceEndpoint) {
72038
72834
  enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
@@ -72683,6 +73479,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72683
73479
  if (this.config.debug) {
72684
73480
  log.info(` Position PKP ID: ${position2.pkpId}`);
72685
73481
  }
73482
+ const termsResult = await this.getTermsWithFees();
73483
+ if (!termsResult.success) {
73484
+ return {
73485
+ success: false,
73486
+ error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
73487
+ };
73488
+ }
73489
+ const positionTermMonths = Number(position2.selectedTerm);
73490
+ const positionTerm = termsResult.value.terms.find(
73491
+ (term) => term.termMonths === positionTermMonths
73492
+ );
73493
+ if (!positionTerm) {
73494
+ return {
73495
+ success: false,
73496
+ error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
73497
+ };
73498
+ }
73499
+ const currentDebtWei = BigInt(position2.ucdDebt);
73500
+ const baseFeeWei = baseMintFeeWei(
73501
+ requestAmountWei,
73502
+ positionTerm.originationFeeBps
73503
+ );
73504
+ if (debtAfterMintExceedsLoanCap({
73505
+ currentDebtWei,
73506
+ mintAmountWei: requestAmountWei,
73507
+ mintFeeWei: baseFeeWei,
73508
+ maxLoanWei: maxLoanValueWei
73509
+ })) {
73510
+ const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
73511
+ const maxPrincipalUcd = Number(
73512
+ maxPrincipalWithinLoanCap({
73513
+ maxLoanWei: maxLoanValueWei,
73514
+ currentDebtWei,
73515
+ originationFeeBps: positionTerm.originationFeeBps
73516
+ }) / BigInt(10 ** 18)
73517
+ );
73518
+ return {
73519
+ success: false,
73520
+ 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.`
73521
+ };
73522
+ }
73523
+ if (this.config.debug) {
73524
+ log.info(
73525
+ `\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers14.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD`,
73526
+ {}
73527
+ );
73528
+ }
72686
73529
  let pkpPublicKey;
72687
73530
  let pkpEthAddress;
72688
73531
  const pkpCache = this.cacheManager.getCache("pkp-data", {
@@ -72772,7 +73615,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72772
73615
  ` UCDController: ${contracts?.UCDController || "MISSING"}`
72773
73616
  );
72774
73617
  }
72775
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
73618
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
72776
73619
  const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
72777
73620
  if (this.config.debug) {
72778
73621
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -73372,6 +74215,25 @@ Error data: none`
73372
74215
  }
73373
74216
  const selector = simError.selector;
73374
74217
  const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
74218
+ const MINT_GUARD_CODES = {
74219
+ "1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
74220
+ "2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
74221
+ "3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
74222
+ };
74223
+ let loanCapDiagnostics = "";
74224
+ if (selector === "0xe6dd4d41") {
74225
+ const guardCode = BigInt(
74226
+ "0x" + String(simError.data).slice(10).padStart(64, "0")
74227
+ ).toString();
74228
+ const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
74229
+ loanCapDiagnostics = `
74230
+
74231
+ MintGuardFailed(${guardCode}): ${guardMeaning}
74232
+ Lit mintAmount: ${validationResponse.mintAmount}
74233
+ Lit mintFee: ${validationResponse.mintFee}
74234
+ Lit newDebt: ${validationResponse.newDebt}
74235
+ Protocol maximum: ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
74236
+ }
73375
74237
  const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
73376
74238
  selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
73377
74239
  selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
@@ -73417,7 +74279,7 @@ Quantum Timing Analysis:
73417
74279
  Error selector: ${selector}
73418
74280
  Error data: ${simError.data}
73419
74281
  Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
73420
- Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
74282
+ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
73421
74283
  );
73422
74284
  }
73423
74285
  const tx2 = await sendEip1559Transaction({
@@ -76025,7 +76887,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76025
76887
  ` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
76026
76888
  );
76027
76889
  }
76028
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
76890
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
76029
76891
  const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
76030
76892
  if (this.config.debug) {
76031
76893
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -76580,13 +77442,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76580
77442
  return { success: false, error: "Failed to resolve PKP public key" };
76581
77443
  }
76582
77444
  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];
77445
+ const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
76590
77446
  if (!chainName) {
76591
77447
  return {
76592
77448
  success: false,
@@ -77808,6 +78664,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77808
78664
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
77809
78665
  return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
77810
78666
  }
78667
+ /**
78668
+ * Combined UCD debt (canonical wei string + display string) and by-status loan
78669
+ * counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
78670
+ * an INDEXED, informational figure that lags writes; never size a transaction
78671
+ * from it (repayments read the chain via `getPositionDetailsView`).
78672
+ *
78673
+ * Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
78674
+ * failure or past 10,000 positions; never returns a partial total.
78675
+ */
78676
+ async getBorrowerUcdDebtSummary(borrower) {
78677
+ return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
78678
+ }
77811
78679
  /**
77812
78680
  * Get all active loans
77813
78681
  *
@@ -77933,11 +78801,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77933
78801
  }
77934
78802
  /**
77935
78803
  * Execute a PSM stablecoin → UCD swap.
77936
- * Handles stablecoin approval to the PSM contract if the current allowance is insufficient.
78804
+ * Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
78805
+ * partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
77937
78806
  *
77938
78807
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
77939
78808
  * @param params.amountWei - Stablecoin amount in native decimals (bigint)
77940
- * @param params.minUcdOutWei - Minimum UCD to receive; reverts if below this (1% slippage guard)
78809
+ * @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
77941
78810
  * @param params.signer - Connected signer for the approval and swap transactions
77942
78811
  */
77943
78812
  async psmSwap(params) {
@@ -77947,32 +78816,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77947
78816
  "SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
77948
78817
  );
77949
78818
  }
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 };
78819
+ return this.runPsmExchange({
78820
+ direction: "swap",
78821
+ signer: params.signer,
78822
+ addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
78823
+ amountIn: params.amountWei,
78824
+ minOut: params.minUcdOutWei
78825
+ });
77967
78826
  }
77968
78827
  /**
77969
78828
  * 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).
78829
+ * Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
78830
+ * M-4 burn allowance guard: UCDToken.burn(from, amount) calls
78831
+ * _spendAllowance(from, msg.sender=ucdController, amount).
77972
78832
  *
77973
78833
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
77974
78834
  * @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
77975
- * @param params.minStablecoinOutWei - Minimum stablecoin to receive (slippage guard)
78835
+ * @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
77976
78836
  * @param params.signer - Connected signer
77977
78837
  */
77978
78838
  async psmRedeem(params) {
@@ -77985,23 +78845,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77985
78845
  throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
77986
78846
  if (!ucdControllerAddress)
77987
78847
  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 };
78848
+ return this.runPsmExchange({
78849
+ direction: "redeem",
78850
+ signer: params.signer,
78851
+ addresses: {
78852
+ psm: psmAddress,
78853
+ stablecoin: params.stablecoinAddress,
78854
+ ucdToken: ucdAddress,
78855
+ ucdController: ucdControllerAddress
78856
+ },
78857
+ amountIn: params.ucdAmountWei,
78858
+ minOut: params.minStablecoinOutWei
78859
+ });
78860
+ }
78861
+ /**
78862
+ * Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
78863
+ * The signer's chain must match the SDK's configured chain — the addresses came from it.
78864
+ */
78865
+ async runPsmExchange(params) {
78866
+ const provider = params.signer.provider;
78867
+ if (!provider) {
78868
+ throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
78869
+ }
78870
+ const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
78871
+ if (typeof configuredChainId !== "number") {
78872
+ throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
78873
+ }
78874
+ const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
78875
+ if (mismatch)
78876
+ throw new Error(mismatch);
78877
+ const vctx = {
78878
+ chainId: configuredChainId,
78879
+ network: String(configuredChainId),
78880
+ contracts: {}
78881
+ };
78882
+ const plan = await planPsmExchange({
78883
+ direction: params.direction,
78884
+ owner: await params.signer.getAddress(),
78885
+ addresses: params.addresses,
78886
+ amountIn: params.amountIn,
78887
+ minOut: params.minOut,
78888
+ vctx,
78889
+ reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
78890
+ });
78891
+ const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
78892
+ return { hash, blockNumber };
78005
78893
  }
78006
78894
  /**
78007
78895
  * Wait for the subgraph to index up to (and including) the given block number.
@@ -78182,18 +79070,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
78182
79070
  const user = await signer.getAddress();
78183
79071
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
78184
79072
  let agentAddress;
78185
- const hasActiveAgent = await registry.isAgentActive(user);
78186
- if (hasActiveAgent) {
78187
- agentAddress = (await registry.agentOf(user)).agent;
79073
+ const [isActive, record, latestBlock] = await Promise.all([
79074
+ registry.isAgentActive(user),
79075
+ registry.agentOf(user),
79076
+ this.getProviderOrThrow().getBlock("latest")
79077
+ ]);
79078
+ if (!latestBlock) {
79079
+ throw new SDKError({
79080
+ message: "Could not read the latest block to check the agent registration's expiry",
79081
+ category: "NETWORK",
79082
+ severity: "HIGH"
79083
+ /* HIGH */
79084
+ });
79085
+ }
79086
+ const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
79087
+ if (plan.kind === "reuse") {
79088
+ agentAddress = plan.agent;
78188
79089
  } else {
78189
79090
  agentAddress = await mintAgentPkp({
78190
79091
  serviceEndpoint: this.config.serviceEndpoint,
78191
79092
  authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
78192
79093
  });
78193
79094
  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();
79095
+ const validUntil = latestBlock.timestamp + validitySeconds;
79096
+ const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
79097
+ await bindTx.wait();
78197
79098
  }
78198
79099
  const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
78199
79100
  () => null
@@ -79585,7 +80486,552 @@ var SUPPORTED_STABLECOINS = `
79585
80486
  }`;
79586
80487
 
79587
80488
  // src/boundary/upstream/real/psm-calls.ts
79588
- var import_ethers32 = require("ethers");
80489
+ var import_ethers42 = require("ethers");
80490
+
80491
+ // node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
80492
+ var import_ethers36 = require("ethers");
80493
+ var import_ethers37 = require("ethers");
80494
+ var import_ethers38 = require("ethers");
80495
+ var import_ethers39 = require("ethers");
80496
+ var import_ethers40 = require("ethers");
80497
+ var import_ethers41 = require("ethers");
80498
+ var TxValidationError3 = class extends Error {
80499
+ /**
80500
+ * @param subject What is being refused. Defaults to the server-returned transaction the
80501
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
80502
+ */
80503
+ constructor(msg, subject = "server-returned transaction") {
80504
+ super(`Refusing to sign ${subject}: ${msg}`);
80505
+ this.name = "TxValidationError";
80506
+ }
80507
+ };
80508
+ var SIGNABLE_FUNCTIONS3 = [
80509
+ "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)",
80510
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
80511
+ // used to sit here; it is not a function on any deployed contract — the
80512
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
80513
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
80514
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
80515
+ // it. A signable-function whitelist should not carry calldata shapes the
80516
+ // protocol cannot execute.
80517
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
80518
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
80519
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
80520
+ // Struct-version: matches the actual on-chain function signature and the
80521
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
80522
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
80523
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
80524
+ "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)",
80525
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
80526
+ // function reverts permanently. The trustless replacement
80527
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
80528
+ // entry when its LIT Action ships.
80529
+ "function approve(address spender, uint256 amount) external returns (bool)",
80530
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
80531
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
80532
+ // without an entry here it decoded as "<unparseable>" and the CLI's
80533
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
80534
+ // collateral had no client-side pin at all.
80535
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
80536
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
80537
+ // AgentModule; the parity test documents them as client-only.
80538
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
80539
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
80540
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
80541
+ // this too is client-only and never module-whitelisted.
80542
+ "function addAddress(string btcAddress) external"
80543
+ ];
80544
+ var IFACE3 = new import_ethers36.ethers.Interface(SIGNABLE_FUNCTIONS3);
80545
+ function encodeSignable3(fn, args) {
80546
+ return IFACE3.encodeFunctionData(fn, args);
80547
+ }
80548
+ function decodeSignable3(data) {
80549
+ try {
80550
+ const parsed = IFACE3.parseTransaction({ data });
80551
+ if (!parsed) {
80552
+ throw new TxValidationError3(
80553
+ `unsignedTx.data does not decode against the signable-function whitelist`
80554
+ );
80555
+ }
80556
+ return { name: parsed.name, args: parsed.args };
80557
+ } catch (e) {
80558
+ if (e instanceof TxValidationError3)
80559
+ throw e;
80560
+ throw new TxValidationError3(
80561
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
80562
+ );
80563
+ }
80564
+ }
80565
+ var MAX_GAS_LIMIT2 = 5000000n;
80566
+ var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
80567
+ var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
80568
+ var DEFAULT_FEE_CEILING2 = {
80569
+ maxGasLimit: MAX_GAS_LIMIT2,
80570
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
80571
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
80572
+ };
80573
+ function fmtEth2(wei) {
80574
+ return `${import_ethers37.ethers.formatEther(wei)} ETH`;
80575
+ }
80576
+ function fmtGwei2(wei) {
80577
+ return `${import_ethers37.ethers.formatUnits(wei, "gwei")} gwei`;
80578
+ }
80579
+ function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
80580
+ if (gasLimit == null || maxFeePerGas == null)
80581
+ return null;
80582
+ return gasLimit * maxFeePerGas;
80583
+ }
80584
+ function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
80585
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
80586
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
80587
+ }
80588
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
80589
+ raise(
80590
+ `maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
80591
+ );
80592
+ }
80593
+ const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
80594
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
80595
+ raise(
80596
+ `worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
80597
+ );
80598
+ }
80599
+ }
80600
+ function eqAddr3(a, b) {
80601
+ if (!a || !b)
80602
+ return false;
80603
+ try {
80604
+ return import_ethers38.ethers.getAddress(a) === import_ethers38.ethers.getAddress(b);
80605
+ } catch {
80606
+ return false;
80607
+ }
80608
+ }
80609
+ function readToAddress3(tx2) {
80610
+ const to = tx2["to"];
80611
+ if (typeof to !== "string") {
80612
+ throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
80613
+ }
80614
+ return to;
80615
+ }
80616
+ function readData3(tx2) {
80617
+ const data = tx2["data"];
80618
+ if (typeof data !== "string" || !data.startsWith("0x")) {
80619
+ throw new TxValidationError3(`unsignedTx.data missing or malformed`);
80620
+ }
80621
+ return data;
80622
+ }
80623
+ function readChainId3(tx2) {
80624
+ const c = tx2["chainId"];
80625
+ if (c == null)
80626
+ return null;
80627
+ if (typeof c === "number")
80628
+ return c;
80629
+ if (typeof c === "string")
80630
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
80631
+ if (typeof c === "bigint")
80632
+ return Number(c);
80633
+ return null;
80634
+ }
80635
+ function readOptionalBigInt2(tx2, key) {
80636
+ const v = tx2[key];
80637
+ if (v == null)
80638
+ return null;
80639
+ try {
80640
+ if (typeof v === "bigint")
80641
+ return v;
80642
+ if (typeof v === "number")
80643
+ return BigInt(v);
80644
+ if (typeof v === "string")
80645
+ return BigInt(v);
80646
+ return BigInt(v.toString());
80647
+ } catch {
80648
+ throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
80649
+ }
80650
+ }
80651
+ function readValue3(tx2) {
80652
+ const v = tx2["value"];
80653
+ if (v == null)
80654
+ return 0n;
80655
+ if (typeof v === "string")
80656
+ return BigInt(v);
80657
+ if (typeof v === "number")
80658
+ return BigInt(v);
80659
+ if (typeof v === "bigint")
80660
+ return v;
80661
+ const maybe = v;
80662
+ if (typeof maybe.toBigInt === "function")
80663
+ return maybe.toBigInt();
80664
+ if (typeof maybe.toString === "function")
80665
+ return BigInt(maybe.toString());
80666
+ throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
80667
+ }
80668
+ function normalizePositionId3(id) {
80669
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
80670
+ return import_ethers38.ethers.zeroPadValue(hex, 32).toLowerCase();
80671
+ }
80672
+ function requirePositionId2(actual, expected) {
80673
+ const txPositionId = String(actual).toLowerCase();
80674
+ if (txPositionId !== normalizePositionId3(expected)) {
80675
+ throw new TxValidationError3(
80676
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
80677
+ );
80678
+ }
80679
+ }
80680
+ function validateUnsignedTx3(unsignedTx, expected, vctx) {
80681
+ const txChainId = readChainId3(unsignedTx);
80682
+ if (txChainId == null) {
80683
+ throw new TxValidationError3(
80684
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
80685
+ );
80686
+ }
80687
+ if (txChainId !== vctx.chainId) {
80688
+ throw new TxValidationError3(
80689
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
80690
+ );
80691
+ }
80692
+ const value = readValue3(unsignedTx);
80693
+ if (value !== 0n) {
80694
+ throw new TxValidationError3(
80695
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
80696
+ );
80697
+ }
80698
+ assertFeeCeiling2(
80699
+ readOptionalBigInt2(unsignedTx, "gasLimit"),
80700
+ readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
80701
+ (msg) => {
80702
+ throw new TxValidationError3(msg);
80703
+ },
80704
+ vctx.feeCeiling
80705
+ );
80706
+ const to = readToAddress3(unsignedTx);
80707
+ const data = readData3(unsignedTx);
80708
+ const { name, args } = decodeSignable3(data);
80709
+ const pm = vctx.contracts.PositionManager;
80710
+ switch (expected.kind) {
80711
+ case "mint": {
80712
+ if (name !== "mintUCD") {
80713
+ throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
80714
+ }
80715
+ if (!eqAddr3(to, pm)) {
80716
+ throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
80717
+ }
80718
+ requirePositionId2(args[0], expected.positionId);
80719
+ const txMintAmount = BigInt(String(args[1]));
80720
+ if (txMintAmount.toString() !== expected.amountWei) {
80721
+ throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
80722
+ }
80723
+ const txMintFee = BigInt(String(args[2]));
80724
+ if (txMintFee.toString() !== expected.mintFeeWei) {
80725
+ throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
80726
+ }
80727
+ break;
80728
+ }
80729
+ case "repay": {
80730
+ if (name !== "makePayment") {
80731
+ throw new TxValidationError3(`expected makePayment, server returned ${name}`);
80732
+ }
80733
+ if (!eqAddr3(to, pm)) {
80734
+ throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
80735
+ }
80736
+ requirePositionId2(args[0], expected.positionId);
80737
+ const txAmount = BigInt(String(args[1]));
80738
+ if (txAmount.toString() !== expected.amountWei) {
80739
+ throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
80740
+ }
80741
+ break;
80742
+ }
80743
+ case "extend": {
80744
+ if (name !== "extendPosition") {
80745
+ throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
80746
+ }
80747
+ if (!eqAddr3(to, pm)) {
80748
+ throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
80749
+ }
80750
+ requirePositionId2(args[0], expected.positionId);
80751
+ const txTerm = Number(args[1]);
80752
+ if (txTerm !== expected.selectedTerm) {
80753
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80754
+ }
80755
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
80756
+ const txFee = BigInt(String(args[5]));
80757
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
80758
+ if (txFee > upper) {
80759
+ throw new TxValidationError3(
80760
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
80761
+ );
80762
+ }
80763
+ }
80764
+ break;
80765
+ }
80766
+ case "withdraw-btc": {
80767
+ if (name !== "withdrawBTC") {
80768
+ throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
80769
+ }
80770
+ if (!eqAddr3(to, pm)) {
80771
+ throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
80772
+ }
80773
+ const paramsTuple = args[0];
80774
+ requirePositionId2(paramsTuple[0], expected.positionId);
80775
+ const txWithdrawalAddress = String(paramsTuple[5]);
80776
+ if (txWithdrawalAddress !== expected.btcAddress) {
80777
+ throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
80778
+ }
80779
+ if (expected.upperBoundTotalDeduction != null) {
80780
+ const txDeduction = BigInt(String(paramsTuple[6]));
80781
+ const upper = BigInt(expected.upperBoundTotalDeduction);
80782
+ if (txDeduction > upper) {
80783
+ throw new TxValidationError3(
80784
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
80785
+ );
80786
+ }
80787
+ }
80788
+ break;
80789
+ }
80790
+ case "ucd-approve": {
80791
+ if (name !== "approve") {
80792
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80793
+ }
80794
+ const ucd = vctx.contracts.UCDToken;
80795
+ if (!eqAddr3(to, ucd)) {
80796
+ throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
80797
+ }
80798
+ const spender = String(args[0]);
80799
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
80800
+ if (!ok2) {
80801
+ throw new TxValidationError3(
80802
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
80803
+ );
80804
+ }
80805
+ const amt = BigInt(String(args[1]));
80806
+ const min = BigInt(expected.minAmountWei);
80807
+ if (amt < min) {
80808
+ throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
80809
+ }
80810
+ const SANITY_MAX = min * 1000n;
80811
+ if (amt > SANITY_MAX) {
80812
+ throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
80813
+ }
80814
+ break;
80815
+ }
80816
+ case "create-position": {
80817
+ if (name !== "createPosition") {
80818
+ throw new TxValidationError3(`expected createPosition, server returned ${name}`);
80819
+ }
80820
+ if (!eqAddr3(to, pm)) {
80821
+ throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
80822
+ }
80823
+ const txTerm = BigInt(String(args[4]));
80824
+ if (txTerm !== BigInt(expected.selectedTerm)) {
80825
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80826
+ }
80827
+ break;
80828
+ }
80829
+ case "set-position-delegate": {
80830
+ if (name !== "setPositionDelegate") {
80831
+ throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
80832
+ }
80833
+ if (!eqAddr3(to, expected.registryAddress)) {
80834
+ throw new TxValidationError3(
80835
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
80836
+ );
80837
+ }
80838
+ requirePositionId2(args[0], expected.positionId);
80839
+ const txDelegate = String(args[1]);
80840
+ if (!eqAddr3(txDelegate, expected.delegate)) {
80841
+ throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
80842
+ }
80843
+ break;
80844
+ }
80845
+ case "bwar-add-address": {
80846
+ if (name !== "addAddress") {
80847
+ throw new TxValidationError3(`expected addAddress, decoded ${name}`);
80848
+ }
80849
+ if (!eqAddr3(to, expected.registryAddress)) {
80850
+ throw new TxValidationError3(
80851
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
80852
+ );
80853
+ }
80854
+ if (String(args[0]) !== expected.btcAddress) {
80855
+ throw new TxValidationError3(
80856
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
80857
+ );
80858
+ }
80859
+ break;
80860
+ }
80861
+ case "stablecoin-approve": {
80862
+ if (name !== "approve") {
80863
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80864
+ }
80865
+ if (!eqAddr3(to, expected.tokenAddress)) {
80866
+ throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
80867
+ }
80868
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80869
+ throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
80870
+ }
80871
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
80872
+ throw new TxValidationError3(
80873
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
80874
+ );
80875
+ }
80876
+ break;
80877
+ }
80878
+ case "ucd-approve-controller": {
80879
+ if (name !== "approve") {
80880
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80881
+ }
80882
+ if (!eqAddr3(to, expected.ucdTokenAddress)) {
80883
+ throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
80884
+ }
80885
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80886
+ throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
80887
+ }
80888
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
80889
+ throw new TxValidationError3(
80890
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
80891
+ );
80892
+ }
80893
+ break;
80894
+ }
80895
+ case "psm-swap": {
80896
+ if (name !== "swap")
80897
+ throw new TxValidationError3(`expected swap, server returned ${name}`);
80898
+ if (!eqAddr3(to, expected.psmAddress)) {
80899
+ throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
80900
+ }
80901
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80902
+ throw new TxValidationError3(`swap stablecoin mismatch`);
80903
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
80904
+ throw new TxValidationError3(`swap amountIn mismatch`);
80905
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
80906
+ throw new TxValidationError3(`swap minUcdOut mismatch`);
80907
+ if (BigInt(expected.minOut) === 0n) {
80908
+ throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
80909
+ }
80910
+ break;
80911
+ }
80912
+ case "psm-redeem": {
80913
+ if (name !== "redeem")
80914
+ throw new TxValidationError3(`expected redeem, server returned ${name}`);
80915
+ if (!eqAddr3(to, expected.psmAddress)) {
80916
+ throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
80917
+ }
80918
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80919
+ throw new TxValidationError3(`redeem stablecoin mismatch`);
80920
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
80921
+ throw new TxValidationError3(`redeem ucdAmount mismatch`);
80922
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
80923
+ throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
80924
+ if (BigInt(expected.minOut) === 0n) {
80925
+ throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
80926
+ }
80927
+ break;
80928
+ }
80929
+ default: {
80930
+ const _exhaustive = expected;
80931
+ throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
80932
+ }
80933
+ }
80934
+ }
80935
+ var SLOT_SECONDS2 = 12;
80936
+ var INCLUSION_SLOT_TOLERANCE2 = 3;
80937
+ var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
80938
+ function buildPsmApproveTx2(p) {
80939
+ return {
80940
+ to: p.token,
80941
+ data: encodeSignable3("approve", [p.spender, p.amount]),
80942
+ value: "0x0",
80943
+ chainId: p.chainId
80944
+ };
80945
+ }
80946
+ function buildPsmSwapTx3(p) {
80947
+ return {
80948
+ to: p.psm,
80949
+ data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
80950
+ value: "0x0",
80951
+ chainId: p.chainId
80952
+ };
80953
+ }
80954
+ function buildPsmRedeemTx3(p) {
80955
+ return {
80956
+ to: p.psm,
80957
+ data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
80958
+ value: "0x0",
80959
+ chainId: p.chainId
80960
+ };
80961
+ }
80962
+ var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
80963
+ var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
80964
+ function psmExchangeReadsFromProvider2(provider, psmAddress) {
80965
+ const psm = new import_ethers41.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
80966
+ return {
80967
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
80968
+ allowance: async (token, owner, spender) => await new import_ethers41.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
80969
+ };
80970
+ }
80971
+ var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
80972
+ function requireAddress2(direction, label, value) {
80973
+ if (!value || !import_ethers41.ethers.isAddress(value)) {
80974
+ throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
80975
+ }
80976
+ return import_ethers41.ethers.getAddress(value);
80977
+ }
80978
+ async function planPsmExchange2(params) {
80979
+ const { direction, amountIn, minOut, vctx, reads } = params;
80980
+ const chainId = vctx.chainId;
80981
+ if (amountIn <= 0n) {
80982
+ throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
80983
+ }
80984
+ if (minOut <= 0n) {
80985
+ throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
80986
+ }
80987
+ const owner = requireAddress2(direction, "owner", params.owner);
80988
+ const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
80989
+ const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
80990
+ const isSwap = direction === "swap";
80991
+ const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
80992
+ const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
80993
+ if (!await reads.isStablecoinSupported(stablecoin)) {
80994
+ throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
80995
+ }
80996
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
80997
+ const allowanceBefore = await reads.allowance(token, owner, spender);
80998
+ const approvals = [];
80999
+ if (allowanceBefore < amountIn) {
81000
+ if (allowanceBefore > 0n) {
81001
+ approvals.push({
81002
+ step: "reset-approve",
81003
+ tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
81004
+ expected: approveExpected(0n)
81005
+ });
81006
+ }
81007
+ approvals.push({
81008
+ step: "approve",
81009
+ tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
81010
+ expected: approveExpected(amountIn)
81011
+ });
81012
+ }
81013
+ const exec = isSwap ? {
81014
+ step: "swap",
81015
+ tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
81016
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
81017
+ } : {
81018
+ step: "redeem",
81019
+ tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
81020
+ expected: {
81021
+ kind: "psm-redeem",
81022
+ psmAddress: psm,
81023
+ stablecoin,
81024
+ amountUcdWei: amountIn.toString(),
81025
+ minOut: minOut.toString()
81026
+ }
81027
+ };
81028
+ for (const leg of [...approvals, exec]) {
81029
+ validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
81030
+ }
81031
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
81032
+ }
81033
+
81034
+ // src/boundary/upstream/real/psm-calls.ts
79589
81035
  var PSM_VIEW_FRAGMENTS = [
79590
81036
  "function VERSION() view returns (string)",
79591
81037
  "function supportedStablecoins(address) view returns (bool)",
@@ -79605,15 +81051,7 @@ var PSM_VIEW_FRAGMENTS = [
79605
81051
  "function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
79606
81052
  "function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
79607
81053
  ];
79608
- var PSM_WRITE_FRAGMENTS = [
79609
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
79610
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
79611
- ];
79612
- var ERC20_FRAGMENTS = [
79613
- "function approve(address spender, uint256 amount) returns (bool)",
79614
- "function balanceOf(address holder) view returns (uint256)"
79615
- ];
79616
- var ERC20_IFACE = new import_ethers32.ethers.Interface(ERC20_FRAGMENTS);
81054
+ var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
79617
81055
  var PSM_ERROR_FRAGMENTS = [
79618
81056
  "error StablecoinNotSupported(address stablecoin)",
79619
81057
  "error InvalidAmount()",
@@ -79661,9 +81099,9 @@ var RENDERERS = {
79661
81099
  var PsmCalls = class {
79662
81100
  constructor(deps) {
79663
81101
  this.deps = deps;
79664
- const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_WRITE_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
79665
- this.iface = new import_ethers32.ethers.Interface(abi);
79666
- this.psm = new import_ethers32.ethers.Contract(deps.psmAddress, abi, deps.provider);
81102
+ const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
81103
+ this.iface = new import_ethers42.ethers.Interface(abi);
81104
+ this.psm = new import_ethers42.ethers.Contract(deps.psmAddress, abi, deps.provider);
79667
81105
  }
79668
81106
  psm;
79669
81107
  iface;
@@ -79676,34 +81114,10 @@ var PsmCalls = class {
79676
81114
  ...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
79677
81115
  };
79678
81116
  }
79679
- // ---- unsigned-tx builders (plan 08 W1): EXACT-amount approvals only; floors pinned ----
79680
- /** Step 1: exact-amount ERC-20 approve. Caller names the direction's REAL spender
79681
- * (swap: stablecoin → the PSM; redeem: UCD → the UCDController). */
79682
- buildApprove(p) {
79683
- return {
79684
- to: p.token,
79685
- data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
79686
- value: "0x0",
79687
- chainId: p.chainId
79688
- };
79689
- }
79690
- /** Step 2, stablecoin → UCD (contract `swap`). */
79691
- buildSwap(p) {
79692
- return {
79693
- to: this.deps.psmAddress,
79694
- data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
79695
- value: "0x0",
79696
- chainId: p.chainId
79697
- };
79698
- }
79699
- /** Step 2, UCD → stablecoin (contract `redeem`). */
79700
- buildRedeem(p) {
79701
- return {
79702
- to: this.deps.psmAddress,
79703
- data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
79704
- value: "0x0",
79705
- chainId: p.chainId
79706
- };
81117
+ /** The two live reads the SDK's exchange planner depends on (supported set + allowance),
81118
+ * over this wrapper's provider and PSM. */
81119
+ exchangeReads() {
81120
+ return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
79707
81121
  }
79708
81122
  /** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
79709
81123
  async balances(holder) {
@@ -79716,8 +81130,8 @@ var PsmCalls = class {
79716
81130
  });
79717
81131
  }
79718
81132
  return this.call(async () => {
79719
- const ucd = new import_ethers32.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
79720
- const stable = new import_ethers32.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
81133
+ const ucd = new import_ethers42.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
81134
+ const stable = new import_ethers42.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
79721
81135
  const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
79722
81136
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79723
81137
  });
@@ -79835,7 +81249,7 @@ var PsmCalls = class {
79835
81249
  };
79836
81250
 
79837
81251
  // src/boundary/upstream/real/session.ts
79838
- var import_ethers33 = require("ethers");
81252
+ var import_ethers43 = require("ethers");
79839
81253
  var REFRESH_LEEWAY_SEC = 30;
79840
81254
  var LOGIN_TYPES_WITH_AUDIENCE3 = {
79841
81255
  DiamondHands: [
@@ -79883,7 +81297,7 @@ var LitOpsSession = class {
79883
81297
  const message = {
79884
81298
  address: this.wallet.address,
79885
81299
  issuedAt: Math.floor(Date.now() / 1e3),
79886
- nonce: "0x" + Buffer.from(import_ethers33.ethers.randomBytes(32)).toString("hex"),
81300
+ nonce: "0x" + Buffer.from(import_ethers43.ethers.randomBytes(32)).toString("hex"),
79887
81301
  audience: this.serviceEndpoint
79888
81302
  };
79889
81303
  const signature = await this.wallet.signTypedData(
@@ -79925,7 +81339,7 @@ function decodeJwtExp(token) {
79925
81339
  }
79926
81340
 
79927
81341
  // src/boundary/upstream/real/write-ops.ts
79928
- var import_ethers35 = require("ethers");
81342
+ var import_ethers45 = require("ethers");
79929
81343
 
79930
81344
  // src/signer/types.ts
79931
81345
  var OperationDeclined = class extends Error {
@@ -79935,7 +81349,7 @@ var OperationDeclined = class extends Error {
79935
81349
  init_tx_validator();
79936
81350
 
79937
81351
  // src/boundary/upstream/shared/external-bridge/page-crypto.ts
79938
- var import_ethers34 = require("ethers");
81352
+ var import_ethers44 = require("ethers");
79939
81353
  var PERSONAL_SIGN_LAYOUTS = {
79940
81354
  "dh-op-envelope-v1": {
79941
81355
  types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
@@ -79956,9 +81370,9 @@ function hashForLayout(layout, fields) {
79956
81370
  const values = def.fieldOrder.map((name) => {
79957
81371
  const raw = fields[name];
79958
81372
  if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
79959
- return hashUtf8.has(name) ? import_ethers34.ethers.keccak256(import_ethers34.ethers.toUtf8Bytes(raw)) : raw;
81373
+ return hashUtf8.has(name) ? import_ethers44.ethers.keccak256(import_ethers44.ethers.toUtf8Bytes(raw)) : raw;
79960
81374
  });
79961
- return import_ethers34.ethers.solidityPackedKeccak256(def.types, values);
81375
+ return import_ethers44.ethers.solidityPackedKeccak256(def.types, values);
79962
81376
  }
79963
81377
  var PAGE_CRYPTO_JS = `"use strict";
79964
81378
  (function () {
@@ -80187,9 +81601,21 @@ function buildValidationContext(network, chainId) {
80187
81601
 
80188
81602
  // src/boundary/upstream/real/write-ops.ts
80189
81603
  var SOURCE5 = "real-ops";
81604
+ function mcpExpected(leg) {
81605
+ const e = leg.expected;
81606
+ switch (e.kind) {
81607
+ case "stablecoin-approve":
81608
+ case "ucd-approve-controller":
81609
+ case "psm-swap":
81610
+ case "psm-redeem":
81611
+ return e;
81612
+ default:
81613
+ throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
81614
+ }
81615
+ }
80190
81616
  var OP_LAYOUT = "dh-op-envelope-v1";
80191
81617
  function randomNonceHex() {
80192
- return "0x" + Buffer.from(import_ethers35.ethers.randomBytes(16)).toString("hex");
81618
+ return "0x" + Buffer.from(import_ethers45.ethers.randomBytes(16)).toString("hex");
80193
81619
  }
80194
81620
  async function postJson(url2, body, headers) {
80195
81621
  const res = await fetch(url2, {
@@ -80250,7 +81676,7 @@ function buildWriteOps(deps) {
80250
81676
  return {
80251
81677
  to: String(tx2["to"] ?? ""),
80252
81678
  data: String(tx2["data"] ?? "0x"),
80253
- value: tx2["value"] != null ? import_ethers35.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
81679
+ value: tx2["value"] != null ? import_ethers45.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
80254
81680
  chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
80255
81681
  };
80256
81682
  }
@@ -80335,8 +81761,9 @@ function buildWriteOps(deps) {
80335
81761
  }
80336
81762
  return {
80337
81763
  createPosition: async (p) => {
80338
- const sdk = deps.getWriteSdk();
80339
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81764
+ const built = await deps.getWriteSdk();
81765
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81766
+ const sdk = built.sdk;
80340
81767
  try {
80341
81768
  await deps.assertValidatorConfigured();
80342
81769
  } catch (e) {
@@ -80415,7 +81842,7 @@ function buildWriteOps(deps) {
80415
81842
  mintedUcdWei: minted,
80416
81843
  feeUcdWei: mintFee,
80417
81844
  echoedAmountUcdWei: minted,
80418
- authorization: auth(action, `mint ${import_ethers35.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
81845
+ authorization: auth(action, `mint ${import_ethers45.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
80419
81846
  },
80420
81847
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80421
81848
  );
@@ -80456,7 +81883,7 @@ function buildWriteOps(deps) {
80456
81883
  txRef: { kind: "eth-tx", id: r.value.txHash },
80457
81884
  paidUcdWei: paid,
80458
81885
  echoedAmountUcdWei: paid,
80459
- authorization: auth(action, `repay ${import_ethers35.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
81886
+ authorization: auth(action, `repay ${import_ethers45.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
80460
81887
  },
80461
81888
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80462
81889
  );
@@ -80496,8 +81923,9 @@ function buildWriteOps(deps) {
80496
81923
  );
80497
81924
  },
80498
81925
  withdraw: async (p) => {
80499
- const sdk = deps.getWriteSdk();
80500
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81926
+ const built = await deps.getWriteSdk();
81927
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81928
+ const sdk = built.sdk;
80501
81929
  const amountSats = Number(p.amountSats);
80502
81930
  const feeSats = Number(p.networkFeeSats);
80503
81931
  let result;
@@ -80526,12 +81954,13 @@ function buildWriteOps(deps) {
80526
81954
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80527
81955
  );
80528
81956
  },
80529
- /** PSM exchange pair (plan 08 W1): pure on-chain calls — no LIT action, no server
80530
- * orchestration. MCP-built txs over the pinned wrapper (the SDK's psmSwap/psmRedeem
80531
- * hardcode MaxUint256 approvals and are FORBIDDEN); exact-amount approve, then the
80532
- * swap/redeem with its mandatory floor, each validated against the M8-11 whitelist,
80533
- * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80534
- * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
81957
+ /** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
81958
+ * orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
81959
+ * builder every client shares (it replaced this file's own builders and the SDK's old
81960
+ * MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
81961
+ * allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
81962
+ * validated again here by the MCP's own whitelist (the one the approval card decodes
81963
+ * with), then signed through the session signer and broadcast — one at a time. */
80535
81964
  psmSwap: async (p) => {
80536
81965
  const pr = await deps.psm(p.stablecoin);
80537
81966
  if (!pr.ok) return upFail(pr.failure);
@@ -80545,11 +81974,7 @@ function buildWriteOps(deps) {
80545
81974
  message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
80546
81975
  });
80547
81976
  }
80548
- const amountIn = BigInt(p.amountIn);
80549
- const minOut = BigInt(p.minOut);
80550
81977
  const vctx = buildValidationContext(config.network, chainId);
80551
- const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
80552
- const spenderAddress = isSwap ? addr.psm : addr.ucdController;
80553
81978
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
80554
81979
  const tokenSymbol = isSwap ? calls.symbol() : "UCD";
80555
81980
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
@@ -80566,49 +81991,66 @@ function buildWriteOps(deps) {
80566
81991
  return submitFailure(leg, e);
80567
81992
  }
80568
81993
  };
80569
- const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
81994
+ let plan;
80570
81995
  try {
80571
- validateUnsignedTx(
80572
- { ...approveTx },
80573
- isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn },
80574
- vctx
80575
- );
80576
- } catch (e) {
80577
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
80578
- }
80579
- const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
80580
- const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
80581
- if (!approveHashR.ok) return approveHashR;
80582
- const approveHash = approveHashR.value;
80583
- 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`;
80584
- const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
80585
- try {
80586
- validateUnsignedTx(
80587
- { ...execTx },
80588
- 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 },
80589
- vctx
80590
- );
81996
+ plan = await planPsmExchange2({
81997
+ direction: p.direction,
81998
+ owner: p.borrower,
81999
+ addresses: addr,
82000
+ amountIn: BigInt(p.amountIn),
82001
+ minOut: BigInt(p.minOut),
82002
+ vctx,
82003
+ reads: calls.exchangeReads()
82004
+ });
80591
82005
  } catch (e) {
80592
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
82006
+ return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
82007
+ kind: "unavailable",
82008
+ source: SOURCE5,
82009
+ message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
82010
+ raw: String(e)
82011
+ });
80593
82012
  }
80594
- const execCard = `${p.direction} ${p.amountIn} ${isSwap ? `${tokenSymbol} smallest units` : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
80595
- const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
80596
- if (!execHashR.ok) {
80597
- const f = execHashR.failure;
80598
- return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
82013
+ const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
82014
+ const unit = `${tokenSymbol} smallest units`;
82015
+ const landed = [];
82016
+ const residualNote = () => {
82017
+ const last = landed[landed.length - 1];
82018
+ 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`;
82019
+ return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
82020
+ };
82021
+ const runLeg = async (leg) => {
82022
+ const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
82023
+ try {
82024
+ validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
82025
+ } catch (e) {
82026
+ return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
82027
+ }
82028
+ const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
82029
+ const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
82030
+ return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
82031
+ };
82032
+ const approvals = [];
82033
+ for (const leg of plan.approvals) {
82034
+ 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})`;
82035
+ const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
82036
+ const r = await runLeg(leg);
82037
+ if (!r.ok) return r;
82038
+ landed.push({ step, hash: r.value });
82039
+ approvals.push({
82040
+ step,
82041
+ txRef: { kind: "eth-tx", id: r.value },
82042
+ amount: leg.step === "reset-approve" ? "0" : p.amountIn,
82043
+ authorization: auth("psm-approve", card, r.value)
82044
+ });
80599
82045
  }
82046
+ 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}`;
82047
+ const execHashR = await runLeg(plan.exec);
82048
+ if (!execHashR.ok) return execHashR;
80600
82049
  const execHash = execHashR.value;
80601
82050
  const balancesR = await calls.balances(p.borrower);
80602
82051
  const row = {
80603
- approve: {
80604
- txRef: { kind: "eth-tx", id: approveHash },
80605
- tokenSymbol,
80606
- tokenAddress,
80607
- spenderAddress,
80608
- spenderContract,
80609
- amount: p.amountIn,
80610
- authorization: auth("psm-approve", approveCard, approveHash)
80611
- },
82052
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
82053
+ approvals,
80612
82054
  execute: {
80613
82055
  txRef: { kind: "eth-tx", id: execHash },
80614
82056
  amountIn: p.amountIn,
@@ -80625,8 +82067,9 @@ function buildWriteOps(deps) {
80625
82067
  // registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
80626
82068
  // msg.sender, so their path is a SafeTx — never this keystore leg.
80627
82069
  allowlistWithdrawalAddress: async (p) => {
80628
- const sdk = deps.getWriteSdk();
80629
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82070
+ const built = await deps.getWriteSdk();
82071
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82072
+ const sdk = built.sdk;
80630
82073
  let result;
80631
82074
  try {
80632
82075
  result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
@@ -80673,8 +82116,9 @@ function buildWriteOps(deps) {
80673
82116
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
80674
82117
  }),
80675
82118
  retryWithdrawExecute: async (p) => {
80676
- const sdk = deps.getWriteSdk();
80677
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82119
+ const built = await deps.getWriteSdk();
82120
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82121
+ const sdk = built.sdk;
80678
82122
  let rows;
80679
82123
  try {
80680
82124
  rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
@@ -80702,7 +82146,7 @@ function buildWriteOps(deps) {
80702
82146
  }
80703
82147
 
80704
82148
  // src/signer/eoa-dh.ts
80705
- var import_ethers36 = require("ethers");
82149
+ var import_ethers46 = require("ethers");
80706
82150
  var EoaDHSigner = class {
80707
82151
  constructor(wallet, broadcast, clock = Date.now) {
80708
82152
  this.wallet = wallet;
@@ -80719,7 +82163,7 @@ var EoaDHSigner = class {
80719
82163
  async signAuthorization(spec) {
80720
82164
  const quantumTs = nextQuantumTimestamp(this.clock());
80721
82165
  const { fields, hashHex } = spec.stamp(quantumTs);
80722
- const signature = await this.wallet.signMessage(import_ethers36.ethers.getBytes(hashHex));
82166
+ const signature = await this.wallet.signMessage(import_ethers46.ethers.getBytes(hashHex));
80723
82167
  return { signature, quantumTs, fields };
80724
82168
  }
80725
82169
  async wrapInnerTx(innerTx) {
@@ -80737,10 +82181,10 @@ var EoaDHSigner = class {
80737
82181
 
80738
82182
  // src/signer/external-eoa.ts
80739
82183
  var import_node_crypto7 = require("crypto");
80740
- var import_ethers38 = require("ethers");
82184
+ var import_ethers48 = require("ethers");
80741
82185
 
80742
82186
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
80743
- var import_ethers37 = require("ethers");
82187
+ var import_ethers47 = require("ethers");
80744
82188
  function eq2(a, b) {
80745
82189
  return a.toLowerCase() === b.toLowerCase();
80746
82190
  }
@@ -80763,7 +82207,7 @@ function compareLandedTx(landed, approved, borrower) {
80763
82207
  return { status: "verified", from: landed.from, hash: landed.hash };
80764
82208
  }
80765
82209
  function verifyRawSignedTx(rawSignedTx, approved, borrower) {
80766
- const parsed = import_ethers37.ethers.Transaction.from(rawSignedTx);
82210
+ const parsed = import_ethers47.ethers.Transaction.from(rawSignedTx);
80767
82211
  if (!parsed.from || !parsed.to || !parsed.hash) {
80768
82212
  return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
80769
82213
  }
@@ -80801,7 +82245,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
80801
82245
  for (let attempt = 0; attempt < 4; attempt++) {
80802
82246
  try {
80803
82247
  const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
80804
- return import_ethers38.ethers.toBeHex(est * 15n / 10n);
82248
+ return import_ethers48.ethers.toBeHex(est * 15n / 10n);
80805
82249
  } catch (e) {
80806
82250
  lastErr = e;
80807
82251
  await new Promise((r) => setTimeout(r, 13e3));
@@ -80851,7 +82295,7 @@ var ExternalEoaDHSigner = class {
80851
82295
  throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
80852
82296
  }
80853
82297
  const finalHash = spec.stamp(used.quantumTs).hashHex;
80854
- const recovered = import_ethers38.ethers.verifyMessage(import_ethers38.ethers.getBytes(finalHash), outcome.signature);
82298
+ const recovered = import_ethers48.ethers.verifyMessage(import_ethers48.ethers.getBytes(finalHash), outcome.signature);
80855
82299
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80856
82300
  throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80857
82301
  }
@@ -80862,7 +82306,7 @@ var ExternalEoaDHSigner = class {
80862
82306
  }
80863
82307
  async submitValidatedTx(outerTx, ctx) {
80864
82308
  const approved = toApprovedTx(outerTx, this.deps.chainId);
80865
- const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
82309
+ const gas = outerTx.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
80866
82310
  const outcome = await this.deps.bridge.requestSignature({
80867
82311
  id: (0, import_node_crypto7.randomUUID)(),
80868
82312
  kind: "transaction",
@@ -80896,7 +82340,7 @@ var ExternalEoaDHSigner = class {
80896
82340
  return new BridgeEthersSigner(this.deps);
80897
82341
  }
80898
82342
  };
80899
- var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ethers.AbstractSigner {
82343
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers48.ethers.AbstractSigner {
80900
82344
  constructor(deps) {
80901
82345
  super(deps.provider);
80902
82346
  this.deps = deps;
@@ -80907,13 +82351,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80907
82351
  return this.deps.borrower;
80908
82352
  }
80909
82353
  async signMessage(message) {
80910
- const bytes = typeof message === "string" ? import_ethers38.ethers.toUtf8Bytes(message) : message;
82354
+ const bytes = typeof message === "string" ? import_ethers48.ethers.toUtf8Bytes(message) : message;
80911
82355
  if (bytes.length !== 32) {
80912
82356
  throw new Error(
80913
82357
  `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.`
80914
82358
  );
80915
82359
  }
80916
- const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
82360
+ const hashHex = import_ethers48.ethers.hexlify(bytes).toLowerCase();
80917
82361
  const nowMs = (this.deps.clock ?? Date.now)();
80918
82362
  const expiresAtSec = nextQuantumTimestamp(nowMs);
80919
82363
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
@@ -80943,7 +82387,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80943
82387
  if (outcome.status !== "approved" || !outcome.signature) {
80944
82388
  throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
80945
82389
  }
80946
- const recovered = import_ethers38.ethers.verifyMessage(bytes, outcome.signature);
82390
+ const recovered = import_ethers48.ethers.verifyMessage(bytes, outcome.signature);
80947
82391
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80948
82392
  throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80949
82393
  }
@@ -80977,11 +82421,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80977
82421
  const approved = {
80978
82422
  to: tx2.to,
80979
82423
  data: tx2.data,
80980
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82424
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
80981
82425
  chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
80982
82426
  };
80983
82427
  const card = cardForTx(approved);
80984
- 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));
82428
+ 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));
80985
82429
  const outcome = await this.deps.bridge.requestSignature({
80986
82430
  id: (0, import_node_crypto7.randomUUID)(),
80987
82431
  kind: "transaction",
@@ -81023,14 +82467,14 @@ function toApprovedTx(tx2, fallbackChainId) {
81023
82467
  return {
81024
82468
  to: tx2.to,
81025
82469
  data: tx2.data,
81026
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82470
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
81027
82471
  chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
81028
82472
  };
81029
82473
  }
81030
82474
  function describeFn(data) {
81031
82475
  try {
81032
- const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
81033
- return decodeSignable2(data).name;
82476
+ const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
82477
+ return decodeSignable4(data).name;
81034
82478
  } catch {
81035
82479
  return "operation";
81036
82480
  }
@@ -81067,7 +82511,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
81067
82511
  var RealUpstreamPlugin = class {
81068
82512
  constructor(config, wallet, runtime) {
81069
82513
  this.config = config;
81070
- this.provider = new import_ethers39.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
82514
+ this.provider = new import_ethers49.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
81071
82515
  this.wallet = wallet ?? null;
81072
82516
  this.runtime = runtime ?? null;
81073
82517
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
@@ -81198,7 +82642,7 @@ var RealUpstreamPlugin = class {
81198
82642
  })
81199
82643
  )
81200
82644
  };
81201
- const writeRefusalReason = !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014 writes need the keystore env pair (DH_KEYSTORE_PATH + DH_KEYSTORE_PASSWORD), or run signer_setup.` : `the lit-ops login session is unavailable \u2014 the keystore is configured but EIP-712 login did not complete; check the broker endpoint and retry.`;
82645
+ const writeRefusalReason = !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014 EVERY write refuses for this same reason until one is, so trying a different write tool will not get past it (reads are unaffected). Writes need the keystore env pair (DH_KEYSTORE_PATH + DH_KEYSTORE_PASSWORD), or run signer_setup.` : `the lit-ops login session is unavailable \u2014 the keystore is configured but EIP-712 login did not complete; check the broker endpoint and retry.`;
81202
82646
  const readOnly = (op) => Promise.resolve(
81203
82647
  upFail({
81204
82648
  kind: "unavailable",
@@ -81260,18 +82704,24 @@ var RealUpstreamPlugin = class {
81260
82704
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
81261
82705
  * and the service-mode SDK routes its own subgraph reads through the same proxy — so
81262
82706
  * writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
81263
- * Safe to call repeatedly; failures leave the write plane honestly unavailable
81264
- * (createPosition/withdraw report the uninitialized SDK). */
82707
+ * Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
82708
+ * first write builds again (see ensureSdk). */
81265
82709
  async initWriteSdk() {
81266
82710
  if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
81267
82711
  const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
81268
82712
  if (!wallet) return;
81269
82713
  await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
81270
82714
  }
81271
- /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
81272
- * the write gateways report the uninitialized SDK honestly, never fake readiness. */
82715
+ /** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
82716
+ *
82717
+ * A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
82718
+ * life of the process and drop the error, which was survivable only while `create` never
82719
+ * touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
82720
+ * RPC blip at boot would have disabled every later write with no reason given. Now each write
82721
+ * retries, and a persistent failure says what it is. Concurrent callers share one build. */
81273
82722
  async ensureSdk(key, signer) {
81274
- if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
82723
+ const cached = this.sdkCache.get(key);
82724
+ if (cached) return { ok: true, sdk: cached };
81275
82725
  const inFlight = this.sdkInFlight.get(key);
81276
82726
  if (inFlight) return inFlight;
81277
82727
  const build = (async () => {
@@ -81291,17 +82741,23 @@ var RealUpstreamPlugin = class {
81291
82741
  // nesting writes under indexer discovery (the M8B-4 coupling this removes).
81292
82742
  ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
81293
82743
  });
81294
- return isSuccess(builtWrite) ? builtWrite.value : null;
81295
- } catch {
81296
- return null;
82744
+ if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
82745
+ return { ok: false, reason: builtWrite.error.message };
82746
+ } catch (e) {
82747
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
81297
82748
  }
81298
82749
  })();
81299
82750
  this.sdkInFlight.set(key, build);
81300
82751
  const built = await build;
81301
82752
  this.sdkInFlight.delete(key);
81302
- this.sdkCache.set(key, built);
82753
+ if (built.ok) this.sdkCache.set(key, built.sdk);
81303
82754
  return built;
81304
82755
  }
82756
+ /** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
82757
+ async writeSdkFor(key, signer) {
82758
+ const built = await this.ensureSdk(key, signer);
82759
+ return built.ok ? { ok: true, sdk: built.sdk } : built;
82760
+ }
81305
82761
  wallet;
81306
82762
  // ---- per-call signer resolution (plan 10 A3) ----
81307
82763
  /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
@@ -81341,7 +82797,7 @@ var RealUpstreamPlugin = class {
81341
82797
  chainId: this.config.chainId,
81342
82798
  dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
81343
82799
  session,
81344
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82800
+ getWriteSdk: () => this.writeSdkFor(key, wallet),
81345
82801
  readDetails: (id) => this.readPositionDetails(id),
81346
82802
  psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81347
82803
  assertValidatorConfigured: () => this.assertValidatorConfigured()
@@ -81357,14 +82813,14 @@ var RealUpstreamPlugin = class {
81357
82813
  if (!pkpValidation) {
81358
82814
  throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
81359
82815
  }
81360
- const registry = new import_ethers39.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
82816
+ const registry = new import_ethers49.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
81361
82817
  let validator;
81362
82818
  try {
81363
82819
  validator = await registry.validatorForVersion(version2);
81364
82820
  } catch (e) {
81365
82821
  throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
81366
82822
  }
81367
- if (validator === import_ethers39.ethers.ZeroAddress) {
82823
+ if (validator === import_ethers49.ethers.ZeroAddress) {
81368
82824
  throw new Error(
81369
82825
  `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.`
81370
82826
  );
@@ -81414,7 +82870,7 @@ var RealUpstreamPlugin = class {
81414
82870
  failure: {
81415
82871
  kind: "signer-missing",
81416
82872
  source: "real-ops",
81417
- message: "no authorization mode is chosen (SIGNER_UNAVAILABLE) \u2014 pick one via signer_setup ('external' = approve in your own wallet, 'keystore' = automatic signing), or set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD in the server environment."
82873
+ message: "no authorization mode is chosen (SIGNER_UNAVAILABLE) \u2014 EVERY fund-moving tool refuses with this same message until one is, so trying a different write tool will not get past it. Reads are unaffected. Pick a mode via signer_setup ('external' = approve in your own wallet, 'keystore' = automatic signing), or set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD in the server environment."
81418
82874
  }
81419
82875
  };
81420
82876
  }
@@ -81438,7 +82894,6 @@ var RealUpstreamPlugin = class {
81438
82894
  gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
81439
82895
  this.opsGatewayCache.set(key, gateway);
81440
82896
  }
81441
- await this.ensureSdk(key, wallet.connect(this.provider));
81442
82897
  return { ok: true, gateway };
81443
82898
  }
81444
82899
  if (mode === "external") {
@@ -81475,14 +82930,13 @@ var RealUpstreamPlugin = class {
81475
82930
  chainId: this.config.chainId,
81476
82931
  dhSigner: new ExternalEoaDHSigner(deps),
81477
82932
  session,
81478
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82933
+ getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
81479
82934
  readDetails: (id) => this.readPositionDetails(id),
81480
82935
  psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81481
82936
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81482
82937
  });
81483
82938
  this.opsGatewayCache.set(key, gateway);
81484
82939
  }
81485
- await this.ensureSdk(key, this.externalSigners.get(key));
81486
82940
  return { ok: true, gateway };
81487
82941
  }
81488
82942
  return {
@@ -81642,7 +83096,7 @@ var RealUpstreamPlugin = class {
81642
83096
  );
81643
83097
  if (!r.ok) return r;
81644
83098
  const raw = r.value.data.supportedStablecoins ?? [];
81645
- const bad = raw.find((x) => !import_ethers39.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
83099
+ const bad = raw.find((x) => !import_ethers49.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
81646
83100
  if (bad) {
81647
83101
  return {
81648
83102
  ok: false,
@@ -81725,7 +83179,7 @@ var RealUpstreamPlugin = class {
81725
83179
  };
81726
83180
  }
81727
83181
  const symbol = raw.toLowerCase();
81728
- if (import_ethers39.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
83182
+ if (import_ethers49.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
81729
83183
  const verified = await this.verifiedStablecoins();
81730
83184
  if (!verified.ok) return { ok: false, failure: verified.failure };
81731
83185
  const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
@@ -81763,7 +83217,7 @@ var RealUpstreamPlugin = class {
81763
83217
  * chain, then sign.
81764
83218
  */
81765
83219
  async psmCallsFor(stablecoinAddress) {
81766
- if (!import_ethers39.ethers.isAddress(stablecoinAddress)) {
83220
+ if (!import_ethers49.ethers.isAddress(stablecoinAddress)) {
81767
83221
  throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
81768
83222
  }
81769
83223
  const key = stablecoinAddress.toLowerCase();
@@ -81783,9 +83237,9 @@ var RealUpstreamPlugin = class {
81783
83237
  let supported;
81784
83238
  let symbol;
81785
83239
  try {
81786
- const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
83240
+ const psm = new import_ethers49.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81787
83241
  supported = await psm["supportedStablecoins"](key);
81788
- const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
83242
+ const erc20 = new import_ethers49.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81789
83243
  symbol = await erc20["symbol"]();
81790
83244
  } catch (e) {
81791
83245
  return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
@@ -81998,7 +83452,7 @@ var RealUpstreamPlugin = class {
81998
83452
  const pm = this.contracts["PositionManager"];
81999
83453
  if (!pm) return false;
82000
83454
  try {
82001
- const c = new import_ethers39.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
83455
+ const c = new import_ethers49.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
82002
83456
  return Boolean(await c["paused"]());
82003
83457
  } catch {
82004
83458
  return false;
@@ -82007,16 +83461,16 @@ var RealUpstreamPlugin = class {
82007
83461
  async readPositionDetails(id) {
82008
83462
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
82009
83463
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
82010
- const c = new import_ethers39.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
83464
+ const c = new import_ethers49.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
82011
83465
  let d;
82012
83466
  try {
82013
- d = await c["getPositionDetails"](import_ethers39.ethers.zeroPadValue(id, 32));
83467
+ d = await c["getPositionDetails"](import_ethers49.ethers.zeroPadValue(id, 32));
82014
83468
  } catch (e) {
82015
83469
  if (e.code === "CALL_EXCEPTION") return null;
82016
83470
  throw e;
82017
83471
  }
82018
83472
  const borrower = String(d["borrower"]);
82019
- if (borrower === import_ethers39.ethers.ZeroAddress) return null;
83473
+ if (borrower === import_ethers49.ethers.ZeroAddress) return null;
82020
83474
  return {
82021
83475
  positionId: String(d["positionId"]),
82022
83476
  pkpId: String(d["pkpId"]),
@@ -83618,8 +85072,8 @@ async function buildBoundary(configResult, overrides) {
83618
85072
  );
83619
85073
  }
83620
85074
  try {
83621
- const decrypted = await import_ethers40.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
83622
- if (!(decrypted instanceof import_ethers40.ethers.Wallet)) {
85075
+ const decrypted = await import_ethers50.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85076
+ if (!(decrypted instanceof import_ethers50.ethers.Wallet)) {
83623
85077
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
83624
85078
  }
83625
85079
  wallet = decrypted;
@@ -84111,7 +85565,7 @@ on the real adapter and the mock.
84111
85565
  | extend | 1 personal-sign + 1 tx |
84112
85566
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
84113
85567
  | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
84114
- | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
85568
+ | PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
84115
85569
 
84116
85570
  **Honesty notes (say these plainly):**
84117
85571
  - **Reads never pop the wallet.** If a read needs a login the user does not have, the
@@ -84255,16 +85709,19 @@ rather than silently deliver less than quoted.
84255
85709
 
84256
85710
  ${psmStablecoinRealityNote(d)}
84257
85711
 
84258
- **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
84259
- result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
85712
+ **Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
85713
+ the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
85714
+ planned against the allowance already standing: none when it covers the amount, one when it
85715
+ is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
84260
85716
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
84261
85717
  the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84262
85718
  you approve UCD to the **UCDController** (the PSM burns your UCD through the
84263
85719
  controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84264
85720
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
84265
85721
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
84266
- own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
84267
- standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
85722
+ own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
85723
+ standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
85724
+ the next exchange that it covers uses it without asking for another approval.
84268
85725
  PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84269
85726
  REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84270
85727
  wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
@@ -84737,7 +86194,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
84737
86194
 
84738
86195
  // src/tools/loan.ts
84739
86196
  var import_zod = require("zod");
84740
- var import_ethers41 = require("ethers");
86197
+ var import_ethers51 = require("ethers");
84741
86198
 
84742
86199
  // src/util/format.ts
84743
86200
  function bigintReplacer(_key, value) {
@@ -84925,7 +86382,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84925
86382
  const b = getB();
84926
86383
  if (!b.ok) return renderError(b.error);
84927
86384
  return renderEnvelope(
84928
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
86385
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers51.parseEther)(amountUcd.toString()).toString() })
84929
86386
  );
84930
86387
  })
84931
86388
  );
@@ -84963,7 +86420,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84963
86420
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
84964
86421
  amountUcdWei = detail.data.debtUcdWei;
84965
86422
  } else {
84966
- amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
86423
+ amountUcdWei = (0, import_ethers51.parseEther)(amountUcd.toString()).toString();
84967
86424
  }
84968
86425
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
84969
86426
  })
@@ -85364,7 +86821,7 @@ function registerPsmTools(server, getB) {
85364
86821
  "psm_swap",
85365
86822
  {
85366
86823
  title: "Exchange UCD \u2194 a stablecoin through the PSM",
85367
- 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).",
86824
+ 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).",
85368
86825
  inputSchema: {
85369
86826
  stablecoin: import_zod4.z.string().min(1).describe(
85370
86827
  "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."
@@ -85380,7 +86837,7 @@ function registerPsmTools(server, getB) {
85380
86837
  const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
85381
86838
  const gate = requireConfirmation(
85382
86839
  confirmed,
85383
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
86840
+ `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"})`
85384
86841
  );
85385
86842
  if (gate) return gate;
85386
86843
  const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
@@ -85566,7 +87023,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
85566
87023
 
85567
87024
  // src/tools/signer.ts
85568
87025
  var import_zod6 = require("zod");
85569
- var import_ethers42 = require("ethers");
87026
+ var import_ethers52 = require("ethers");
85570
87027
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
85571
87028
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
85572
87029
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -85608,7 +87065,7 @@ function registerSignerTool(server, getRuntime, opts) {
85608
87065
  if (mode !== void 0 && !offeredModes.includes(mode)) {
85609
87066
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
85610
87067
  }
85611
- if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
87068
+ if (safeAddress !== void 0 && !import_ethers52.ethers.isAddress(safeAddress)) {
85612
87069
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
85613
87070
  }
85614
87071
  if (action === "status") {
@@ -86544,9 +88001,9 @@ function composeConnector(opts, rawPublicOrigin) {
86544
88001
  }
86545
88002
  if (opts.serveLandingPage) {
86546
88003
  app.get("/", (_req, res) => {
86547
- const { nonce, headers } = htmlPageSecurityHeaders({ "img-src": [BACKGROUND_IMAGE_ORIGIN, "data:"] });
88004
+ const { headers } = htmlPageSecurityHeaders({ "img-src": [BACKGROUND_IMAGE_ORIGIN, "data:"] });
86548
88005
  for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
86549
- res.type("text/html; charset=utf-8").send(renderLandingPage({ publicOrigin, networks: allowedNetworks, version: SERVER_VERSION, nonce }));
88006
+ res.type("text/html; charset=utf-8").send(renderLandingPage({ publicOrigin, version: SERVER_VERSION }));
86550
88007
  });
86551
88008
  }
86552
88009
  app.use((_req, res) => deny(res, 404, "not found \u2014 the MCP endpoint is /mcp"));