@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.
package/dist/connector.js CHANGED
@@ -15552,7 +15552,7 @@ ${errorReport}`);
15552
15552
  }
15553
15553
  init_debug_logger();
15554
15554
  init_session_signature_cache();
15555
- var import_ethers43 = require("ethers");
15555
+ var import_ethers53 = require("ethers");
15556
15556
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15557
15557
  var GRACE_PERIOD_DAYS = 30;
15558
15558
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -18468,12 +18468,12 @@ ${auth.clientId}`;
18468
18468
  }
18469
18469
  async function executeVaultSnapshot(params) {
18470
18470
  global.ethers = {
18471
- ...import_ethers43.ethers,
18471
+ ...import_ethers53.ethers,
18472
18472
  providers: {
18473
- StaticJsonRpcProvider: import_ethers43.ethers.JsonRpcProvider
18473
+ StaticJsonRpcProvider: import_ethers53.ethers.JsonRpcProvider
18474
18474
  },
18475
- Contract: import_ethers43.ethers.Contract,
18476
- utils: import_ethers43.ethers
18475
+ Contract: import_ethers53.ethers.Contract,
18476
+ utils: import_ethers53.ethers
18477
18477
  // v6 moved utils to top level
18478
18478
  };
18479
18479
  global.Lit = {
@@ -25682,7 +25682,10 @@ var require_lit_core_lit_action_client = __commonJS({
25682
25682
  "node_modules/@gvnrdao/dh-lit-ops/dist/utils/lit-core-lit-action-client.js"(exports2) {
25683
25683
  "use strict";
25684
25684
  Object.defineProperty(exports2, "__esModule", { value: true });
25685
+ exports2.CORE_API_TRANSPORT_FAILURE_MARKER = void 0;
25685
25686
  exports2.normalizeCoreLitActionResult = normalizeCoreLitActionResult;
25687
+ exports2.describeErrorWithCause = describeErrorWithCause;
25688
+ exports2.isCoreApiTransportError = isCoreApiTransportError;
25686
25689
  exports2.executeLitActionViaCoreApi = executeLitActionViaCoreApi;
25687
25690
  var fetch_lit_action_from_ipfs_1 = require_fetch_lit_action_from_ipfs();
25688
25691
  function parseResponsePayload(raw) {
@@ -25733,6 +25736,27 @@ var require_lit_core_lit_action_client = __commonJS({
25733
25736
  const fromEnv = process.env.LIT_CORE_API_BASE_URL;
25734
25737
  return (explicit || fromEnv || "https://api.chipotle.litprotocol.com").replace(/\/$/, "");
25735
25738
  }
25739
+ exports2.CORE_API_TRANSPORT_FAILURE_MARKER = "Lit Core lit_action transport failure";
25740
+ function describeErrorWithCause(e) {
25741
+ const parts = [];
25742
+ let current = e;
25743
+ const seen = /* @__PURE__ */ new Set();
25744
+ while (current != null && !seen.has(current) && parts.length < 5) {
25745
+ seen.add(current);
25746
+ if (current instanceof Error) {
25747
+ const code = current.code;
25748
+ parts.push(typeof code === "string" && !current.message.includes(code) ? `${code}: ${current.message}` : current.message);
25749
+ current = current.cause;
25750
+ } else {
25751
+ parts.push(String(current));
25752
+ break;
25753
+ }
25754
+ }
25755
+ return parts.length === 0 ? String(e) : parts.join(" <- ");
25756
+ }
25757
+ function isCoreApiTransportError(message) {
25758
+ return message.includes(exports2.CORE_API_TRANSPORT_FAILURE_MARKER);
25759
+ }
25736
25760
  async function executeLitActionViaCoreApi(options) {
25737
25761
  let resolvedCode = options.code || "";
25738
25762
  if (!resolvedCode.trim()) {
@@ -25794,13 +25818,11 @@ var require_lit_core_lit_action_client = __commonJS({
25794
25818
  return normalizeCoreLitActionResult(body);
25795
25819
  } catch (e) {
25796
25820
  const msg = e instanceof Error ? e.message : String(e);
25821
+ const error = msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : `${exports2.CORE_API_TRANSPORT_FAILURE_MARKER}: ${describeErrorWithCause(e)}`;
25797
25822
  if (options.debug) {
25798
- console.error("\u274C [executeLitActionViaCoreApi]", msg);
25823
+ console.error("\u274C [executeLitActionViaCoreApi]", error);
25799
25824
  }
25800
- return {
25801
- success: false,
25802
- error: msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : msg
25803
- };
25825
+ return { success: false, error };
25804
25826
  } finally {
25805
25827
  clearTimeout(timer);
25806
25828
  }
@@ -26782,7 +26804,8 @@ var require_lit_ops_module = __commonJS({
26782
26804
  const borrowerAddress = borrowerOverride ?? this.config.serverAddress ?? await this.config.signer.getAddress();
26783
26805
  const pkpValidatorInfo = DH_LIT_ACTIONS_CHIPOTLE.pkpValidator;
26784
26806
  const validatorWalletAddress = process.env.LIT_PKP_VALIDATOR_WALLET_OVERRIDE || pkpValidatorInfo?.validatorWalletAddress;
26785
- const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(e instanceof Error ? e.message : String(e));
26807
+ const errorMessage = (e) => e instanceof Error ? e.message : String(e);
26808
+ const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(errorMessage(e));
26786
26809
  const propagationRetries = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_RETRIES) || 8;
26787
26810
  const propagationDelayMs = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_DELAY_MS) || 15e3;
26788
26811
  let coreResponse;
@@ -26803,10 +26826,12 @@ var require_lit_ops_module = __commonJS({
26803
26826
  coreResponse = exec.response;
26804
26827
  break;
26805
26828
  } catch (e) {
26806
- if (!isWalletPropagationError(e) || attempt === propagationRetries) {
26829
+ const propagating = isWalletPropagationError(e);
26830
+ const transport = (0, lit_core_lit_action_client_1.isCoreApiTransportError)(errorMessage(e));
26831
+ if (!propagating && !transport || attempt === propagationRetries) {
26807
26832
  throw e;
26808
26833
  }
26809
- console.log(`[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
26834
+ console.log(propagating ? `[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms` : `[ChipotlePKP] vault PKP ${pkpId} validator call failed in transport (${errorMessage(e)}); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
26810
26835
  await new Promise((r) => setTimeout(r, propagationDelayMs));
26811
26836
  }
26812
26837
  }
@@ -40531,7 +40556,7 @@ var require_dist3 = __commonJS({
40531
40556
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
40532
40557
  };
40533
40558
  Object.defineProperty(exports2, "__esModule", { value: true });
40534
- exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
40559
+ exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
40535
40560
  __exportStar(require_interfaces(), exports2);
40536
40561
  var dh_lit_actions_1 = require_pkg_src();
40537
40562
  Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
@@ -40601,6 +40626,15 @@ var require_dist3 = __commonJS({
40601
40626
  Object.defineProperty(exports2, "normalizeCoreLitActionResult", { enumerable: true, get: function() {
40602
40627
  return lit_core_lit_action_client_1.normalizeCoreLitActionResult;
40603
40628
  } });
40629
+ Object.defineProperty(exports2, "describeErrorWithCause", { enumerable: true, get: function() {
40630
+ return lit_core_lit_action_client_1.describeErrorWithCause;
40631
+ } });
40632
+ Object.defineProperty(exports2, "isCoreApiTransportError", { enumerable: true, get: function() {
40633
+ return lit_core_lit_action_client_1.isCoreApiTransportError;
40634
+ } });
40635
+ Object.defineProperty(exports2, "CORE_API_TRANSPORT_FAILURE_MARKER", { enumerable: true, get: function() {
40636
+ return lit_core_lit_action_client_1.CORE_API_TRANSPORT_FAILURE_MARKER;
40637
+ } });
40604
40638
  var bitcoin_signature_1 = require_bitcoin_signature();
40605
40639
  Object.defineProperty(exports2, "convertEthereumSignatureToBitcoinDER", { enumerable: true, get: function() {
40606
40640
  return bitcoin_signature_1.convertEthereumSignatureToBitcoinDER;
@@ -40800,8 +40834,10 @@ An agent on the user's own machine can skip this service and talk to the protoco
40800
40834
  directly through the published MCP server, which carries the same tools:
40801
40835
 
40802
40836
  - \`npx -y @gvnrdao/dh-mcp\` (requires Node \u2265 18)
40803
- - \`curl -fsSL https://assets.gvnr.xyz/dh-mcp/install.sh | sh\` (self-contained binary)
40804
- - Claude Desktop bundle and checksums: <https://assets.gvnr.xyz/dh-mcp/>
40837
+
40838
+ That is the only self-hosted path. The downloadable binaries and Claude Desktop bundle
40839
+ that this document used to list were withdrawn on 2026-09-18; nothing is served under
40840
+ \`assets.gvnr.xyz/dh-mcp\` any more.
40805
40841
 
40806
40842
  ## Contact
40807
40843
 
@@ -40820,31 +40856,10 @@ var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).rep
40820
40856
  var BACKGROUND_IMAGE_ORIGIN = "https://images.gvnr.xyz";
40821
40857
  var BACKGROUND_IMAGE_URL = `${BACKGROUND_IMAGE_ORIGIN}/images/layout/backgroundCorleoneb.jpg`;
40822
40858
  var escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
40823
- function moneyReality(networks2) {
40824
- const mainnet = networks2.includes("mainnet");
40825
- const sepolia = networks2.includes("sepolia");
40826
- if (mainnet && sepolia) {
40827
- return {
40828
- label: "REAL MONEY on mainnet \xB7 practice funds on sepolia",
40829
- 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."
40830
- };
40831
- }
40832
- if (mainnet) {
40833
- return {
40834
- label: "REAL MONEY \u2014 Ethereum mainnet",
40835
- 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."
40836
- };
40837
- }
40838
- return {
40839
- label: "PRACTICE FUNDS \u2014 sepolia test network",
40840
- detail: "This deployment serves sepolia only. The contracts and ceremonies are real, the money is not. Nothing here can move mainnet funds."
40841
- };
40842
- }
40859
+ var CONNECT_URL = "https://app.diamondhands.credit/connect";
40843
40860
  function renderLandingPage(input) {
40844
- const { publicOrigin, networks: networks2, version: version2, nonce } = input;
40861
+ const { publicOrigin, version: version2 } = input;
40845
40862
  const origin2 = escapeHtml(publicOrigin);
40846
- const money = moneyReality(networks2);
40847
- const config = JSON.stringify({ mcpServers: { "diamond-hands": { type: "http", url: `${publicOrigin}/mcp` } } }, null, 2);
40848
40863
  return `<!doctype html>
40849
40864
  <html lang="en">
40850
40865
  <head>
@@ -40869,135 +40884,34 @@ function renderLandingPage(input) {
40869
40884
  .scroll { height:100%; overflow-y:auto; overscroll-behavior:contain; }
40870
40885
  main { max-width:41rem; margin:0 auto; padding:1.9rem 1.25rem 2rem;
40871
40886
  text-shadow:0 1px 3px rgba(0,0,0,.85); }
40872
- /* Wide viewports: the lower half goes side-by-side so the whole page fits without the
40873
- viewport scrolling \u2014 the house treatment is a full-bleed image, not a long page. */
40874
- @media (min-width: 62rem) and (min-height: 34rem) {
40875
- main { max-width:62rem; }
40876
- .cols { display:grid; grid-template-columns:1fr 1fr; gap:0 1.6rem; align-items:start; }
40877
- .cols h2:first-child { margin-top:0; }
40878
- }
40879
40887
  h1 { font-size:1.35rem; margin:0 0 .25rem; letter-spacing:-.01em; }
40880
40888
  .sub { color:#dfe3ea; margin:0 0 1.1rem; font-size:14px; }
40881
- .card { background:rgba(6,8,12,.62); border:1px solid rgba(255,255,255,.16);
40882
- border-radius:10px; padding:.75rem .95rem; margin:0 0 .8rem;
40883
- backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px); }
40884
- .money { border-left:3px solid #f59e0b; }
40885
- .money strong { display:block; margin-bottom:.15rem; }
40886
- h2 { font-size:.72rem; text-transform:uppercase; letter-spacing:.08em; color:#cbd2dc;
40887
- margin:1.1rem 0 .45rem; font-weight:600; }
40888
- pre { margin:0; padding:.7rem .9rem; background:rgba(0,0,0,.66);
40889
- border:1px solid rgba(255,255,255,.16); border-radius:8px; overflow-x:auto;
40890
- font-size:12.5px; line-height:1.45; text-shadow:none;
40891
- font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
40892
40889
  code { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:.92em; }
40893
- table { border-collapse:collapse; width:100%; font-size:13.5px; }
40894
- td { padding:.3rem .6rem .3rem 0; border-bottom:1px solid rgba(255,255,255,.12); vertical-align:top; }
40895
- td:first-child { color:#cbd2dc; white-space:nowrap; width:10.5rem; }
40896
- tr:last-child td { border-bottom:0; }
40897
40890
  a { color:inherit; text-decoration:underline; text-underline-offset:2px; }
40898
- .row { display:flex; align-items:center; gap:.6rem; margin-bottom:.4rem; font-size:13px; }
40899
- button { font:inherit; font-size:12.5px; padding:.25rem .65rem;
40900
- border:1px solid rgba(255,255,255,.24); border-radius:6px;
40901
- background:rgba(0,0,0,.55); color:#f3f4f6; cursor:pointer; text-shadow:none; }
40902
- button:hover { background:rgba(0,0,0,.75); }
40903
40891
  footer { color:#cbd2dc; font-size:12.5px; margin-top:1.1rem; padding-top:.7rem;
40904
40892
  border-top:1px solid rgba(255,255,255,.14); }
40905
- [hidden] { display:none !important; }
40906
- #reveal-wrap { margin:0 0 .4rem; }
40907
- #reveal { display:inline-block; padding:.4rem .85rem; border-radius:6px;
40908
- border:1px solid rgba(255,255,255,.26); background:rgba(6,8,12,.62);
40909
- backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px);
40910
- text-decoration:none; font-size:13.5px; text-shadow:none; cursor:pointer; }
40911
- #reveal:hover { background:rgba(6,8,12,.85); border-color:rgba(255,255,255,.4); }
40912
- #reveal::after { content:" \u2193"; opacity:.7; }
40893
+ #cta-wrap { margin:.2rem 0 0; }
40894
+ #cta { display:inline-block; padding:.4rem .85rem; border-radius:6px;
40895
+ border:1px solid rgba(255,255,255,.26); background:rgba(6,8,12,.62);
40896
+ backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px);
40897
+ text-decoration:none; font-size:13.5px; text-shadow:none; cursor:pointer; }
40898
+ #cta:hover { background:rgba(6,8,12,.85); border-color:rgba(255,255,255,.4); }
40899
+ #cta::after { content:" \u2192"; opacity:.7; }
40913
40900
  </style>
40914
40901
  </head>
40915
40902
  <body>
40916
40903
  <div class="scroll">
40917
40904
  <main>
40918
40905
  <h1>Diamond Hands \u2014 MCP endpoint</h1>
40919
- <p class="sub">This host is a <strong>Model Context Protocol</strong> server, not a website.
40920
- There is no app to use here. If you are a person, the app is at
40921
- <a href="https://app.diamondhands.credit/">app.diamondhands.credit</a>.</p>
40922
-
40923
- <!-- Revealed BY SCRIPT, hidden in the served markup \u2014 the inverse of #details below.
40924
- With no JS this stays hidden and the details stay open, so the page degrades to
40925
- everything-visible rather than to a trigger that does nothing. -->
40926
- <p id="reveal-wrap" hidden><a href="#details" id="reveal" role="button">View MCP installation details</a></p>
40927
-
40928
- <div id="details">
40929
- <div class="card money">
40930
- <strong>${escapeHtml(money.label)}</strong>
40931
- ${escapeHtml(money.detail)}
40932
- </div>
40933
-
40934
- <div class="cols">
40935
- <section>
40936
- <h2>Connect an agent</h2>
40937
- <div class="row">
40938
- <span style="color:var(--muted);font-size:13px">Add this to your MCP client configuration:</span>
40939
- <button id="copy" type="button">Copy</button>
40940
- </div>
40941
- <pre id="cfg">${escapeHtml(config)}</pre>
40942
-
40943
- <h2>How authorization works</h2>
40944
- <div class="card">
40945
- Identity is a <strong>wallet</strong>, not an account: OAuth 2.1 with dynamic client
40946
- registration (RFC 7591) and PKCE, where the login is an Ethereum signature (EIP-4361).
40947
- No passwords, no user database. The bearer token proves <em>session identity only</em> \u2014
40948
- it signs nothing and can never move funds; every fund-moving step raises its own approval
40949
- in your own wallet. Session state is in memory, so a restart means signing in again.
40950
- </div>
40951
- </section>
40952
-
40953
- <section>
40954
- <h2>Endpoints</h2>
40955
- <div class="card">
40956
- <table>
40957
- <tr><td>MCP</td><td><code>${origin2}/mcp</code> \u2014 streamable HTTP</td></tr>
40958
- <tr><td>Networks served</td><td><code>${escapeHtml(networks2.join(", "))}</code></td></tr>
40959
- <tr><td>Registration</td><td><a href="/auth.md">/auth.md</a> \u2014 how an agent registers and signs in</td></tr>
40960
- <tr><td>Resource metadata</td><td><a href="/.well-known/oauth-protected-resource">/.well-known/oauth-protected-resource</a></td></tr>
40961
- <tr><td>Auth server metadata</td><td><a href="/.well-known/oauth-authorization-server">/.well-known/oauth-authorization-server</a></td></tr>
40962
- </table>
40963
- </div>
40906
+ <p class="sub">Welcome to the Diamond Hands <strong>Model Context Protocol</strong> server.</p>
40964
40907
 
40965
- </section>
40966
- </div>
40908
+ <p id="cta-wrap"><a href="${CONNECT_URL}" id="cta" role="button">View MCP installation details</a></p>
40967
40909
 
40968
40910
  <footer>
40969
40911
  <code>@gvnrdao/dh-mcp</code> v${escapeHtml(version2)} \xB7 origin <code>${origin2}</code>
40970
40912
  </footer>
40971
- </div>
40972
40913
  </main>
40973
40914
  </div>
40974
- <script nonce="${escapeHtml(nonce)}">
40975
- // Progressive disclosure, applied by SCRIPT rather than baked into the markup: the
40976
- // details ship visible, and only a browser that can re-open them is allowed to close
40977
- // them. A page whose whole content sits behind a trigger that needs JS is a page that
40978
- // shows two sentences and nothing else when the script does not run.
40979
- (function () {
40980
- var details = document.getElementById('details');
40981
- var wrap = document.getElementById('reveal-wrap');
40982
- var link = document.getElementById('reveal');
40983
- if (!details || !wrap || !link) return;
40984
- details.hidden = true;
40985
- wrap.hidden = false;
40986
- link.addEventListener('click', function (e) {
40987
- e.preventDefault();
40988
- wrap.hidden = true;
40989
- details.hidden = false;
40990
- });
40991
- })();
40992
-
40993
- document.getElementById('copy').addEventListener('click', function () {
40994
- var t = document.getElementById('cfg').textContent;
40995
- navigator.clipboard.writeText(t).then(function () {
40996
- var b = document.getElementById('copy');
40997
- b.textContent = 'Copied'; setTimeout(function () { b.textContent = 'Copy'; }, 1400);
40998
- });
40999
- });
41000
- </script>
41001
40915
  </body>
41002
40916
  </html>
41003
40917
  `;
@@ -41032,7 +40946,7 @@ function htmlPageSecurityHeaders(extra) {
41032
40946
  }
41033
40947
 
41034
40948
  // src/version.ts
41035
- var SERVER_VERSION = "0.5.16";
40949
+ var SERVER_VERSION = "0.5.18";
41036
40950
 
41037
40951
  // src/connector/siwe-oauth.ts
41038
40952
  var import_node_crypto2 = require("crypto");
@@ -41554,16 +41468,18 @@ function resolveWcProjectId(raw, problems) {
41554
41468
  }
41555
41469
  return raw;
41556
41470
  }
41471
+ var RPC_PROXY_ORIGIN = "https://api.gvnr.xyz";
41472
+ var rpcProxy = (chainId) => `${RPC_PROXY_ORIGIN}/v1/proxy/rpc/${chainId}`;
41557
41473
  var NETWORK_DEFAULTS = {
41558
41474
  sepolia: {
41559
- rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
41475
+ rpcUrl: rpcProxy(11155111),
41560
41476
  serviceEndpoint: "https://ops-test.gvnr.xyz",
41561
41477
  litNetwork: "chipotle",
41562
41478
  validatorVersion: 3
41563
41479
  // on-chain validator generation, sepolia (2026-07-30)
41564
41480
  },
41565
41481
  mainnet: {
41566
- rpcUrl: "https://ethereum-rpc.publicnode.com",
41482
+ rpcUrl: rpcProxy(1),
41567
41483
  // Cutover 2026-09-08 — see sdk/src/constants/chunks/network-configs.ts for the full
41568
41484
  // reasoning. Widening, not a rename: ops.gvnr.xyz serves the same broker and cannot be
41569
41485
  // retired while installed copies call it. The sepolia entry above deliberately stays on
@@ -41681,11 +41597,11 @@ function resolveRealConfig(env) {
41681
41597
  problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
41682
41598
  }
41683
41599
  }
41684
- const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "sepolia" : env["DH_NETWORK"];
41600
+ const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "mainnet" : env["DH_NETWORK"];
41685
41601
  if (NETWORKS[network] === void 0) {
41686
41602
  problems.push(`DH_NETWORK='${network}' is not supported. Allowed: ${Object.keys(NETWORKS).join(" | ")}.`);
41687
41603
  }
41688
- const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.sepolia;
41604
+ const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.mainnet;
41689
41605
  const rpcUrl = env["ETH_RPC_URL"] || defaults2.rpcUrl;
41690
41606
  const serviceEndpoint = env["DH_SERVICE_ENDPOINT"] || defaults2.serviceEndpoint;
41691
41607
  if (!/^https:\/\//.test(serviceEndpoint) && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(serviceEndpoint)) {
@@ -41750,7 +41666,7 @@ function resolveRealConfig(env) {
41750
41666
 
41751
41667
  // src/boot.ts
41752
41668
  var fs6 = __toESM(require("fs"));
41753
- var import_ethers40 = require("ethers");
41669
+ var import_ethers50 = require("ethers");
41754
41670
 
41755
41671
  // src/boundary/index.ts
41756
41672
  var import_node_crypto9 = require("crypto");
@@ -42167,7 +42083,7 @@ var BoundaryCore = class {
42167
42083
  const inToken = toUcd ? s.stablecoinSymbol : "UCD";
42168
42084
  const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
42169
42085
  const amountIn = parseDecimalUnits(p.amount, inDecimals);
42170
- const refuse = (refusal, message, details) => ({
42086
+ const refuse3 = (refusal, message, details) => ({
42171
42087
  env: errEnvelope(
42172
42088
  boundaryError("UPSTREAM_REJECTED", message, {
42173
42089
  source: statusR.source.id,
@@ -42178,13 +42094,13 @@ var BoundaryCore = class {
42178
42094
  });
42179
42095
  const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
42180
42096
  if (s.paused) {
42181
- return refuse(
42097
+ return refuse3(
42182
42098
  "psm-paused",
42183
42099
  "the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
42184
42100
  );
42185
42101
  }
42186
42102
  if (!toUcd && !s.redeemEnabled) {
42187
- return refuse(
42103
+ return refuse3(
42188
42104
  "redeem-disabled",
42189
42105
  `redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
42190
42106
  );
@@ -42195,20 +42111,20 @@ var BoundaryCore = class {
42195
42111
  const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
42196
42112
  const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
42197
42113
  if (amountIn < min) {
42198
- return refuse(
42114
+ return refuse3(
42199
42115
  "below-min",
42200
42116
  `${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
42201
42117
  { amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
42202
42118
  );
42203
42119
  }
42204
42120
  if (max === 0n) {
42205
- return refuse(
42121
+ return refuse3(
42206
42122
  "direction-disabled",
42207
42123
  `the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
42208
42124
  );
42209
42125
  }
42210
42126
  if (amountIn > max) {
42211
- return refuse(
42127
+ return refuse3(
42212
42128
  "above-max",
42213
42129
  `${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
42214
42130
  { amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
@@ -42228,7 +42144,7 @@ var BoundaryCore = class {
42228
42144
  if (!toUcd) {
42229
42145
  const available = BigInt(s.availableReserves);
42230
42146
  if (available < amountOut) {
42231
- return refuse(
42147
+ return refuse3(
42232
42148
  "insufficient-reserves",
42233
42149
  `the PSM cannot pay this redemption: available reserves ${formatDecimalUnits(available, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${available} smallest units), required ${formatDecimalUnits(amountOut, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${amountOut} smallest units).`,
42234
42150
  { available: available.toString(), required: amountOut.toString(), unit: outUnit }
@@ -42304,20 +42220,31 @@ var BoundaryCore = class {
42304
42220
  const inDecimals = toUcd ? s.stablecoinDecimals : 18;
42305
42221
  const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
42306
42222
  const viaSafe = this.deps.signer?.mode() === "safe";
42223
+ const a = v.allowance;
42224
+ const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
42225
+ 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(
42226
+ (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}`
42227
+ ).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
42307
42228
  const data = {
42308
42229
  direction: p.direction,
42309
42230
  contractCall: q.contractCall,
42310
- approve: {
42311
- txRef: v.approve.txRef,
42312
- token: v.approve.tokenSymbol,
42313
- tokenAddress: v.approve.tokenAddress,
42314
- spenderAddress: v.approve.spenderAddress,
42315
- spenderContract: v.approve.spenderContract,
42316
- spenderReason: v.approve.spenderContract === "SimplePSMV2" ? "the PSM contract itself pulls the USDC it converts (transferFrom), so the USDC allowance goes to the PSM" : "the PSM burns your UCD THROUGH the UCDController (controller.burnFromPsm), so the UCD allowance goes to the UCDController \u2014 a different contract than the PSM, by design",
42317
- amount: v.approve.amount,
42231
+ allowance: {
42232
+ token: a.tokenSymbol,
42233
+ tokenAddress: a.tokenAddress,
42234
+ spenderAddress: a.spenderAddress,
42235
+ spenderContract: a.spenderContract,
42236
+ 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",
42237
+ before: a.before,
42318
42238
  amountUnit: q.amountInUnit,
42319
- authorization: v.approve.authorization
42239
+ basis: "approvals are planned against the allowance read before signing: none when it already covers the amount; an exact approve when it is 0; a partial allowance is reset to 0 first (some tokens refuse a non-zero \u2192 non-zero approve). Every approve is EXACTLY the input amount \u2014 never unlimited."
42320
42240
  },
42241
+ approvals: v.approvals.map((leg) => ({
42242
+ step: leg.step,
42243
+ txRef: leg.txRef,
42244
+ amount: leg.amount,
42245
+ amountUnit: q.amountInUnit,
42246
+ authorization: leg.authorization
42247
+ })),
42321
42248
  execute: {
42322
42249
  txRef: v.execute.txRef,
42323
42250
  amountIn: v.execute.amountIn,
@@ -42339,7 +42266,7 @@ var BoundaryCore = class {
42339
42266
  note: viaSafe ? "output lands AT THE SAFE \u2014 both transactions execute BY the Safe (the Safe is msg.sender, and the contract pays msg.sender only; there is no recipient parameter)" : "output goes to the signer's own address \u2014 the contract pays msg.sender only; there is no recipient parameter"
42340
42267
  },
42341
42268
  balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
42342
- human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}). Ceremony 1: approved EXACTLY ${formatDecimalUnits(BigInt(v.approve.amount), inDecimals)} ${v.approve.tokenSymbol} to ${v.approve.spenderContract}. Ceremony 2: ${q.contractCall} executed with floor ${formatDecimalUnits(BigInt(v.execute.minOut), outDecimals)} ${q.amountOutToken} (quote \u2212 ${PSM_FLOOR_TOLERANCE_BPS} bps). ` + (viaSafe ? `Both executed BY the Safe as consecutive Safe transactions; output to the Safe: ${auth.borrower}.` : `Output to the signer: ${auth.borrower}.`)
42269
+ human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}). ${approvalsHuman} Ceremony ${v.approvals.length + 1}: ${q.contractCall} executed with floor ${formatDecimalUnits(BigInt(v.execute.minOut), outDecimals)} ${q.amountOutToken} (quote \u2212 ${PSM_FLOOR_TOLERANCE_BPS} bps). ` + (viaSafe ? `All executed BY the Safe as consecutive Safe transactions; output to the Safe: ${auth.borrower}.` : `Output to the signer: ${auth.borrower}.`)
42343
42270
  };
42344
42271
  return okEnvelope(data, r.source, warnings);
42345
42272
  }
@@ -44198,6 +44125,16 @@ function buildExtendTx(ctx, p) {
44198
44125
  );
44199
44126
  }
44200
44127
 
44128
+ // src/boundary/upstream/shared/psm-approval-steps.ts
44129
+ function psmApprovalSteps(allowanceBefore, amountIn) {
44130
+ if (allowanceBefore >= amountIn) return [];
44131
+ if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
44132
+ return [
44133
+ { step: "reset-approve", amount: 0n },
44134
+ { step: "approve", amount: amountIn }
44135
+ ];
44136
+ }
44137
+
44201
44138
  // src/boundary/upstream/mock/sink-contracts.ts
44202
44139
  var import_ethers6 = require("ethers");
44203
44140
  function sinkAddress(label) {
@@ -44354,9 +44291,25 @@ var SignerManager = class {
44354
44291
  pendingCeremonies: this.deps.pendingCeremonies()
44355
44292
  };
44356
44293
  }
44357
- /** The conversational first-run text every write answers with under mode `none`. */
44294
+ /**
44295
+ * The conversational first-run text every write answers with under mode `none`.
44296
+ *
44297
+ * It states the SCOPE of the refusal first, because the tool list does not change with
44298
+ * signer mode: an assistant that meets this on `loan_mint` still sees `loan_pay`,
44299
+ * `loan_withdraw` and `psm_swap` advertised, and its natural next move is to try one
44300
+ * rather than to run setup. Every one of them refuses identically here
44301
+ * (`BoundaryCore.requireBorrower`), so without that sentence the model rediscovers the
44302
+ * same wall N times and the user watches it flail. Naming the scope converts N refusals
44303
+ * into one instruction.
44304
+ *
44305
+ * It also says reads still work, so "no signer" is not misread as "server broken", and
44306
+ * it offers ONLY the modes this composition can actually construct — a build with no
44307
+ * keystore runtime must not suggest one (the same rule G-CONN-14 holds the guide to).
44308
+ */
44358
44309
  invitation() {
44359
- 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'.";
44310
+ const keystoreOffered = this.deps.keystore !== null;
44311
+ 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. ";
44312
+ 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'.`;
44360
44313
  }
44361
44314
  };
44362
44315
  var KeystoreProvider = class {
@@ -45033,8 +44986,9 @@ var MockUpstreamPlugin = class {
45033
44986
  return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
45034
44987
  });
45035
44988
  }
45036
- /** PSM exchange pair (plan 08 W1): TWO ceremonies in ONE ops call — the exact-amount
45037
- * approve (spender asymmetric by direction, contract truth), then the swap/redeem with
44989
+ /** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
44990
+ * or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
44991
+ * asymmetric by direction, contract truth), then the swap/redeem with
45038
44992
  * its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
45039
44993
  * AFTER the approve reports the step that declined AND the residual exact-amount
45040
44994
  * allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
@@ -45053,55 +45007,75 @@ var MockUpstreamPlugin = class {
45053
45007
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
45054
45008
  const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
45055
45009
  const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
45056
- const residualNote = `the approve step already completed \u2014 an exact-amount allowance of ${p.amountIn} ${tokenUnit} to ${spenderContract} remains standing; it authorizes only that amount and nothing else. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
45057
- const approveCard = `approve exactly ${p.amountIn} ${tokenUnit} to ${spenderContract} (${spenderReason})`;
45010
+ const standing = this.world.psmAllowancesOf(p.borrower);
45011
+ const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
45012
+ const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
45013
+ const landed = [];
45014
+ const residualNote = () => {
45015
+ const last = landed[landed.length - 1];
45016
+ 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`;
45017
+ return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
45018
+ };
45058
45019
  const executeCard = `${isSwap ? "exchange" : "redeem"} ${p.amountIn} ${tokenUnit} via the PSM (contract ${p.direction}): quote ${plan.value.out} ${outUnit} (fee ${plan.value.fee} ${outUnit}), floor ${p.minOut} ${outUnit} \u2014 output to ${p.borrower}`;
45059
45020
  const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
45060
45021
  const cer = this.ceremonyNow();
45061
- let approveAuth = null;
45062
- if (cer) {
45063
- const chainId = cer.txContext().chainId;
45064
- const approveTx = buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount: p.amountIn });
45065
- const r = await cer.authorizeTx({
45066
- action: "psm-approve",
45067
- borrower: p.borrower,
45068
- tx: approveTx,
45069
- expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn }
45070
- });
45071
- if (!r.ok) {
45072
- return upFail({
45073
- kind: "rejected",
45074
- source: "mock-ops",
45075
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(r.failure)} \u2014 no allowance was granted and no funds moved`
45022
+ const approvals = [];
45023
+ for (const s of steps) {
45024
+ const amount = s.amount.toString();
45025
+ const isReset = s.step === "reset-approve";
45026
+ const label = isReset ? "RESET-APPROVE" : "APPROVE";
45027
+ 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";
45028
+ 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})`;
45029
+ let legAuth = null;
45030
+ if (cer) {
45031
+ const chainId = cer.txContext().chainId;
45032
+ const r = await cer.authorizeTx({
45033
+ action: "psm-approve",
45034
+ borrower: p.borrower,
45035
+ tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
45036
+ expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
45076
45037
  });
45038
+ if (!r.ok) {
45039
+ return upFail({
45040
+ kind: "rejected",
45041
+ source: "mock-ops",
45042
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
45043
+ });
45044
+ }
45045
+ this.bindIfDiscovering(r.authorization);
45046
+ legAuth = r.authorization;
45077
45047
  }
45078
- this.bindIfDiscovering(r.authorization);
45079
- approveAuth = r.authorization;
45080
- }
45081
- const step1 = await this.write("psmSwap", () => {
45082
- const sig = approveAuth ? { ok: true, authorization: approveAuth } : this.sign("psm-approve", p.borrower, approveCard);
45083
- if (!sig.ok) {
45084
- return upFail({
45085
- kind: "rejected",
45086
- source: "mock-ops",
45087
- message: `psmSwap declined at the APPROVE step: ${declinedMessage(sig.failure)} \u2014 no allowance was granted and no funds moved`
45048
+ const leg = await this.write("psmSwap", () => {
45049
+ const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
45050
+ if (!sig.ok) {
45051
+ return upFail({
45052
+ kind: "rejected",
45053
+ source: "mock-ops",
45054
+ message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
45055
+ });
45056
+ }
45057
+ const applied = this.applyAuthorized(sig.authorization, () => {
45058
+ this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
45059
+ return { ok: true, value: void 0 };
45088
45060
  });
45089
- }
45090
- const applied = this.applyAuthorized(sig.authorization, () => {
45091
- this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount: p.amountIn });
45092
- return { ok: true, value: void 0 };
45061
+ if (!applied.ok) {
45062
+ return upFail({
45063
+ kind: "rejected",
45064
+ source: "mock-ops",
45065
+ message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
45066
+ });
45067
+ }
45068
+ return upOk(sig.authorization, this.src("mock-ops"));
45093
45069
  });
45094
- if (!applied.ok) {
45095
- return upFail({
45096
- kind: "rejected",
45097
- source: "mock-ops",
45098
- message: `psmSwap failed at the APPROVE step: ${applied.reason} \u2014 no allowance was granted and no funds moved`
45099
- });
45100
- }
45101
- return upOk(sig.authorization, this.src("mock-ops"));
45102
- });
45103
- if (!step1.ok) return step1;
45104
- const aAuth = step1.value;
45070
+ if (!leg.ok) return leg;
45071
+ landed.push(s.step);
45072
+ approvals.push({
45073
+ step: s.step,
45074
+ txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
45075
+ amount,
45076
+ authorization: leg.value
45077
+ });
45078
+ }
45105
45079
  let executeAuth = null;
45106
45080
  if (cer) {
45107
45081
  const chainId = cer.txContext().chainId;
@@ -45116,7 +45090,7 @@ var MockUpstreamPlugin = class {
45116
45090
  return upFail({
45117
45091
  kind: "rejected",
45118
45092
  source: "mock-ops",
45119
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
45093
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
45120
45094
  });
45121
45095
  }
45122
45096
  executeAuth = r.authorization;
@@ -45127,23 +45101,16 @@ var MockUpstreamPlugin = class {
45127
45101
  return upFail({
45128
45102
  kind: "rejected",
45129
45103
  source: "mock-ops",
45130
- message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
45104
+ message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
45131
45105
  });
45132
45106
  }
45133
45107
  const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
45134
- if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
45108
+ if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
45135
45109
  const bal = this.world.balancesOf(p.borrower);
45136
45110
  return upOk(
45137
45111
  {
45138
- approve: {
45139
- txRef: approveAuth ? { kind: "eth-tx", id: aAuth.digest } : this.world.nextTxRef(),
45140
- tokenSymbol,
45141
- tokenAddress,
45142
- spenderAddress,
45143
- spenderContract,
45144
- amount: p.amountIn,
45145
- authorization: aAuth
45146
- },
45112
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
45113
+ approvals,
45147
45114
  execute: {
45148
45115
  txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
45149
45116
  amountIn: p.amountIn,
@@ -46324,7 +46291,7 @@ var SafeModuleCeremony = class {
46324
46291
  };
46325
46292
 
46326
46293
  // src/boundary/upstream/real/plugin.ts
46327
- var import_ethers39 = require("ethers");
46294
+ var import_ethers49 = require("ethers");
46328
46295
 
46329
46296
  // node_modules/@gvnrdao/dh-sdk/dist/index.mjs
46330
46297
  var import_ethers14 = require("ethers");
@@ -52415,8 +52382,12 @@ var {
52415
52382
  var import_ethers28 = require("ethers");
52416
52383
  var import_ethers29 = require("ethers");
52417
52384
  var import_ethers30 = require("ethers");
52418
- var import_dh_lit_ops = __toESM(require_dist3(), 1);
52419
52385
  var import_ethers31 = require("ethers");
52386
+ var import_ethers32 = require("ethers");
52387
+ var import_ethers33 = require("ethers");
52388
+ var import_ethers34 = require("ethers");
52389
+ var import_dh_lit_ops = __toESM(require_dist3(), 1);
52390
+ var import_ethers35 = require("ethers");
52420
52391
  var __create2 = Object.create;
52421
52392
  var __defProp2 = Object.defineProperty;
52422
52393
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -54779,7 +54750,7 @@ ${errorReport}`);
54779
54750
  }
54780
54751
  init_debug_logger();
54781
54752
  init_session_signature_cache();
54782
- var import_ethers192 = __require("ethers");
54753
+ var import_ethers232 = __require("ethers");
54783
54754
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
54784
54755
  var GRACE_PERIOD_DAYS = 30;
54785
54756
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -57707,12 +57678,12 @@ ${auth.clientId}`;
57707
57678
  }
57708
57679
  async function executeVaultSnapshot(params) {
57709
57680
  global.ethers = {
57710
- ...import_ethers192.ethers,
57681
+ ...import_ethers232.ethers,
57711
57682
  providers: {
57712
- StaticJsonRpcProvider: import_ethers192.ethers.JsonRpcProvider
57683
+ StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
57713
57684
  },
57714
- Contract: import_ethers192.ethers.Contract,
57715
- utils: import_ethers192.ethers
57685
+ Contract: import_ethers232.ethers.Contract,
57686
+ utils: import_ethers232.ethers
57716
57687
  // v6 moved utils to top level
57717
57688
  };
57718
57689
  global.Lit = {
@@ -57966,8 +57937,8 @@ function getSepoliaConfig() {
57966
57937
  positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
57967
57938
  positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
57968
57939
  simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
57969
- mockUsdcToken: SEPOLIA_CONTRACTS["MockUSDC"] || "",
57970
- mockUsdtToken: SEPOLIA_CONTRACTS["MockUSDT"] || "",
57940
+ mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
57941
+ mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
57971
57942
  loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
57972
57943
  termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
57973
57944
  circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
@@ -58043,14 +58014,17 @@ function getMainnetConfig() {
58043
58014
  agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
58044
58015
  },
58045
58016
  subgraphs: {
58046
- // KNOWN-WRONG placeholder (see GOAL-PLAN step 2 / dogfood F-CLI-4): this is a
58047
- // SEPOLIA subgraph id in a mainnet (chainId 1) config, and this gateway host
58048
- // needs an Authorization key the SDK does not (and must not) hold — so the
58049
- // URL is doubly unusable. The `CCTPsd…` path segment is the subgraph's
58050
- // PUBLIC ID, not a credential. The fix is a chain-correct SERVER-side proxy
58051
- // (see mcp/docs/SUBGRAPH-PROXY-PLAN.md) — same rule as rpcUrls above:
58052
- // never ship an API-keyed URL in a client config.
58053
- diamondHandsUrl: "https://gateway-arbitrum.network.thegraph.com/api/subgraphs/id/CCTPsdYqco2jChDLLBQTbdJWwoukVoMt1cXeR9ti6r9A"
58017
+ // The MAINNET subgraph on The Graph's decentralized network — the same id
58018
+ // lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
58019
+ // the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
58020
+ // chainId-1 config: unusable as shipped, but a caller who added their own key would have
58021
+ // read Sepolia data as mainnet.
58022
+ //
58023
+ // The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
58024
+ // not) hold, so this URL only works for a standalone caller supplying their own key.
58025
+ // Service mode never uses it — queries go through the lit-ops-server proxy, which adds
58026
+ // the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
58027
+ diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
58054
58028
  },
58055
58029
  litNetwork: "chipotle",
58056
58030
  debug: false
@@ -59071,6 +59045,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
59071
59045
  }
59072
59046
  return { timestamp: result.timestamp, signature: result.signature };
59073
59047
  }
59048
+ function baseMintFeeWei(mintAmountWei, originationFeeBps) {
59049
+ if (mintAmountWei < 0n)
59050
+ throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
59051
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59052
+ throw new Error(
59053
+ `baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59054
+ );
59055
+ }
59056
+ return mintAmountWei * BigInt(originationFeeBps) / 10000n;
59057
+ }
59058
+ function debtAfterMintExceedsLoanCap(params) {
59059
+ const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
59060
+ for (const [name, v] of Object.entries(params)) {
59061
+ if (v < 0n)
59062
+ throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
59063
+ }
59064
+ return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
59065
+ }
59066
+ function maxPrincipalWithinLoanCap(params) {
59067
+ const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
59068
+ if (maxLoanWei < 0n || currentDebtWei < 0n) {
59069
+ throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
59070
+ }
59071
+ if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59072
+ throw new Error(
59073
+ `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59074
+ );
59075
+ }
59076
+ const room = maxLoanWei - currentDebtWei;
59077
+ if (room <= 0n)
59078
+ return 0n;
59079
+ return room * 10000n / (10000n + BigInt(originationFeeBps));
59080
+ }
59074
59081
  function buildLoginDomain(chainId) {
59075
59082
  return {
59076
59083
  name: "Diamond Hands",
@@ -60480,23 +60487,37 @@ var BitcoinUtils = class {
60480
60487
  return getBitcoinAddressesFromPkp(pkpPublicKey);
60481
60488
  }
60482
60489
  };
60483
- function safeValidateBitcoinAddress(address, network = "regtest") {
60490
+ function networksOfValidAddress(address) {
60491
+ const lower2 = address.toLowerCase();
60492
+ if (lower2.startsWith("bcrt1"))
60493
+ return ["regtest"];
60494
+ if (lower2.startsWith("bc1"))
60495
+ return ["mainnet"];
60496
+ if (lower2.startsWith("tb1"))
60497
+ return ["testnet"];
60498
+ if (address.startsWith("1") || address.startsWith("3"))
60499
+ return ["mainnet"];
60500
+ return ["testnet", "regtest"];
60501
+ }
60502
+ function safeValidateBitcoinAddress(address, network) {
60484
60503
  if (!address || typeof address !== "string") {
60485
60504
  throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
60486
60505
  }
60487
- const base58Pattern = /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/;
60488
- const bech32Pattern = /^(bc1|tb1|bcrt1)[a-z0-9]+$/;
60489
- if (!base58Pattern.test(address) && !bech32Pattern.test(address)) {
60490
- throw new Error(`Invalid Bitcoin address format: ${address}`);
60506
+ if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
60507
+ throw new Error(
60508
+ `Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
60509
+ );
60510
+ }
60511
+ if (!BitcoinUtils.validateAddress(address)) {
60512
+ throw new Error(
60513
+ `Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
60514
+ );
60491
60515
  }
60492
- if (network === "regtest" || network === "testnet") {
60493
- if (!address.startsWith("m") && !address.startsWith("n") && !address.startsWith("2") && !address.startsWith("tb1") && !address.startsWith("bcrt1")) {
60494
- throw new Error(`Invalid ${network} Bitcoin address: ${address} (must start with m, n, 2, tb1, or bcrt1)`);
60495
- }
60496
- } else if (network === "mainnet") {
60497
- if (!address.startsWith("1") && !address.startsWith("3") && !address.startsWith("bc1")) {
60498
- throw new Error(`Invalid mainnet Bitcoin address: ${address} (must start with 1, 3, or bc1)`);
60499
- }
60516
+ const belongsTo = networksOfValidAddress(address);
60517
+ if (!belongsTo.includes(network)) {
60518
+ throw new Error(
60519
+ `Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
60520
+ );
60500
60521
  }
60501
60522
  return address;
60502
60523
  }
@@ -62605,6 +62626,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
62605
62626
  LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
62606
62627
  return LoanStatus2;
62607
62628
  })(LoanStatus || {});
62629
+ var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
62630
+ var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
62631
+ var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
62632
+ async function collectBorrowerDebtRows(fetchPage) {
62633
+ const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
62634
+ const rows = [];
62635
+ for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
62636
+ const batch = await fetchPage(page * pageSize, pageSize);
62637
+ if (batch.length > pageSize) {
62638
+ throw new Error(
62639
+ `Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
62640
+ );
62641
+ }
62642
+ rows.push(...batch);
62643
+ if (batch.length < pageSize) {
62644
+ return rows;
62645
+ }
62646
+ }
62647
+ throw new Error(
62648
+ `Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
62649
+ );
62650
+ }
62651
+ function parseSubgraphLoanStatus(label) {
62652
+ if (typeof label !== "string") {
62653
+ throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
62654
+ }
62655
+ const value = LoanStatus[label];
62656
+ if (typeof value !== "number") {
62657
+ throw new Error(`Unknown subgraph loan status label: "${label}"`);
62658
+ }
62659
+ return value;
62660
+ }
62661
+ function parseSubgraphWei(row) {
62662
+ const raw = row.ucdDebt || "0";
62663
+ if (typeof raw !== "string") {
62664
+ throw new Error(
62665
+ `ucdDebt on position ${row.id} is not a string: ${String(raw)}`
62666
+ );
62667
+ }
62668
+ let wei;
62669
+ try {
62670
+ wei = BigInt(raw);
62671
+ } catch (error) {
62672
+ throw new Error(
62673
+ `ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
62674
+ { cause: error }
62675
+ );
62676
+ }
62677
+ if (wei < 0n) {
62678
+ throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
62679
+ }
62680
+ return wei;
62681
+ }
62682
+ var WEI_PER_UCD = 10n ** 18n;
62683
+ function weiToHumanUcdString(wei) {
62684
+ if (wei < 0n) {
62685
+ throw new Error(`Cannot render negative wei: ${wei}`);
62686
+ }
62687
+ const whole = wei / WEI_PER_UCD;
62688
+ const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
62689
+ return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
62690
+ }
62691
+ var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
62692
+ function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
62693
+ let totalWei = 0n;
62694
+ const counts = /* @__PURE__ */ new Map();
62695
+ for (const row of rows) {
62696
+ totalWei += parseSubgraphWei(row);
62697
+ const status = parseSubgraphLoanStatus(row.status);
62698
+ counts.set(status, (counts.get(status) ?? 0) + 1);
62699
+ }
62700
+ const byStatus = [];
62701
+ for (const status of STATUS_ORDINALS) {
62702
+ const count = counts.get(status);
62703
+ if (count === void 0) {
62704
+ continue;
62705
+ }
62706
+ byStatus.push({ status, statusLabel: LoanStatus[status], count });
62707
+ }
62708
+ return {
62709
+ borrower: borrower.toLowerCase(),
62710
+ loanCount: rows.length,
62711
+ totalUcdDebt: totalWei.toString(),
62712
+ totalUcdDebtHuman: weiToHumanUcdString(totalWei),
62713
+ byStatus,
62714
+ source: "subgraph",
62715
+ fetchedAt
62716
+ };
62717
+ }
62608
62718
  var POSITION_CORE_ABI = [
62609
62719
  "function getPositionDetails(bytes32) view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status, uint40 previousExpiryAt, uint16 totalTerm))"
62610
62720
  ];
@@ -62997,6 +63107,43 @@ var LoanQuery = class {
62997
63107
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
62998
63108
  return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
62999
63109
  }
63110
+ /**
63111
+ * Combined UCD debt + by-status counts for a borrower from ONE pass over the
63112
+ * subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
63113
+ * status labels, `source: "subgraph"`.
63114
+ *
63115
+ * INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
63116
+ * sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
63117
+ * failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
63118
+ * is no partial total.
63119
+ */
63120
+ async getBorrowerUcdDebtSummary(borrower) {
63121
+ const trimmed = typeof borrower === "string" ? borrower.trim() : "";
63122
+ if (!(0, import_ethers26.isAddress)(trimmed)) {
63123
+ return failure(
63124
+ new SDKError({
63125
+ message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
63126
+ category: "VALIDATION",
63127
+ severity: "LOW",
63128
+ context: { borrower: trimmed }
63129
+ })
63130
+ );
63131
+ }
63132
+ return tryCatchAsync(
63133
+ async () => {
63134
+ const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
63135
+ return buildBorrowerUcdDebtSummary(trimmed, rows);
63136
+ },
63137
+ (error) => error instanceof SDKError ? error : new SDKError({
63138
+ message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
63139
+ category: "SUBGRAPH",
63140
+ severity: "MEDIUM",
63141
+ originalError: error instanceof Error ? error : void 0,
63142
+ cause: error,
63143
+ context: { borrower: trimmed }
63144
+ })
63145
+ );
63146
+ }
63000
63147
  /**
63001
63148
  * Get active loans (status = ACTIVE)
63002
63149
  *
@@ -64522,7 +64669,35 @@ var GraphClient = class {
64522
64669
  await new Promise((r) => setTimeout(r, ms));
64523
64670
  }
64524
64671
  };
64525
- var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
64672
+ var GET_USER_POSITIONS_DOCUMENT = `
64673
+ query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64674
+ user(id: $borrower) {
64675
+ id
64676
+ positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64677
+ id
64678
+ pkpId
64679
+ borrower {
64680
+ createdAt
64681
+ id
64682
+ }
64683
+ # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64684
+ ucdMinted
64685
+ ucdPaid
64686
+ ucdDebt
64687
+ collateralRatio
64688
+ requestedCollateralRatio
64689
+ selectedTerm
64690
+ status
64691
+ createdAt
64692
+ createdAtBlock
64693
+ lastUpdated
64694
+ originalTerm
64695
+ remainingDebt
64696
+ expiryAt
64697
+ }
64698
+ }
64699
+ }
64700
+ `;
64526
64701
  function normalizePkpId2(pkpId) {
64527
64702
  const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
64528
64703
  if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
@@ -64840,35 +65015,7 @@ var DiamondHandsGraph = class {
64840
65015
  * Get user positions from subgraph
64841
65016
  */
64842
65017
  async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
64843
- const query = `
64844
- query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
64845
- user(id: $borrower) {
64846
- id
64847
- positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
64848
- id
64849
- pkpId
64850
- borrower {
64851
- createdAt
64852
- id
64853
- }
64854
- # btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
64855
- ucdMinted
64856
- ucdPaid
64857
- ucdDebt
64858
- collateralRatio
64859
- requestedCollateralRatio
64860
- selectedTerm
64861
- status
64862
- createdAt
64863
- createdAtBlock
64864
- lastUpdated
64865
- originalTerm
64866
- remainingDebt
64867
- expiryAt
64868
- }
64869
- }
64870
- }
64871
- `;
65018
+ const query = GET_USER_POSITIONS_DOCUMENT;
64872
65019
  const variables = {
64873
65020
  borrower: userAddress.toLowerCase(),
64874
65021
  first: first || void 0,
@@ -64886,6 +65033,45 @@ var DiamondHandsGraph = class {
64886
65033
  }
64887
65034
  return positions;
64888
65035
  }
65036
+ /**
65037
+ * Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
65038
+ * 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
65039
+ * coerces wei to a float and leaves `status` a string cast to the numeric enum).
65040
+ *
65041
+ * Deliberately issues the `GetUserPositions` document rather than a leaner one: the
65042
+ * lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
65043
+ * and that one is already listed, so this needs no server change. The extra fields
65044
+ * cost bytes, not round trips.
65045
+ *
65046
+ * Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
65047
+ */
65048
+ async getBorrowerDebtRows(borrower) {
65049
+ const borrowerId = borrower.toLowerCase();
65050
+ return collectBorrowerDebtRows(async (skip, first) => {
65051
+ const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
65052
+ borrower: borrowerId,
65053
+ first,
65054
+ skip,
65055
+ orderBy: "id",
65056
+ orderDirection: "asc"
65057
+ });
65058
+ if (result?.user == null) {
65059
+ if (skip > 0) {
65060
+ throw new Error(
65061
+ `getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
65062
+ );
65063
+ }
65064
+ return [];
65065
+ }
65066
+ const positions = result.user.positions;
65067
+ if (!Array.isArray(positions)) {
65068
+ throw new Error(
65069
+ `getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
65070
+ );
65071
+ }
65072
+ return positions.filter((p) => p != null);
65073
+ });
65074
+ }
64889
65075
  /**
64890
65076
  * Get user positions, plus an accurate total count.
64891
65077
  *
@@ -71054,6 +71240,603 @@ async function mintAgentPkp(params) {
71054
71240
  clearTimeout(timeout);
71055
71241
  }
71056
71242
  }
71243
+ var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
71244
+ function planAgentBinding(params) {
71245
+ const { isActive, record, nowSeconds } = params;
71246
+ if (isActive)
71247
+ return { kind: "reuse", agent: record.agent };
71248
+ const status = Number(record.status);
71249
+ if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
71250
+ return { kind: "register" };
71251
+ }
71252
+ if (status !== AGENT_STATUS.Active) {
71253
+ throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
71254
+ }
71255
+ if (Number(record.validUntil) > nowSeconds) {
71256
+ throw new Error(
71257
+ "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
71258
+ );
71259
+ }
71260
+ return { kind: "rotate" };
71261
+ }
71262
+ async function describeProviderChainMismatch(provider, chainId) {
71263
+ const actual = Number((await provider.getNetwork()).chainId);
71264
+ if (actual === chainId)
71265
+ return null;
71266
+ 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.`;
71267
+ }
71268
+ var TxValidationError2 = class extends Error {
71269
+ /**
71270
+ * @param subject What is being refused. Defaults to the server-returned transaction the
71271
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
71272
+ */
71273
+ constructor(msg, subject = "server-returned transaction") {
71274
+ super(`Refusing to sign ${subject}: ${msg}`);
71275
+ this.name = "TxValidationError";
71276
+ }
71277
+ };
71278
+ var SIGNABLE_FUNCTIONS2 = [
71279
+ "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)",
71280
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
71281
+ // used to sit here; it is not a function on any deployed contract — the
71282
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
71283
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
71284
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
71285
+ // it. A signable-function whitelist should not carry calldata shapes the
71286
+ // protocol cannot execute.
71287
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
71288
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
71289
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
71290
+ // Struct-version: matches the actual on-chain function signature and the
71291
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
71292
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
71293
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
71294
+ "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)",
71295
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
71296
+ // function reverts permanently. The trustless replacement
71297
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
71298
+ // entry when its LIT Action ships.
71299
+ "function approve(address spender, uint256 amount) external returns (bool)",
71300
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
71301
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
71302
+ // without an entry here it decoded as "<unparseable>" and the CLI's
71303
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
71304
+ // collateral had no client-side pin at all.
71305
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
71306
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
71307
+ // AgentModule; the parity test documents them as client-only.
71308
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
71309
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
71310
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
71311
+ // this too is client-only and never module-whitelisted.
71312
+ "function addAddress(string btcAddress) external"
71313
+ ];
71314
+ var IFACE2 = new import_ethers32.ethers.Interface(SIGNABLE_FUNCTIONS2);
71315
+ function encodeSignable2(fn, args) {
71316
+ return IFACE2.encodeFunctionData(fn, args);
71317
+ }
71318
+ function decodeSignable2(data) {
71319
+ try {
71320
+ const parsed = IFACE2.parseTransaction({ data });
71321
+ if (!parsed) {
71322
+ throw new TxValidationError2(
71323
+ `unsignedTx.data does not decode against the signable-function whitelist`
71324
+ );
71325
+ }
71326
+ return { name: parsed.name, args: parsed.args };
71327
+ } catch (e) {
71328
+ if (e instanceof TxValidationError2)
71329
+ throw e;
71330
+ throw new TxValidationError2(
71331
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
71332
+ );
71333
+ }
71334
+ }
71335
+ var MAX_GAS_LIMIT = 5000000n;
71336
+ var MAX_FEE_PER_GAS_WEI = 2000000000000n;
71337
+ var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
71338
+ var DEFAULT_FEE_CEILING = {
71339
+ maxGasLimit: MAX_GAS_LIMIT,
71340
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
71341
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
71342
+ };
71343
+ function fmtEth(wei) {
71344
+ return `${import_ethers34.ethers.formatEther(wei)} ETH`;
71345
+ }
71346
+ function fmtGwei(wei) {
71347
+ return `${import_ethers34.ethers.formatUnits(wei, "gwei")} gwei`;
71348
+ }
71349
+ function worstCaseFeeWei(gasLimit, maxFeePerGas) {
71350
+ if (gasLimit == null || maxFeePerGas == null)
71351
+ return null;
71352
+ return gasLimit * maxFeePerGas;
71353
+ }
71354
+ function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
71355
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
71356
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
71357
+ }
71358
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
71359
+ raise(
71360
+ `maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
71361
+ );
71362
+ }
71363
+ const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
71364
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
71365
+ raise(
71366
+ `worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
71367
+ );
71368
+ }
71369
+ }
71370
+ function eqAddr2(a, b) {
71371
+ if (!a || !b)
71372
+ return false;
71373
+ try {
71374
+ return import_ethers33.ethers.getAddress(a) === import_ethers33.ethers.getAddress(b);
71375
+ } catch {
71376
+ return false;
71377
+ }
71378
+ }
71379
+ function readToAddress2(tx2) {
71380
+ const to = tx2["to"];
71381
+ if (typeof to !== "string") {
71382
+ throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
71383
+ }
71384
+ return to;
71385
+ }
71386
+ function readData2(tx2) {
71387
+ const data = tx2["data"];
71388
+ if (typeof data !== "string" || !data.startsWith("0x")) {
71389
+ throw new TxValidationError2(`unsignedTx.data missing or malformed`);
71390
+ }
71391
+ return data;
71392
+ }
71393
+ function readChainId2(tx2) {
71394
+ const c = tx2["chainId"];
71395
+ if (c == null)
71396
+ return null;
71397
+ if (typeof c === "number")
71398
+ return c;
71399
+ if (typeof c === "string")
71400
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
71401
+ if (typeof c === "bigint")
71402
+ return Number(c);
71403
+ return null;
71404
+ }
71405
+ function readOptionalBigInt(tx2, key) {
71406
+ const v = tx2[key];
71407
+ if (v == null)
71408
+ return null;
71409
+ try {
71410
+ if (typeof v === "bigint")
71411
+ return v;
71412
+ if (typeof v === "number")
71413
+ return BigInt(v);
71414
+ if (typeof v === "string")
71415
+ return BigInt(v);
71416
+ return BigInt(v.toString());
71417
+ } catch {
71418
+ throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
71419
+ }
71420
+ }
71421
+ function readValue2(tx2) {
71422
+ const v = tx2["value"];
71423
+ if (v == null)
71424
+ return 0n;
71425
+ if (typeof v === "string")
71426
+ return BigInt(v);
71427
+ if (typeof v === "number")
71428
+ return BigInt(v);
71429
+ if (typeof v === "bigint")
71430
+ return v;
71431
+ const maybe = v;
71432
+ if (typeof maybe.toBigInt === "function")
71433
+ return maybe.toBigInt();
71434
+ if (typeof maybe.toString === "function")
71435
+ return BigInt(maybe.toString());
71436
+ throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
71437
+ }
71438
+ function normalizePositionId2(id) {
71439
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
71440
+ return import_ethers33.ethers.zeroPadValue(hex, 32).toLowerCase();
71441
+ }
71442
+ function requirePositionId(actual, expected) {
71443
+ const txPositionId = String(actual).toLowerCase();
71444
+ if (txPositionId !== normalizePositionId2(expected)) {
71445
+ throw new TxValidationError2(
71446
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
71447
+ );
71448
+ }
71449
+ }
71450
+ function validateUnsignedTx2(unsignedTx, expected, vctx) {
71451
+ const txChainId = readChainId2(unsignedTx);
71452
+ if (txChainId == null) {
71453
+ throw new TxValidationError2(
71454
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
71455
+ );
71456
+ }
71457
+ if (txChainId !== vctx.chainId) {
71458
+ throw new TxValidationError2(
71459
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
71460
+ );
71461
+ }
71462
+ const value = readValue2(unsignedTx);
71463
+ if (value !== 0n) {
71464
+ throw new TxValidationError2(
71465
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
71466
+ );
71467
+ }
71468
+ assertFeeCeiling(
71469
+ readOptionalBigInt(unsignedTx, "gasLimit"),
71470
+ readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
71471
+ (msg) => {
71472
+ throw new TxValidationError2(msg);
71473
+ },
71474
+ vctx.feeCeiling
71475
+ );
71476
+ const to = readToAddress2(unsignedTx);
71477
+ const data = readData2(unsignedTx);
71478
+ const { name, args } = decodeSignable2(data);
71479
+ const pm = vctx.contracts.PositionManager;
71480
+ switch (expected.kind) {
71481
+ case "mint": {
71482
+ if (name !== "mintUCD") {
71483
+ throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
71484
+ }
71485
+ if (!eqAddr2(to, pm)) {
71486
+ throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
71487
+ }
71488
+ requirePositionId(args[0], expected.positionId);
71489
+ const txMintAmount = BigInt(String(args[1]));
71490
+ if (txMintAmount.toString() !== expected.amountWei) {
71491
+ throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
71492
+ }
71493
+ const txMintFee = BigInt(String(args[2]));
71494
+ if (txMintFee.toString() !== expected.mintFeeWei) {
71495
+ throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
71496
+ }
71497
+ break;
71498
+ }
71499
+ case "repay": {
71500
+ if (name !== "makePayment") {
71501
+ throw new TxValidationError2(`expected makePayment, server returned ${name}`);
71502
+ }
71503
+ if (!eqAddr2(to, pm)) {
71504
+ throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
71505
+ }
71506
+ requirePositionId(args[0], expected.positionId);
71507
+ const txAmount = BigInt(String(args[1]));
71508
+ if (txAmount.toString() !== expected.amountWei) {
71509
+ throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
71510
+ }
71511
+ break;
71512
+ }
71513
+ case "extend": {
71514
+ if (name !== "extendPosition") {
71515
+ throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
71516
+ }
71517
+ if (!eqAddr2(to, pm)) {
71518
+ throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
71519
+ }
71520
+ requirePositionId(args[0], expected.positionId);
71521
+ const txTerm = Number(args[1]);
71522
+ if (txTerm !== expected.selectedTerm) {
71523
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71524
+ }
71525
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
71526
+ const txFee = BigInt(String(args[5]));
71527
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
71528
+ if (txFee > upper) {
71529
+ throw new TxValidationError2(
71530
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
71531
+ );
71532
+ }
71533
+ }
71534
+ break;
71535
+ }
71536
+ case "withdraw-btc": {
71537
+ if (name !== "withdrawBTC") {
71538
+ throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
71539
+ }
71540
+ if (!eqAddr2(to, pm)) {
71541
+ throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
71542
+ }
71543
+ const paramsTuple = args[0];
71544
+ requirePositionId(paramsTuple[0], expected.positionId);
71545
+ const txWithdrawalAddress = String(paramsTuple[5]);
71546
+ if (txWithdrawalAddress !== expected.btcAddress) {
71547
+ throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
71548
+ }
71549
+ if (expected.upperBoundTotalDeduction != null) {
71550
+ const txDeduction = BigInt(String(paramsTuple[6]));
71551
+ const upper = BigInt(expected.upperBoundTotalDeduction);
71552
+ if (txDeduction > upper) {
71553
+ throw new TxValidationError2(
71554
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
71555
+ );
71556
+ }
71557
+ }
71558
+ break;
71559
+ }
71560
+ case "ucd-approve": {
71561
+ if (name !== "approve") {
71562
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71563
+ }
71564
+ const ucd = vctx.contracts.UCDToken;
71565
+ if (!eqAddr2(to, ucd)) {
71566
+ throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
71567
+ }
71568
+ const spender = String(args[0]);
71569
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
71570
+ if (!ok2) {
71571
+ throw new TxValidationError2(
71572
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
71573
+ );
71574
+ }
71575
+ const amt = BigInt(String(args[1]));
71576
+ const min = BigInt(expected.minAmountWei);
71577
+ if (amt < min) {
71578
+ throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
71579
+ }
71580
+ const SANITY_MAX = min * 1000n;
71581
+ if (amt > SANITY_MAX) {
71582
+ throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
71583
+ }
71584
+ break;
71585
+ }
71586
+ case "create-position": {
71587
+ if (name !== "createPosition") {
71588
+ throw new TxValidationError2(`expected createPosition, server returned ${name}`);
71589
+ }
71590
+ if (!eqAddr2(to, pm)) {
71591
+ throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
71592
+ }
71593
+ const txTerm = BigInt(String(args[4]));
71594
+ if (txTerm !== BigInt(expected.selectedTerm)) {
71595
+ throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
71596
+ }
71597
+ break;
71598
+ }
71599
+ case "set-position-delegate": {
71600
+ if (name !== "setPositionDelegate") {
71601
+ throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
71602
+ }
71603
+ if (!eqAddr2(to, expected.registryAddress)) {
71604
+ throw new TxValidationError2(
71605
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
71606
+ );
71607
+ }
71608
+ requirePositionId(args[0], expected.positionId);
71609
+ const txDelegate = String(args[1]);
71610
+ if (!eqAddr2(txDelegate, expected.delegate)) {
71611
+ throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
71612
+ }
71613
+ break;
71614
+ }
71615
+ case "bwar-add-address": {
71616
+ if (name !== "addAddress") {
71617
+ throw new TxValidationError2(`expected addAddress, decoded ${name}`);
71618
+ }
71619
+ if (!eqAddr2(to, expected.registryAddress)) {
71620
+ throw new TxValidationError2(
71621
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
71622
+ );
71623
+ }
71624
+ if (String(args[0]) !== expected.btcAddress) {
71625
+ throw new TxValidationError2(
71626
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
71627
+ );
71628
+ }
71629
+ break;
71630
+ }
71631
+ case "stablecoin-approve": {
71632
+ if (name !== "approve") {
71633
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71634
+ }
71635
+ if (!eqAddr2(to, expected.tokenAddress)) {
71636
+ throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
71637
+ }
71638
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71639
+ throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
71640
+ }
71641
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
71642
+ throw new TxValidationError2(
71643
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
71644
+ );
71645
+ }
71646
+ break;
71647
+ }
71648
+ case "ucd-approve-controller": {
71649
+ if (name !== "approve") {
71650
+ throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
71651
+ }
71652
+ if (!eqAddr2(to, expected.ucdTokenAddress)) {
71653
+ throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
71654
+ }
71655
+ if (!eqAddr2(String(args[0]), expected.spender)) {
71656
+ throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
71657
+ }
71658
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
71659
+ throw new TxValidationError2(
71660
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
71661
+ );
71662
+ }
71663
+ break;
71664
+ }
71665
+ case "psm-swap": {
71666
+ if (name !== "swap")
71667
+ throw new TxValidationError2(`expected swap, server returned ${name}`);
71668
+ if (!eqAddr2(to, expected.psmAddress)) {
71669
+ throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
71670
+ }
71671
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71672
+ throw new TxValidationError2(`swap stablecoin mismatch`);
71673
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
71674
+ throw new TxValidationError2(`swap amountIn mismatch`);
71675
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71676
+ throw new TxValidationError2(`swap minUcdOut mismatch`);
71677
+ if (BigInt(expected.minOut) === 0n) {
71678
+ throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71679
+ }
71680
+ break;
71681
+ }
71682
+ case "psm-redeem": {
71683
+ if (name !== "redeem")
71684
+ throw new TxValidationError2(`expected redeem, server returned ${name}`);
71685
+ if (!eqAddr2(to, expected.psmAddress)) {
71686
+ throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
71687
+ }
71688
+ if (!eqAddr2(String(args[0]), expected.stablecoin))
71689
+ throw new TxValidationError2(`redeem stablecoin mismatch`);
71690
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
71691
+ throw new TxValidationError2(`redeem ucdAmount mismatch`);
71692
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
71693
+ throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
71694
+ if (BigInt(expected.minOut) === 0n) {
71695
+ throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
71696
+ }
71697
+ break;
71698
+ }
71699
+ default: {
71700
+ const _exhaustive = expected;
71701
+ throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
71702
+ }
71703
+ }
71704
+ }
71705
+ function buildPsmApproveTx(p) {
71706
+ return {
71707
+ to: p.token,
71708
+ data: encodeSignable2("approve", [p.spender, p.amount]),
71709
+ value: "0x0",
71710
+ chainId: p.chainId
71711
+ };
71712
+ }
71713
+ function buildPsmSwapTx2(p) {
71714
+ return {
71715
+ to: p.psm,
71716
+ data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
71717
+ value: "0x0",
71718
+ chainId: p.chainId
71719
+ };
71720
+ }
71721
+ function buildPsmRedeemTx2(p) {
71722
+ return {
71723
+ to: p.psm,
71724
+ data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
71725
+ value: "0x0",
71726
+ chainId: p.chainId
71727
+ };
71728
+ }
71729
+ var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
71730
+ var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
71731
+ function psmExchangeReadsFromProvider(provider, psmAddress) {
71732
+ const psm = new import_ethers31.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
71733
+ return {
71734
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
71735
+ allowance: async (token, owner, spender) => await new import_ethers31.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
71736
+ };
71737
+ }
71738
+ var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
71739
+ function requireAddress(direction, label, value) {
71740
+ if (!value || !import_ethers31.ethers.isAddress(value)) {
71741
+ throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
71742
+ }
71743
+ return import_ethers31.ethers.getAddress(value);
71744
+ }
71745
+ async function planPsmExchange(params) {
71746
+ const { direction, amountIn, minOut, vctx, reads } = params;
71747
+ const chainId = vctx.chainId;
71748
+ if (amountIn <= 0n) {
71749
+ throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
71750
+ }
71751
+ if (minOut <= 0n) {
71752
+ throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
71753
+ }
71754
+ const owner = requireAddress(direction, "owner", params.owner);
71755
+ const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
71756
+ const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
71757
+ const isSwap = direction === "swap";
71758
+ const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
71759
+ const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
71760
+ if (!await reads.isStablecoinSupported(stablecoin)) {
71761
+ throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
71762
+ }
71763
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
71764
+ const allowanceBefore = await reads.allowance(token, owner, spender);
71765
+ const approvals = [];
71766
+ if (allowanceBefore < amountIn) {
71767
+ if (allowanceBefore > 0n) {
71768
+ approvals.push({
71769
+ step: "reset-approve",
71770
+ tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
71771
+ expected: approveExpected(0n)
71772
+ });
71773
+ }
71774
+ approvals.push({
71775
+ step: "approve",
71776
+ tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
71777
+ expected: approveExpected(amountIn)
71778
+ });
71779
+ }
71780
+ const exec = isSwap ? {
71781
+ step: "swap",
71782
+ tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
71783
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
71784
+ } : {
71785
+ step: "redeem",
71786
+ tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
71787
+ expected: {
71788
+ kind: "psm-redeem",
71789
+ psmAddress: psm,
71790
+ stablecoin,
71791
+ amountUcdWei: amountIn.toString(),
71792
+ minOut: minOut.toString()
71793
+ }
71794
+ };
71795
+ for (const leg of [...approvals, exec]) {
71796
+ validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
71797
+ }
71798
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
71799
+ }
71800
+ async function executePsmPlan(plan, signer, vctx) {
71801
+ const approvalHashes = [];
71802
+ 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.`;
71803
+ const sendLeg = async (leg) => {
71804
+ const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
71805
+ validateUnsignedTx2({ ...request }, leg.expected, vctx);
71806
+ const sent = await signer.sendTransaction(request);
71807
+ const receipt = await sent.wait();
71808
+ if (!receipt)
71809
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
71810
+ if (receipt.status !== 1)
71811
+ throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
71812
+ return { hash: sent.hash, blockNumber: receipt.blockNumber };
71813
+ };
71814
+ for (const leg of plan.approvals) {
71815
+ const landed = await sendLeg(leg).catch((e) => {
71816
+ throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71817
+ });
71818
+ approvalHashes.push(landed.hash);
71819
+ }
71820
+ const exec = await sendLeg(plan.exec).catch((e) => {
71821
+ throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
71822
+ });
71823
+ return { ...exec, approvalHashes };
71824
+ }
71825
+ var LIT_ACTION_CHAIN_NAMES = Object.freeze({
71826
+ 1: "ethereum",
71827
+ 11155111: "sepolia",
71828
+ 1337: "hardhat",
71829
+ 31337: "hardhat"
71830
+ });
71831
+ function litActionChainNameForChainId(chainId) {
71832
+ const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
71833
+ if (!name) {
71834
+ throw new Error(
71835
+ `Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
71836
+ );
71837
+ }
71838
+ return name;
71839
+ }
71057
71840
  var MockTokenManager = class {
71058
71841
  config;
71059
71842
  constructor(config) {
@@ -72027,6 +72810,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72027
72810
  */
72028
72811
  static async create(config) {
72029
72812
  const userProvidedServiceEndpoint = config.serviceEndpoint;
72813
+ if (typeof config.chainId === "number" && config.provider) {
72814
+ const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
72815
+ if (mismatch) {
72816
+ return failure(
72817
+ new SDKError({
72818
+ message: mismatch,
72819
+ category: "CONFIGURATION",
72820
+ severity: "HIGH"
72821
+ /* HIGH */
72822
+ })
72823
+ );
72824
+ }
72825
+ }
72030
72826
  const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
72031
72827
  if (userProvidedServiceEndpoint) {
72032
72828
  enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
@@ -72677,6 +73473,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72677
73473
  if (this.config.debug) {
72678
73474
  log.info(` Position PKP ID: ${position2.pkpId}`);
72679
73475
  }
73476
+ const termsResult = await this.getTermsWithFees();
73477
+ if (!termsResult.success) {
73478
+ return {
73479
+ success: false,
73480
+ error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
73481
+ };
73482
+ }
73483
+ const positionTermMonths = Number(position2.selectedTerm);
73484
+ const positionTerm = termsResult.value.terms.find(
73485
+ (term) => term.termMonths === positionTermMonths
73486
+ );
73487
+ if (!positionTerm) {
73488
+ return {
73489
+ success: false,
73490
+ error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
73491
+ };
73492
+ }
73493
+ const currentDebtWei = BigInt(position2.ucdDebt);
73494
+ const baseFeeWei = baseMintFeeWei(
73495
+ requestAmountWei,
73496
+ positionTerm.originationFeeBps
73497
+ );
73498
+ if (debtAfterMintExceedsLoanCap({
73499
+ currentDebtWei,
73500
+ mintAmountWei: requestAmountWei,
73501
+ mintFeeWei: baseFeeWei,
73502
+ maxLoanWei: maxLoanValueWei
73503
+ })) {
73504
+ const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
73505
+ const maxPrincipalUcd = Number(
73506
+ maxPrincipalWithinLoanCap({
73507
+ maxLoanWei: maxLoanValueWei,
73508
+ currentDebtWei,
73509
+ originationFeeBps: positionTerm.originationFeeBps
73510
+ }) / BigInt(10 ** 18)
73511
+ );
73512
+ return {
73513
+ success: false,
73514
+ 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.`
73515
+ };
73516
+ }
73517
+ if (this.config.debug) {
73518
+ log.info(
73519
+ `\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers14.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD`,
73520
+ {}
73521
+ );
73522
+ }
72680
73523
  let pkpPublicKey;
72681
73524
  let pkpEthAddress;
72682
73525
  const pkpCache = this.cacheManager.getCache("pkp-data", {
@@ -72766,7 +73609,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
72766
73609
  ` UCDController: ${contracts?.UCDController || "MISSING"}`
72767
73610
  );
72768
73611
  }
72769
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
73612
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
72770
73613
  const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
72771
73614
  if (this.config.debug) {
72772
73615
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -73366,6 +74209,25 @@ Error data: none`
73366
74209
  }
73367
74210
  const selector = simError.selector;
73368
74211
  const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
74212
+ const MINT_GUARD_CODES = {
74213
+ "1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
74214
+ "2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
74215
+ "3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
74216
+ };
74217
+ let loanCapDiagnostics = "";
74218
+ if (selector === "0xe6dd4d41") {
74219
+ const guardCode = BigInt(
74220
+ "0x" + String(simError.data).slice(10).padStart(64, "0")
74221
+ ).toString();
74222
+ const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
74223
+ loanCapDiagnostics = `
74224
+
74225
+ MintGuardFailed(${guardCode}): ${guardMeaning}
74226
+ Lit mintAmount: ${validationResponse.mintAmount}
74227
+ Lit mintFee: ${validationResponse.mintFee}
74228
+ Lit newDebt: ${validationResponse.newDebt}
74229
+ Protocol maximum: ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
74230
+ }
73369
74231
  const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
73370
74232
  selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
73371
74233
  selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
@@ -73411,7 +74273,7 @@ Quantum Timing Analysis:
73411
74273
  Error selector: ${selector}
73412
74274
  Error data: ${simError.data}
73413
74275
  Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
73414
- Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
74276
+ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
73415
74277
  );
73416
74278
  }
73417
74279
  const tx2 = await sendEip1559Transaction({
@@ -76019,7 +76881,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76019
76881
  ` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
76020
76882
  );
76021
76883
  }
76022
- const chain = this.config.chain || (Number(network.chainId) === 1 ? "ethereum" : "sepolia");
76884
+ const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
76023
76885
  const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
76024
76886
  if (this.config.debug) {
76025
76887
  log.info(` Network: ${chain} (chainId: ${network.chainId})`);
@@ -76574,13 +77436,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
76574
77436
  return { success: false, error: "Failed to resolve PKP public key" };
76575
77437
  }
76576
77438
  const chipotlePkpAddress = (0, import_ethers14.computeAddress)(publicKey);
76577
- const STANDALONE_CHAIN_NAMES = {
76578
- 1: "ethereum",
76579
- 11155111: "sepolia",
76580
- 1337: "hardhat",
76581
- 31337: "hardhat"
76582
- };
76583
- const chainName = STANDALONE_CHAIN_NAMES[chainId];
77439
+ const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
76584
77440
  if (!chainName) {
76585
77441
  return {
76586
77442
  success: false,
@@ -77802,6 +78658,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77802
78658
  async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
77803
78659
  return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
77804
78660
  }
78661
+ /**
78662
+ * Combined UCD debt (canonical wei string + display string) and by-status loan
78663
+ * counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
78664
+ * an INDEXED, informational figure that lags writes; never size a transaction
78665
+ * from it (repayments read the chain via `getPositionDetailsView`).
78666
+ *
78667
+ * Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
78668
+ * failure or past 10,000 positions; never returns a partial total.
78669
+ */
78670
+ async getBorrowerUcdDebtSummary(borrower) {
78671
+ return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
78672
+ }
77805
78673
  /**
77806
78674
  * Get all active loans
77807
78675
  *
@@ -77927,11 +78795,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77927
78795
  }
77928
78796
  /**
77929
78797
  * Execute a PSM stablecoin → UCD swap.
77930
- * Handles stablecoin approval to the PSM contract if the current allowance is insufficient.
78798
+ * Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
78799
+ * partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
77931
78800
  *
77932
78801
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
77933
78802
  * @param params.amountWei - Stablecoin amount in native decimals (bigint)
77934
- * @param params.minUcdOutWei - Minimum UCD to receive; reverts if below this (1% slippage guard)
78803
+ * @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
77935
78804
  * @param params.signer - Connected signer for the approval and swap transactions
77936
78805
  */
77937
78806
  async psmSwap(params) {
@@ -77941,32 +78810,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77941
78810
  "SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
77942
78811
  );
77943
78812
  }
77944
- const signerAddress = await params.signer.getAddress();
77945
- const erc20Abi = [
77946
- "function allowance(address owner, address spender) view returns (uint256)",
77947
- "function approve(address spender, uint256 amount) returns (bool)"
77948
- ];
77949
- const stablecoin = new import_ethers14.Contract(params.stablecoinAddress, erc20Abi, params.signer);
77950
- const allowance = await stablecoin.allowance(signerAddress, psmAddress);
77951
- if (allowance < params.amountWei) {
77952
- const approveTx = await stablecoin.approve(psmAddress, import_ethers14.MaxUint256);
77953
- await approveTx.wait();
77954
- }
77955
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77956
- const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
77957
- const receipt = await tx2.wait();
77958
- if (!receipt)
77959
- throw new Error("PSM swap transaction receipt unavailable");
77960
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78813
+ return this.runPsmExchange({
78814
+ direction: "swap",
78815
+ signer: params.signer,
78816
+ addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
78817
+ amountIn: params.amountWei,
78818
+ minOut: params.minUcdOutWei
78819
+ });
77961
78820
  }
77962
78821
  /**
77963
78822
  * Execute a PSM UCD → stablecoin redeem.
77964
- * Handles UCD approval to UCDController (not PSM) to satisfy the M-4 burn allowance guard:
77965
- * UCDToken.burn(from, amount) calls _spendAllowance(from, msg.sender=ucdController, amount).
78823
+ * Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
78824
+ * M-4 burn allowance guard: UCDToken.burn(from, amount) calls
78825
+ * _spendAllowance(from, msg.sender=ucdController, amount).
77966
78826
  *
77967
78827
  * @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
77968
78828
  * @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
77969
- * @param params.minStablecoinOutWei - Minimum stablecoin to receive (slippage guard)
78829
+ * @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
77970
78830
  * @param params.signer - Connected signer
77971
78831
  */
77972
78832
  async psmRedeem(params) {
@@ -77979,23 +78839,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
77979
78839
  throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
77980
78840
  if (!ucdControllerAddress)
77981
78841
  throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
77982
- const signerAddress = await params.signer.getAddress();
77983
- const erc20Abi = [
77984
- "function allowance(address owner, address spender) view returns (uint256)",
77985
- "function approve(address spender, uint256 amount) returns (bool)"
77986
- ];
77987
- const ucdToken = new import_ethers14.Contract(ucdAddress, erc20Abi, params.signer);
77988
- const allowance = await ucdToken.allowance(signerAddress, ucdControllerAddress);
77989
- if (allowance < params.ucdAmountWei) {
77990
- const approveTx = await ucdToken.approve(ucdControllerAddress, import_ethers14.MaxUint256);
77991
- await approveTx.wait();
77992
- }
77993
- const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
77994
- const tx2 = await psm.redeem(params.stablecoinAddress, params.ucdAmountWei, params.minStablecoinOutWei);
77995
- const receipt = await tx2.wait();
77996
- if (!receipt)
77997
- throw new Error("PSM redeem transaction receipt unavailable");
77998
- return { hash: tx2.hash, blockNumber: receipt.blockNumber };
78842
+ return this.runPsmExchange({
78843
+ direction: "redeem",
78844
+ signer: params.signer,
78845
+ addresses: {
78846
+ psm: psmAddress,
78847
+ stablecoin: params.stablecoinAddress,
78848
+ ucdToken: ucdAddress,
78849
+ ucdController: ucdControllerAddress
78850
+ },
78851
+ amountIn: params.ucdAmountWei,
78852
+ minOut: params.minStablecoinOutWei
78853
+ });
78854
+ }
78855
+ /**
78856
+ * Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
78857
+ * The signer's chain must match the SDK's configured chain — the addresses came from it.
78858
+ */
78859
+ async runPsmExchange(params) {
78860
+ const provider = params.signer.provider;
78861
+ if (!provider) {
78862
+ throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
78863
+ }
78864
+ const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
78865
+ if (typeof configuredChainId !== "number") {
78866
+ throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
78867
+ }
78868
+ const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
78869
+ if (mismatch)
78870
+ throw new Error(mismatch);
78871
+ const vctx = {
78872
+ chainId: configuredChainId,
78873
+ network: String(configuredChainId),
78874
+ contracts: {}
78875
+ };
78876
+ const plan = await planPsmExchange({
78877
+ direction: params.direction,
78878
+ owner: await params.signer.getAddress(),
78879
+ addresses: params.addresses,
78880
+ amountIn: params.amountIn,
78881
+ minOut: params.minOut,
78882
+ vctx,
78883
+ reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
78884
+ });
78885
+ const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
78886
+ return { hash, blockNumber };
77999
78887
  }
78000
78888
  /**
78001
78889
  * Wait for the subgraph to index up to (and including) the given block number.
@@ -78176,18 +79064,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
78176
79064
  const user = await signer.getAddress();
78177
79065
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
78178
79066
  let agentAddress;
78179
- const hasActiveAgent = await registry.isAgentActive(user);
78180
- if (hasActiveAgent) {
78181
- agentAddress = (await registry.agentOf(user)).agent;
79067
+ const [isActive, record, latestBlock] = await Promise.all([
79068
+ registry.isAgentActive(user),
79069
+ registry.agentOf(user),
79070
+ this.getProviderOrThrow().getBlock("latest")
79071
+ ]);
79072
+ if (!latestBlock) {
79073
+ throw new SDKError({
79074
+ message: "Could not read the latest block to check the agent registration's expiry",
79075
+ category: "NETWORK",
79076
+ severity: "HIGH"
79077
+ /* HIGH */
79078
+ });
79079
+ }
79080
+ const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
79081
+ if (plan.kind === "reuse") {
79082
+ agentAddress = plan.agent;
78182
79083
  } else {
78183
79084
  agentAddress = await mintAgentPkp({
78184
79085
  serviceEndpoint: this.config.serviceEndpoint,
78185
79086
  authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
78186
79087
  });
78187
79088
  const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
78188
- const validUntil = Math.floor(Date.now() / 1e3) + validitySeconds;
78189
- const regTx = await registry.registerAgent(user, agentAddress, validUntil);
78190
- await regTx.wait();
79089
+ const validUntil = latestBlock.timestamp + validitySeconds;
79090
+ const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
79091
+ await bindTx.wait();
78191
79092
  }
78192
79093
  const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
78193
79094
  () => null
@@ -79579,7 +80480,552 @@ var SUPPORTED_STABLECOINS = `
79579
80480
  }`;
79580
80481
 
79581
80482
  // src/boundary/upstream/real/psm-calls.ts
79582
- var import_ethers32 = require("ethers");
80483
+ var import_ethers42 = require("ethers");
80484
+
80485
+ // node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
80486
+ var import_ethers36 = require("ethers");
80487
+ var import_ethers37 = require("ethers");
80488
+ var import_ethers38 = require("ethers");
80489
+ var import_ethers39 = require("ethers");
80490
+ var import_ethers40 = require("ethers");
80491
+ var import_ethers41 = require("ethers");
80492
+ var TxValidationError3 = class extends Error {
80493
+ /**
80494
+ * @param subject What is being refused. Defaults to the server-returned transaction the
80495
+ * validator exists for; client-built flows (the PSM exchange) name themselves instead.
80496
+ */
80497
+ constructor(msg, subject = "server-returned transaction") {
80498
+ super(`Refusing to sign ${subject}: ${msg}`);
80499
+ this.name = "TxValidationError";
80500
+ }
80501
+ };
80502
+ var SIGNABLE_FUNCTIONS3 = [
80503
+ "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)",
80504
+ // `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
80505
+ // used to sit here; it is not a function on any deployed contract — the
80506
+ // compiled PositionManager ABI has no `repay*` function at all, and the name
80507
+ // survives only in `archive/` prototypes. Nothing in lit-ops-server, the
80508
+ // lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
80509
+ // it. A signable-function whitelist should not carry calldata shapes the
80510
+ // protocol cannot execute.
80511
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
80512
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
80513
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
80514
+ // Struct-version: matches the actual on-chain function signature and the
80515
+ // SDK's calldata builder. An earlier 3-arg declaration was stale and would
80516
+ // silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
80517
+ // contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
80518
+ "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)",
80519
+ // `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
80520
+ // function reverts permanently. The trustless replacement
80521
+ // (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
80522
+ // entry when its LIT Action ships.
80523
+ "function approve(address spender, uint256 amount) external returns (bool)",
80524
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
80525
+ // Position creation. Signed opaquely by the SDK (like withdrawBTC), so
80526
+ // without an entry here it decoded as "<unparseable>" and the CLI's
80527
+ // WithdrawGuard waved it through — the flow that locks the user's BTC
80528
+ // collateral had no client-side pin at all.
80529
+ "function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
80530
+ // SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
80531
+ // AgentModule; the parity test documents them as client-only.
80532
+ "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
80533
+ "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
80534
+ // BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
80535
+ // this too is client-only and never module-whitelisted.
80536
+ "function addAddress(string btcAddress) external"
80537
+ ];
80538
+ var IFACE3 = new import_ethers36.ethers.Interface(SIGNABLE_FUNCTIONS3);
80539
+ function encodeSignable3(fn, args) {
80540
+ return IFACE3.encodeFunctionData(fn, args);
80541
+ }
80542
+ function decodeSignable3(data) {
80543
+ try {
80544
+ const parsed = IFACE3.parseTransaction({ data });
80545
+ if (!parsed) {
80546
+ throw new TxValidationError3(
80547
+ `unsignedTx.data does not decode against the signable-function whitelist`
80548
+ );
80549
+ }
80550
+ return { name: parsed.name, args: parsed.args };
80551
+ } catch (e) {
80552
+ if (e instanceof TxValidationError3)
80553
+ throw e;
80554
+ throw new TxValidationError3(
80555
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
80556
+ );
80557
+ }
80558
+ }
80559
+ var MAX_GAS_LIMIT2 = 5000000n;
80560
+ var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
80561
+ var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
80562
+ var DEFAULT_FEE_CEILING2 = {
80563
+ maxGasLimit: MAX_GAS_LIMIT2,
80564
+ maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
80565
+ maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
80566
+ };
80567
+ function fmtEth2(wei) {
80568
+ return `${import_ethers37.ethers.formatEther(wei)} ETH`;
80569
+ }
80570
+ function fmtGwei2(wei) {
80571
+ return `${import_ethers37.ethers.formatUnits(wei, "gwei")} gwei`;
80572
+ }
80573
+ function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
80574
+ if (gasLimit == null || maxFeePerGas == null)
80575
+ return null;
80576
+ return gasLimit * maxFeePerGas;
80577
+ }
80578
+ function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
80579
+ if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
80580
+ raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
80581
+ }
80582
+ if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
80583
+ raise(
80584
+ `maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
80585
+ );
80586
+ }
80587
+ const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
80588
+ if (worst != null && worst > ceiling.maxTxFeeWei) {
80589
+ raise(
80590
+ `worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
80591
+ );
80592
+ }
80593
+ }
80594
+ function eqAddr3(a, b) {
80595
+ if (!a || !b)
80596
+ return false;
80597
+ try {
80598
+ return import_ethers38.ethers.getAddress(a) === import_ethers38.ethers.getAddress(b);
80599
+ } catch {
80600
+ return false;
80601
+ }
80602
+ }
80603
+ function readToAddress3(tx2) {
80604
+ const to = tx2["to"];
80605
+ if (typeof to !== "string") {
80606
+ throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
80607
+ }
80608
+ return to;
80609
+ }
80610
+ function readData3(tx2) {
80611
+ const data = tx2["data"];
80612
+ if (typeof data !== "string" || !data.startsWith("0x")) {
80613
+ throw new TxValidationError3(`unsignedTx.data missing or malformed`);
80614
+ }
80615
+ return data;
80616
+ }
80617
+ function readChainId3(tx2) {
80618
+ const c = tx2["chainId"];
80619
+ if (c == null)
80620
+ return null;
80621
+ if (typeof c === "number")
80622
+ return c;
80623
+ if (typeof c === "string")
80624
+ return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
80625
+ if (typeof c === "bigint")
80626
+ return Number(c);
80627
+ return null;
80628
+ }
80629
+ function readOptionalBigInt2(tx2, key) {
80630
+ const v = tx2[key];
80631
+ if (v == null)
80632
+ return null;
80633
+ try {
80634
+ if (typeof v === "bigint")
80635
+ return v;
80636
+ if (typeof v === "number")
80637
+ return BigInt(v);
80638
+ if (typeof v === "string")
80639
+ return BigInt(v);
80640
+ return BigInt(v.toString());
80641
+ } catch {
80642
+ throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
80643
+ }
80644
+ }
80645
+ function readValue3(tx2) {
80646
+ const v = tx2["value"];
80647
+ if (v == null)
80648
+ return 0n;
80649
+ if (typeof v === "string")
80650
+ return BigInt(v);
80651
+ if (typeof v === "number")
80652
+ return BigInt(v);
80653
+ if (typeof v === "bigint")
80654
+ return v;
80655
+ const maybe = v;
80656
+ if (typeof maybe.toBigInt === "function")
80657
+ return maybe.toBigInt();
80658
+ if (typeof maybe.toString === "function")
80659
+ return BigInt(maybe.toString());
80660
+ throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
80661
+ }
80662
+ function normalizePositionId3(id) {
80663
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
80664
+ return import_ethers38.ethers.zeroPadValue(hex, 32).toLowerCase();
80665
+ }
80666
+ function requirePositionId2(actual, expected) {
80667
+ const txPositionId = String(actual).toLowerCase();
80668
+ if (txPositionId !== normalizePositionId3(expected)) {
80669
+ throw new TxValidationError3(
80670
+ `positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
80671
+ );
80672
+ }
80673
+ }
80674
+ function validateUnsignedTx3(unsignedTx, expected, vctx) {
80675
+ const txChainId = readChainId3(unsignedTx);
80676
+ if (txChainId == null) {
80677
+ throw new TxValidationError3(
80678
+ `unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
80679
+ );
80680
+ }
80681
+ if (txChainId !== vctx.chainId) {
80682
+ throw new TxValidationError3(
80683
+ `chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
80684
+ );
80685
+ }
80686
+ const value = readValue3(unsignedTx);
80687
+ if (value !== 0n) {
80688
+ throw new TxValidationError3(
80689
+ `unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
80690
+ );
80691
+ }
80692
+ assertFeeCeiling2(
80693
+ readOptionalBigInt2(unsignedTx, "gasLimit"),
80694
+ readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
80695
+ (msg) => {
80696
+ throw new TxValidationError3(msg);
80697
+ },
80698
+ vctx.feeCeiling
80699
+ );
80700
+ const to = readToAddress3(unsignedTx);
80701
+ const data = readData3(unsignedTx);
80702
+ const { name, args } = decodeSignable3(data);
80703
+ const pm = vctx.contracts.PositionManager;
80704
+ switch (expected.kind) {
80705
+ case "mint": {
80706
+ if (name !== "mintUCD") {
80707
+ throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
80708
+ }
80709
+ if (!eqAddr3(to, pm)) {
80710
+ throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
80711
+ }
80712
+ requirePositionId2(args[0], expected.positionId);
80713
+ const txMintAmount = BigInt(String(args[1]));
80714
+ if (txMintAmount.toString() !== expected.amountWei) {
80715
+ throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
80716
+ }
80717
+ const txMintFee = BigInt(String(args[2]));
80718
+ if (txMintFee.toString() !== expected.mintFeeWei) {
80719
+ throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
80720
+ }
80721
+ break;
80722
+ }
80723
+ case "repay": {
80724
+ if (name !== "makePayment") {
80725
+ throw new TxValidationError3(`expected makePayment, server returned ${name}`);
80726
+ }
80727
+ if (!eqAddr3(to, pm)) {
80728
+ throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
80729
+ }
80730
+ requirePositionId2(args[0], expected.positionId);
80731
+ const txAmount = BigInt(String(args[1]));
80732
+ if (txAmount.toString() !== expected.amountWei) {
80733
+ throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
80734
+ }
80735
+ break;
80736
+ }
80737
+ case "extend": {
80738
+ if (name !== "extendPosition") {
80739
+ throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
80740
+ }
80741
+ if (!eqAddr3(to, pm)) {
80742
+ throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
80743
+ }
80744
+ requirePositionId2(args[0], expected.positionId);
80745
+ const txTerm = Number(args[1]);
80746
+ if (txTerm !== expected.selectedTerm) {
80747
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80748
+ }
80749
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
80750
+ const txFee = BigInt(String(args[5]));
80751
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
80752
+ if (txFee > upper) {
80753
+ throw new TxValidationError3(
80754
+ `proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
80755
+ );
80756
+ }
80757
+ }
80758
+ break;
80759
+ }
80760
+ case "withdraw-btc": {
80761
+ if (name !== "withdrawBTC") {
80762
+ throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
80763
+ }
80764
+ if (!eqAddr3(to, pm)) {
80765
+ throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
80766
+ }
80767
+ const paramsTuple = args[0];
80768
+ requirePositionId2(paramsTuple[0], expected.positionId);
80769
+ const txWithdrawalAddress = String(paramsTuple[5]);
80770
+ if (txWithdrawalAddress !== expected.btcAddress) {
80771
+ throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
80772
+ }
80773
+ if (expected.upperBoundTotalDeduction != null) {
80774
+ const txDeduction = BigInt(String(paramsTuple[6]));
80775
+ const upper = BigInt(expected.upperBoundTotalDeduction);
80776
+ if (txDeduction > upper) {
80777
+ throw new TxValidationError3(
80778
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
80779
+ );
80780
+ }
80781
+ }
80782
+ break;
80783
+ }
80784
+ case "ucd-approve": {
80785
+ if (name !== "approve") {
80786
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80787
+ }
80788
+ const ucd = vctx.contracts.UCDToken;
80789
+ if (!eqAddr3(to, ucd)) {
80790
+ throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
80791
+ }
80792
+ const spender = String(args[0]);
80793
+ const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
80794
+ if (!ok2) {
80795
+ throw new TxValidationError3(
80796
+ `approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
80797
+ );
80798
+ }
80799
+ const amt = BigInt(String(args[1]));
80800
+ const min = BigInt(expected.minAmountWei);
80801
+ if (amt < min) {
80802
+ throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
80803
+ }
80804
+ const SANITY_MAX = min * 1000n;
80805
+ if (amt > SANITY_MAX) {
80806
+ throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
80807
+ }
80808
+ break;
80809
+ }
80810
+ case "create-position": {
80811
+ if (name !== "createPosition") {
80812
+ throw new TxValidationError3(`expected createPosition, server returned ${name}`);
80813
+ }
80814
+ if (!eqAddr3(to, pm)) {
80815
+ throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
80816
+ }
80817
+ const txTerm = BigInt(String(args[4]));
80818
+ if (txTerm !== BigInt(expected.selectedTerm)) {
80819
+ throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
80820
+ }
80821
+ break;
80822
+ }
80823
+ case "set-position-delegate": {
80824
+ if (name !== "setPositionDelegate") {
80825
+ throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
80826
+ }
80827
+ if (!eqAddr3(to, expected.registryAddress)) {
80828
+ throw new TxValidationError3(
80829
+ `setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
80830
+ );
80831
+ }
80832
+ requirePositionId2(args[0], expected.positionId);
80833
+ const txDelegate = String(args[1]);
80834
+ if (!eqAddr3(txDelegate, expected.delegate)) {
80835
+ throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
80836
+ }
80837
+ break;
80838
+ }
80839
+ case "bwar-add-address": {
80840
+ if (name !== "addAddress") {
80841
+ throw new TxValidationError3(`expected addAddress, decoded ${name}`);
80842
+ }
80843
+ if (!eqAddr3(to, expected.registryAddress)) {
80844
+ throw new TxValidationError3(
80845
+ `addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
80846
+ );
80847
+ }
80848
+ if (String(args[0]) !== expected.btcAddress) {
80849
+ throw new TxValidationError3(
80850
+ `btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
80851
+ );
80852
+ }
80853
+ break;
80854
+ }
80855
+ case "stablecoin-approve": {
80856
+ if (name !== "approve") {
80857
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80858
+ }
80859
+ if (!eqAddr3(to, expected.tokenAddress)) {
80860
+ throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
80861
+ }
80862
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80863
+ throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
80864
+ }
80865
+ if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
80866
+ throw new TxValidationError3(
80867
+ `approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
80868
+ );
80869
+ }
80870
+ break;
80871
+ }
80872
+ case "ucd-approve-controller": {
80873
+ if (name !== "approve") {
80874
+ throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
80875
+ }
80876
+ if (!eqAddr3(to, expected.ucdTokenAddress)) {
80877
+ throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
80878
+ }
80879
+ if (!eqAddr3(String(args[0]), expected.spender)) {
80880
+ throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
80881
+ }
80882
+ if (BigInt(String(args[1])).toString() !== expected.amountWei) {
80883
+ throw new TxValidationError3(
80884
+ `approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
80885
+ );
80886
+ }
80887
+ break;
80888
+ }
80889
+ case "psm-swap": {
80890
+ if (name !== "swap")
80891
+ throw new TxValidationError3(`expected swap, server returned ${name}`);
80892
+ if (!eqAddr3(to, expected.psmAddress)) {
80893
+ throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
80894
+ }
80895
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80896
+ throw new TxValidationError3(`swap stablecoin mismatch`);
80897
+ if (BigInt(String(args[1])).toString() !== expected.amountIn)
80898
+ throw new TxValidationError3(`swap amountIn mismatch`);
80899
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
80900
+ throw new TxValidationError3(`swap minUcdOut mismatch`);
80901
+ if (BigInt(expected.minOut) === 0n) {
80902
+ throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
80903
+ }
80904
+ break;
80905
+ }
80906
+ case "psm-redeem": {
80907
+ if (name !== "redeem")
80908
+ throw new TxValidationError3(`expected redeem, server returned ${name}`);
80909
+ if (!eqAddr3(to, expected.psmAddress)) {
80910
+ throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
80911
+ }
80912
+ if (!eqAddr3(String(args[0]), expected.stablecoin))
80913
+ throw new TxValidationError3(`redeem stablecoin mismatch`);
80914
+ if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
80915
+ throw new TxValidationError3(`redeem ucdAmount mismatch`);
80916
+ if (BigInt(String(args[2])).toString() !== expected.minOut)
80917
+ throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
80918
+ if (BigInt(expected.minOut) === 0n) {
80919
+ throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
80920
+ }
80921
+ break;
80922
+ }
80923
+ default: {
80924
+ const _exhaustive = expected;
80925
+ throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
80926
+ }
80927
+ }
80928
+ }
80929
+ var SLOT_SECONDS2 = 12;
80930
+ var INCLUSION_SLOT_TOLERANCE2 = 3;
80931
+ var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
80932
+ function buildPsmApproveTx2(p) {
80933
+ return {
80934
+ to: p.token,
80935
+ data: encodeSignable3("approve", [p.spender, p.amount]),
80936
+ value: "0x0",
80937
+ chainId: p.chainId
80938
+ };
80939
+ }
80940
+ function buildPsmSwapTx3(p) {
80941
+ return {
80942
+ to: p.psm,
80943
+ data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
80944
+ value: "0x0",
80945
+ chainId: p.chainId
80946
+ };
80947
+ }
80948
+ function buildPsmRedeemTx3(p) {
80949
+ return {
80950
+ to: p.psm,
80951
+ data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
80952
+ value: "0x0",
80953
+ chainId: p.chainId
80954
+ };
80955
+ }
80956
+ var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
80957
+ var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
80958
+ function psmExchangeReadsFromProvider2(provider, psmAddress) {
80959
+ const psm = new import_ethers41.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
80960
+ return {
80961
+ isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
80962
+ allowance: async (token, owner, spender) => await new import_ethers41.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
80963
+ };
80964
+ }
80965
+ var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
80966
+ function requireAddress2(direction, label, value) {
80967
+ if (!value || !import_ethers41.ethers.isAddress(value)) {
80968
+ throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
80969
+ }
80970
+ return import_ethers41.ethers.getAddress(value);
80971
+ }
80972
+ async function planPsmExchange2(params) {
80973
+ const { direction, amountIn, minOut, vctx, reads } = params;
80974
+ const chainId = vctx.chainId;
80975
+ if (amountIn <= 0n) {
80976
+ throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
80977
+ }
80978
+ if (minOut <= 0n) {
80979
+ throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
80980
+ }
80981
+ const owner = requireAddress2(direction, "owner", params.owner);
80982
+ const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
80983
+ const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
80984
+ const isSwap = direction === "swap";
80985
+ const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
80986
+ const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
80987
+ if (!await reads.isStablecoinSupported(stablecoin)) {
80988
+ throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
80989
+ }
80990
+ const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
80991
+ const allowanceBefore = await reads.allowance(token, owner, spender);
80992
+ const approvals = [];
80993
+ if (allowanceBefore < amountIn) {
80994
+ if (allowanceBefore > 0n) {
80995
+ approvals.push({
80996
+ step: "reset-approve",
80997
+ tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
80998
+ expected: approveExpected(0n)
80999
+ });
81000
+ }
81001
+ approvals.push({
81002
+ step: "approve",
81003
+ tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
81004
+ expected: approveExpected(amountIn)
81005
+ });
81006
+ }
81007
+ const exec = isSwap ? {
81008
+ step: "swap",
81009
+ tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
81010
+ expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
81011
+ } : {
81012
+ step: "redeem",
81013
+ tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
81014
+ expected: {
81015
+ kind: "psm-redeem",
81016
+ psmAddress: psm,
81017
+ stablecoin,
81018
+ amountUcdWei: amountIn.toString(),
81019
+ minOut: minOut.toString()
81020
+ }
81021
+ };
81022
+ for (const leg of [...approvals, exec]) {
81023
+ validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
81024
+ }
81025
+ return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
81026
+ }
81027
+
81028
+ // src/boundary/upstream/real/psm-calls.ts
79583
81029
  var PSM_VIEW_FRAGMENTS = [
79584
81030
  "function VERSION() view returns (string)",
79585
81031
  "function supportedStablecoins(address) view returns (bool)",
@@ -79599,15 +81045,7 @@ var PSM_VIEW_FRAGMENTS = [
79599
81045
  "function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
79600
81046
  "function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
79601
81047
  ];
79602
- var PSM_WRITE_FRAGMENTS = [
79603
- "function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
79604
- "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
79605
- ];
79606
- var ERC20_FRAGMENTS = [
79607
- "function approve(address spender, uint256 amount) returns (bool)",
79608
- "function balanceOf(address holder) view returns (uint256)"
79609
- ];
79610
- var ERC20_IFACE = new import_ethers32.ethers.Interface(ERC20_FRAGMENTS);
81048
+ var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
79611
81049
  var PSM_ERROR_FRAGMENTS = [
79612
81050
  "error StablecoinNotSupported(address stablecoin)",
79613
81051
  "error InvalidAmount()",
@@ -79655,9 +81093,9 @@ var RENDERERS = {
79655
81093
  var PsmCalls = class {
79656
81094
  constructor(deps) {
79657
81095
  this.deps = deps;
79658
- const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_WRITE_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
79659
- this.iface = new import_ethers32.ethers.Interface(abi);
79660
- this.psm = new import_ethers32.ethers.Contract(deps.psmAddress, abi, deps.provider);
81096
+ const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
81097
+ this.iface = new import_ethers42.ethers.Interface(abi);
81098
+ this.psm = new import_ethers42.ethers.Contract(deps.psmAddress, abi, deps.provider);
79661
81099
  }
79662
81100
  psm;
79663
81101
  iface;
@@ -79670,34 +81108,10 @@ var PsmCalls = class {
79670
81108
  ...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
79671
81109
  };
79672
81110
  }
79673
- // ---- unsigned-tx builders (plan 08 W1): EXACT-amount approvals only; floors pinned ----
79674
- /** Step 1: exact-amount ERC-20 approve. Caller names the direction's REAL spender
79675
- * (swap: stablecoin → the PSM; redeem: UCD → the UCDController). */
79676
- buildApprove(p) {
79677
- return {
79678
- to: p.token,
79679
- data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
79680
- value: "0x0",
79681
- chainId: p.chainId
79682
- };
79683
- }
79684
- /** Step 2, stablecoin → UCD (contract `swap`). */
79685
- buildSwap(p) {
79686
- return {
79687
- to: this.deps.psmAddress,
79688
- data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
79689
- value: "0x0",
79690
- chainId: p.chainId
79691
- };
79692
- }
79693
- /** Step 2, UCD → stablecoin (contract `redeem`). */
79694
- buildRedeem(p) {
79695
- return {
79696
- to: this.deps.psmAddress,
79697
- data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
79698
- value: "0x0",
79699
- chainId: p.chainId
79700
- };
81111
+ /** The two live reads the SDK's exchange planner depends on (supported set + allowance),
81112
+ * over this wrapper's provider and PSM. */
81113
+ exchangeReads() {
81114
+ return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
79701
81115
  }
79702
81116
  /** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
79703
81117
  async balances(holder) {
@@ -79710,8 +81124,8 @@ var PsmCalls = class {
79710
81124
  });
79711
81125
  }
79712
81126
  return this.call(async () => {
79713
- const ucd = new import_ethers32.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
79714
- const stable = new import_ethers32.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
81127
+ const ucd = new import_ethers42.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
81128
+ const stable = new import_ethers42.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
79715
81129
  const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
79716
81130
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79717
81131
  });
@@ -79829,7 +81243,7 @@ var PsmCalls = class {
79829
81243
  };
79830
81244
 
79831
81245
  // src/boundary/upstream/real/session.ts
79832
- var import_ethers33 = require("ethers");
81246
+ var import_ethers43 = require("ethers");
79833
81247
  var REFRESH_LEEWAY_SEC = 30;
79834
81248
  var LOGIN_TYPES_WITH_AUDIENCE3 = {
79835
81249
  DiamondHands: [
@@ -79877,7 +81291,7 @@ var LitOpsSession = class {
79877
81291
  const message = {
79878
81292
  address: this.wallet.address,
79879
81293
  issuedAt: Math.floor(Date.now() / 1e3),
79880
- nonce: "0x" + Buffer.from(import_ethers33.ethers.randomBytes(32)).toString("hex"),
81294
+ nonce: "0x" + Buffer.from(import_ethers43.ethers.randomBytes(32)).toString("hex"),
79881
81295
  audience: this.serviceEndpoint
79882
81296
  };
79883
81297
  const signature = await this.wallet.signTypedData(
@@ -79919,7 +81333,7 @@ function decodeJwtExp(token) {
79919
81333
  }
79920
81334
 
79921
81335
  // src/boundary/upstream/real/write-ops.ts
79922
- var import_ethers35 = require("ethers");
81336
+ var import_ethers45 = require("ethers");
79923
81337
 
79924
81338
  // src/signer/types.ts
79925
81339
  var OperationDeclined = class extends Error {
@@ -79929,7 +81343,7 @@ var OperationDeclined = class extends Error {
79929
81343
  init_tx_validator();
79930
81344
 
79931
81345
  // src/boundary/upstream/shared/external-bridge/page-crypto.ts
79932
- var import_ethers34 = require("ethers");
81346
+ var import_ethers44 = require("ethers");
79933
81347
  var PERSONAL_SIGN_LAYOUTS = {
79934
81348
  "dh-op-envelope-v1": {
79935
81349
  types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
@@ -79950,9 +81364,9 @@ function hashForLayout(layout, fields) {
79950
81364
  const values = def.fieldOrder.map((name) => {
79951
81365
  const raw = fields[name];
79952
81366
  if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
79953
- return hashUtf8.has(name) ? import_ethers34.ethers.keccak256(import_ethers34.ethers.toUtf8Bytes(raw)) : raw;
81367
+ return hashUtf8.has(name) ? import_ethers44.ethers.keccak256(import_ethers44.ethers.toUtf8Bytes(raw)) : raw;
79954
81368
  });
79955
- return import_ethers34.ethers.solidityPackedKeccak256(def.types, values);
81369
+ return import_ethers44.ethers.solidityPackedKeccak256(def.types, values);
79956
81370
  }
79957
81371
  var PAGE_CRYPTO_JS = `"use strict";
79958
81372
  (function () {
@@ -80181,9 +81595,21 @@ function buildValidationContext(network, chainId) {
80181
81595
 
80182
81596
  // src/boundary/upstream/real/write-ops.ts
80183
81597
  var SOURCE5 = "real-ops";
81598
+ function mcpExpected(leg) {
81599
+ const e = leg.expected;
81600
+ switch (e.kind) {
81601
+ case "stablecoin-approve":
81602
+ case "ucd-approve-controller":
81603
+ case "psm-swap":
81604
+ case "psm-redeem":
81605
+ return e;
81606
+ default:
81607
+ throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
81608
+ }
81609
+ }
80184
81610
  var OP_LAYOUT = "dh-op-envelope-v1";
80185
81611
  function randomNonceHex() {
80186
- return "0x" + Buffer.from(import_ethers35.ethers.randomBytes(16)).toString("hex");
81612
+ return "0x" + Buffer.from(import_ethers45.ethers.randomBytes(16)).toString("hex");
80187
81613
  }
80188
81614
  async function postJson(url2, body, headers) {
80189
81615
  const res = await fetch(url2, {
@@ -80244,7 +81670,7 @@ function buildWriteOps(deps) {
80244
81670
  return {
80245
81671
  to: String(tx2["to"] ?? ""),
80246
81672
  data: String(tx2["data"] ?? "0x"),
80247
- value: tx2["value"] != null ? import_ethers35.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
81673
+ value: tx2["value"] != null ? import_ethers45.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
80248
81674
  chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
80249
81675
  };
80250
81676
  }
@@ -80329,8 +81755,9 @@ function buildWriteOps(deps) {
80329
81755
  }
80330
81756
  return {
80331
81757
  createPosition: async (p) => {
80332
- const sdk = deps.getWriteSdk();
80333
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81758
+ const built = await deps.getWriteSdk();
81759
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81760
+ const sdk = built.sdk;
80334
81761
  try {
80335
81762
  await deps.assertValidatorConfigured();
80336
81763
  } catch (e) {
@@ -80409,7 +81836,7 @@ function buildWriteOps(deps) {
80409
81836
  mintedUcdWei: minted,
80410
81837
  feeUcdWei: mintFee,
80411
81838
  echoedAmountUcdWei: minted,
80412
- authorization: auth(action, `mint ${import_ethers35.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
81839
+ authorization: auth(action, `mint ${import_ethers45.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
80413
81840
  },
80414
81841
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80415
81842
  );
@@ -80450,7 +81877,7 @@ function buildWriteOps(deps) {
80450
81877
  txRef: { kind: "eth-tx", id: r.value.txHash },
80451
81878
  paidUcdWei: paid,
80452
81879
  echoedAmountUcdWei: paid,
80453
- authorization: auth(action, `repay ${import_ethers35.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
81880
+ authorization: auth(action, `repay ${import_ethers45.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
80454
81881
  },
80455
81882
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80456
81883
  );
@@ -80490,8 +81917,9 @@ function buildWriteOps(deps) {
80490
81917
  );
80491
81918
  },
80492
81919
  withdraw: async (p) => {
80493
- const sdk = deps.getWriteSdk();
80494
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
81920
+ const built = await deps.getWriteSdk();
81921
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
81922
+ const sdk = built.sdk;
80495
81923
  const amountSats = Number(p.amountSats);
80496
81924
  const feeSats = Number(p.networkFeeSats);
80497
81925
  let result;
@@ -80520,12 +81948,13 @@ function buildWriteOps(deps) {
80520
81948
  { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
80521
81949
  );
80522
81950
  },
80523
- /** PSM exchange pair (plan 08 W1): pure on-chain calls — no LIT action, no server
80524
- * orchestration. MCP-built txs over the pinned wrapper (the SDK's psmSwap/psmRedeem
80525
- * hardcode MaxUint256 approvals and are FORBIDDEN); exact-amount approve, then the
80526
- * swap/redeem with its mandatory floor, each validated against the M8-11 whitelist,
80527
- * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80528
- * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
81951
+ /** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
81952
+ * orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
81953
+ * builder every client shares (it replaced this file's own builders and the SDK's old
81954
+ * MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
81955
+ * allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
81956
+ * validated again here by the MCP's own whitelist (the one the approval card decodes
81957
+ * with), then signed through the session signer and broadcast — one at a time. */
80529
81958
  psmSwap: async (p) => {
80530
81959
  const pr = await deps.psm(p.stablecoin);
80531
81960
  if (!pr.ok) return upFail(pr.failure);
@@ -80539,11 +81968,7 @@ function buildWriteOps(deps) {
80539
81968
  message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
80540
81969
  });
80541
81970
  }
80542
- const amountIn = BigInt(p.amountIn);
80543
- const minOut = BigInt(p.minOut);
80544
81971
  const vctx = buildValidationContext(config.network, chainId);
80545
- const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
80546
- const spenderAddress = isSwap ? addr.psm : addr.ucdController;
80547
81972
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
80548
81973
  const tokenSymbol = isSwap ? calls.symbol() : "UCD";
80549
81974
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
@@ -80560,49 +81985,66 @@ function buildWriteOps(deps) {
80560
81985
  return submitFailure(leg, e);
80561
81986
  }
80562
81987
  };
80563
- const approveTx = calls.buildApprove({ token: tokenAddress, spender: spenderAddress, amount: amountIn, chainId });
81988
+ let plan;
80564
81989
  try {
80565
- validateUnsignedTx(
80566
- { ...approveTx },
80567
- isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: p.amountIn } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: p.amountIn },
80568
- vctx
80569
- );
80570
- } catch (e) {
80571
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM approve tx failed the whitelist: ${e.message}` });
80572
- }
80573
- const approveCard = `approve exactly ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} (${spenderAddress})`;
80574
- const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
80575
- if (!approveHashR.ok) return approveHashR;
80576
- const approveHash = approveHashR.value;
80577
- const residualNote = `the approve ALREADY broadcast (tx ${approveHash}) \u2014 an exact-amount allowance of ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} stands; it authorizes only that amount and nothing else. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
80578
- const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
80579
- try {
80580
- validateUnsignedTx(
80581
- { ...execTx },
80582
- isSwap ? { kind: "psm-swap", psmAddress: addr.psm, stablecoin: addr.stablecoin, amountIn: p.amountIn, minOut: p.minOut } : { kind: "psm-redeem", psmAddress: addr.psm, stablecoin: addr.stablecoin, amountUcdWei: p.amountIn, minOut: p.minOut },
80583
- vctx
80584
- );
81990
+ plan = await planPsmExchange2({
81991
+ direction: p.direction,
81992
+ owner: p.borrower,
81993
+ addresses: addr,
81994
+ amountIn: BigInt(p.amountIn),
81995
+ minOut: BigInt(p.minOut),
81996
+ vctx,
81997
+ reads: calls.exchangeReads()
81998
+ });
80585
81999
  } catch (e) {
80586
- return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
82000
+ return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
82001
+ kind: "unavailable",
82002
+ source: SOURCE5,
82003
+ message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
82004
+ raw: String(e)
82005
+ });
80587
82006
  }
80588
- const execCard = `${p.direction} ${p.amountIn} ${isSwap ? `${tokenSymbol} smallest units` : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
80589
- const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
80590
- if (!execHashR.ok) {
80591
- const f = execHashR.failure;
80592
- return upFail({ ...f, message: `${f.message} \u2014 ${residualNote}` });
82007
+ const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
82008
+ const unit = `${tokenSymbol} smallest units`;
82009
+ const landed = [];
82010
+ const residualNote = () => {
82011
+ const last = landed[landed.length - 1];
82012
+ 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`;
82013
+ return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
82014
+ };
82015
+ const runLeg = async (leg) => {
82016
+ const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
82017
+ try {
82018
+ validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
82019
+ } catch (e) {
82020
+ return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
82021
+ }
82022
+ const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
82023
+ const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
82024
+ return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
82025
+ };
82026
+ const approvals = [];
82027
+ for (const leg of plan.approvals) {
82028
+ 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})`;
82029
+ const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
82030
+ const r = await runLeg(leg);
82031
+ if (!r.ok) return r;
82032
+ landed.push({ step, hash: r.value });
82033
+ approvals.push({
82034
+ step,
82035
+ txRef: { kind: "eth-tx", id: r.value },
82036
+ amount: leg.step === "reset-approve" ? "0" : p.amountIn,
82037
+ authorization: auth("psm-approve", card, r.value)
82038
+ });
80593
82039
  }
82040
+ 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}`;
82041
+ const execHashR = await runLeg(plan.exec);
82042
+ if (!execHashR.ok) return execHashR;
80594
82043
  const execHash = execHashR.value;
80595
82044
  const balancesR = await calls.balances(p.borrower);
80596
82045
  const row = {
80597
- approve: {
80598
- txRef: { kind: "eth-tx", id: approveHash },
80599
- tokenSymbol,
80600
- tokenAddress,
80601
- spenderAddress,
80602
- spenderContract,
80603
- amount: p.amountIn,
80604
- authorization: auth("psm-approve", approveCard, approveHash)
80605
- },
82046
+ allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
82047
+ approvals,
80606
82048
  execute: {
80607
82049
  txRef: { kind: "eth-tx", id: execHash },
80608
82050
  amountIn: p.amountIn,
@@ -80619,8 +82061,9 @@ function buildWriteOps(deps) {
80619
82061
  // registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
80620
82062
  // msg.sender, so their path is a SafeTx — never this keystore leg.
80621
82063
  allowlistWithdrawalAddress: async (p) => {
80622
- const sdk = deps.getWriteSdk();
80623
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82064
+ const built = await deps.getWriteSdk();
82065
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82066
+ const sdk = built.sdk;
80624
82067
  let result;
80625
82068
  try {
80626
82069
  result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
@@ -80667,8 +82110,9 @@ function buildWriteOps(deps) {
80667
82110
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
80668
82111
  }),
80669
82112
  retryWithdrawExecute: async (p) => {
80670
- const sdk = deps.getWriteSdk();
80671
- if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
82113
+ const built = await deps.getWriteSdk();
82114
+ if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
82115
+ const sdk = built.sdk;
80672
82116
  let rows;
80673
82117
  try {
80674
82118
  rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
@@ -80696,7 +82140,7 @@ function buildWriteOps(deps) {
80696
82140
  }
80697
82141
 
80698
82142
  // src/signer/eoa-dh.ts
80699
- var import_ethers36 = require("ethers");
82143
+ var import_ethers46 = require("ethers");
80700
82144
  var EoaDHSigner = class {
80701
82145
  constructor(wallet, broadcast, clock = Date.now) {
80702
82146
  this.wallet = wallet;
@@ -80713,7 +82157,7 @@ var EoaDHSigner = class {
80713
82157
  async signAuthorization(spec) {
80714
82158
  const quantumTs = nextQuantumTimestamp(this.clock());
80715
82159
  const { fields, hashHex } = spec.stamp(quantumTs);
80716
- const signature = await this.wallet.signMessage(import_ethers36.ethers.getBytes(hashHex));
82160
+ const signature = await this.wallet.signMessage(import_ethers46.ethers.getBytes(hashHex));
80717
82161
  return { signature, quantumTs, fields };
80718
82162
  }
80719
82163
  async wrapInnerTx(innerTx) {
@@ -80731,10 +82175,10 @@ var EoaDHSigner = class {
80731
82175
 
80732
82176
  // src/signer/external-eoa.ts
80733
82177
  var import_node_crypto7 = require("crypto");
80734
- var import_ethers38 = require("ethers");
82178
+ var import_ethers48 = require("ethers");
80735
82179
 
80736
82180
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
80737
- var import_ethers37 = require("ethers");
82181
+ var import_ethers47 = require("ethers");
80738
82182
  function eq2(a, b) {
80739
82183
  return a.toLowerCase() === b.toLowerCase();
80740
82184
  }
@@ -80757,7 +82201,7 @@ function compareLandedTx(landed, approved, borrower) {
80757
82201
  return { status: "verified", from: landed.from, hash: landed.hash };
80758
82202
  }
80759
82203
  function verifyRawSignedTx(rawSignedTx, approved, borrower) {
80760
- const parsed = import_ethers37.ethers.Transaction.from(rawSignedTx);
82204
+ const parsed = import_ethers47.ethers.Transaction.from(rawSignedTx);
80761
82205
  if (!parsed.from || !parsed.to || !parsed.hash) {
80762
82206
  return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
80763
82207
  }
@@ -80795,7 +82239,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
80795
82239
  for (let attempt = 0; attempt < 4; attempt++) {
80796
82240
  try {
80797
82241
  const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
80798
- return import_ethers38.ethers.toBeHex(est * 15n / 10n);
82242
+ return import_ethers48.ethers.toBeHex(est * 15n / 10n);
80799
82243
  } catch (e) {
80800
82244
  lastErr = e;
80801
82245
  await new Promise((r) => setTimeout(r, 13e3));
@@ -80845,7 +82289,7 @@ var ExternalEoaDHSigner = class {
80845
82289
  throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
80846
82290
  }
80847
82291
  const finalHash = spec.stamp(used.quantumTs).hashHex;
80848
- const recovered = import_ethers38.ethers.verifyMessage(import_ethers38.ethers.getBytes(finalHash), outcome.signature);
82292
+ const recovered = import_ethers48.ethers.verifyMessage(import_ethers48.ethers.getBytes(finalHash), outcome.signature);
80849
82293
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80850
82294
  throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80851
82295
  }
@@ -80856,7 +82300,7 @@ var ExternalEoaDHSigner = class {
80856
82300
  }
80857
82301
  async submitValidatedTx(outerTx, ctx) {
80858
82302
  const approved = toApprovedTx(outerTx, this.deps.chainId);
80859
- const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
82303
+ const gas = outerTx.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
80860
82304
  const outcome = await this.deps.bridge.requestSignature({
80861
82305
  id: (0, import_node_crypto7.randomUUID)(),
80862
82306
  kind: "transaction",
@@ -80890,7 +82334,7 @@ var ExternalEoaDHSigner = class {
80890
82334
  return new BridgeEthersSigner(this.deps);
80891
82335
  }
80892
82336
  };
80893
- var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ethers.AbstractSigner {
82337
+ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers48.ethers.AbstractSigner {
80894
82338
  constructor(deps) {
80895
82339
  super(deps.provider);
80896
82340
  this.deps = deps;
@@ -80901,13 +82345,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80901
82345
  return this.deps.borrower;
80902
82346
  }
80903
82347
  async signMessage(message) {
80904
- const bytes = typeof message === "string" ? import_ethers38.ethers.toUtf8Bytes(message) : message;
82348
+ const bytes = typeof message === "string" ? import_ethers48.ethers.toUtf8Bytes(message) : message;
80905
82349
  if (bytes.length !== 32) {
80906
82350
  throw new Error(
80907
82351
  `external-wallet signMessage accepts only the SDK's bare 32-byte auth hashes (got ${bytes.length} bytes) \u2014 no other raw-message signing rides this path.`
80908
82352
  );
80909
82353
  }
80910
- const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
82354
+ const hashHex = import_ethers48.ethers.hexlify(bytes).toLowerCase();
80911
82355
  const nowMs = (this.deps.clock ?? Date.now)();
80912
82356
  const expiresAtSec = nextQuantumTimestamp(nowMs);
80913
82357
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
@@ -80937,7 +82381,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80937
82381
  if (outcome.status !== "approved" || !outcome.signature) {
80938
82382
  throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
80939
82383
  }
80940
- const recovered = import_ethers38.ethers.verifyMessage(bytes, outcome.signature);
82384
+ const recovered = import_ethers48.ethers.verifyMessage(bytes, outcome.signature);
80941
82385
  if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
80942
82386
  throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
80943
82387
  }
@@ -80971,11 +82415,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80971
82415
  const approved = {
80972
82416
  to: tx2.to,
80973
82417
  data: tx2.data,
80974
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82418
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
80975
82419
  chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
80976
82420
  };
80977
82421
  const card = cardForTx(approved);
80978
- const gas = tx2.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
82422
+ const gas = tx2.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
80979
82423
  const outcome = await this.deps.bridge.requestSignature({
80980
82424
  id: (0, import_node_crypto7.randomUUID)(),
80981
82425
  kind: "transaction",
@@ -81017,14 +82461,14 @@ function toApprovedTx(tx2, fallbackChainId) {
81017
82461
  return {
81018
82462
  to: tx2.to,
81019
82463
  data: tx2.data,
81020
- value: tx2.value != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
82464
+ value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
81021
82465
  chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
81022
82466
  };
81023
82467
  }
81024
82468
  function describeFn(data) {
81025
82469
  try {
81026
- const { decodeSignable: decodeSignable2 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
81027
- return decodeSignable2(data).name;
82470
+ const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
82471
+ return decodeSignable4(data).name;
81028
82472
  } catch {
81029
82473
  return "operation";
81030
82474
  }
@@ -81061,7 +82505,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
81061
82505
  var RealUpstreamPlugin = class {
81062
82506
  constructor(config, wallet, runtime) {
81063
82507
  this.config = config;
81064
- this.provider = new import_ethers39.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
82508
+ this.provider = new import_ethers49.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
81065
82509
  this.wallet = wallet ?? null;
81066
82510
  this.runtime = runtime ?? null;
81067
82511
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
@@ -81192,7 +82636,7 @@ var RealUpstreamPlugin = class {
81192
82636
  })
81193
82637
  )
81194
82638
  };
81195
- 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.`;
82639
+ 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.`;
81196
82640
  const readOnly = (op) => Promise.resolve(
81197
82641
  upFail({
81198
82642
  kind: "unavailable",
@@ -81254,18 +82698,24 @@ var RealUpstreamPlugin = class {
81254
82698
  * the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
81255
82699
  * and the service-mode SDK routes its own subgraph reads through the same proxy — so
81256
82700
  * writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
81257
- * Safe to call repeatedly; failures leave the write plane honestly unavailable
81258
- * (createPosition/withdraw report the uninitialized SDK). */
82701
+ * Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
82702
+ * first write builds again (see ensureSdk). */
81259
82703
  async initWriteSdk() {
81260
82704
  if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
81261
82705
  const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
81262
82706
  if (!wallet) return;
81263
82707
  await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
81264
82708
  }
81265
- /** Build (once per identity key) the signer-bearing WRITE SDK. Failures cache `null` —
81266
- * the write gateways report the uninitialized SDK honestly, never fake readiness. */
82709
+ /** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
82710
+ *
82711
+ * A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
82712
+ * life of the process and drop the error, which was survivable only while `create` never
82713
+ * touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
82714
+ * RPC blip at boot would have disabled every later write with no reason given. Now each write
82715
+ * retries, and a persistent failure says what it is. Concurrent callers share one build. */
81267
82716
  async ensureSdk(key, signer) {
81268
- if (this.sdkCache.has(key)) return this.sdkCache.get(key) ?? null;
82717
+ const cached = this.sdkCache.get(key);
82718
+ if (cached) return { ok: true, sdk: cached };
81269
82719
  const inFlight = this.sdkInFlight.get(key);
81270
82720
  if (inFlight) return inFlight;
81271
82721
  const build = (async () => {
@@ -81285,17 +82735,23 @@ var RealUpstreamPlugin = class {
81285
82735
  // nesting writes under indexer discovery (the M8B-4 coupling this removes).
81286
82736
  ...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
81287
82737
  });
81288
- return isSuccess(builtWrite) ? builtWrite.value : null;
81289
- } catch {
81290
- return null;
82738
+ if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
82739
+ return { ok: false, reason: builtWrite.error.message };
82740
+ } catch (e) {
82741
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
81291
82742
  }
81292
82743
  })();
81293
82744
  this.sdkInFlight.set(key, build);
81294
82745
  const built = await build;
81295
82746
  this.sdkInFlight.delete(key);
81296
- this.sdkCache.set(key, built);
82747
+ if (built.ok) this.sdkCache.set(key, built.sdk);
81297
82748
  return built;
81298
82749
  }
82750
+ /** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
82751
+ async writeSdkFor(key, signer) {
82752
+ const built = await this.ensureSdk(key, signer);
82753
+ return built.ok ? { ok: true, sdk: built.sdk } : built;
82754
+ }
81299
82755
  wallet;
81300
82756
  // ---- per-call signer resolution (plan 10 A3) ----
81301
82757
  /** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
@@ -81335,7 +82791,7 @@ var RealUpstreamPlugin = class {
81335
82791
  chainId: this.config.chainId,
81336
82792
  dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
81337
82793
  session,
81338
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82794
+ getWriteSdk: () => this.writeSdkFor(key, wallet),
81339
82795
  readDetails: (id) => this.readPositionDetails(id),
81340
82796
  psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81341
82797
  assertValidatorConfigured: () => this.assertValidatorConfigured()
@@ -81351,14 +82807,14 @@ var RealUpstreamPlugin = class {
81351
82807
  if (!pkpValidation) {
81352
82808
  throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
81353
82809
  }
81354
- const registry = new import_ethers39.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
82810
+ const registry = new import_ethers49.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
81355
82811
  let validator;
81356
82812
  try {
81357
82813
  validator = await registry.validatorForVersion(version2);
81358
82814
  } catch (e) {
81359
82815
  throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
81360
82816
  }
81361
- if (validator === import_ethers39.ethers.ZeroAddress) {
82817
+ if (validator === import_ethers49.ethers.ZeroAddress) {
81362
82818
  throw new Error(
81363
82819
  `validator version ${version2} is NOT registered on ${this.config.network} (PKPValidation ${pkpValidation} returns the zero address) \u2014 the transaction would revert ValidatorNotConfigured. Set DH_VALIDATOR_VERSION to the network's registered generation.`
81364
82820
  );
@@ -81408,7 +82864,7 @@ var RealUpstreamPlugin = class {
81408
82864
  failure: {
81409
82865
  kind: "signer-missing",
81410
82866
  source: "real-ops",
81411
- 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."
82867
+ 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."
81412
82868
  }
81413
82869
  };
81414
82870
  }
@@ -81432,7 +82888,6 @@ var RealUpstreamPlugin = class {
81432
82888
  gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
81433
82889
  this.opsGatewayCache.set(key, gateway);
81434
82890
  }
81435
- await this.ensureSdk(key, wallet.connect(this.provider));
81436
82891
  return { ok: true, gateway };
81437
82892
  }
81438
82893
  if (mode === "external") {
@@ -81469,14 +82924,13 @@ var RealUpstreamPlugin = class {
81469
82924
  chainId: this.config.chainId,
81470
82925
  dhSigner: new ExternalEoaDHSigner(deps),
81471
82926
  session,
81472
- getWriteSdk: () => this.sdkCache.get(key) ?? null,
82927
+ getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
81473
82928
  readDetails: (id) => this.readPositionDetails(id),
81474
82929
  psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81475
82930
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81476
82931
  });
81477
82932
  this.opsGatewayCache.set(key, gateway);
81478
82933
  }
81479
- await this.ensureSdk(key, this.externalSigners.get(key));
81480
82934
  return { ok: true, gateway };
81481
82935
  }
81482
82936
  return {
@@ -81636,7 +83090,7 @@ var RealUpstreamPlugin = class {
81636
83090
  );
81637
83091
  if (!r.ok) return r;
81638
83092
  const raw = r.value.data.supportedStablecoins ?? [];
81639
- const bad = raw.find((x) => !import_ethers39.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
83093
+ const bad = raw.find((x) => !import_ethers49.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
81640
83094
  if (bad) {
81641
83095
  return {
81642
83096
  ok: false,
@@ -81719,7 +83173,7 @@ var RealUpstreamPlugin = class {
81719
83173
  };
81720
83174
  }
81721
83175
  const symbol = raw.toLowerCase();
81722
- if (import_ethers39.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
83176
+ if (import_ethers49.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
81723
83177
  const verified = await this.verifiedStablecoins();
81724
83178
  if (!verified.ok) return { ok: false, failure: verified.failure };
81725
83179
  const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
@@ -81757,7 +83211,7 @@ var RealUpstreamPlugin = class {
81757
83211
  * chain, then sign.
81758
83212
  */
81759
83213
  async psmCallsFor(stablecoinAddress) {
81760
- if (!import_ethers39.ethers.isAddress(stablecoinAddress)) {
83214
+ if (!import_ethers49.ethers.isAddress(stablecoinAddress)) {
81761
83215
  throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
81762
83216
  }
81763
83217
  const key = stablecoinAddress.toLowerCase();
@@ -81777,9 +83231,9 @@ var RealUpstreamPlugin = class {
81777
83231
  let supported;
81778
83232
  let symbol;
81779
83233
  try {
81780
- const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
83234
+ const psm = new import_ethers49.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81781
83235
  supported = await psm["supportedStablecoins"](key);
81782
- const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
83236
+ const erc20 = new import_ethers49.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81783
83237
  symbol = await erc20["symbol"]();
81784
83238
  } catch (e) {
81785
83239
  return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
@@ -81992,7 +83446,7 @@ var RealUpstreamPlugin = class {
81992
83446
  const pm = this.contracts["PositionManager"];
81993
83447
  if (!pm) return false;
81994
83448
  try {
81995
- const c = new import_ethers39.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
83449
+ const c = new import_ethers49.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
81996
83450
  return Boolean(await c["paused"]());
81997
83451
  } catch {
81998
83452
  return false;
@@ -82001,16 +83455,16 @@ var RealUpstreamPlugin = class {
82001
83455
  async readPositionDetails(id) {
82002
83456
  const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
82003
83457
  if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
82004
- const c = new import_ethers39.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
83458
+ const c = new import_ethers49.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
82005
83459
  let d;
82006
83460
  try {
82007
- d = await c["getPositionDetails"](import_ethers39.ethers.zeroPadValue(id, 32));
83461
+ d = await c["getPositionDetails"](import_ethers49.ethers.zeroPadValue(id, 32));
82008
83462
  } catch (e) {
82009
83463
  if (e.code === "CALL_EXCEPTION") return null;
82010
83464
  throw e;
82011
83465
  }
82012
83466
  const borrower = String(d["borrower"]);
82013
- if (borrower === import_ethers39.ethers.ZeroAddress) return null;
83467
+ if (borrower === import_ethers49.ethers.ZeroAddress) return null;
82014
83468
  return {
82015
83469
  positionId: String(d["positionId"]),
82016
83470
  pkpId: String(d["pkpId"]),
@@ -83612,8 +85066,8 @@ async function buildBoundary(configResult, overrides) {
83612
85066
  );
83613
85067
  }
83614
85068
  try {
83615
- const decrypted = await import_ethers40.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
83616
- if (!(decrypted instanceof import_ethers40.ethers.Wallet)) {
85069
+ const decrypted = await import_ethers50.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85070
+ if (!(decrypted instanceof import_ethers50.ethers.Wallet)) {
83617
85071
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
83618
85072
  }
83619
85073
  wallet = decrypted;
@@ -84105,7 +85559,7 @@ on the real adapter and the mock.
84105
85559
  | extend | 1 personal-sign + 1 tx |
84106
85560
  | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
84107
85561
  | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
84108
- | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
85562
+ | PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
84109
85563
 
84110
85564
  **Honesty notes (say these plainly):**
84111
85565
  - **Reads never pop the wallet.** If a read needs a login the user does not have, the
@@ -84249,16 +85703,19 @@ rather than silently deliver less than quoted.
84249
85703
 
84250
85704
  ${psmStablecoinRealityNote(d)}
84251
85705
 
84252
- **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
84253
- result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
85706
+ **Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
85707
+ the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
85708
+ planned against the allowance already standing: none when it covers the amount, one when it
85709
+ is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
84254
85710
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
84255
85711
  the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84256
85712
  you approve UCD to the **UCDController** (the PSM burns your UCD through the
84257
85713
  controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84258
85714
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
84259
85715
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
84260
- own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
84261
- standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
85716
+ own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
85717
+ standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
85718
+ the next exchange that it covers uses it without asking for another approval.
84262
85719
  PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84263
85720
  REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84264
85721
  wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
@@ -84731,7 +86188,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
84731
86188
 
84732
86189
  // src/tools/loan.ts
84733
86190
  var import_zod = require("zod");
84734
- var import_ethers41 = require("ethers");
86191
+ var import_ethers51 = require("ethers");
84735
86192
 
84736
86193
  // src/util/format.ts
84737
86194
  function bigintReplacer(_key, value) {
@@ -84919,7 +86376,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84919
86376
  const b = getB();
84920
86377
  if (!b.ok) return renderError(b.error);
84921
86378
  return renderEnvelope(
84922
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
86379
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers51.parseEther)(amountUcd.toString()).toString() })
84923
86380
  );
84924
86381
  })
84925
86382
  );
@@ -84957,7 +86414,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
84957
86414
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
84958
86415
  amountUcdWei = detail.data.debtUcdWei;
84959
86416
  } else {
84960
- amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
86417
+ amountUcdWei = (0, import_ethers51.parseEther)(amountUcd.toString()).toString();
84961
86418
  }
84962
86419
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
84963
86420
  })
@@ -85358,7 +86815,7 @@ function registerPsmTools(server, getB) {
85358
86815
  "psm_swap",
85359
86816
  {
85360
86817
  title: "Exchange UCD \u2194 a stablecoin through the PSM",
85361
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
86818
+ description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as explicit on-chain ceremonies, each signed by the session signer and all reported in the result: (1) the approvals the input token NEEDS, planned against its standing allowance \u2014 none when the allowance already covers the amount; one EXACT-AMOUNT approval when it is 0; a reset to 0 followed by the exact approval when a partial allowance stands. to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
85362
86819
  inputSchema: {
85363
86820
  stablecoin: import_zod4.z.string().min(1).describe(
85364
86821
  "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
@@ -85374,7 +86831,7 @@ function registerPsmTools(server, getB) {
85374
86831
  const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
85375
86832
  const gate = requireConfirmation(
85376
86833
  confirmed,
85377
- `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
86834
+ `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (exact-amount approval if the standing allowance does not cover it, then ${direction === "to-ucd" ? "swap" : "redeem"})`
85378
86835
  );
85379
86836
  if (gate) return gate;
85380
86837
  const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
@@ -85560,7 +87017,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
85560
87017
 
85561
87018
  // src/tools/signer.ts
85562
87019
  var import_zod6 = require("zod");
85563
- var import_ethers42 = require("ethers");
87020
+ var import_ethers52 = require("ethers");
85564
87021
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
85565
87022
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
85566
87023
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -85602,7 +87059,7 @@ function registerSignerTool(server, getRuntime, opts) {
85602
87059
  if (mode !== void 0 && !offeredModes.includes(mode)) {
85603
87060
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
85604
87061
  }
85605
- if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
87062
+ if (safeAddress !== void 0 && !import_ethers52.ethers.isAddress(safeAddress)) {
85606
87063
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
85607
87064
  }
85608
87065
  if (action === "status") {
@@ -86538,9 +87995,9 @@ function composeConnector(opts, rawPublicOrigin) {
86538
87995
  }
86539
87996
  if (opts.serveLandingPage) {
86540
87997
  app.get("/", (_req, res) => {
86541
- const { nonce, headers } = htmlPageSecurityHeaders({ "img-src": [BACKGROUND_IMAGE_ORIGIN, "data:"] });
87998
+ const { headers } = htmlPageSecurityHeaders({ "img-src": [BACKGROUND_IMAGE_ORIGIN, "data:"] });
86542
87999
  for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
86543
- res.type("text/html; charset=utf-8").send(renderLandingPage({ publicOrigin, networks: allowedNetworks, version: SERVER_VERSION, nonce }));
88000
+ res.type("text/html; charset=utf-8").send(renderLandingPage({ publicOrigin, version: SERVER_VERSION }));
86544
88001
  });
86545
88002
  }
86546
88003
  app.use((_req, res) => deny(res, 404, "not found \u2014 the MCP endpoint is /mcp"));