@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/README.md +88 -35
- package/dist/boundary.js +1933 -359
- package/dist/connector-embed.js +1969 -512
- package/dist/connector.js +1969 -512
- package/dist/index.js +1952 -375
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -15431,7 +15431,7 @@ ${errorReport}`);
|
|
|
15431
15431
|
}
|
|
15432
15432
|
init_debug_logger();
|
|
15433
15433
|
init_session_signature_cache();
|
|
15434
|
-
var
|
|
15434
|
+
var import_ethers52 = require("ethers");
|
|
15435
15435
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
15436
15436
|
var GRACE_PERIOD_DAYS = 30;
|
|
15437
15437
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -18347,12 +18347,12 @@ ${auth.clientId}`;
|
|
|
18347
18347
|
}
|
|
18348
18348
|
async function executeVaultSnapshot(params) {
|
|
18349
18349
|
global.ethers = {
|
|
18350
|
-
...
|
|
18350
|
+
...import_ethers52.ethers,
|
|
18351
18351
|
providers: {
|
|
18352
|
-
StaticJsonRpcProvider:
|
|
18352
|
+
StaticJsonRpcProvider: import_ethers52.ethers.JsonRpcProvider
|
|
18353
18353
|
},
|
|
18354
|
-
Contract:
|
|
18355
|
-
utils:
|
|
18354
|
+
Contract: import_ethers52.ethers.Contract,
|
|
18355
|
+
utils: import_ethers52.ethers
|
|
18356
18356
|
// v6 moved utils to top level
|
|
18357
18357
|
};
|
|
18358
18358
|
global.Lit = {
|
|
@@ -25561,7 +25561,10 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25561
25561
|
"node_modules/@gvnrdao/dh-lit-ops/dist/utils/lit-core-lit-action-client.js"(exports2) {
|
|
25562
25562
|
"use strict";
|
|
25563
25563
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
25564
|
+
exports2.CORE_API_TRANSPORT_FAILURE_MARKER = void 0;
|
|
25564
25565
|
exports2.normalizeCoreLitActionResult = normalizeCoreLitActionResult;
|
|
25566
|
+
exports2.describeErrorWithCause = describeErrorWithCause;
|
|
25567
|
+
exports2.isCoreApiTransportError = isCoreApiTransportError;
|
|
25565
25568
|
exports2.executeLitActionViaCoreApi = executeLitActionViaCoreApi;
|
|
25566
25569
|
var fetch_lit_action_from_ipfs_1 = require_fetch_lit_action_from_ipfs();
|
|
25567
25570
|
function parseResponsePayload(raw) {
|
|
@@ -25612,6 +25615,27 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25612
25615
|
const fromEnv = process.env.LIT_CORE_API_BASE_URL;
|
|
25613
25616
|
return (explicit || fromEnv || "https://api.chipotle.litprotocol.com").replace(/\/$/, "");
|
|
25614
25617
|
}
|
|
25618
|
+
exports2.CORE_API_TRANSPORT_FAILURE_MARKER = "Lit Core lit_action transport failure";
|
|
25619
|
+
function describeErrorWithCause(e) {
|
|
25620
|
+
const parts = [];
|
|
25621
|
+
let current = e;
|
|
25622
|
+
const seen = /* @__PURE__ */ new Set();
|
|
25623
|
+
while (current != null && !seen.has(current) && parts.length < 5) {
|
|
25624
|
+
seen.add(current);
|
|
25625
|
+
if (current instanceof Error) {
|
|
25626
|
+
const code = current.code;
|
|
25627
|
+
parts.push(typeof code === "string" && !current.message.includes(code) ? `${code}: ${current.message}` : current.message);
|
|
25628
|
+
current = current.cause;
|
|
25629
|
+
} else {
|
|
25630
|
+
parts.push(String(current));
|
|
25631
|
+
break;
|
|
25632
|
+
}
|
|
25633
|
+
}
|
|
25634
|
+
return parts.length === 0 ? String(e) : parts.join(" <- ");
|
|
25635
|
+
}
|
|
25636
|
+
function isCoreApiTransportError(message) {
|
|
25637
|
+
return message.includes(exports2.CORE_API_TRANSPORT_FAILURE_MARKER);
|
|
25638
|
+
}
|
|
25615
25639
|
async function executeLitActionViaCoreApi(options) {
|
|
25616
25640
|
let resolvedCode = options.code || "";
|
|
25617
25641
|
if (!resolvedCode.trim()) {
|
|
@@ -25673,13 +25697,11 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25673
25697
|
return normalizeCoreLitActionResult(body);
|
|
25674
25698
|
} catch (e) {
|
|
25675
25699
|
const msg = e instanceof Error ? e.message : String(e);
|
|
25700
|
+
const error = msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : `${exports2.CORE_API_TRANSPORT_FAILURE_MARKER}: ${describeErrorWithCause(e)}`;
|
|
25676
25701
|
if (options.debug) {
|
|
25677
|
-
console.error("\u274C [executeLitActionViaCoreApi]",
|
|
25702
|
+
console.error("\u274C [executeLitActionViaCoreApi]", error);
|
|
25678
25703
|
}
|
|
25679
|
-
return {
|
|
25680
|
-
success: false,
|
|
25681
|
-
error: msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : msg
|
|
25682
|
-
};
|
|
25704
|
+
return { success: false, error };
|
|
25683
25705
|
} finally {
|
|
25684
25706
|
clearTimeout(timer);
|
|
25685
25707
|
}
|
|
@@ -26661,7 +26683,8 @@ var require_lit_ops_module = __commonJS({
|
|
|
26661
26683
|
const borrowerAddress = borrowerOverride ?? this.config.serverAddress ?? await this.config.signer.getAddress();
|
|
26662
26684
|
const pkpValidatorInfo = DH_LIT_ACTIONS_CHIPOTLE.pkpValidator;
|
|
26663
26685
|
const validatorWalletAddress = process.env.LIT_PKP_VALIDATOR_WALLET_OVERRIDE || pkpValidatorInfo?.validatorWalletAddress;
|
|
26664
|
-
const
|
|
26686
|
+
const errorMessage = (e) => e instanceof Error ? e.message : String(e);
|
|
26687
|
+
const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(errorMessage(e));
|
|
26665
26688
|
const propagationRetries = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_RETRIES) || 8;
|
|
26666
26689
|
const propagationDelayMs = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_DELAY_MS) || 15e3;
|
|
26667
26690
|
let coreResponse;
|
|
@@ -26682,10 +26705,12 @@ var require_lit_ops_module = __commonJS({
|
|
|
26682
26705
|
coreResponse = exec.response;
|
|
26683
26706
|
break;
|
|
26684
26707
|
} catch (e) {
|
|
26685
|
-
|
|
26708
|
+
const propagating = isWalletPropagationError(e);
|
|
26709
|
+
const transport = (0, lit_core_lit_action_client_1.isCoreApiTransportError)(errorMessage(e));
|
|
26710
|
+
if (!propagating && !transport || attempt === propagationRetries) {
|
|
26686
26711
|
throw e;
|
|
26687
26712
|
}
|
|
26688
|
-
console.log(`[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
|
|
26713
|
+
console.log(propagating ? `[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms` : `[ChipotlePKP] vault PKP ${pkpId} validator call failed in transport (${errorMessage(e)}); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
|
|
26689
26714
|
await new Promise((r) => setTimeout(r, propagationDelayMs));
|
|
26690
26715
|
}
|
|
26691
26716
|
}
|
|
@@ -40410,7 +40435,7 @@ var require_dist3 = __commonJS({
|
|
|
40410
40435
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
|
|
40411
40436
|
};
|
|
40412
40437
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
40413
|
-
exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
|
|
40438
|
+
exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
|
|
40414
40439
|
__exportStar(require_interfaces(), exports2);
|
|
40415
40440
|
var dh_lit_actions_1 = require_pkg_src();
|
|
40416
40441
|
Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
|
|
@@ -40480,6 +40505,15 @@ var require_dist3 = __commonJS({
|
|
|
40480
40505
|
Object.defineProperty(exports2, "normalizeCoreLitActionResult", { enumerable: true, get: function() {
|
|
40481
40506
|
return lit_core_lit_action_client_1.normalizeCoreLitActionResult;
|
|
40482
40507
|
} });
|
|
40508
|
+
Object.defineProperty(exports2, "describeErrorWithCause", { enumerable: true, get: function() {
|
|
40509
|
+
return lit_core_lit_action_client_1.describeErrorWithCause;
|
|
40510
|
+
} });
|
|
40511
|
+
Object.defineProperty(exports2, "isCoreApiTransportError", { enumerable: true, get: function() {
|
|
40512
|
+
return lit_core_lit_action_client_1.isCoreApiTransportError;
|
|
40513
|
+
} });
|
|
40514
|
+
Object.defineProperty(exports2, "CORE_API_TRANSPORT_FAILURE_MARKER", { enumerable: true, get: function() {
|
|
40515
|
+
return lit_core_lit_action_client_1.CORE_API_TRANSPORT_FAILURE_MARKER;
|
|
40516
|
+
} });
|
|
40483
40517
|
var bitcoin_signature_1 = require_bitcoin_signature();
|
|
40484
40518
|
Object.defineProperty(exports2, "convertEthereumSignatureToBitcoinDER", { enumerable: true, get: function() {
|
|
40485
40519
|
return bitcoin_signature_1.convertEthereumSignatureToBitcoinDER;
|
|
@@ -40651,16 +40685,18 @@ function resolveWcProjectId(raw, problems) {
|
|
|
40651
40685
|
}
|
|
40652
40686
|
return raw;
|
|
40653
40687
|
}
|
|
40688
|
+
var RPC_PROXY_ORIGIN = "https://api.gvnr.xyz";
|
|
40689
|
+
var rpcProxy = (chainId) => `${RPC_PROXY_ORIGIN}/v1/proxy/rpc/${chainId}`;
|
|
40654
40690
|
var NETWORK_DEFAULTS = {
|
|
40655
40691
|
sepolia: {
|
|
40656
|
-
rpcUrl:
|
|
40692
|
+
rpcUrl: rpcProxy(11155111),
|
|
40657
40693
|
serviceEndpoint: "https://ops-test.gvnr.xyz",
|
|
40658
40694
|
litNetwork: "chipotle",
|
|
40659
40695
|
validatorVersion: 3
|
|
40660
40696
|
// on-chain validator generation, sepolia (2026-07-30)
|
|
40661
40697
|
},
|
|
40662
40698
|
mainnet: {
|
|
40663
|
-
rpcUrl:
|
|
40699
|
+
rpcUrl: rpcProxy(1),
|
|
40664
40700
|
// Cutover 2026-09-08 — see sdk/src/constants/chunks/network-configs.ts for the full
|
|
40665
40701
|
// reasoning. Widening, not a rename: ops.gvnr.xyz serves the same broker and cannot be
|
|
40666
40702
|
// retired while installed copies call it. The sepolia entry above deliberately stays on
|
|
@@ -40778,11 +40814,11 @@ function resolveRealConfig(env) {
|
|
|
40778
40814
|
problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
|
|
40779
40815
|
}
|
|
40780
40816
|
}
|
|
40781
|
-
const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "
|
|
40817
|
+
const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "mainnet" : env["DH_NETWORK"];
|
|
40782
40818
|
if (NETWORKS[network] === void 0) {
|
|
40783
40819
|
problems.push(`DH_NETWORK='${network}' is not supported. Allowed: ${Object.keys(NETWORKS).join(" | ")}.`);
|
|
40784
40820
|
}
|
|
40785
|
-
const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.
|
|
40821
|
+
const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.mainnet;
|
|
40786
40822
|
const rpcUrl = env["ETH_RPC_URL"] || defaults2.rpcUrl;
|
|
40787
40823
|
const serviceEndpoint = env["DH_SERVICE_ENDPOINT"] || defaults2.serviceEndpoint;
|
|
40788
40824
|
if (!/^https:\/\//.test(serviceEndpoint) && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(serviceEndpoint)) {
|
|
@@ -40847,7 +40883,7 @@ function resolveRealConfig(env) {
|
|
|
40847
40883
|
|
|
40848
40884
|
// src/boot.ts
|
|
40849
40885
|
var fs6 = __toESM(require("fs"));
|
|
40850
|
-
var
|
|
40886
|
+
var import_ethers49 = require("ethers");
|
|
40851
40887
|
|
|
40852
40888
|
// src/boundary/index.ts
|
|
40853
40889
|
var import_node_crypto8 = require("crypto");
|
|
@@ -41264,7 +41300,7 @@ var BoundaryCore = class {
|
|
|
41264
41300
|
const inToken = toUcd ? s.stablecoinSymbol : "UCD";
|
|
41265
41301
|
const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
|
|
41266
41302
|
const amountIn = parseDecimalUnits(p.amount, inDecimals);
|
|
41267
|
-
const
|
|
41303
|
+
const refuse3 = (refusal, message, details) => ({
|
|
41268
41304
|
env: errEnvelope(
|
|
41269
41305
|
boundaryError("UPSTREAM_REJECTED", message, {
|
|
41270
41306
|
source: statusR.source.id,
|
|
@@ -41275,13 +41311,13 @@ var BoundaryCore = class {
|
|
|
41275
41311
|
});
|
|
41276
41312
|
const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
|
|
41277
41313
|
if (s.paused) {
|
|
41278
|
-
return
|
|
41314
|
+
return refuse3(
|
|
41279
41315
|
"psm-paused",
|
|
41280
41316
|
"the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
|
|
41281
41317
|
);
|
|
41282
41318
|
}
|
|
41283
41319
|
if (!toUcd && !s.redeemEnabled) {
|
|
41284
|
-
return
|
|
41320
|
+
return refuse3(
|
|
41285
41321
|
"redeem-disabled",
|
|
41286
41322
|
`redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
|
|
41287
41323
|
);
|
|
@@ -41292,20 +41328,20 @@ var BoundaryCore = class {
|
|
|
41292
41328
|
const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
|
|
41293
41329
|
const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
|
|
41294
41330
|
if (amountIn < min) {
|
|
41295
|
-
return
|
|
41331
|
+
return refuse3(
|
|
41296
41332
|
"below-min",
|
|
41297
41333
|
`${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
|
|
41298
41334
|
{ amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
|
|
41299
41335
|
);
|
|
41300
41336
|
}
|
|
41301
41337
|
if (max === 0n) {
|
|
41302
|
-
return
|
|
41338
|
+
return refuse3(
|
|
41303
41339
|
"direction-disabled",
|
|
41304
41340
|
`the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
|
|
41305
41341
|
);
|
|
41306
41342
|
}
|
|
41307
41343
|
if (amountIn > max) {
|
|
41308
|
-
return
|
|
41344
|
+
return refuse3(
|
|
41309
41345
|
"above-max",
|
|
41310
41346
|
`${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
|
|
41311
41347
|
{ amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
|
|
@@ -41325,7 +41361,7 @@ var BoundaryCore = class {
|
|
|
41325
41361
|
if (!toUcd) {
|
|
41326
41362
|
const available = BigInt(s.availableReserves);
|
|
41327
41363
|
if (available < amountOut) {
|
|
41328
|
-
return
|
|
41364
|
+
return refuse3(
|
|
41329
41365
|
"insufficient-reserves",
|
|
41330
41366
|
`the PSM cannot pay this redemption: available reserves ${formatDecimalUnits(available, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${available} smallest units), required ${formatDecimalUnits(amountOut, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${amountOut} smallest units).`,
|
|
41331
41367
|
{ available: available.toString(), required: amountOut.toString(), unit: outUnit }
|
|
@@ -41401,20 +41437,31 @@ var BoundaryCore = class {
|
|
|
41401
41437
|
const inDecimals = toUcd ? s.stablecoinDecimals : 18;
|
|
41402
41438
|
const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
|
|
41403
41439
|
const viaSafe = this.deps.signer?.mode() === "safe";
|
|
41440
|
+
const a = v.allowance;
|
|
41441
|
+
const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
|
|
41442
|
+
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(
|
|
41443
|
+
(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}`
|
|
41444
|
+
).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
|
|
41404
41445
|
const data = {
|
|
41405
41446
|
direction: p.direction,
|
|
41406
41447
|
contractCall: q.contractCall,
|
|
41407
|
-
|
|
41408
|
-
|
|
41409
|
-
|
|
41410
|
-
|
|
41411
|
-
|
|
41412
|
-
|
|
41413
|
-
|
|
41414
|
-
amount: v.approve.amount,
|
|
41448
|
+
allowance: {
|
|
41449
|
+
token: a.tokenSymbol,
|
|
41450
|
+
tokenAddress: a.tokenAddress,
|
|
41451
|
+
spenderAddress: a.spenderAddress,
|
|
41452
|
+
spenderContract: a.spenderContract,
|
|
41453
|
+
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",
|
|
41454
|
+
before: a.before,
|
|
41415
41455
|
amountUnit: q.amountInUnit,
|
|
41416
|
-
|
|
41456
|
+
basis: "approvals are planned against the allowance read before signing: none when it already covers the amount; an exact approve when it is 0; a partial allowance is reset to 0 first (some tokens refuse a non-zero \u2192 non-zero approve). Every approve is EXACTLY the input amount \u2014 never unlimited."
|
|
41417
41457
|
},
|
|
41458
|
+
approvals: v.approvals.map((leg) => ({
|
|
41459
|
+
step: leg.step,
|
|
41460
|
+
txRef: leg.txRef,
|
|
41461
|
+
amount: leg.amount,
|
|
41462
|
+
amountUnit: q.amountInUnit,
|
|
41463
|
+
authorization: leg.authorization
|
|
41464
|
+
})),
|
|
41418
41465
|
execute: {
|
|
41419
41466
|
txRef: v.execute.txRef,
|
|
41420
41467
|
amountIn: v.execute.amountIn,
|
|
@@ -41436,7 +41483,7 @@ var BoundaryCore = class {
|
|
|
41436
41483
|
note: viaSafe ? "output lands AT THE SAFE \u2014 both transactions execute BY the Safe (the Safe is msg.sender, and the contract pays msg.sender only; there is no recipient parameter)" : "output goes to the signer's own address \u2014 the contract pays msg.sender only; there is no recipient parameter"
|
|
41437
41484
|
},
|
|
41438
41485
|
balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
|
|
41439
|
-
human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}).
|
|
41486
|
+
human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}). ${approvalsHuman} Ceremony ${v.approvals.length + 1}: ${q.contractCall} executed with floor ${formatDecimalUnits(BigInt(v.execute.minOut), outDecimals)} ${q.amountOutToken} (quote \u2212 ${PSM_FLOOR_TOLERANCE_BPS} bps). ` + (viaSafe ? `All executed BY the Safe as consecutive Safe transactions; output to the Safe: ${auth.borrower}.` : `Output to the signer: ${auth.borrower}.`)
|
|
41440
41487
|
};
|
|
41441
41488
|
return okEnvelope(data, r.source, warnings);
|
|
41442
41489
|
}
|
|
@@ -43295,6 +43342,16 @@ function buildExtendTx(ctx, p) {
|
|
|
43295
43342
|
);
|
|
43296
43343
|
}
|
|
43297
43344
|
|
|
43345
|
+
// src/boundary/upstream/shared/psm-approval-steps.ts
|
|
43346
|
+
function psmApprovalSteps(allowanceBefore, amountIn) {
|
|
43347
|
+
if (allowanceBefore >= amountIn) return [];
|
|
43348
|
+
if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
|
|
43349
|
+
return [
|
|
43350
|
+
{ step: "reset-approve", amount: 0n },
|
|
43351
|
+
{ step: "approve", amount: amountIn }
|
|
43352
|
+
];
|
|
43353
|
+
}
|
|
43354
|
+
|
|
43298
43355
|
// src/boundary/upstream/mock/sink-contracts.ts
|
|
43299
43356
|
var import_ethers5 = require("ethers");
|
|
43300
43357
|
function sinkAddress(label) {
|
|
@@ -43442,9 +43499,25 @@ var SignerManager = class {
|
|
|
43442
43499
|
pendingCeremonies: this.deps.pendingCeremonies()
|
|
43443
43500
|
};
|
|
43444
43501
|
}
|
|
43445
|
-
/**
|
|
43502
|
+
/**
|
|
43503
|
+
* The conversational first-run text every write answers with under mode `none`.
|
|
43504
|
+
*
|
|
43505
|
+
* It states the SCOPE of the refusal first, because the tool list does not change with
|
|
43506
|
+
* signer mode: an assistant that meets this on `loan_mint` still sees `loan_pay`,
|
|
43507
|
+
* `loan_withdraw` and `psm_swap` advertised, and its natural next move is to try one
|
|
43508
|
+
* rather than to run setup. Every one of them refuses identically here
|
|
43509
|
+
* (`BoundaryCore.requireBorrower`), so without that sentence the model rediscovers the
|
|
43510
|
+
* same wall N times and the user watches it flail. Naming the scope converts N refusals
|
|
43511
|
+
* into one instruction.
|
|
43512
|
+
*
|
|
43513
|
+
* It also says reads still work, so "no signer" is not misread as "server broken", and
|
|
43514
|
+
* it offers ONLY the modes this composition can actually construct — a build with no
|
|
43515
|
+
* keystore runtime must not suggest one (the same rule G-CONN-14 holds the guide to).
|
|
43516
|
+
*/
|
|
43446
43517
|
invitation() {
|
|
43447
|
-
|
|
43518
|
+
const keystoreOffered = this.deps.keystore !== null;
|
|
43519
|
+
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. ";
|
|
43520
|
+
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'.`;
|
|
43448
43521
|
}
|
|
43449
43522
|
};
|
|
43450
43523
|
var KeystoreProvider = class {
|
|
@@ -44121,8 +44194,9 @@ var MockUpstreamPlugin = class {
|
|
|
44121
44194
|
return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
|
|
44122
44195
|
});
|
|
44123
44196
|
}
|
|
44124
|
-
/** PSM exchange
|
|
44125
|
-
* approve
|
|
44197
|
+
/** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
|
|
44198
|
+
* or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
|
|
44199
|
+
* asymmetric by direction, contract truth), then the swap/redeem with
|
|
44126
44200
|
* its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
|
|
44127
44201
|
* AFTER the approve reports the step that declined AND the residual exact-amount
|
|
44128
44202
|
* allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
|
|
@@ -44141,55 +44215,75 @@ var MockUpstreamPlugin = class {
|
|
|
44141
44215
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
44142
44216
|
const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
|
|
44143
44217
|
const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
|
|
44144
|
-
const
|
|
44145
|
-
const
|
|
44218
|
+
const standing = this.world.psmAllowancesOf(p.borrower);
|
|
44219
|
+
const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
|
|
44220
|
+
const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
|
|
44221
|
+
const landed = [];
|
|
44222
|
+
const residualNote = () => {
|
|
44223
|
+
const last = landed[landed.length - 1];
|
|
44224
|
+
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`;
|
|
44225
|
+
return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
44226
|
+
};
|
|
44146
44227
|
const executeCard = `${isSwap ? "exchange" : "redeem"} ${p.amountIn} ${tokenUnit} via the PSM (contract ${p.direction}): quote ${plan.value.out} ${outUnit} (fee ${plan.value.fee} ${outUnit}), floor ${p.minOut} ${outUnit} \u2014 output to ${p.borrower}`;
|
|
44147
44228
|
const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
|
|
44148
44229
|
const cer = this.ceremonyNow();
|
|
44149
|
-
|
|
44150
|
-
|
|
44151
|
-
const
|
|
44152
|
-
const
|
|
44153
|
-
const
|
|
44154
|
-
|
|
44155
|
-
|
|
44156
|
-
|
|
44157
|
-
|
|
44158
|
-
|
|
44159
|
-
|
|
44160
|
-
|
|
44161
|
-
|
|
44162
|
-
|
|
44163
|
-
|
|
44230
|
+
const approvals = [];
|
|
44231
|
+
for (const s of steps) {
|
|
44232
|
+
const amount = s.amount.toString();
|
|
44233
|
+
const isReset = s.step === "reset-approve";
|
|
44234
|
+
const label = isReset ? "RESET-APPROVE" : "APPROVE";
|
|
44235
|
+
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";
|
|
44236
|
+
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})`;
|
|
44237
|
+
let legAuth = null;
|
|
44238
|
+
if (cer) {
|
|
44239
|
+
const chainId = cer.txContext().chainId;
|
|
44240
|
+
const r = await cer.authorizeTx({
|
|
44241
|
+
action: "psm-approve",
|
|
44242
|
+
borrower: p.borrower,
|
|
44243
|
+
tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
|
|
44244
|
+
expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
|
|
44164
44245
|
});
|
|
44246
|
+
if (!r.ok) {
|
|
44247
|
+
return upFail({
|
|
44248
|
+
kind: "rejected",
|
|
44249
|
+
source: "mock-ops",
|
|
44250
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
|
|
44251
|
+
});
|
|
44252
|
+
}
|
|
44253
|
+
this.bindIfDiscovering(r.authorization);
|
|
44254
|
+
legAuth = r.authorization;
|
|
44165
44255
|
}
|
|
44166
|
-
this.
|
|
44167
|
-
|
|
44168
|
-
|
|
44169
|
-
|
|
44170
|
-
|
|
44171
|
-
|
|
44172
|
-
|
|
44173
|
-
|
|
44174
|
-
|
|
44175
|
-
|
|
44256
|
+
const leg = await this.write("psmSwap", () => {
|
|
44257
|
+
const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
|
|
44258
|
+
if (!sig.ok) {
|
|
44259
|
+
return upFail({
|
|
44260
|
+
kind: "rejected",
|
|
44261
|
+
source: "mock-ops",
|
|
44262
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
|
|
44263
|
+
});
|
|
44264
|
+
}
|
|
44265
|
+
const applied = this.applyAuthorized(sig.authorization, () => {
|
|
44266
|
+
this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
|
|
44267
|
+
return { ok: true, value: void 0 };
|
|
44176
44268
|
});
|
|
44177
|
-
|
|
44178
|
-
|
|
44179
|
-
|
|
44180
|
-
|
|
44269
|
+
if (!applied.ok) {
|
|
44270
|
+
return upFail({
|
|
44271
|
+
kind: "rejected",
|
|
44272
|
+
source: "mock-ops",
|
|
44273
|
+
message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
|
|
44274
|
+
});
|
|
44275
|
+
}
|
|
44276
|
+
return upOk(sig.authorization, this.src("mock-ops"));
|
|
44181
44277
|
});
|
|
44182
|
-
if (!
|
|
44183
|
-
|
|
44184
|
-
|
|
44185
|
-
|
|
44186
|
-
|
|
44187
|
-
|
|
44188
|
-
|
|
44189
|
-
|
|
44190
|
-
}
|
|
44191
|
-
if (!step1.ok) return step1;
|
|
44192
|
-
const aAuth = step1.value;
|
|
44278
|
+
if (!leg.ok) return leg;
|
|
44279
|
+
landed.push(s.step);
|
|
44280
|
+
approvals.push({
|
|
44281
|
+
step: s.step,
|
|
44282
|
+
txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
|
|
44283
|
+
amount,
|
|
44284
|
+
authorization: leg.value
|
|
44285
|
+
});
|
|
44286
|
+
}
|
|
44193
44287
|
let executeAuth = null;
|
|
44194
44288
|
if (cer) {
|
|
44195
44289
|
const chainId = cer.txContext().chainId;
|
|
@@ -44204,7 +44298,7 @@ var MockUpstreamPlugin = class {
|
|
|
44204
44298
|
return upFail({
|
|
44205
44299
|
kind: "rejected",
|
|
44206
44300
|
source: "mock-ops",
|
|
44207
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
|
|
44301
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
|
|
44208
44302
|
});
|
|
44209
44303
|
}
|
|
44210
44304
|
executeAuth = r.authorization;
|
|
@@ -44215,23 +44309,16 @@ var MockUpstreamPlugin = class {
|
|
|
44215
44309
|
return upFail({
|
|
44216
44310
|
kind: "rejected",
|
|
44217
44311
|
source: "mock-ops",
|
|
44218
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
|
|
44312
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
|
|
44219
44313
|
});
|
|
44220
44314
|
}
|
|
44221
44315
|
const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
|
|
44222
|
-
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
|
|
44316
|
+
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
|
|
44223
44317
|
const bal = this.world.balancesOf(p.borrower);
|
|
44224
44318
|
return upOk(
|
|
44225
44319
|
{
|
|
44226
|
-
|
|
44227
|
-
|
|
44228
|
-
tokenSymbol,
|
|
44229
|
-
tokenAddress,
|
|
44230
|
-
spenderAddress,
|
|
44231
|
-
spenderContract,
|
|
44232
|
-
amount: p.amountIn,
|
|
44233
|
-
authorization: aAuth
|
|
44234
|
-
},
|
|
44320
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
44321
|
+
approvals,
|
|
44235
44322
|
execute: {
|
|
44236
44323
|
txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
|
|
44237
44324
|
amountIn: p.amountIn,
|
|
@@ -45412,7 +45499,7 @@ var SafeModuleCeremony = class {
|
|
|
45412
45499
|
};
|
|
45413
45500
|
|
|
45414
45501
|
// src/boundary/upstream/real/plugin.ts
|
|
45415
|
-
var
|
|
45502
|
+
var import_ethers48 = require("ethers");
|
|
45416
45503
|
|
|
45417
45504
|
// node_modules/@gvnrdao/dh-sdk/dist/index.mjs
|
|
45418
45505
|
var import_ethers13 = require("ethers");
|
|
@@ -51503,8 +51590,12 @@ var {
|
|
|
51503
51590
|
var import_ethers27 = require("ethers");
|
|
51504
51591
|
var import_ethers28 = require("ethers");
|
|
51505
51592
|
var import_ethers29 = require("ethers");
|
|
51506
|
-
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
51507
51593
|
var import_ethers30 = require("ethers");
|
|
51594
|
+
var import_ethers31 = require("ethers");
|
|
51595
|
+
var import_ethers32 = require("ethers");
|
|
51596
|
+
var import_ethers33 = require("ethers");
|
|
51597
|
+
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
51598
|
+
var import_ethers34 = require("ethers");
|
|
51508
51599
|
var __create2 = Object.create;
|
|
51509
51600
|
var __defProp2 = Object.defineProperty;
|
|
51510
51601
|
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
@@ -53867,7 +53958,7 @@ ${errorReport}`);
|
|
|
53867
53958
|
}
|
|
53868
53959
|
init_debug_logger();
|
|
53869
53960
|
init_session_signature_cache();
|
|
53870
|
-
var
|
|
53961
|
+
var import_ethers232 = __require("ethers");
|
|
53871
53962
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
53872
53963
|
var GRACE_PERIOD_DAYS = 30;
|
|
53873
53964
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -56795,12 +56886,12 @@ ${auth.clientId}`;
|
|
|
56795
56886
|
}
|
|
56796
56887
|
async function executeVaultSnapshot(params) {
|
|
56797
56888
|
global.ethers = {
|
|
56798
|
-
...
|
|
56889
|
+
...import_ethers232.ethers,
|
|
56799
56890
|
providers: {
|
|
56800
|
-
StaticJsonRpcProvider:
|
|
56891
|
+
StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
|
|
56801
56892
|
},
|
|
56802
|
-
Contract:
|
|
56803
|
-
utils:
|
|
56893
|
+
Contract: import_ethers232.ethers.Contract,
|
|
56894
|
+
utils: import_ethers232.ethers
|
|
56804
56895
|
// v6 moved utils to top level
|
|
56805
56896
|
};
|
|
56806
56897
|
global.Lit = {
|
|
@@ -57054,8 +57145,8 @@ function getSepoliaConfig() {
|
|
|
57054
57145
|
positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
|
|
57055
57146
|
positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
|
|
57056
57147
|
simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
|
|
57057
|
-
mockUsdcToken: SEPOLIA_CONTRACTS
|
|
57058
|
-
mockUsdtToken: SEPOLIA_CONTRACTS
|
|
57148
|
+
mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
|
|
57149
|
+
mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
|
|
57059
57150
|
loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
|
|
57060
57151
|
termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
|
|
57061
57152
|
circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
|
|
@@ -57131,14 +57222,17 @@ function getMainnetConfig() {
|
|
|
57131
57222
|
agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
|
|
57132
57223
|
},
|
|
57133
57224
|
subgraphs: {
|
|
57134
|
-
//
|
|
57135
|
-
//
|
|
57136
|
-
//
|
|
57137
|
-
//
|
|
57138
|
-
//
|
|
57139
|
-
//
|
|
57140
|
-
//
|
|
57141
|
-
|
|
57225
|
+
// The MAINNET subgraph on The Graph's decentralized network — the same id
|
|
57226
|
+
// lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
|
|
57227
|
+
// the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
|
|
57228
|
+
// chainId-1 config: unusable as shipped, but a caller who added their own key would have
|
|
57229
|
+
// read Sepolia data as mainnet.
|
|
57230
|
+
//
|
|
57231
|
+
// The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
|
|
57232
|
+
// not) hold, so this URL only works for a standalone caller supplying their own key.
|
|
57233
|
+
// Service mode never uses it — queries go through the lit-ops-server proxy, which adds
|
|
57234
|
+
// the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
|
|
57235
|
+
diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
|
|
57142
57236
|
},
|
|
57143
57237
|
litNetwork: "chipotle",
|
|
57144
57238
|
debug: false
|
|
@@ -58159,6 +58253,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
|
|
|
58159
58253
|
}
|
|
58160
58254
|
return { timestamp: result.timestamp, signature: result.signature };
|
|
58161
58255
|
}
|
|
58256
|
+
function baseMintFeeWei(mintAmountWei, originationFeeBps) {
|
|
58257
|
+
if (mintAmountWei < 0n)
|
|
58258
|
+
throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
|
|
58259
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
58260
|
+
throw new Error(
|
|
58261
|
+
`baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
58262
|
+
);
|
|
58263
|
+
}
|
|
58264
|
+
return mintAmountWei * BigInt(originationFeeBps) / 10000n;
|
|
58265
|
+
}
|
|
58266
|
+
function debtAfterMintExceedsLoanCap(params) {
|
|
58267
|
+
const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
|
|
58268
|
+
for (const [name, v] of Object.entries(params)) {
|
|
58269
|
+
if (v < 0n)
|
|
58270
|
+
throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
|
|
58271
|
+
}
|
|
58272
|
+
return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
|
|
58273
|
+
}
|
|
58274
|
+
function maxPrincipalWithinLoanCap(params) {
|
|
58275
|
+
const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
|
|
58276
|
+
if (maxLoanWei < 0n || currentDebtWei < 0n) {
|
|
58277
|
+
throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
|
|
58278
|
+
}
|
|
58279
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
58280
|
+
throw new Error(
|
|
58281
|
+
`maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
58282
|
+
);
|
|
58283
|
+
}
|
|
58284
|
+
const room = maxLoanWei - currentDebtWei;
|
|
58285
|
+
if (room <= 0n)
|
|
58286
|
+
return 0n;
|
|
58287
|
+
return room * 10000n / (10000n + BigInt(originationFeeBps));
|
|
58288
|
+
}
|
|
58162
58289
|
function buildLoginDomain(chainId) {
|
|
58163
58290
|
return {
|
|
58164
58291
|
name: "Diamond Hands",
|
|
@@ -59568,23 +59695,37 @@ var BitcoinUtils = class {
|
|
|
59568
59695
|
return getBitcoinAddressesFromPkp(pkpPublicKey);
|
|
59569
59696
|
}
|
|
59570
59697
|
};
|
|
59571
|
-
function
|
|
59698
|
+
function networksOfValidAddress(address) {
|
|
59699
|
+
const lower2 = address.toLowerCase();
|
|
59700
|
+
if (lower2.startsWith("bcrt1"))
|
|
59701
|
+
return ["regtest"];
|
|
59702
|
+
if (lower2.startsWith("bc1"))
|
|
59703
|
+
return ["mainnet"];
|
|
59704
|
+
if (lower2.startsWith("tb1"))
|
|
59705
|
+
return ["testnet"];
|
|
59706
|
+
if (address.startsWith("1") || address.startsWith("3"))
|
|
59707
|
+
return ["mainnet"];
|
|
59708
|
+
return ["testnet", "regtest"];
|
|
59709
|
+
}
|
|
59710
|
+
function safeValidateBitcoinAddress(address, network) {
|
|
59572
59711
|
if (!address || typeof address !== "string") {
|
|
59573
59712
|
throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
|
|
59574
59713
|
}
|
|
59575
|
-
|
|
59576
|
-
|
|
59577
|
-
|
|
59578
|
-
|
|
59714
|
+
if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
|
|
59715
|
+
throw new Error(
|
|
59716
|
+
`Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
|
|
59717
|
+
);
|
|
59579
59718
|
}
|
|
59580
|
-
if (
|
|
59581
|
-
|
|
59582
|
-
|
|
59583
|
-
|
|
59584
|
-
}
|
|
59585
|
-
|
|
59586
|
-
|
|
59587
|
-
|
|
59719
|
+
if (!BitcoinUtils.validateAddress(address)) {
|
|
59720
|
+
throw new Error(
|
|
59721
|
+
`Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
|
|
59722
|
+
);
|
|
59723
|
+
}
|
|
59724
|
+
const belongsTo = networksOfValidAddress(address);
|
|
59725
|
+
if (!belongsTo.includes(network)) {
|
|
59726
|
+
throw new Error(
|
|
59727
|
+
`Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
|
|
59728
|
+
);
|
|
59588
59729
|
}
|
|
59589
59730
|
return address;
|
|
59590
59731
|
}
|
|
@@ -61693,6 +61834,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
|
|
|
61693
61834
|
LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
|
|
61694
61835
|
return LoanStatus2;
|
|
61695
61836
|
})(LoanStatus || {});
|
|
61837
|
+
var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
|
|
61838
|
+
var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
|
|
61839
|
+
var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
|
|
61840
|
+
async function collectBorrowerDebtRows(fetchPage) {
|
|
61841
|
+
const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
|
|
61842
|
+
const rows = [];
|
|
61843
|
+
for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
|
|
61844
|
+
const batch = await fetchPage(page * pageSize, pageSize);
|
|
61845
|
+
if (batch.length > pageSize) {
|
|
61846
|
+
throw new Error(
|
|
61847
|
+
`Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
|
|
61848
|
+
);
|
|
61849
|
+
}
|
|
61850
|
+
rows.push(...batch);
|
|
61851
|
+
if (batch.length < pageSize) {
|
|
61852
|
+
return rows;
|
|
61853
|
+
}
|
|
61854
|
+
}
|
|
61855
|
+
throw new Error(
|
|
61856
|
+
`Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
|
|
61857
|
+
);
|
|
61858
|
+
}
|
|
61859
|
+
function parseSubgraphLoanStatus(label) {
|
|
61860
|
+
if (typeof label !== "string") {
|
|
61861
|
+
throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
|
|
61862
|
+
}
|
|
61863
|
+
const value = LoanStatus[label];
|
|
61864
|
+
if (typeof value !== "number") {
|
|
61865
|
+
throw new Error(`Unknown subgraph loan status label: "${label}"`);
|
|
61866
|
+
}
|
|
61867
|
+
return value;
|
|
61868
|
+
}
|
|
61869
|
+
function parseSubgraphWei(row) {
|
|
61870
|
+
const raw = row.ucdDebt || "0";
|
|
61871
|
+
if (typeof raw !== "string") {
|
|
61872
|
+
throw new Error(
|
|
61873
|
+
`ucdDebt on position ${row.id} is not a string: ${String(raw)}`
|
|
61874
|
+
);
|
|
61875
|
+
}
|
|
61876
|
+
let wei;
|
|
61877
|
+
try {
|
|
61878
|
+
wei = BigInt(raw);
|
|
61879
|
+
} catch (error) {
|
|
61880
|
+
throw new Error(
|
|
61881
|
+
`ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
|
|
61882
|
+
{ cause: error }
|
|
61883
|
+
);
|
|
61884
|
+
}
|
|
61885
|
+
if (wei < 0n) {
|
|
61886
|
+
throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
|
|
61887
|
+
}
|
|
61888
|
+
return wei;
|
|
61889
|
+
}
|
|
61890
|
+
var WEI_PER_UCD = 10n ** 18n;
|
|
61891
|
+
function weiToHumanUcdString(wei) {
|
|
61892
|
+
if (wei < 0n) {
|
|
61893
|
+
throw new Error(`Cannot render negative wei: ${wei}`);
|
|
61894
|
+
}
|
|
61895
|
+
const whole = wei / WEI_PER_UCD;
|
|
61896
|
+
const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
|
|
61897
|
+
return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
|
|
61898
|
+
}
|
|
61899
|
+
var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
|
|
61900
|
+
function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
|
|
61901
|
+
let totalWei = 0n;
|
|
61902
|
+
const counts = /* @__PURE__ */ new Map();
|
|
61903
|
+
for (const row of rows) {
|
|
61904
|
+
totalWei += parseSubgraphWei(row);
|
|
61905
|
+
const status = parseSubgraphLoanStatus(row.status);
|
|
61906
|
+
counts.set(status, (counts.get(status) ?? 0) + 1);
|
|
61907
|
+
}
|
|
61908
|
+
const byStatus = [];
|
|
61909
|
+
for (const status of STATUS_ORDINALS) {
|
|
61910
|
+
const count = counts.get(status);
|
|
61911
|
+
if (count === void 0) {
|
|
61912
|
+
continue;
|
|
61913
|
+
}
|
|
61914
|
+
byStatus.push({ status, statusLabel: LoanStatus[status], count });
|
|
61915
|
+
}
|
|
61916
|
+
return {
|
|
61917
|
+
borrower: borrower.toLowerCase(),
|
|
61918
|
+
loanCount: rows.length,
|
|
61919
|
+
totalUcdDebt: totalWei.toString(),
|
|
61920
|
+
totalUcdDebtHuman: weiToHumanUcdString(totalWei),
|
|
61921
|
+
byStatus,
|
|
61922
|
+
source: "subgraph",
|
|
61923
|
+
fetchedAt
|
|
61924
|
+
};
|
|
61925
|
+
}
|
|
61696
61926
|
var POSITION_CORE_ABI = [
|
|
61697
61927
|
"function getPositionDetails(bytes32) view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status, uint40 previousExpiryAt, uint16 totalTerm))"
|
|
61698
61928
|
];
|
|
@@ -62085,6 +62315,43 @@ var LoanQuery = class {
|
|
|
62085
62315
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
62086
62316
|
return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
|
|
62087
62317
|
}
|
|
62318
|
+
/**
|
|
62319
|
+
* Combined UCD debt + by-status counts for a borrower from ONE pass over the
|
|
62320
|
+
* subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
|
|
62321
|
+
* status labels, `source: "subgraph"`.
|
|
62322
|
+
*
|
|
62323
|
+
* INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
|
|
62324
|
+
* sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
|
|
62325
|
+
* failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
|
|
62326
|
+
* is no partial total.
|
|
62327
|
+
*/
|
|
62328
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
62329
|
+
const trimmed = typeof borrower === "string" ? borrower.trim() : "";
|
|
62330
|
+
if (!(0, import_ethers25.isAddress)(trimmed)) {
|
|
62331
|
+
return failure(
|
|
62332
|
+
new SDKError({
|
|
62333
|
+
message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
|
|
62334
|
+
category: "VALIDATION",
|
|
62335
|
+
severity: "LOW",
|
|
62336
|
+
context: { borrower: trimmed }
|
|
62337
|
+
})
|
|
62338
|
+
);
|
|
62339
|
+
}
|
|
62340
|
+
return tryCatchAsync(
|
|
62341
|
+
async () => {
|
|
62342
|
+
const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
|
|
62343
|
+
return buildBorrowerUcdDebtSummary(trimmed, rows);
|
|
62344
|
+
},
|
|
62345
|
+
(error) => error instanceof SDKError ? error : new SDKError({
|
|
62346
|
+
message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
|
|
62347
|
+
category: "SUBGRAPH",
|
|
62348
|
+
severity: "MEDIUM",
|
|
62349
|
+
originalError: error instanceof Error ? error : void 0,
|
|
62350
|
+
cause: error,
|
|
62351
|
+
context: { borrower: trimmed }
|
|
62352
|
+
})
|
|
62353
|
+
);
|
|
62354
|
+
}
|
|
62088
62355
|
/**
|
|
62089
62356
|
* Get active loans (status = ACTIVE)
|
|
62090
62357
|
*
|
|
@@ -63610,7 +63877,35 @@ var GraphClient = class {
|
|
|
63610
63877
|
await new Promise((r) => setTimeout(r, ms));
|
|
63611
63878
|
}
|
|
63612
63879
|
};
|
|
63613
|
-
var
|
|
63880
|
+
var GET_USER_POSITIONS_DOCUMENT = `
|
|
63881
|
+
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
63882
|
+
user(id: $borrower) {
|
|
63883
|
+
id
|
|
63884
|
+
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
63885
|
+
id
|
|
63886
|
+
pkpId
|
|
63887
|
+
borrower {
|
|
63888
|
+
createdAt
|
|
63889
|
+
id
|
|
63890
|
+
}
|
|
63891
|
+
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
63892
|
+
ucdMinted
|
|
63893
|
+
ucdPaid
|
|
63894
|
+
ucdDebt
|
|
63895
|
+
collateralRatio
|
|
63896
|
+
requestedCollateralRatio
|
|
63897
|
+
selectedTerm
|
|
63898
|
+
status
|
|
63899
|
+
createdAt
|
|
63900
|
+
createdAtBlock
|
|
63901
|
+
lastUpdated
|
|
63902
|
+
originalTerm
|
|
63903
|
+
remainingDebt
|
|
63904
|
+
expiryAt
|
|
63905
|
+
}
|
|
63906
|
+
}
|
|
63907
|
+
}
|
|
63908
|
+
`;
|
|
63614
63909
|
function normalizePkpId2(pkpId) {
|
|
63615
63910
|
const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
|
|
63616
63911
|
if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
|
|
@@ -63928,35 +64223,7 @@ var DiamondHandsGraph = class {
|
|
|
63928
64223
|
* Get user positions from subgraph
|
|
63929
64224
|
*/
|
|
63930
64225
|
async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
|
|
63931
|
-
const query =
|
|
63932
|
-
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
63933
|
-
user(id: $borrower) {
|
|
63934
|
-
id
|
|
63935
|
-
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
63936
|
-
id
|
|
63937
|
-
pkpId
|
|
63938
|
-
borrower {
|
|
63939
|
-
createdAt
|
|
63940
|
-
id
|
|
63941
|
-
}
|
|
63942
|
-
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
63943
|
-
ucdMinted
|
|
63944
|
-
ucdPaid
|
|
63945
|
-
ucdDebt
|
|
63946
|
-
collateralRatio
|
|
63947
|
-
requestedCollateralRatio
|
|
63948
|
-
selectedTerm
|
|
63949
|
-
status
|
|
63950
|
-
createdAt
|
|
63951
|
-
createdAtBlock
|
|
63952
|
-
lastUpdated
|
|
63953
|
-
originalTerm
|
|
63954
|
-
remainingDebt
|
|
63955
|
-
expiryAt
|
|
63956
|
-
}
|
|
63957
|
-
}
|
|
63958
|
-
}
|
|
63959
|
-
`;
|
|
64226
|
+
const query = GET_USER_POSITIONS_DOCUMENT;
|
|
63960
64227
|
const variables = {
|
|
63961
64228
|
borrower: userAddress.toLowerCase(),
|
|
63962
64229
|
first: first || void 0,
|
|
@@ -63974,6 +64241,45 @@ var DiamondHandsGraph = class {
|
|
|
63974
64241
|
}
|
|
63975
64242
|
return positions;
|
|
63976
64243
|
}
|
|
64244
|
+
/**
|
|
64245
|
+
* Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
|
|
64246
|
+
* 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
|
|
64247
|
+
* coerces wei to a float and leaves `status` a string cast to the numeric enum).
|
|
64248
|
+
*
|
|
64249
|
+
* Deliberately issues the `GetUserPositions` document rather than a leaner one: the
|
|
64250
|
+
* lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
|
|
64251
|
+
* and that one is already listed, so this needs no server change. The extra fields
|
|
64252
|
+
* cost bytes, not round trips.
|
|
64253
|
+
*
|
|
64254
|
+
* Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
|
|
64255
|
+
*/
|
|
64256
|
+
async getBorrowerDebtRows(borrower) {
|
|
64257
|
+
const borrowerId = borrower.toLowerCase();
|
|
64258
|
+
return collectBorrowerDebtRows(async (skip, first) => {
|
|
64259
|
+
const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
|
|
64260
|
+
borrower: borrowerId,
|
|
64261
|
+
first,
|
|
64262
|
+
skip,
|
|
64263
|
+
orderBy: "id",
|
|
64264
|
+
orderDirection: "asc"
|
|
64265
|
+
});
|
|
64266
|
+
if (result?.user == null) {
|
|
64267
|
+
if (skip > 0) {
|
|
64268
|
+
throw new Error(
|
|
64269
|
+
`getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
|
|
64270
|
+
);
|
|
64271
|
+
}
|
|
64272
|
+
return [];
|
|
64273
|
+
}
|
|
64274
|
+
const positions = result.user.positions;
|
|
64275
|
+
if (!Array.isArray(positions)) {
|
|
64276
|
+
throw new Error(
|
|
64277
|
+
`getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
|
|
64278
|
+
);
|
|
64279
|
+
}
|
|
64280
|
+
return positions.filter((p) => p != null);
|
|
64281
|
+
});
|
|
64282
|
+
}
|
|
63977
64283
|
/**
|
|
63978
64284
|
* Get user positions, plus an accurate total count.
|
|
63979
64285
|
*
|
|
@@ -70142,6 +70448,603 @@ async function mintAgentPkp(params) {
|
|
|
70142
70448
|
clearTimeout(timeout);
|
|
70143
70449
|
}
|
|
70144
70450
|
}
|
|
70451
|
+
var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
|
|
70452
|
+
function planAgentBinding(params) {
|
|
70453
|
+
const { isActive, record, nowSeconds } = params;
|
|
70454
|
+
if (isActive)
|
|
70455
|
+
return { kind: "reuse", agent: record.agent };
|
|
70456
|
+
const status = Number(record.status);
|
|
70457
|
+
if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
|
|
70458
|
+
return { kind: "register" };
|
|
70459
|
+
}
|
|
70460
|
+
if (status !== AGENT_STATUS.Active) {
|
|
70461
|
+
throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
|
|
70462
|
+
}
|
|
70463
|
+
if (Number(record.validUntil) > nowSeconds) {
|
|
70464
|
+
throw new Error(
|
|
70465
|
+
"AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
|
|
70466
|
+
);
|
|
70467
|
+
}
|
|
70468
|
+
return { kind: "rotate" };
|
|
70469
|
+
}
|
|
70470
|
+
async function describeProviderChainMismatch(provider, chainId) {
|
|
70471
|
+
const actual = Number((await provider.getNetwork()).chainId);
|
|
70472
|
+
if (actual === chainId)
|
|
70473
|
+
return null;
|
|
70474
|
+
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.`;
|
|
70475
|
+
}
|
|
70476
|
+
var TxValidationError2 = class extends Error {
|
|
70477
|
+
/**
|
|
70478
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
70479
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
70480
|
+
*/
|
|
70481
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
70482
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
70483
|
+
this.name = "TxValidationError";
|
|
70484
|
+
}
|
|
70485
|
+
};
|
|
70486
|
+
var SIGNABLE_FUNCTIONS2 = [
|
|
70487
|
+
"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)",
|
|
70488
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
70489
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
70490
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
70491
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
70492
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
70493
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
70494
|
+
// protocol cannot execute.
|
|
70495
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
70496
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
70497
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
70498
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
70499
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
70500
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
70501
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
70502
|
+
"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)",
|
|
70503
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
70504
|
+
// function reverts permanently. The trustless replacement
|
|
70505
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
70506
|
+
// entry when its LIT Action ships.
|
|
70507
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
70508
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
70509
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
70510
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
70511
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
70512
|
+
// collateral had no client-side pin at all.
|
|
70513
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
70514
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
70515
|
+
// AgentModule; the parity test documents them as client-only.
|
|
70516
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
70517
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
70518
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
70519
|
+
// this too is client-only and never module-whitelisted.
|
|
70520
|
+
"function addAddress(string btcAddress) external"
|
|
70521
|
+
];
|
|
70522
|
+
var IFACE2 = new import_ethers31.ethers.Interface(SIGNABLE_FUNCTIONS2);
|
|
70523
|
+
function encodeSignable2(fn, args) {
|
|
70524
|
+
return IFACE2.encodeFunctionData(fn, args);
|
|
70525
|
+
}
|
|
70526
|
+
function decodeSignable2(data) {
|
|
70527
|
+
try {
|
|
70528
|
+
const parsed = IFACE2.parseTransaction({ data });
|
|
70529
|
+
if (!parsed) {
|
|
70530
|
+
throw new TxValidationError2(
|
|
70531
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
70532
|
+
);
|
|
70533
|
+
}
|
|
70534
|
+
return { name: parsed.name, args: parsed.args };
|
|
70535
|
+
} catch (e) {
|
|
70536
|
+
if (e instanceof TxValidationError2)
|
|
70537
|
+
throw e;
|
|
70538
|
+
throw new TxValidationError2(
|
|
70539
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
70540
|
+
);
|
|
70541
|
+
}
|
|
70542
|
+
}
|
|
70543
|
+
var MAX_GAS_LIMIT = 5000000n;
|
|
70544
|
+
var MAX_FEE_PER_GAS_WEI = 2000000000000n;
|
|
70545
|
+
var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
|
|
70546
|
+
var DEFAULT_FEE_CEILING = {
|
|
70547
|
+
maxGasLimit: MAX_GAS_LIMIT,
|
|
70548
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
|
|
70549
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
|
|
70550
|
+
};
|
|
70551
|
+
function fmtEth(wei) {
|
|
70552
|
+
return `${import_ethers33.ethers.formatEther(wei)} ETH`;
|
|
70553
|
+
}
|
|
70554
|
+
function fmtGwei(wei) {
|
|
70555
|
+
return `${import_ethers33.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
70556
|
+
}
|
|
70557
|
+
function worstCaseFeeWei(gasLimit, maxFeePerGas) {
|
|
70558
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
70559
|
+
return null;
|
|
70560
|
+
return gasLimit * maxFeePerGas;
|
|
70561
|
+
}
|
|
70562
|
+
function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
|
|
70563
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
70564
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
70565
|
+
}
|
|
70566
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
70567
|
+
raise(
|
|
70568
|
+
`maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
|
|
70569
|
+
);
|
|
70570
|
+
}
|
|
70571
|
+
const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
|
|
70572
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
70573
|
+
raise(
|
|
70574
|
+
`worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
70575
|
+
);
|
|
70576
|
+
}
|
|
70577
|
+
}
|
|
70578
|
+
function eqAddr2(a, b) {
|
|
70579
|
+
if (!a || !b)
|
|
70580
|
+
return false;
|
|
70581
|
+
try {
|
|
70582
|
+
return import_ethers32.ethers.getAddress(a) === import_ethers32.ethers.getAddress(b);
|
|
70583
|
+
} catch {
|
|
70584
|
+
return false;
|
|
70585
|
+
}
|
|
70586
|
+
}
|
|
70587
|
+
function readToAddress2(tx2) {
|
|
70588
|
+
const to = tx2["to"];
|
|
70589
|
+
if (typeof to !== "string") {
|
|
70590
|
+
throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
|
|
70591
|
+
}
|
|
70592
|
+
return to;
|
|
70593
|
+
}
|
|
70594
|
+
function readData2(tx2) {
|
|
70595
|
+
const data = tx2["data"];
|
|
70596
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
70597
|
+
throw new TxValidationError2(`unsignedTx.data missing or malformed`);
|
|
70598
|
+
}
|
|
70599
|
+
return data;
|
|
70600
|
+
}
|
|
70601
|
+
function readChainId2(tx2) {
|
|
70602
|
+
const c = tx2["chainId"];
|
|
70603
|
+
if (c == null)
|
|
70604
|
+
return null;
|
|
70605
|
+
if (typeof c === "number")
|
|
70606
|
+
return c;
|
|
70607
|
+
if (typeof c === "string")
|
|
70608
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
70609
|
+
if (typeof c === "bigint")
|
|
70610
|
+
return Number(c);
|
|
70611
|
+
return null;
|
|
70612
|
+
}
|
|
70613
|
+
function readOptionalBigInt(tx2, key) {
|
|
70614
|
+
const v = tx2[key];
|
|
70615
|
+
if (v == null)
|
|
70616
|
+
return null;
|
|
70617
|
+
try {
|
|
70618
|
+
if (typeof v === "bigint")
|
|
70619
|
+
return v;
|
|
70620
|
+
if (typeof v === "number")
|
|
70621
|
+
return BigInt(v);
|
|
70622
|
+
if (typeof v === "string")
|
|
70623
|
+
return BigInt(v);
|
|
70624
|
+
return BigInt(v.toString());
|
|
70625
|
+
} catch {
|
|
70626
|
+
throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
|
|
70627
|
+
}
|
|
70628
|
+
}
|
|
70629
|
+
function readValue2(tx2) {
|
|
70630
|
+
const v = tx2["value"];
|
|
70631
|
+
if (v == null)
|
|
70632
|
+
return 0n;
|
|
70633
|
+
if (typeof v === "string")
|
|
70634
|
+
return BigInt(v);
|
|
70635
|
+
if (typeof v === "number")
|
|
70636
|
+
return BigInt(v);
|
|
70637
|
+
if (typeof v === "bigint")
|
|
70638
|
+
return v;
|
|
70639
|
+
const maybe = v;
|
|
70640
|
+
if (typeof maybe.toBigInt === "function")
|
|
70641
|
+
return maybe.toBigInt();
|
|
70642
|
+
if (typeof maybe.toString === "function")
|
|
70643
|
+
return BigInt(maybe.toString());
|
|
70644
|
+
throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
|
|
70645
|
+
}
|
|
70646
|
+
function normalizePositionId2(id) {
|
|
70647
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
70648
|
+
return import_ethers32.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
70649
|
+
}
|
|
70650
|
+
function requirePositionId(actual, expected) {
|
|
70651
|
+
const txPositionId = String(actual).toLowerCase();
|
|
70652
|
+
if (txPositionId !== normalizePositionId2(expected)) {
|
|
70653
|
+
throw new TxValidationError2(
|
|
70654
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
|
|
70655
|
+
);
|
|
70656
|
+
}
|
|
70657
|
+
}
|
|
70658
|
+
function validateUnsignedTx2(unsignedTx, expected, vctx) {
|
|
70659
|
+
const txChainId = readChainId2(unsignedTx);
|
|
70660
|
+
if (txChainId == null) {
|
|
70661
|
+
throw new TxValidationError2(
|
|
70662
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
70663
|
+
);
|
|
70664
|
+
}
|
|
70665
|
+
if (txChainId !== vctx.chainId) {
|
|
70666
|
+
throw new TxValidationError2(
|
|
70667
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
70668
|
+
);
|
|
70669
|
+
}
|
|
70670
|
+
const value = readValue2(unsignedTx);
|
|
70671
|
+
if (value !== 0n) {
|
|
70672
|
+
throw new TxValidationError2(
|
|
70673
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
70674
|
+
);
|
|
70675
|
+
}
|
|
70676
|
+
assertFeeCeiling(
|
|
70677
|
+
readOptionalBigInt(unsignedTx, "gasLimit"),
|
|
70678
|
+
readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
|
|
70679
|
+
(msg) => {
|
|
70680
|
+
throw new TxValidationError2(msg);
|
|
70681
|
+
},
|
|
70682
|
+
vctx.feeCeiling
|
|
70683
|
+
);
|
|
70684
|
+
const to = readToAddress2(unsignedTx);
|
|
70685
|
+
const data = readData2(unsignedTx);
|
|
70686
|
+
const { name, args } = decodeSignable2(data);
|
|
70687
|
+
const pm = vctx.contracts.PositionManager;
|
|
70688
|
+
switch (expected.kind) {
|
|
70689
|
+
case "mint": {
|
|
70690
|
+
if (name !== "mintUCD") {
|
|
70691
|
+
throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
|
|
70692
|
+
}
|
|
70693
|
+
if (!eqAddr2(to, pm)) {
|
|
70694
|
+
throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
70695
|
+
}
|
|
70696
|
+
requirePositionId(args[0], expected.positionId);
|
|
70697
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
70698
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
70699
|
+
throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
70700
|
+
}
|
|
70701
|
+
const txMintFee = BigInt(String(args[2]));
|
|
70702
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
70703
|
+
throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
70704
|
+
}
|
|
70705
|
+
break;
|
|
70706
|
+
}
|
|
70707
|
+
case "repay": {
|
|
70708
|
+
if (name !== "makePayment") {
|
|
70709
|
+
throw new TxValidationError2(`expected makePayment, server returned ${name}`);
|
|
70710
|
+
}
|
|
70711
|
+
if (!eqAddr2(to, pm)) {
|
|
70712
|
+
throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
70713
|
+
}
|
|
70714
|
+
requirePositionId(args[0], expected.positionId);
|
|
70715
|
+
const txAmount = BigInt(String(args[1]));
|
|
70716
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
70717
|
+
throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
70718
|
+
}
|
|
70719
|
+
break;
|
|
70720
|
+
}
|
|
70721
|
+
case "extend": {
|
|
70722
|
+
if (name !== "extendPosition") {
|
|
70723
|
+
throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
|
|
70724
|
+
}
|
|
70725
|
+
if (!eqAddr2(to, pm)) {
|
|
70726
|
+
throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
70727
|
+
}
|
|
70728
|
+
requirePositionId(args[0], expected.positionId);
|
|
70729
|
+
const txTerm = Number(args[1]);
|
|
70730
|
+
if (txTerm !== expected.selectedTerm) {
|
|
70731
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
70732
|
+
}
|
|
70733
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
70734
|
+
const txFee = BigInt(String(args[5]));
|
|
70735
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
70736
|
+
if (txFee > upper) {
|
|
70737
|
+
throw new TxValidationError2(
|
|
70738
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
70739
|
+
);
|
|
70740
|
+
}
|
|
70741
|
+
}
|
|
70742
|
+
break;
|
|
70743
|
+
}
|
|
70744
|
+
case "withdraw-btc": {
|
|
70745
|
+
if (name !== "withdrawBTC") {
|
|
70746
|
+
throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
|
|
70747
|
+
}
|
|
70748
|
+
if (!eqAddr2(to, pm)) {
|
|
70749
|
+
throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
70750
|
+
}
|
|
70751
|
+
const paramsTuple = args[0];
|
|
70752
|
+
requirePositionId(paramsTuple[0], expected.positionId);
|
|
70753
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
70754
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
70755
|
+
throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
70756
|
+
}
|
|
70757
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
70758
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
70759
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
70760
|
+
if (txDeduction > upper) {
|
|
70761
|
+
throw new TxValidationError2(
|
|
70762
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
70763
|
+
);
|
|
70764
|
+
}
|
|
70765
|
+
}
|
|
70766
|
+
break;
|
|
70767
|
+
}
|
|
70768
|
+
case "ucd-approve": {
|
|
70769
|
+
if (name !== "approve") {
|
|
70770
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70771
|
+
}
|
|
70772
|
+
const ucd = vctx.contracts.UCDToken;
|
|
70773
|
+
if (!eqAddr2(to, ucd)) {
|
|
70774
|
+
throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
70775
|
+
}
|
|
70776
|
+
const spender = String(args[0]);
|
|
70777
|
+
const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
|
|
70778
|
+
if (!ok2) {
|
|
70779
|
+
throw new TxValidationError2(
|
|
70780
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
70781
|
+
);
|
|
70782
|
+
}
|
|
70783
|
+
const amt = BigInt(String(args[1]));
|
|
70784
|
+
const min = BigInt(expected.minAmountWei);
|
|
70785
|
+
if (amt < min) {
|
|
70786
|
+
throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
|
|
70787
|
+
}
|
|
70788
|
+
const SANITY_MAX = min * 1000n;
|
|
70789
|
+
if (amt > SANITY_MAX) {
|
|
70790
|
+
throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
70791
|
+
}
|
|
70792
|
+
break;
|
|
70793
|
+
}
|
|
70794
|
+
case "create-position": {
|
|
70795
|
+
if (name !== "createPosition") {
|
|
70796
|
+
throw new TxValidationError2(`expected createPosition, server returned ${name}`);
|
|
70797
|
+
}
|
|
70798
|
+
if (!eqAddr2(to, pm)) {
|
|
70799
|
+
throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
70800
|
+
}
|
|
70801
|
+
const txTerm = BigInt(String(args[4]));
|
|
70802
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
70803
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
70804
|
+
}
|
|
70805
|
+
break;
|
|
70806
|
+
}
|
|
70807
|
+
case "set-position-delegate": {
|
|
70808
|
+
if (name !== "setPositionDelegate") {
|
|
70809
|
+
throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
|
|
70810
|
+
}
|
|
70811
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
70812
|
+
throw new TxValidationError2(
|
|
70813
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
70814
|
+
);
|
|
70815
|
+
}
|
|
70816
|
+
requirePositionId(args[0], expected.positionId);
|
|
70817
|
+
const txDelegate = String(args[1]);
|
|
70818
|
+
if (!eqAddr2(txDelegate, expected.delegate)) {
|
|
70819
|
+
throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
70820
|
+
}
|
|
70821
|
+
break;
|
|
70822
|
+
}
|
|
70823
|
+
case "bwar-add-address": {
|
|
70824
|
+
if (name !== "addAddress") {
|
|
70825
|
+
throw new TxValidationError2(`expected addAddress, decoded ${name}`);
|
|
70826
|
+
}
|
|
70827
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
70828
|
+
throw new TxValidationError2(
|
|
70829
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
70830
|
+
);
|
|
70831
|
+
}
|
|
70832
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
70833
|
+
throw new TxValidationError2(
|
|
70834
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
70835
|
+
);
|
|
70836
|
+
}
|
|
70837
|
+
break;
|
|
70838
|
+
}
|
|
70839
|
+
case "stablecoin-approve": {
|
|
70840
|
+
if (name !== "approve") {
|
|
70841
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70842
|
+
}
|
|
70843
|
+
if (!eqAddr2(to, expected.tokenAddress)) {
|
|
70844
|
+
throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
70845
|
+
}
|
|
70846
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
70847
|
+
throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
70848
|
+
}
|
|
70849
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
70850
|
+
throw new TxValidationError2(
|
|
70851
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
70852
|
+
);
|
|
70853
|
+
}
|
|
70854
|
+
break;
|
|
70855
|
+
}
|
|
70856
|
+
case "ucd-approve-controller": {
|
|
70857
|
+
if (name !== "approve") {
|
|
70858
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70859
|
+
}
|
|
70860
|
+
if (!eqAddr2(to, expected.ucdTokenAddress)) {
|
|
70861
|
+
throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
70862
|
+
}
|
|
70863
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
70864
|
+
throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
70865
|
+
}
|
|
70866
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
70867
|
+
throw new TxValidationError2(
|
|
70868
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
70869
|
+
);
|
|
70870
|
+
}
|
|
70871
|
+
break;
|
|
70872
|
+
}
|
|
70873
|
+
case "psm-swap": {
|
|
70874
|
+
if (name !== "swap")
|
|
70875
|
+
throw new TxValidationError2(`expected swap, server returned ${name}`);
|
|
70876
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
70877
|
+
throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
70878
|
+
}
|
|
70879
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
70880
|
+
throw new TxValidationError2(`swap stablecoin mismatch`);
|
|
70881
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
70882
|
+
throw new TxValidationError2(`swap amountIn mismatch`);
|
|
70883
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
70884
|
+
throw new TxValidationError2(`swap minUcdOut mismatch`);
|
|
70885
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
70886
|
+
throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
70887
|
+
}
|
|
70888
|
+
break;
|
|
70889
|
+
}
|
|
70890
|
+
case "psm-redeem": {
|
|
70891
|
+
if (name !== "redeem")
|
|
70892
|
+
throw new TxValidationError2(`expected redeem, server returned ${name}`);
|
|
70893
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
70894
|
+
throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
70895
|
+
}
|
|
70896
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
70897
|
+
throw new TxValidationError2(`redeem stablecoin mismatch`);
|
|
70898
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
70899
|
+
throw new TxValidationError2(`redeem ucdAmount mismatch`);
|
|
70900
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
70901
|
+
throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
|
|
70902
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
70903
|
+
throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
70904
|
+
}
|
|
70905
|
+
break;
|
|
70906
|
+
}
|
|
70907
|
+
default: {
|
|
70908
|
+
const _exhaustive = expected;
|
|
70909
|
+
throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
70910
|
+
}
|
|
70911
|
+
}
|
|
70912
|
+
}
|
|
70913
|
+
function buildPsmApproveTx(p) {
|
|
70914
|
+
return {
|
|
70915
|
+
to: p.token,
|
|
70916
|
+
data: encodeSignable2("approve", [p.spender, p.amount]),
|
|
70917
|
+
value: "0x0",
|
|
70918
|
+
chainId: p.chainId
|
|
70919
|
+
};
|
|
70920
|
+
}
|
|
70921
|
+
function buildPsmSwapTx2(p) {
|
|
70922
|
+
return {
|
|
70923
|
+
to: p.psm,
|
|
70924
|
+
data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
70925
|
+
value: "0x0",
|
|
70926
|
+
chainId: p.chainId
|
|
70927
|
+
};
|
|
70928
|
+
}
|
|
70929
|
+
function buildPsmRedeemTx2(p) {
|
|
70930
|
+
return {
|
|
70931
|
+
to: p.psm,
|
|
70932
|
+
data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
70933
|
+
value: "0x0",
|
|
70934
|
+
chainId: p.chainId
|
|
70935
|
+
};
|
|
70936
|
+
}
|
|
70937
|
+
var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
|
|
70938
|
+
var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
70939
|
+
function psmExchangeReadsFromProvider(provider, psmAddress) {
|
|
70940
|
+
const psm = new import_ethers30.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
|
|
70941
|
+
return {
|
|
70942
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
70943
|
+
allowance: async (token, owner, spender) => await new import_ethers30.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
|
|
70944
|
+
};
|
|
70945
|
+
}
|
|
70946
|
+
var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
|
|
70947
|
+
function requireAddress(direction, label, value) {
|
|
70948
|
+
if (!value || !import_ethers30.ethers.isAddress(value)) {
|
|
70949
|
+
throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
70950
|
+
}
|
|
70951
|
+
return import_ethers30.ethers.getAddress(value);
|
|
70952
|
+
}
|
|
70953
|
+
async function planPsmExchange(params) {
|
|
70954
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
70955
|
+
const chainId = vctx.chainId;
|
|
70956
|
+
if (amountIn <= 0n) {
|
|
70957
|
+
throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
70958
|
+
}
|
|
70959
|
+
if (minOut <= 0n) {
|
|
70960
|
+
throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
70961
|
+
}
|
|
70962
|
+
const owner = requireAddress(direction, "owner", params.owner);
|
|
70963
|
+
const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
|
|
70964
|
+
const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
|
|
70965
|
+
const isSwap = direction === "swap";
|
|
70966
|
+
const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
|
|
70967
|
+
const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
|
|
70968
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
70969
|
+
throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
70970
|
+
}
|
|
70971
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
70972
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
70973
|
+
const approvals = [];
|
|
70974
|
+
if (allowanceBefore < amountIn) {
|
|
70975
|
+
if (allowanceBefore > 0n) {
|
|
70976
|
+
approvals.push({
|
|
70977
|
+
step: "reset-approve",
|
|
70978
|
+
tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
|
|
70979
|
+
expected: approveExpected(0n)
|
|
70980
|
+
});
|
|
70981
|
+
}
|
|
70982
|
+
approvals.push({
|
|
70983
|
+
step: "approve",
|
|
70984
|
+
tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
|
|
70985
|
+
expected: approveExpected(amountIn)
|
|
70986
|
+
});
|
|
70987
|
+
}
|
|
70988
|
+
const exec = isSwap ? {
|
|
70989
|
+
step: "swap",
|
|
70990
|
+
tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
70991
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
70992
|
+
} : {
|
|
70993
|
+
step: "redeem",
|
|
70994
|
+
tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
70995
|
+
expected: {
|
|
70996
|
+
kind: "psm-redeem",
|
|
70997
|
+
psmAddress: psm,
|
|
70998
|
+
stablecoin,
|
|
70999
|
+
amountUcdWei: amountIn.toString(),
|
|
71000
|
+
minOut: minOut.toString()
|
|
71001
|
+
}
|
|
71002
|
+
};
|
|
71003
|
+
for (const leg of [...approvals, exec]) {
|
|
71004
|
+
validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
|
|
71005
|
+
}
|
|
71006
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
71007
|
+
}
|
|
71008
|
+
async function executePsmPlan(plan, signer, vctx) {
|
|
71009
|
+
const approvalHashes = [];
|
|
71010
|
+
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.`;
|
|
71011
|
+
const sendLeg = async (leg) => {
|
|
71012
|
+
const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
|
|
71013
|
+
validateUnsignedTx2({ ...request }, leg.expected, vctx);
|
|
71014
|
+
const sent = await signer.sendTransaction(request);
|
|
71015
|
+
const receipt = await sent.wait();
|
|
71016
|
+
if (!receipt)
|
|
71017
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
|
|
71018
|
+
if (receipt.status !== 1)
|
|
71019
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
|
|
71020
|
+
return { hash: sent.hash, blockNumber: receipt.blockNumber };
|
|
71021
|
+
};
|
|
71022
|
+
for (const leg of plan.approvals) {
|
|
71023
|
+
const landed = await sendLeg(leg).catch((e) => {
|
|
71024
|
+
throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
71025
|
+
});
|
|
71026
|
+
approvalHashes.push(landed.hash);
|
|
71027
|
+
}
|
|
71028
|
+
const exec = await sendLeg(plan.exec).catch((e) => {
|
|
71029
|
+
throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
71030
|
+
});
|
|
71031
|
+
return { ...exec, approvalHashes };
|
|
71032
|
+
}
|
|
71033
|
+
var LIT_ACTION_CHAIN_NAMES = Object.freeze({
|
|
71034
|
+
1: "ethereum",
|
|
71035
|
+
11155111: "sepolia",
|
|
71036
|
+
1337: "hardhat",
|
|
71037
|
+
31337: "hardhat"
|
|
71038
|
+
});
|
|
71039
|
+
function litActionChainNameForChainId(chainId) {
|
|
71040
|
+
const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
|
|
71041
|
+
if (!name) {
|
|
71042
|
+
throw new Error(
|
|
71043
|
+
`Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
|
|
71044
|
+
);
|
|
71045
|
+
}
|
|
71046
|
+
return name;
|
|
71047
|
+
}
|
|
70145
71048
|
var MockTokenManager = class {
|
|
70146
71049
|
config;
|
|
70147
71050
|
constructor(config) {
|
|
@@ -71115,6 +72018,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71115
72018
|
*/
|
|
71116
72019
|
static async create(config) {
|
|
71117
72020
|
const userProvidedServiceEndpoint = config.serviceEndpoint;
|
|
72021
|
+
if (typeof config.chainId === "number" && config.provider) {
|
|
72022
|
+
const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
|
|
72023
|
+
if (mismatch) {
|
|
72024
|
+
return failure(
|
|
72025
|
+
new SDKError({
|
|
72026
|
+
message: mismatch,
|
|
72027
|
+
category: "CONFIGURATION",
|
|
72028
|
+
severity: "HIGH"
|
|
72029
|
+
/* HIGH */
|
|
72030
|
+
})
|
|
72031
|
+
);
|
|
72032
|
+
}
|
|
72033
|
+
}
|
|
71118
72034
|
const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
|
|
71119
72035
|
if (userProvidedServiceEndpoint) {
|
|
71120
72036
|
enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
|
|
@@ -71765,6 +72681,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71765
72681
|
if (this.config.debug) {
|
|
71766
72682
|
log.info(` Position PKP ID: ${position2.pkpId}`);
|
|
71767
72683
|
}
|
|
72684
|
+
const termsResult = await this.getTermsWithFees();
|
|
72685
|
+
if (!termsResult.success) {
|
|
72686
|
+
return {
|
|
72687
|
+
success: false,
|
|
72688
|
+
error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
|
|
72689
|
+
};
|
|
72690
|
+
}
|
|
72691
|
+
const positionTermMonths = Number(position2.selectedTerm);
|
|
72692
|
+
const positionTerm = termsResult.value.terms.find(
|
|
72693
|
+
(term) => term.termMonths === positionTermMonths
|
|
72694
|
+
);
|
|
72695
|
+
if (!positionTerm) {
|
|
72696
|
+
return {
|
|
72697
|
+
success: false,
|
|
72698
|
+
error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
|
|
72699
|
+
};
|
|
72700
|
+
}
|
|
72701
|
+
const currentDebtWei = BigInt(position2.ucdDebt);
|
|
72702
|
+
const baseFeeWei = baseMintFeeWei(
|
|
72703
|
+
requestAmountWei,
|
|
72704
|
+
positionTerm.originationFeeBps
|
|
72705
|
+
);
|
|
72706
|
+
if (debtAfterMintExceedsLoanCap({
|
|
72707
|
+
currentDebtWei,
|
|
72708
|
+
mintAmountWei: requestAmountWei,
|
|
72709
|
+
mintFeeWei: baseFeeWei,
|
|
72710
|
+
maxLoanWei: maxLoanValueWei
|
|
72711
|
+
})) {
|
|
72712
|
+
const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
|
|
72713
|
+
const maxPrincipalUcd = Number(
|
|
72714
|
+
maxPrincipalWithinLoanCap({
|
|
72715
|
+
maxLoanWei: maxLoanValueWei,
|
|
72716
|
+
currentDebtWei,
|
|
72717
|
+
originationFeeBps: positionTerm.originationFeeBps
|
|
72718
|
+
}) / BigInt(10 ** 18)
|
|
72719
|
+
);
|
|
72720
|
+
return {
|
|
72721
|
+
success: false,
|
|
72722
|
+
error: `Amount ${request.amount} UCD plus the ${positionTerm.originationFeeBps / 100}% origination fee (${(0, import_ethers13.formatEther)(baseFeeWei)} UCD) would take this loan's debt to ${(0, import_ethers13.formatEther)(debtAfterWei)} UCD, above the protocol maximum of ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD. The largest amount you can mint now is ${maxPrincipalUcd} UCD.`
|
|
72723
|
+
};
|
|
72724
|
+
}
|
|
72725
|
+
if (this.config.debug) {
|
|
72726
|
+
log.info(
|
|
72727
|
+
`\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers13.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD`,
|
|
72728
|
+
{}
|
|
72729
|
+
);
|
|
72730
|
+
}
|
|
71768
72731
|
let pkpPublicKey;
|
|
71769
72732
|
let pkpEthAddress;
|
|
71770
72733
|
const pkpCache = this.cacheManager.getCache("pkp-data", {
|
|
@@ -71854,7 +72817,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71854
72817
|
` UCDController: ${contracts?.UCDController || "MISSING"}`
|
|
71855
72818
|
);
|
|
71856
72819
|
}
|
|
71857
|
-
const chain = this.config.chain || (
|
|
72820
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
71858
72821
|
const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
|
|
71859
72822
|
if (this.config.debug) {
|
|
71860
72823
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -72454,6 +73417,25 @@ Error data: none`
|
|
|
72454
73417
|
}
|
|
72455
73418
|
const selector = simError.selector;
|
|
72456
73419
|
const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
|
|
73420
|
+
const MINT_GUARD_CODES = {
|
|
73421
|
+
"1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
|
|
73422
|
+
"2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
|
|
73423
|
+
"3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
|
|
73424
|
+
};
|
|
73425
|
+
let loanCapDiagnostics = "";
|
|
73426
|
+
if (selector === "0xe6dd4d41") {
|
|
73427
|
+
const guardCode = BigInt(
|
|
73428
|
+
"0x" + String(simError.data).slice(10).padStart(64, "0")
|
|
73429
|
+
).toString();
|
|
73430
|
+
const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
|
|
73431
|
+
loanCapDiagnostics = `
|
|
73432
|
+
|
|
73433
|
+
MintGuardFailed(${guardCode}): ${guardMeaning}
|
|
73434
|
+
Lit mintAmount: ${validationResponse.mintAmount}
|
|
73435
|
+
Lit mintFee: ${validationResponse.mintFee}
|
|
73436
|
+
Lit newDebt: ${validationResponse.newDebt}
|
|
73437
|
+
Protocol maximum: ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
|
|
73438
|
+
}
|
|
72457
73439
|
const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
|
|
72458
73440
|
selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
|
|
72459
73441
|
selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
|
|
@@ -72499,7 +73481,7 @@ Quantum Timing Analysis:
|
|
|
72499
73481
|
Error selector: ${selector}
|
|
72500
73482
|
Error data: ${simError.data}
|
|
72501
73483
|
Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
|
|
72502
|
-
Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
73484
|
+
Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
|
|
72503
73485
|
);
|
|
72504
73486
|
}
|
|
72505
73487
|
const tx2 = await sendEip1559Transaction({
|
|
@@ -75107,7 +76089,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
75107
76089
|
` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
|
|
75108
76090
|
);
|
|
75109
76091
|
}
|
|
75110
|
-
const chain = this.config.chain || (
|
|
76092
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
75111
76093
|
const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
|
|
75112
76094
|
if (this.config.debug) {
|
|
75113
76095
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -75662,13 +76644,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
75662
76644
|
return { success: false, error: "Failed to resolve PKP public key" };
|
|
75663
76645
|
}
|
|
75664
76646
|
const chipotlePkpAddress = (0, import_ethers13.computeAddress)(publicKey);
|
|
75665
|
-
const
|
|
75666
|
-
1: "ethereum",
|
|
75667
|
-
11155111: "sepolia",
|
|
75668
|
-
1337: "hardhat",
|
|
75669
|
-
31337: "hardhat"
|
|
75670
|
-
};
|
|
75671
|
-
const chainName = STANDALONE_CHAIN_NAMES[chainId];
|
|
76647
|
+
const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
|
|
75672
76648
|
if (!chainName) {
|
|
75673
76649
|
return {
|
|
75674
76650
|
success: false,
|
|
@@ -76890,6 +77866,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76890
77866
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
76891
77867
|
return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
|
|
76892
77868
|
}
|
|
77869
|
+
/**
|
|
77870
|
+
* Combined UCD debt (canonical wei string + display string) and by-status loan
|
|
77871
|
+
* counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
|
|
77872
|
+
* an INDEXED, informational figure that lags writes; never size a transaction
|
|
77873
|
+
* from it (repayments read the chain via `getPositionDetailsView`).
|
|
77874
|
+
*
|
|
77875
|
+
* Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
|
|
77876
|
+
* failure or past 10,000 positions; never returns a partial total.
|
|
77877
|
+
*/
|
|
77878
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
77879
|
+
return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
|
|
77880
|
+
}
|
|
76893
77881
|
/**
|
|
76894
77882
|
* Get all active loans
|
|
76895
77883
|
*
|
|
@@ -77015,11 +78003,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77015
78003
|
}
|
|
77016
78004
|
/**
|
|
77017
78005
|
* Execute a PSM stablecoin → UCD swap.
|
|
77018
|
-
*
|
|
78006
|
+
* Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
|
|
78007
|
+
* partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
|
|
77019
78008
|
*
|
|
77020
78009
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
|
|
77021
78010
|
* @param params.amountWei - Stablecoin amount in native decimals (bigint)
|
|
77022
|
-
* @param params.minUcdOutWei - Minimum UCD to receive;
|
|
78011
|
+
* @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
|
|
77023
78012
|
* @param params.signer - Connected signer for the approval and swap transactions
|
|
77024
78013
|
*/
|
|
77025
78014
|
async psmSwap(params) {
|
|
@@ -77029,32 +78018,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77029
78018
|
"SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
|
|
77030
78019
|
);
|
|
77031
78020
|
}
|
|
77032
|
-
|
|
77033
|
-
|
|
77034
|
-
|
|
77035
|
-
|
|
77036
|
-
|
|
77037
|
-
|
|
77038
|
-
|
|
77039
|
-
if (allowance < params.amountWei) {
|
|
77040
|
-
const approveTx = await stablecoin.approve(psmAddress, import_ethers13.MaxUint256);
|
|
77041
|
-
await approveTx.wait();
|
|
77042
|
-
}
|
|
77043
|
-
const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
|
|
77044
|
-
const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
|
|
77045
|
-
const receipt = await tx2.wait();
|
|
77046
|
-
if (!receipt)
|
|
77047
|
-
throw new Error("PSM swap transaction receipt unavailable");
|
|
77048
|
-
return { hash: tx2.hash, blockNumber: receipt.blockNumber };
|
|
78021
|
+
return this.runPsmExchange({
|
|
78022
|
+
direction: "swap",
|
|
78023
|
+
signer: params.signer,
|
|
78024
|
+
addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
|
|
78025
|
+
amountIn: params.amountWei,
|
|
78026
|
+
minOut: params.minUcdOutWei
|
|
78027
|
+
});
|
|
77049
78028
|
}
|
|
77050
78029
|
/**
|
|
77051
78030
|
* Execute a PSM UCD → stablecoin redeem.
|
|
77052
|
-
*
|
|
77053
|
-
* UCDToken.burn(from, amount) calls
|
|
78031
|
+
* Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
|
|
78032
|
+
* M-4 burn allowance guard: UCDToken.burn(from, amount) calls
|
|
78033
|
+
* _spendAllowance(from, msg.sender=ucdController, amount).
|
|
77054
78034
|
*
|
|
77055
78035
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
|
|
77056
78036
|
* @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
|
|
77057
|
-
* @param params.minStablecoinOutWei - Minimum stablecoin to receive
|
|
78037
|
+
* @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
|
|
77058
78038
|
* @param params.signer - Connected signer
|
|
77059
78039
|
*/
|
|
77060
78040
|
async psmRedeem(params) {
|
|
@@ -77067,23 +78047,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77067
78047
|
throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
|
|
77068
78048
|
if (!ucdControllerAddress)
|
|
77069
78049
|
throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
|
|
77070
|
-
|
|
77071
|
-
|
|
77072
|
-
|
|
77073
|
-
|
|
77074
|
-
|
|
77075
|
-
|
|
77076
|
-
|
|
77077
|
-
|
|
77078
|
-
|
|
77079
|
-
|
|
77080
|
-
|
|
77081
|
-
|
|
77082
|
-
|
|
77083
|
-
|
|
77084
|
-
|
|
77085
|
-
|
|
77086
|
-
|
|
78050
|
+
return this.runPsmExchange({
|
|
78051
|
+
direction: "redeem",
|
|
78052
|
+
signer: params.signer,
|
|
78053
|
+
addresses: {
|
|
78054
|
+
psm: psmAddress,
|
|
78055
|
+
stablecoin: params.stablecoinAddress,
|
|
78056
|
+
ucdToken: ucdAddress,
|
|
78057
|
+
ucdController: ucdControllerAddress
|
|
78058
|
+
},
|
|
78059
|
+
amountIn: params.ucdAmountWei,
|
|
78060
|
+
minOut: params.minStablecoinOutWei
|
|
78061
|
+
});
|
|
78062
|
+
}
|
|
78063
|
+
/**
|
|
78064
|
+
* Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
|
|
78065
|
+
* The signer's chain must match the SDK's configured chain — the addresses came from it.
|
|
78066
|
+
*/
|
|
78067
|
+
async runPsmExchange(params) {
|
|
78068
|
+
const provider = params.signer.provider;
|
|
78069
|
+
if (!provider) {
|
|
78070
|
+
throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
|
|
78071
|
+
}
|
|
78072
|
+
const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
|
|
78073
|
+
if (typeof configuredChainId !== "number") {
|
|
78074
|
+
throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
|
|
78075
|
+
}
|
|
78076
|
+
const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
|
|
78077
|
+
if (mismatch)
|
|
78078
|
+
throw new Error(mismatch);
|
|
78079
|
+
const vctx = {
|
|
78080
|
+
chainId: configuredChainId,
|
|
78081
|
+
network: String(configuredChainId),
|
|
78082
|
+
contracts: {}
|
|
78083
|
+
};
|
|
78084
|
+
const plan = await planPsmExchange({
|
|
78085
|
+
direction: params.direction,
|
|
78086
|
+
owner: await params.signer.getAddress(),
|
|
78087
|
+
addresses: params.addresses,
|
|
78088
|
+
amountIn: params.amountIn,
|
|
78089
|
+
minOut: params.minOut,
|
|
78090
|
+
vctx,
|
|
78091
|
+
reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
|
|
78092
|
+
});
|
|
78093
|
+
const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
|
|
78094
|
+
return { hash, blockNumber };
|
|
77087
78095
|
}
|
|
77088
78096
|
/**
|
|
77089
78097
|
* Wait for the subgraph to index up to (and including) the given block number.
|
|
@@ -77264,18 +78272,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77264
78272
|
const user = await signer.getAddress();
|
|
77265
78273
|
const registry = AgentDelegationRegistry__factory.connect(addr, signer);
|
|
77266
78274
|
let agentAddress;
|
|
77267
|
-
const
|
|
77268
|
-
|
|
77269
|
-
|
|
78275
|
+
const [isActive, record, latestBlock] = await Promise.all([
|
|
78276
|
+
registry.isAgentActive(user),
|
|
78277
|
+
registry.agentOf(user),
|
|
78278
|
+
this.getProviderOrThrow().getBlock("latest")
|
|
78279
|
+
]);
|
|
78280
|
+
if (!latestBlock) {
|
|
78281
|
+
throw new SDKError({
|
|
78282
|
+
message: "Could not read the latest block to check the agent registration's expiry",
|
|
78283
|
+
category: "NETWORK",
|
|
78284
|
+
severity: "HIGH"
|
|
78285
|
+
/* HIGH */
|
|
78286
|
+
});
|
|
78287
|
+
}
|
|
78288
|
+
const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
|
|
78289
|
+
if (plan.kind === "reuse") {
|
|
78290
|
+
agentAddress = plan.agent;
|
|
77270
78291
|
} else {
|
|
77271
78292
|
agentAddress = await mintAgentPkp({
|
|
77272
78293
|
serviceEndpoint: this.config.serviceEndpoint,
|
|
77273
78294
|
authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
|
|
77274
78295
|
});
|
|
77275
78296
|
const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
|
|
77276
|
-
const validUntil =
|
|
77277
|
-
const
|
|
77278
|
-
await
|
|
78297
|
+
const validUntil = latestBlock.timestamp + validitySeconds;
|
|
78298
|
+
const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
|
|
78299
|
+
await bindTx.wait();
|
|
77279
78300
|
}
|
|
77280
78301
|
const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
|
|
77281
78302
|
() => null
|
|
@@ -78667,7 +79688,552 @@ var SUPPORTED_STABLECOINS = `
|
|
|
78667
79688
|
}`;
|
|
78668
79689
|
|
|
78669
79690
|
// src/boundary/upstream/real/psm-calls.ts
|
|
78670
|
-
var
|
|
79691
|
+
var import_ethers41 = require("ethers");
|
|
79692
|
+
|
|
79693
|
+
// node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
|
|
79694
|
+
var import_ethers35 = require("ethers");
|
|
79695
|
+
var import_ethers36 = require("ethers");
|
|
79696
|
+
var import_ethers37 = require("ethers");
|
|
79697
|
+
var import_ethers38 = require("ethers");
|
|
79698
|
+
var import_ethers39 = require("ethers");
|
|
79699
|
+
var import_ethers40 = require("ethers");
|
|
79700
|
+
var TxValidationError3 = class extends Error {
|
|
79701
|
+
/**
|
|
79702
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
79703
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
79704
|
+
*/
|
|
79705
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
79706
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
79707
|
+
this.name = "TxValidationError";
|
|
79708
|
+
}
|
|
79709
|
+
};
|
|
79710
|
+
var SIGNABLE_FUNCTIONS3 = [
|
|
79711
|
+
"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)",
|
|
79712
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
79713
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
79714
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
79715
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
79716
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
79717
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
79718
|
+
// protocol cannot execute.
|
|
79719
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
79720
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
79721
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
79722
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
79723
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
79724
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
79725
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
79726
|
+
"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)",
|
|
79727
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
79728
|
+
// function reverts permanently. The trustless replacement
|
|
79729
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
79730
|
+
// entry when its LIT Action ships.
|
|
79731
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
79732
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
79733
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
79734
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
79735
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
79736
|
+
// collateral had no client-side pin at all.
|
|
79737
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
79738
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
79739
|
+
// AgentModule; the parity test documents them as client-only.
|
|
79740
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
79741
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
79742
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
79743
|
+
// this too is client-only and never module-whitelisted.
|
|
79744
|
+
"function addAddress(string btcAddress) external"
|
|
79745
|
+
];
|
|
79746
|
+
var IFACE3 = new import_ethers35.ethers.Interface(SIGNABLE_FUNCTIONS3);
|
|
79747
|
+
function encodeSignable3(fn, args) {
|
|
79748
|
+
return IFACE3.encodeFunctionData(fn, args);
|
|
79749
|
+
}
|
|
79750
|
+
function decodeSignable3(data) {
|
|
79751
|
+
try {
|
|
79752
|
+
const parsed = IFACE3.parseTransaction({ data });
|
|
79753
|
+
if (!parsed) {
|
|
79754
|
+
throw new TxValidationError3(
|
|
79755
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
79756
|
+
);
|
|
79757
|
+
}
|
|
79758
|
+
return { name: parsed.name, args: parsed.args };
|
|
79759
|
+
} catch (e) {
|
|
79760
|
+
if (e instanceof TxValidationError3)
|
|
79761
|
+
throw e;
|
|
79762
|
+
throw new TxValidationError3(
|
|
79763
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
79764
|
+
);
|
|
79765
|
+
}
|
|
79766
|
+
}
|
|
79767
|
+
var MAX_GAS_LIMIT2 = 5000000n;
|
|
79768
|
+
var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
|
|
79769
|
+
var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
|
|
79770
|
+
var DEFAULT_FEE_CEILING2 = {
|
|
79771
|
+
maxGasLimit: MAX_GAS_LIMIT2,
|
|
79772
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
|
|
79773
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
|
|
79774
|
+
};
|
|
79775
|
+
function fmtEth2(wei) {
|
|
79776
|
+
return `${import_ethers36.ethers.formatEther(wei)} ETH`;
|
|
79777
|
+
}
|
|
79778
|
+
function fmtGwei2(wei) {
|
|
79779
|
+
return `${import_ethers36.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
79780
|
+
}
|
|
79781
|
+
function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
|
|
79782
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
79783
|
+
return null;
|
|
79784
|
+
return gasLimit * maxFeePerGas;
|
|
79785
|
+
}
|
|
79786
|
+
function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
|
|
79787
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
79788
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
79789
|
+
}
|
|
79790
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
79791
|
+
raise(
|
|
79792
|
+
`maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
|
|
79793
|
+
);
|
|
79794
|
+
}
|
|
79795
|
+
const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
|
|
79796
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
79797
|
+
raise(
|
|
79798
|
+
`worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
79799
|
+
);
|
|
79800
|
+
}
|
|
79801
|
+
}
|
|
79802
|
+
function eqAddr3(a, b) {
|
|
79803
|
+
if (!a || !b)
|
|
79804
|
+
return false;
|
|
79805
|
+
try {
|
|
79806
|
+
return import_ethers37.ethers.getAddress(a) === import_ethers37.ethers.getAddress(b);
|
|
79807
|
+
} catch {
|
|
79808
|
+
return false;
|
|
79809
|
+
}
|
|
79810
|
+
}
|
|
79811
|
+
function readToAddress3(tx2) {
|
|
79812
|
+
const to = tx2["to"];
|
|
79813
|
+
if (typeof to !== "string") {
|
|
79814
|
+
throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
|
|
79815
|
+
}
|
|
79816
|
+
return to;
|
|
79817
|
+
}
|
|
79818
|
+
function readData3(tx2) {
|
|
79819
|
+
const data = tx2["data"];
|
|
79820
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
79821
|
+
throw new TxValidationError3(`unsignedTx.data missing or malformed`);
|
|
79822
|
+
}
|
|
79823
|
+
return data;
|
|
79824
|
+
}
|
|
79825
|
+
function readChainId3(tx2) {
|
|
79826
|
+
const c = tx2["chainId"];
|
|
79827
|
+
if (c == null)
|
|
79828
|
+
return null;
|
|
79829
|
+
if (typeof c === "number")
|
|
79830
|
+
return c;
|
|
79831
|
+
if (typeof c === "string")
|
|
79832
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
79833
|
+
if (typeof c === "bigint")
|
|
79834
|
+
return Number(c);
|
|
79835
|
+
return null;
|
|
79836
|
+
}
|
|
79837
|
+
function readOptionalBigInt2(tx2, key) {
|
|
79838
|
+
const v = tx2[key];
|
|
79839
|
+
if (v == null)
|
|
79840
|
+
return null;
|
|
79841
|
+
try {
|
|
79842
|
+
if (typeof v === "bigint")
|
|
79843
|
+
return v;
|
|
79844
|
+
if (typeof v === "number")
|
|
79845
|
+
return BigInt(v);
|
|
79846
|
+
if (typeof v === "string")
|
|
79847
|
+
return BigInt(v);
|
|
79848
|
+
return BigInt(v.toString());
|
|
79849
|
+
} catch {
|
|
79850
|
+
throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
|
|
79851
|
+
}
|
|
79852
|
+
}
|
|
79853
|
+
function readValue3(tx2) {
|
|
79854
|
+
const v = tx2["value"];
|
|
79855
|
+
if (v == null)
|
|
79856
|
+
return 0n;
|
|
79857
|
+
if (typeof v === "string")
|
|
79858
|
+
return BigInt(v);
|
|
79859
|
+
if (typeof v === "number")
|
|
79860
|
+
return BigInt(v);
|
|
79861
|
+
if (typeof v === "bigint")
|
|
79862
|
+
return v;
|
|
79863
|
+
const maybe = v;
|
|
79864
|
+
if (typeof maybe.toBigInt === "function")
|
|
79865
|
+
return maybe.toBigInt();
|
|
79866
|
+
if (typeof maybe.toString === "function")
|
|
79867
|
+
return BigInt(maybe.toString());
|
|
79868
|
+
throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
|
|
79869
|
+
}
|
|
79870
|
+
function normalizePositionId3(id) {
|
|
79871
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
79872
|
+
return import_ethers37.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
79873
|
+
}
|
|
79874
|
+
function requirePositionId2(actual, expected) {
|
|
79875
|
+
const txPositionId = String(actual).toLowerCase();
|
|
79876
|
+
if (txPositionId !== normalizePositionId3(expected)) {
|
|
79877
|
+
throw new TxValidationError3(
|
|
79878
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
|
|
79879
|
+
);
|
|
79880
|
+
}
|
|
79881
|
+
}
|
|
79882
|
+
function validateUnsignedTx3(unsignedTx, expected, vctx) {
|
|
79883
|
+
const txChainId = readChainId3(unsignedTx);
|
|
79884
|
+
if (txChainId == null) {
|
|
79885
|
+
throw new TxValidationError3(
|
|
79886
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
79887
|
+
);
|
|
79888
|
+
}
|
|
79889
|
+
if (txChainId !== vctx.chainId) {
|
|
79890
|
+
throw new TxValidationError3(
|
|
79891
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
79892
|
+
);
|
|
79893
|
+
}
|
|
79894
|
+
const value = readValue3(unsignedTx);
|
|
79895
|
+
if (value !== 0n) {
|
|
79896
|
+
throw new TxValidationError3(
|
|
79897
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
79898
|
+
);
|
|
79899
|
+
}
|
|
79900
|
+
assertFeeCeiling2(
|
|
79901
|
+
readOptionalBigInt2(unsignedTx, "gasLimit"),
|
|
79902
|
+
readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
|
|
79903
|
+
(msg) => {
|
|
79904
|
+
throw new TxValidationError3(msg);
|
|
79905
|
+
},
|
|
79906
|
+
vctx.feeCeiling
|
|
79907
|
+
);
|
|
79908
|
+
const to = readToAddress3(unsignedTx);
|
|
79909
|
+
const data = readData3(unsignedTx);
|
|
79910
|
+
const { name, args } = decodeSignable3(data);
|
|
79911
|
+
const pm = vctx.contracts.PositionManager;
|
|
79912
|
+
switch (expected.kind) {
|
|
79913
|
+
case "mint": {
|
|
79914
|
+
if (name !== "mintUCD") {
|
|
79915
|
+
throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
|
|
79916
|
+
}
|
|
79917
|
+
if (!eqAddr3(to, pm)) {
|
|
79918
|
+
throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
79919
|
+
}
|
|
79920
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79921
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
79922
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
79923
|
+
throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
79924
|
+
}
|
|
79925
|
+
const txMintFee = BigInt(String(args[2]));
|
|
79926
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
79927
|
+
throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
79928
|
+
}
|
|
79929
|
+
break;
|
|
79930
|
+
}
|
|
79931
|
+
case "repay": {
|
|
79932
|
+
if (name !== "makePayment") {
|
|
79933
|
+
throw new TxValidationError3(`expected makePayment, server returned ${name}`);
|
|
79934
|
+
}
|
|
79935
|
+
if (!eqAddr3(to, pm)) {
|
|
79936
|
+
throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
79937
|
+
}
|
|
79938
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79939
|
+
const txAmount = BigInt(String(args[1]));
|
|
79940
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
79941
|
+
throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
79942
|
+
}
|
|
79943
|
+
break;
|
|
79944
|
+
}
|
|
79945
|
+
case "extend": {
|
|
79946
|
+
if (name !== "extendPosition") {
|
|
79947
|
+
throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
|
|
79948
|
+
}
|
|
79949
|
+
if (!eqAddr3(to, pm)) {
|
|
79950
|
+
throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
79951
|
+
}
|
|
79952
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79953
|
+
const txTerm = Number(args[1]);
|
|
79954
|
+
if (txTerm !== expected.selectedTerm) {
|
|
79955
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
79956
|
+
}
|
|
79957
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
79958
|
+
const txFee = BigInt(String(args[5]));
|
|
79959
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
79960
|
+
if (txFee > upper) {
|
|
79961
|
+
throw new TxValidationError3(
|
|
79962
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
79963
|
+
);
|
|
79964
|
+
}
|
|
79965
|
+
}
|
|
79966
|
+
break;
|
|
79967
|
+
}
|
|
79968
|
+
case "withdraw-btc": {
|
|
79969
|
+
if (name !== "withdrawBTC") {
|
|
79970
|
+
throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
|
|
79971
|
+
}
|
|
79972
|
+
if (!eqAddr3(to, pm)) {
|
|
79973
|
+
throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
79974
|
+
}
|
|
79975
|
+
const paramsTuple = args[0];
|
|
79976
|
+
requirePositionId2(paramsTuple[0], expected.positionId);
|
|
79977
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
79978
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
79979
|
+
throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
79980
|
+
}
|
|
79981
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
79982
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
79983
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
79984
|
+
if (txDeduction > upper) {
|
|
79985
|
+
throw new TxValidationError3(
|
|
79986
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
79987
|
+
);
|
|
79988
|
+
}
|
|
79989
|
+
}
|
|
79990
|
+
break;
|
|
79991
|
+
}
|
|
79992
|
+
case "ucd-approve": {
|
|
79993
|
+
if (name !== "approve") {
|
|
79994
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79995
|
+
}
|
|
79996
|
+
const ucd = vctx.contracts.UCDToken;
|
|
79997
|
+
if (!eqAddr3(to, ucd)) {
|
|
79998
|
+
throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
79999
|
+
}
|
|
80000
|
+
const spender = String(args[0]);
|
|
80001
|
+
const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
|
|
80002
|
+
if (!ok2) {
|
|
80003
|
+
throw new TxValidationError3(
|
|
80004
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
80005
|
+
);
|
|
80006
|
+
}
|
|
80007
|
+
const amt = BigInt(String(args[1]));
|
|
80008
|
+
const min = BigInt(expected.minAmountWei);
|
|
80009
|
+
if (amt < min) {
|
|
80010
|
+
throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
|
|
80011
|
+
}
|
|
80012
|
+
const SANITY_MAX = min * 1000n;
|
|
80013
|
+
if (amt > SANITY_MAX) {
|
|
80014
|
+
throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
80015
|
+
}
|
|
80016
|
+
break;
|
|
80017
|
+
}
|
|
80018
|
+
case "create-position": {
|
|
80019
|
+
if (name !== "createPosition") {
|
|
80020
|
+
throw new TxValidationError3(`expected createPosition, server returned ${name}`);
|
|
80021
|
+
}
|
|
80022
|
+
if (!eqAddr3(to, pm)) {
|
|
80023
|
+
throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
80024
|
+
}
|
|
80025
|
+
const txTerm = BigInt(String(args[4]));
|
|
80026
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
80027
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
80028
|
+
}
|
|
80029
|
+
break;
|
|
80030
|
+
}
|
|
80031
|
+
case "set-position-delegate": {
|
|
80032
|
+
if (name !== "setPositionDelegate") {
|
|
80033
|
+
throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
|
|
80034
|
+
}
|
|
80035
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
80036
|
+
throw new TxValidationError3(
|
|
80037
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
80038
|
+
);
|
|
80039
|
+
}
|
|
80040
|
+
requirePositionId2(args[0], expected.positionId);
|
|
80041
|
+
const txDelegate = String(args[1]);
|
|
80042
|
+
if (!eqAddr3(txDelegate, expected.delegate)) {
|
|
80043
|
+
throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
80044
|
+
}
|
|
80045
|
+
break;
|
|
80046
|
+
}
|
|
80047
|
+
case "bwar-add-address": {
|
|
80048
|
+
if (name !== "addAddress") {
|
|
80049
|
+
throw new TxValidationError3(`expected addAddress, decoded ${name}`);
|
|
80050
|
+
}
|
|
80051
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
80052
|
+
throw new TxValidationError3(
|
|
80053
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
80054
|
+
);
|
|
80055
|
+
}
|
|
80056
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
80057
|
+
throw new TxValidationError3(
|
|
80058
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
80059
|
+
);
|
|
80060
|
+
}
|
|
80061
|
+
break;
|
|
80062
|
+
}
|
|
80063
|
+
case "stablecoin-approve": {
|
|
80064
|
+
if (name !== "approve") {
|
|
80065
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
80066
|
+
}
|
|
80067
|
+
if (!eqAddr3(to, expected.tokenAddress)) {
|
|
80068
|
+
throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
80069
|
+
}
|
|
80070
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
80071
|
+
throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
80072
|
+
}
|
|
80073
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
80074
|
+
throw new TxValidationError3(
|
|
80075
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
80076
|
+
);
|
|
80077
|
+
}
|
|
80078
|
+
break;
|
|
80079
|
+
}
|
|
80080
|
+
case "ucd-approve-controller": {
|
|
80081
|
+
if (name !== "approve") {
|
|
80082
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
80083
|
+
}
|
|
80084
|
+
if (!eqAddr3(to, expected.ucdTokenAddress)) {
|
|
80085
|
+
throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
80086
|
+
}
|
|
80087
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
80088
|
+
throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
80089
|
+
}
|
|
80090
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
80091
|
+
throw new TxValidationError3(
|
|
80092
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
80093
|
+
);
|
|
80094
|
+
}
|
|
80095
|
+
break;
|
|
80096
|
+
}
|
|
80097
|
+
case "psm-swap": {
|
|
80098
|
+
if (name !== "swap")
|
|
80099
|
+
throw new TxValidationError3(`expected swap, server returned ${name}`);
|
|
80100
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
80101
|
+
throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
80102
|
+
}
|
|
80103
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
80104
|
+
throw new TxValidationError3(`swap stablecoin mismatch`);
|
|
80105
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
80106
|
+
throw new TxValidationError3(`swap amountIn mismatch`);
|
|
80107
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
80108
|
+
throw new TxValidationError3(`swap minUcdOut mismatch`);
|
|
80109
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
80110
|
+
throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
80111
|
+
}
|
|
80112
|
+
break;
|
|
80113
|
+
}
|
|
80114
|
+
case "psm-redeem": {
|
|
80115
|
+
if (name !== "redeem")
|
|
80116
|
+
throw new TxValidationError3(`expected redeem, server returned ${name}`);
|
|
80117
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
80118
|
+
throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
80119
|
+
}
|
|
80120
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
80121
|
+
throw new TxValidationError3(`redeem stablecoin mismatch`);
|
|
80122
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
80123
|
+
throw new TxValidationError3(`redeem ucdAmount mismatch`);
|
|
80124
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
80125
|
+
throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
|
|
80126
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
80127
|
+
throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
80128
|
+
}
|
|
80129
|
+
break;
|
|
80130
|
+
}
|
|
80131
|
+
default: {
|
|
80132
|
+
const _exhaustive = expected;
|
|
80133
|
+
throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
80134
|
+
}
|
|
80135
|
+
}
|
|
80136
|
+
}
|
|
80137
|
+
var SLOT_SECONDS2 = 12;
|
|
80138
|
+
var INCLUSION_SLOT_TOLERANCE2 = 3;
|
|
80139
|
+
var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
|
|
80140
|
+
function buildPsmApproveTx2(p) {
|
|
80141
|
+
return {
|
|
80142
|
+
to: p.token,
|
|
80143
|
+
data: encodeSignable3("approve", [p.spender, p.amount]),
|
|
80144
|
+
value: "0x0",
|
|
80145
|
+
chainId: p.chainId
|
|
80146
|
+
};
|
|
80147
|
+
}
|
|
80148
|
+
function buildPsmSwapTx3(p) {
|
|
80149
|
+
return {
|
|
80150
|
+
to: p.psm,
|
|
80151
|
+
data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
80152
|
+
value: "0x0",
|
|
80153
|
+
chainId: p.chainId
|
|
80154
|
+
};
|
|
80155
|
+
}
|
|
80156
|
+
function buildPsmRedeemTx3(p) {
|
|
80157
|
+
return {
|
|
80158
|
+
to: p.psm,
|
|
80159
|
+
data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
80160
|
+
value: "0x0",
|
|
80161
|
+
chainId: p.chainId
|
|
80162
|
+
};
|
|
80163
|
+
}
|
|
80164
|
+
var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
|
|
80165
|
+
var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
80166
|
+
function psmExchangeReadsFromProvider2(provider, psmAddress) {
|
|
80167
|
+
const psm = new import_ethers40.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
|
|
80168
|
+
return {
|
|
80169
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
80170
|
+
allowance: async (token, owner, spender) => await new import_ethers40.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
|
|
80171
|
+
};
|
|
80172
|
+
}
|
|
80173
|
+
var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
|
|
80174
|
+
function requireAddress2(direction, label, value) {
|
|
80175
|
+
if (!value || !import_ethers40.ethers.isAddress(value)) {
|
|
80176
|
+
throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
80177
|
+
}
|
|
80178
|
+
return import_ethers40.ethers.getAddress(value);
|
|
80179
|
+
}
|
|
80180
|
+
async function planPsmExchange2(params) {
|
|
80181
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
80182
|
+
const chainId = vctx.chainId;
|
|
80183
|
+
if (amountIn <= 0n) {
|
|
80184
|
+
throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
80185
|
+
}
|
|
80186
|
+
if (minOut <= 0n) {
|
|
80187
|
+
throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
80188
|
+
}
|
|
80189
|
+
const owner = requireAddress2(direction, "owner", params.owner);
|
|
80190
|
+
const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
|
|
80191
|
+
const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
|
|
80192
|
+
const isSwap = direction === "swap";
|
|
80193
|
+
const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
|
|
80194
|
+
const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
|
|
80195
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
80196
|
+
throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
80197
|
+
}
|
|
80198
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
80199
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
80200
|
+
const approvals = [];
|
|
80201
|
+
if (allowanceBefore < amountIn) {
|
|
80202
|
+
if (allowanceBefore > 0n) {
|
|
80203
|
+
approvals.push({
|
|
80204
|
+
step: "reset-approve",
|
|
80205
|
+
tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
|
|
80206
|
+
expected: approveExpected(0n)
|
|
80207
|
+
});
|
|
80208
|
+
}
|
|
80209
|
+
approvals.push({
|
|
80210
|
+
step: "approve",
|
|
80211
|
+
tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
|
|
80212
|
+
expected: approveExpected(amountIn)
|
|
80213
|
+
});
|
|
80214
|
+
}
|
|
80215
|
+
const exec = isSwap ? {
|
|
80216
|
+
step: "swap",
|
|
80217
|
+
tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
80218
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
80219
|
+
} : {
|
|
80220
|
+
step: "redeem",
|
|
80221
|
+
tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
80222
|
+
expected: {
|
|
80223
|
+
kind: "psm-redeem",
|
|
80224
|
+
psmAddress: psm,
|
|
80225
|
+
stablecoin,
|
|
80226
|
+
amountUcdWei: amountIn.toString(),
|
|
80227
|
+
minOut: minOut.toString()
|
|
80228
|
+
}
|
|
80229
|
+
};
|
|
80230
|
+
for (const leg of [...approvals, exec]) {
|
|
80231
|
+
validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
|
|
80232
|
+
}
|
|
80233
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
80234
|
+
}
|
|
80235
|
+
|
|
80236
|
+
// src/boundary/upstream/real/psm-calls.ts
|
|
78671
80237
|
var PSM_VIEW_FRAGMENTS = [
|
|
78672
80238
|
"function VERSION() view returns (string)",
|
|
78673
80239
|
"function supportedStablecoins(address) view returns (bool)",
|
|
@@ -78687,15 +80253,7 @@ var PSM_VIEW_FRAGMENTS = [
|
|
|
78687
80253
|
"function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
|
|
78688
80254
|
"function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
|
|
78689
80255
|
];
|
|
78690
|
-
var
|
|
78691
|
-
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
|
|
78692
|
-
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
|
|
78693
|
-
];
|
|
78694
|
-
var ERC20_FRAGMENTS = [
|
|
78695
|
-
"function approve(address spender, uint256 amount) returns (bool)",
|
|
78696
|
-
"function balanceOf(address holder) view returns (uint256)"
|
|
78697
|
-
];
|
|
78698
|
-
var ERC20_IFACE = new import_ethers31.ethers.Interface(ERC20_FRAGMENTS);
|
|
80256
|
+
var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
|
|
78699
80257
|
var PSM_ERROR_FRAGMENTS = [
|
|
78700
80258
|
"error StablecoinNotSupported(address stablecoin)",
|
|
78701
80259
|
"error InvalidAmount()",
|
|
@@ -78743,9 +80301,9 @@ var RENDERERS = {
|
|
|
78743
80301
|
var PsmCalls = class {
|
|
78744
80302
|
constructor(deps) {
|
|
78745
80303
|
this.deps = deps;
|
|
78746
|
-
const abi = [...PSM_VIEW_FRAGMENTS, ...
|
|
78747
|
-
this.iface = new
|
|
78748
|
-
this.psm = new
|
|
80304
|
+
const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
|
|
80305
|
+
this.iface = new import_ethers41.ethers.Interface(abi);
|
|
80306
|
+
this.psm = new import_ethers41.ethers.Contract(deps.psmAddress, abi, deps.provider);
|
|
78749
80307
|
}
|
|
78750
80308
|
psm;
|
|
78751
80309
|
iface;
|
|
@@ -78758,34 +80316,10 @@ var PsmCalls = class {
|
|
|
78758
80316
|
...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
|
|
78759
80317
|
};
|
|
78760
80318
|
}
|
|
78761
|
-
|
|
78762
|
-
|
|
78763
|
-
|
|
78764
|
-
|
|
78765
|
-
return {
|
|
78766
|
-
to: p.token,
|
|
78767
|
-
data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
|
|
78768
|
-
value: "0x0",
|
|
78769
|
-
chainId: p.chainId
|
|
78770
|
-
};
|
|
78771
|
-
}
|
|
78772
|
-
/** Step 2, stablecoin → UCD (contract `swap`). */
|
|
78773
|
-
buildSwap(p) {
|
|
78774
|
-
return {
|
|
78775
|
-
to: this.deps.psmAddress,
|
|
78776
|
-
data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
|
|
78777
|
-
value: "0x0",
|
|
78778
|
-
chainId: p.chainId
|
|
78779
|
-
};
|
|
78780
|
-
}
|
|
78781
|
-
/** Step 2, UCD → stablecoin (contract `redeem`). */
|
|
78782
|
-
buildRedeem(p) {
|
|
78783
|
-
return {
|
|
78784
|
-
to: this.deps.psmAddress,
|
|
78785
|
-
data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
|
|
78786
|
-
value: "0x0",
|
|
78787
|
-
chainId: p.chainId
|
|
78788
|
-
};
|
|
80319
|
+
/** The two live reads the SDK's exchange planner depends on (supported set + allowance),
|
|
80320
|
+
* over this wrapper's provider and PSM. */
|
|
80321
|
+
exchangeReads() {
|
|
80322
|
+
return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
|
|
78789
80323
|
}
|
|
78790
80324
|
/** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
|
|
78791
80325
|
async balances(holder) {
|
|
@@ -78798,8 +80332,8 @@ var PsmCalls = class {
|
|
|
78798
80332
|
});
|
|
78799
80333
|
}
|
|
78800
80334
|
return this.call(async () => {
|
|
78801
|
-
const ucd = new
|
|
78802
|
-
const stable = new
|
|
80335
|
+
const ucd = new import_ethers41.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
|
|
80336
|
+
const stable = new import_ethers41.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
|
|
78803
80337
|
const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
|
|
78804
80338
|
return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
|
|
78805
80339
|
});
|
|
@@ -78917,7 +80451,7 @@ var PsmCalls = class {
|
|
|
78917
80451
|
};
|
|
78918
80452
|
|
|
78919
80453
|
// src/boundary/upstream/real/session.ts
|
|
78920
|
-
var
|
|
80454
|
+
var import_ethers42 = require("ethers");
|
|
78921
80455
|
var REFRESH_LEEWAY_SEC = 30;
|
|
78922
80456
|
var LOGIN_TYPES_WITH_AUDIENCE3 = {
|
|
78923
80457
|
DiamondHands: [
|
|
@@ -78965,7 +80499,7 @@ var LitOpsSession = class {
|
|
|
78965
80499
|
const message = {
|
|
78966
80500
|
address: this.wallet.address,
|
|
78967
80501
|
issuedAt: Math.floor(Date.now() / 1e3),
|
|
78968
|
-
nonce: "0x" + Buffer.from(
|
|
80502
|
+
nonce: "0x" + Buffer.from(import_ethers42.ethers.randomBytes(32)).toString("hex"),
|
|
78969
80503
|
audience: this.serviceEndpoint
|
|
78970
80504
|
};
|
|
78971
80505
|
const signature = await this.wallet.signTypedData(
|
|
@@ -79007,7 +80541,7 @@ function decodeJwtExp(token) {
|
|
|
79007
80541
|
}
|
|
79008
80542
|
|
|
79009
80543
|
// src/boundary/upstream/real/write-ops.ts
|
|
79010
|
-
var
|
|
80544
|
+
var import_ethers44 = require("ethers");
|
|
79011
80545
|
|
|
79012
80546
|
// src/signer/types.ts
|
|
79013
80547
|
var OperationDeclined = class extends Error {
|
|
@@ -79017,7 +80551,7 @@ var OperationDeclined = class extends Error {
|
|
|
79017
80551
|
init_tx_validator();
|
|
79018
80552
|
|
|
79019
80553
|
// src/boundary/upstream/shared/external-bridge/page-crypto.ts
|
|
79020
|
-
var
|
|
80554
|
+
var import_ethers43 = require("ethers");
|
|
79021
80555
|
var PERSONAL_SIGN_LAYOUTS = {
|
|
79022
80556
|
"dh-op-envelope-v1": {
|
|
79023
80557
|
types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
|
|
@@ -79038,9 +80572,9 @@ function hashForLayout(layout, fields) {
|
|
|
79038
80572
|
const values = def.fieldOrder.map((name) => {
|
|
79039
80573
|
const raw = fields[name];
|
|
79040
80574
|
if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
|
|
79041
|
-
return hashUtf8.has(name) ?
|
|
80575
|
+
return hashUtf8.has(name) ? import_ethers43.ethers.keccak256(import_ethers43.ethers.toUtf8Bytes(raw)) : raw;
|
|
79042
80576
|
});
|
|
79043
|
-
return
|
|
80577
|
+
return import_ethers43.ethers.solidityPackedKeccak256(def.types, values);
|
|
79044
80578
|
}
|
|
79045
80579
|
var PAGE_CRYPTO_JS = `"use strict";
|
|
79046
80580
|
(function () {
|
|
@@ -79269,9 +80803,21 @@ function buildValidationContext(network, chainId) {
|
|
|
79269
80803
|
|
|
79270
80804
|
// src/boundary/upstream/real/write-ops.ts
|
|
79271
80805
|
var SOURCE5 = "real-ops";
|
|
80806
|
+
function mcpExpected(leg) {
|
|
80807
|
+
const e = leg.expected;
|
|
80808
|
+
switch (e.kind) {
|
|
80809
|
+
case "stablecoin-approve":
|
|
80810
|
+
case "ucd-approve-controller":
|
|
80811
|
+
case "psm-swap":
|
|
80812
|
+
case "psm-redeem":
|
|
80813
|
+
return e;
|
|
80814
|
+
default:
|
|
80815
|
+
throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
|
|
80816
|
+
}
|
|
80817
|
+
}
|
|
79272
80818
|
var OP_LAYOUT = "dh-op-envelope-v1";
|
|
79273
80819
|
function randomNonceHex() {
|
|
79274
|
-
return "0x" + Buffer.from(
|
|
80820
|
+
return "0x" + Buffer.from(import_ethers44.ethers.randomBytes(16)).toString("hex");
|
|
79275
80821
|
}
|
|
79276
80822
|
async function postJson(url2, body, headers) {
|
|
79277
80823
|
const res = await fetch(url2, {
|
|
@@ -79332,7 +80878,7 @@ function buildWriteOps(deps) {
|
|
|
79332
80878
|
return {
|
|
79333
80879
|
to: String(tx2["to"] ?? ""),
|
|
79334
80880
|
data: String(tx2["data"] ?? "0x"),
|
|
79335
|
-
value: tx2["value"] != null ?
|
|
80881
|
+
value: tx2["value"] != null ? import_ethers44.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
|
|
79336
80882
|
chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
|
|
79337
80883
|
};
|
|
79338
80884
|
}
|
|
@@ -79417,8 +80963,9 @@ function buildWriteOps(deps) {
|
|
|
79417
80963
|
}
|
|
79418
80964
|
return {
|
|
79419
80965
|
createPosition: async (p) => {
|
|
79420
|
-
const
|
|
79421
|
-
if (!
|
|
80966
|
+
const built = await deps.getWriteSdk();
|
|
80967
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
80968
|
+
const sdk = built.sdk;
|
|
79422
80969
|
try {
|
|
79423
80970
|
await deps.assertValidatorConfigured();
|
|
79424
80971
|
} catch (e) {
|
|
@@ -79497,7 +81044,7 @@ function buildWriteOps(deps) {
|
|
|
79497
81044
|
mintedUcdWei: minted,
|
|
79498
81045
|
feeUcdWei: mintFee,
|
|
79499
81046
|
echoedAmountUcdWei: minted,
|
|
79500
|
-
authorization: auth(action, `mint ${
|
|
81047
|
+
authorization: auth(action, `mint ${import_ethers44.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
|
|
79501
81048
|
},
|
|
79502
81049
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79503
81050
|
);
|
|
@@ -79538,7 +81085,7 @@ function buildWriteOps(deps) {
|
|
|
79538
81085
|
txRef: { kind: "eth-tx", id: r.value.txHash },
|
|
79539
81086
|
paidUcdWei: paid,
|
|
79540
81087
|
echoedAmountUcdWei: paid,
|
|
79541
|
-
authorization: auth(action, `repay ${
|
|
81088
|
+
authorization: auth(action, `repay ${import_ethers44.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
|
|
79542
81089
|
},
|
|
79543
81090
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79544
81091
|
);
|
|
@@ -79578,8 +81125,9 @@ function buildWriteOps(deps) {
|
|
|
79578
81125
|
);
|
|
79579
81126
|
},
|
|
79580
81127
|
withdraw: async (p) => {
|
|
79581
|
-
const
|
|
79582
|
-
if (!
|
|
81128
|
+
const built = await deps.getWriteSdk();
|
|
81129
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81130
|
+
const sdk = built.sdk;
|
|
79583
81131
|
const amountSats = Number(p.amountSats);
|
|
79584
81132
|
const feeSats = Number(p.networkFeeSats);
|
|
79585
81133
|
let result;
|
|
@@ -79608,12 +81156,13 @@ function buildWriteOps(deps) {
|
|
|
79608
81156
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79609
81157
|
);
|
|
79610
81158
|
},
|
|
79611
|
-
/** PSM exchange
|
|
79612
|
-
* orchestration.
|
|
79613
|
-
*
|
|
79614
|
-
*
|
|
79615
|
-
*
|
|
79616
|
-
*
|
|
81159
|
+
/** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
|
|
81160
|
+
* orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
|
|
81161
|
+
* builder every client shares (it replaced this file's own builders and the SDK's old
|
|
81162
|
+
* MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
|
|
81163
|
+
* allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
|
|
81164
|
+
* validated again here by the MCP's own whitelist (the one the approval card decodes
|
|
81165
|
+
* with), then signed through the session signer and broadcast — one at a time. */
|
|
79617
81166
|
psmSwap: async (p) => {
|
|
79618
81167
|
const pr = await deps.psm(p.stablecoin);
|
|
79619
81168
|
if (!pr.ok) return upFail(pr.failure);
|
|
@@ -79627,11 +81176,7 @@ function buildWriteOps(deps) {
|
|
|
79627
81176
|
message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
|
|
79628
81177
|
});
|
|
79629
81178
|
}
|
|
79630
|
-
const amountIn = BigInt(p.amountIn);
|
|
79631
|
-
const minOut = BigInt(p.minOut);
|
|
79632
81179
|
const vctx = buildValidationContext(config.network, chainId);
|
|
79633
|
-
const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
|
|
79634
|
-
const spenderAddress = isSwap ? addr.psm : addr.ucdController;
|
|
79635
81180
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
79636
81181
|
const tokenSymbol = isSwap ? calls.symbol() : "UCD";
|
|
79637
81182
|
const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
|
|
@@ -79648,49 +81193,66 @@ function buildWriteOps(deps) {
|
|
|
79648
81193
|
return submitFailure(leg, e);
|
|
79649
81194
|
}
|
|
79650
81195
|
};
|
|
79651
|
-
|
|
81196
|
+
let plan;
|
|
79652
81197
|
try {
|
|
79653
|
-
|
|
79654
|
-
|
|
79655
|
-
|
|
79656
|
-
|
|
79657
|
-
|
|
79658
|
-
|
|
79659
|
-
|
|
79660
|
-
|
|
79661
|
-
|
|
79662
|
-
const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
|
|
79663
|
-
if (!approveHashR.ok) return approveHashR;
|
|
79664
|
-
const approveHash = approveHashR.value;
|
|
79665
|
-
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`;
|
|
79666
|
-
const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
|
|
79667
|
-
try {
|
|
79668
|
-
validateUnsignedTx(
|
|
79669
|
-
{ ...execTx },
|
|
79670
|
-
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 },
|
|
79671
|
-
vctx
|
|
79672
|
-
);
|
|
81198
|
+
plan = await planPsmExchange2({
|
|
81199
|
+
direction: p.direction,
|
|
81200
|
+
owner: p.borrower,
|
|
81201
|
+
addresses: addr,
|
|
81202
|
+
amountIn: BigInt(p.amountIn),
|
|
81203
|
+
minOut: BigInt(p.minOut),
|
|
81204
|
+
vctx,
|
|
81205
|
+
reads: calls.exchangeReads()
|
|
81206
|
+
});
|
|
79673
81207
|
} catch (e) {
|
|
79674
|
-
return upFail({ kind: "rejected", source: SOURCE5, message:
|
|
81208
|
+
return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
|
|
81209
|
+
kind: "unavailable",
|
|
81210
|
+
source: SOURCE5,
|
|
81211
|
+
message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
|
|
81212
|
+
raw: String(e)
|
|
81213
|
+
});
|
|
79675
81214
|
}
|
|
79676
|
-
const
|
|
79677
|
-
const
|
|
79678
|
-
|
|
79679
|
-
|
|
79680
|
-
|
|
81215
|
+
const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
|
|
81216
|
+
const unit = `${tokenSymbol} smallest units`;
|
|
81217
|
+
const landed = [];
|
|
81218
|
+
const residualNote = () => {
|
|
81219
|
+
const last = landed[landed.length - 1];
|
|
81220
|
+
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`;
|
|
81221
|
+
return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
81222
|
+
};
|
|
81223
|
+
const runLeg = async (leg) => {
|
|
81224
|
+
const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
|
|
81225
|
+
try {
|
|
81226
|
+
validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
|
|
81227
|
+
} catch (e) {
|
|
81228
|
+
return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
|
|
81229
|
+
}
|
|
81230
|
+
const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
|
|
81231
|
+
const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
|
|
81232
|
+
return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
|
|
81233
|
+
};
|
|
81234
|
+
const approvals = [];
|
|
81235
|
+
for (const leg of plan.approvals) {
|
|
81236
|
+
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})`;
|
|
81237
|
+
const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
|
|
81238
|
+
const r = await runLeg(leg);
|
|
81239
|
+
if (!r.ok) return r;
|
|
81240
|
+
landed.push({ step, hash: r.value });
|
|
81241
|
+
approvals.push({
|
|
81242
|
+
step,
|
|
81243
|
+
txRef: { kind: "eth-tx", id: r.value },
|
|
81244
|
+
amount: leg.step === "reset-approve" ? "0" : p.amountIn,
|
|
81245
|
+
authorization: auth("psm-approve", card, r.value)
|
|
81246
|
+
});
|
|
79681
81247
|
}
|
|
81248
|
+
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}`;
|
|
81249
|
+
const execHashR = await runLeg(plan.exec);
|
|
81250
|
+
if (!execHashR.ok) return execHashR;
|
|
79682
81251
|
const execHash = execHashR.value;
|
|
79683
81252
|
const balancesR = await calls.balances(p.borrower);
|
|
79684
81253
|
const row = {
|
|
79685
|
-
|
|
79686
|
-
|
|
79687
|
-
tokenSymbol,
|
|
79688
|
-
tokenAddress,
|
|
79689
|
-
spenderAddress,
|
|
79690
|
-
spenderContract,
|
|
79691
|
-
amount: p.amountIn,
|
|
79692
|
-
authorization: auth("psm-approve", approveCard, approveHash)
|
|
79693
|
-
},
|
|
81254
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
81255
|
+
approvals,
|
|
79694
81256
|
execute: {
|
|
79695
81257
|
txRef: { kind: "eth-tx", id: execHash },
|
|
79696
81258
|
amountIn: p.amountIn,
|
|
@@ -79707,8 +81269,9 @@ function buildWriteOps(deps) {
|
|
|
79707
81269
|
// registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
|
|
79708
81270
|
// msg.sender, so their path is a SafeTx — never this keystore leg.
|
|
79709
81271
|
allowlistWithdrawalAddress: async (p) => {
|
|
79710
|
-
const
|
|
79711
|
-
if (!
|
|
81272
|
+
const built = await deps.getWriteSdk();
|
|
81273
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81274
|
+
const sdk = built.sdk;
|
|
79712
81275
|
let result;
|
|
79713
81276
|
try {
|
|
79714
81277
|
result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
|
|
@@ -79755,8 +81318,9 @@ function buildWriteOps(deps) {
|
|
|
79755
81318
|
message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
|
|
79756
81319
|
}),
|
|
79757
81320
|
retryWithdrawExecute: async (p) => {
|
|
79758
|
-
const
|
|
79759
|
-
if (!
|
|
81321
|
+
const built = await deps.getWriteSdk();
|
|
81322
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81323
|
+
const sdk = built.sdk;
|
|
79760
81324
|
let rows;
|
|
79761
81325
|
try {
|
|
79762
81326
|
rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
|
|
@@ -79784,7 +81348,7 @@ function buildWriteOps(deps) {
|
|
|
79784
81348
|
}
|
|
79785
81349
|
|
|
79786
81350
|
// src/signer/eoa-dh.ts
|
|
79787
|
-
var
|
|
81351
|
+
var import_ethers45 = require("ethers");
|
|
79788
81352
|
var EoaDHSigner = class {
|
|
79789
81353
|
constructor(wallet, broadcast, clock = Date.now) {
|
|
79790
81354
|
this.wallet = wallet;
|
|
@@ -79801,7 +81365,7 @@ var EoaDHSigner = class {
|
|
|
79801
81365
|
async signAuthorization(spec) {
|
|
79802
81366
|
const quantumTs = nextQuantumTimestamp(this.clock());
|
|
79803
81367
|
const { fields, hashHex } = spec.stamp(quantumTs);
|
|
79804
|
-
const signature = await this.wallet.signMessage(
|
|
81368
|
+
const signature = await this.wallet.signMessage(import_ethers45.ethers.getBytes(hashHex));
|
|
79805
81369
|
return { signature, quantumTs, fields };
|
|
79806
81370
|
}
|
|
79807
81371
|
async wrapInnerTx(innerTx) {
|
|
@@ -79819,10 +81383,10 @@ var EoaDHSigner = class {
|
|
|
79819
81383
|
|
|
79820
81384
|
// src/signer/external-eoa.ts
|
|
79821
81385
|
var import_node_crypto5 = require("crypto");
|
|
79822
|
-
var
|
|
81386
|
+
var import_ethers47 = require("ethers");
|
|
79823
81387
|
|
|
79824
81388
|
// src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
|
|
79825
|
-
var
|
|
81389
|
+
var import_ethers46 = require("ethers");
|
|
79826
81390
|
function eq2(a, b) {
|
|
79827
81391
|
return a.toLowerCase() === b.toLowerCase();
|
|
79828
81392
|
}
|
|
@@ -79845,7 +81409,7 @@ function compareLandedTx(landed, approved, borrower) {
|
|
|
79845
81409
|
return { status: "verified", from: landed.from, hash: landed.hash };
|
|
79846
81410
|
}
|
|
79847
81411
|
function verifyRawSignedTx(rawSignedTx, approved, borrower) {
|
|
79848
|
-
const parsed =
|
|
81412
|
+
const parsed = import_ethers46.ethers.Transaction.from(rawSignedTx);
|
|
79849
81413
|
if (!parsed.from || !parsed.to || !parsed.hash) {
|
|
79850
81414
|
return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
|
|
79851
81415
|
}
|
|
@@ -79883,7 +81447,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
|
|
|
79883
81447
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
79884
81448
|
try {
|
|
79885
81449
|
const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
|
|
79886
|
-
return
|
|
81450
|
+
return import_ethers47.ethers.toBeHex(est * 15n / 10n);
|
|
79887
81451
|
} catch (e) {
|
|
79888
81452
|
lastErr = e;
|
|
79889
81453
|
await new Promise((r) => setTimeout(r, 13e3));
|
|
@@ -79933,7 +81497,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79933
81497
|
throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
|
|
79934
81498
|
}
|
|
79935
81499
|
const finalHash = spec.stamp(used.quantumTs).hashHex;
|
|
79936
|
-
const recovered =
|
|
81500
|
+
const recovered = import_ethers47.ethers.verifyMessage(import_ethers47.ethers.getBytes(finalHash), outcome.signature);
|
|
79937
81501
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
79938
81502
|
throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
79939
81503
|
}
|
|
@@ -79944,7 +81508,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79944
81508
|
}
|
|
79945
81509
|
async submitValidatedTx(outerTx, ctx) {
|
|
79946
81510
|
const approved = toApprovedTx(outerTx, this.deps.chainId);
|
|
79947
|
-
const gas = outerTx.gasLimit != null ?
|
|
81511
|
+
const gas = outerTx.gasLimit != null ? import_ethers47.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
|
|
79948
81512
|
const outcome = await this.deps.bridge.requestSignature({
|
|
79949
81513
|
id: (0, import_node_crypto5.randomUUID)(),
|
|
79950
81514
|
kind: "transaction",
|
|
@@ -79978,7 +81542,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79978
81542
|
return new BridgeEthersSigner(this.deps);
|
|
79979
81543
|
}
|
|
79980
81544
|
};
|
|
79981
|
-
var BridgeEthersSigner = class _BridgeEthersSigner extends
|
|
81545
|
+
var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers47.ethers.AbstractSigner {
|
|
79982
81546
|
constructor(deps) {
|
|
79983
81547
|
super(deps.provider);
|
|
79984
81548
|
this.deps = deps;
|
|
@@ -79989,13 +81553,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79989
81553
|
return this.deps.borrower;
|
|
79990
81554
|
}
|
|
79991
81555
|
async signMessage(message) {
|
|
79992
|
-
const bytes = typeof message === "string" ?
|
|
81556
|
+
const bytes = typeof message === "string" ? import_ethers47.ethers.toUtf8Bytes(message) : message;
|
|
79993
81557
|
if (bytes.length !== 32) {
|
|
79994
81558
|
throw new Error(
|
|
79995
81559
|
`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.`
|
|
79996
81560
|
);
|
|
79997
81561
|
}
|
|
79998
|
-
const hashHex =
|
|
81562
|
+
const hashHex = import_ethers47.ethers.hexlify(bytes).toLowerCase();
|
|
79999
81563
|
const nowMs = (this.deps.clock ?? Date.now)();
|
|
80000
81564
|
const expiresAtSec = nextQuantumTimestamp(nowMs);
|
|
80001
81565
|
const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
|
|
@@ -80025,7 +81589,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
80025
81589
|
if (outcome.status !== "approved" || !outcome.signature) {
|
|
80026
81590
|
throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
|
|
80027
81591
|
}
|
|
80028
|
-
const recovered =
|
|
81592
|
+
const recovered = import_ethers47.ethers.verifyMessage(bytes, outcome.signature);
|
|
80029
81593
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
80030
81594
|
throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
80031
81595
|
}
|
|
@@ -80059,11 +81623,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
80059
81623
|
const approved = {
|
|
80060
81624
|
to: tx2.to,
|
|
80061
81625
|
data: tx2.data,
|
|
80062
|
-
value: tx2.value != null ?
|
|
81626
|
+
value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
80063
81627
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
|
|
80064
81628
|
};
|
|
80065
81629
|
const card = cardForTx(approved);
|
|
80066
|
-
const gas = tx2.gasLimit != null ?
|
|
81630
|
+
const gas = tx2.gasLimit != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
|
|
80067
81631
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80068
81632
|
id: (0, import_node_crypto5.randomUUID)(),
|
|
80069
81633
|
kind: "transaction",
|
|
@@ -80105,14 +81669,14 @@ function toApprovedTx(tx2, fallbackChainId) {
|
|
|
80105
81669
|
return {
|
|
80106
81670
|
to: tx2.to,
|
|
80107
81671
|
data: tx2.data,
|
|
80108
|
-
value: tx2.value != null ?
|
|
81672
|
+
value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
80109
81673
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
|
|
80110
81674
|
};
|
|
80111
81675
|
}
|
|
80112
81676
|
function describeFn(data) {
|
|
80113
81677
|
try {
|
|
80114
|
-
const { decodeSignable:
|
|
80115
|
-
return
|
|
81678
|
+
const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
|
|
81679
|
+
return decodeSignable4(data).name;
|
|
80116
81680
|
} catch {
|
|
80117
81681
|
return "operation";
|
|
80118
81682
|
}
|
|
@@ -80149,7 +81713,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
|
|
|
80149
81713
|
var RealUpstreamPlugin = class {
|
|
80150
81714
|
constructor(config, wallet, runtime) {
|
|
80151
81715
|
this.config = config;
|
|
80152
|
-
this.provider = new
|
|
81716
|
+
this.provider = new import_ethers48.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
|
|
80153
81717
|
this.wallet = wallet ?? null;
|
|
80154
81718
|
this.runtime = runtime ?? null;
|
|
80155
81719
|
this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
|
|
@@ -80280,7 +81844,7 @@ var RealUpstreamPlugin = class {
|
|
|
80280
81844
|
})
|
|
80281
81845
|
)
|
|
80282
81846
|
};
|
|
80283
|
-
const writeRefusalReason = !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014
|
|
81847
|
+
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.`;
|
|
80284
81848
|
const readOnly = (op) => Promise.resolve(
|
|
80285
81849
|
upFail({
|
|
80286
81850
|
kind: "unavailable",
|
|
@@ -80342,18 +81906,24 @@ var RealUpstreamPlugin = class {
|
|
|
80342
81906
|
* the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
|
|
80343
81907
|
* and the service-mode SDK routes its own subgraph reads through the same proxy — so
|
|
80344
81908
|
* writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
|
|
80345
|
-
* Safe to call repeatedly
|
|
80346
|
-
*
|
|
81909
|
+
* Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
|
|
81910
|
+
* first write builds again (see ensureSdk). */
|
|
80347
81911
|
async initWriteSdk() {
|
|
80348
81912
|
if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
|
|
80349
81913
|
const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
|
|
80350
81914
|
if (!wallet) return;
|
|
80351
81915
|
await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
|
|
80352
81916
|
}
|
|
80353
|
-
/**
|
|
80354
|
-
*
|
|
81917
|
+
/** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
|
|
81918
|
+
*
|
|
81919
|
+
* A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
|
|
81920
|
+
* life of the process and drop the error, which was survivable only while `create` never
|
|
81921
|
+
* touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
|
|
81922
|
+
* RPC blip at boot would have disabled every later write with no reason given. Now each write
|
|
81923
|
+
* retries, and a persistent failure says what it is. Concurrent callers share one build. */
|
|
80355
81924
|
async ensureSdk(key, signer) {
|
|
80356
|
-
|
|
81925
|
+
const cached = this.sdkCache.get(key);
|
|
81926
|
+
if (cached) return { ok: true, sdk: cached };
|
|
80357
81927
|
const inFlight = this.sdkInFlight.get(key);
|
|
80358
81928
|
if (inFlight) return inFlight;
|
|
80359
81929
|
const build = (async () => {
|
|
@@ -80373,17 +81943,23 @@ var RealUpstreamPlugin = class {
|
|
|
80373
81943
|
// nesting writes under indexer discovery (the M8B-4 coupling this removes).
|
|
80374
81944
|
...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
|
|
80375
81945
|
});
|
|
80376
|
-
|
|
80377
|
-
|
|
80378
|
-
|
|
81946
|
+
if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
|
|
81947
|
+
return { ok: false, reason: builtWrite.error.message };
|
|
81948
|
+
} catch (e) {
|
|
81949
|
+
return { ok: false, reason: e instanceof Error ? e.message : String(e) };
|
|
80379
81950
|
}
|
|
80380
81951
|
})();
|
|
80381
81952
|
this.sdkInFlight.set(key, build);
|
|
80382
81953
|
const built = await build;
|
|
80383
81954
|
this.sdkInFlight.delete(key);
|
|
80384
|
-
this.sdkCache.set(key, built);
|
|
81955
|
+
if (built.ok) this.sdkCache.set(key, built.sdk);
|
|
80385
81956
|
return built;
|
|
80386
81957
|
}
|
|
81958
|
+
/** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
|
|
81959
|
+
async writeSdkFor(key, signer) {
|
|
81960
|
+
const built = await this.ensureSdk(key, signer);
|
|
81961
|
+
return built.ok ? { ok: true, sdk: built.sdk } : built;
|
|
81962
|
+
}
|
|
80387
81963
|
wallet;
|
|
80388
81964
|
// ---- per-call signer resolution (plan 10 A3) ----
|
|
80389
81965
|
/** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
|
|
@@ -80423,7 +81999,7 @@ var RealUpstreamPlugin = class {
|
|
|
80423
81999
|
chainId: this.config.chainId,
|
|
80424
82000
|
dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
|
|
80425
82001
|
session,
|
|
80426
|
-
getWriteSdk: () => this.
|
|
82002
|
+
getWriteSdk: () => this.writeSdkFor(key, wallet),
|
|
80427
82003
|
readDetails: (id) => this.readPositionDetails(id),
|
|
80428
82004
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
80429
82005
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
@@ -80439,14 +82015,14 @@ var RealUpstreamPlugin = class {
|
|
|
80439
82015
|
if (!pkpValidation) {
|
|
80440
82016
|
throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
|
|
80441
82017
|
}
|
|
80442
|
-
const registry = new
|
|
82018
|
+
const registry = new import_ethers48.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
|
|
80443
82019
|
let validator;
|
|
80444
82020
|
try {
|
|
80445
82021
|
validator = await registry.validatorForVersion(version2);
|
|
80446
82022
|
} catch (e) {
|
|
80447
82023
|
throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
|
|
80448
82024
|
}
|
|
80449
|
-
if (validator ===
|
|
82025
|
+
if (validator === import_ethers48.ethers.ZeroAddress) {
|
|
80450
82026
|
throw new Error(
|
|
80451
82027
|
`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.`
|
|
80452
82028
|
);
|
|
@@ -80496,7 +82072,7 @@ var RealUpstreamPlugin = class {
|
|
|
80496
82072
|
failure: {
|
|
80497
82073
|
kind: "signer-missing",
|
|
80498
82074
|
source: "real-ops",
|
|
80499
|
-
message: "no authorization mode is chosen (SIGNER_UNAVAILABLE) \u2014
|
|
82075
|
+
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."
|
|
80500
82076
|
}
|
|
80501
82077
|
};
|
|
80502
82078
|
}
|
|
@@ -80520,7 +82096,6 @@ var RealUpstreamPlugin = class {
|
|
|
80520
82096
|
gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
|
|
80521
82097
|
this.opsGatewayCache.set(key, gateway);
|
|
80522
82098
|
}
|
|
80523
|
-
await this.ensureSdk(key, wallet.connect(this.provider));
|
|
80524
82099
|
return { ok: true, gateway };
|
|
80525
82100
|
}
|
|
80526
82101
|
if (mode === "external") {
|
|
@@ -80557,14 +82132,13 @@ var RealUpstreamPlugin = class {
|
|
|
80557
82132
|
chainId: this.config.chainId,
|
|
80558
82133
|
dhSigner: new ExternalEoaDHSigner(deps),
|
|
80559
82134
|
session,
|
|
80560
|
-
getWriteSdk: () => this.
|
|
82135
|
+
getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
|
|
80561
82136
|
readDetails: (id) => this.readPositionDetails(id),
|
|
80562
82137
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
80563
82138
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
80564
82139
|
});
|
|
80565
82140
|
this.opsGatewayCache.set(key, gateway);
|
|
80566
82141
|
}
|
|
80567
|
-
await this.ensureSdk(key, this.externalSigners.get(key));
|
|
80568
82142
|
return { ok: true, gateway };
|
|
80569
82143
|
}
|
|
80570
82144
|
return {
|
|
@@ -80724,7 +82298,7 @@ var RealUpstreamPlugin = class {
|
|
|
80724
82298
|
);
|
|
80725
82299
|
if (!r.ok) return r;
|
|
80726
82300
|
const raw = r.value.data.supportedStablecoins ?? [];
|
|
80727
|
-
const bad = raw.find((x) => !
|
|
82301
|
+
const bad = raw.find((x) => !import_ethers48.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
|
|
80728
82302
|
if (bad) {
|
|
80729
82303
|
return {
|
|
80730
82304
|
ok: false,
|
|
@@ -80807,7 +82381,7 @@ var RealUpstreamPlugin = class {
|
|
|
80807
82381
|
};
|
|
80808
82382
|
}
|
|
80809
82383
|
const symbol = raw.toLowerCase();
|
|
80810
|
-
if (
|
|
82384
|
+
if (import_ethers48.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
|
|
80811
82385
|
const verified = await this.verifiedStablecoins();
|
|
80812
82386
|
if (!verified.ok) return { ok: false, failure: verified.failure };
|
|
80813
82387
|
const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
|
|
@@ -80845,7 +82419,7 @@ var RealUpstreamPlugin = class {
|
|
|
80845
82419
|
* chain, then sign.
|
|
80846
82420
|
*/
|
|
80847
82421
|
async psmCallsFor(stablecoinAddress) {
|
|
80848
|
-
if (!
|
|
82422
|
+
if (!import_ethers48.ethers.isAddress(stablecoinAddress)) {
|
|
80849
82423
|
throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
|
|
80850
82424
|
}
|
|
80851
82425
|
const key = stablecoinAddress.toLowerCase();
|
|
@@ -80865,9 +82439,9 @@ var RealUpstreamPlugin = class {
|
|
|
80865
82439
|
let supported;
|
|
80866
82440
|
let symbol;
|
|
80867
82441
|
try {
|
|
80868
|
-
const psm = new
|
|
82442
|
+
const psm = new import_ethers48.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
|
|
80869
82443
|
supported = await psm["supportedStablecoins"](key);
|
|
80870
|
-
const erc20 = new
|
|
82444
|
+
const erc20 = new import_ethers48.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
|
|
80871
82445
|
symbol = await erc20["symbol"]();
|
|
80872
82446
|
} catch (e) {
|
|
80873
82447
|
return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
|
|
@@ -81080,7 +82654,7 @@ var RealUpstreamPlugin = class {
|
|
|
81080
82654
|
const pm = this.contracts["PositionManager"];
|
|
81081
82655
|
if (!pm) return false;
|
|
81082
82656
|
try {
|
|
81083
|
-
const c = new
|
|
82657
|
+
const c = new import_ethers48.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
|
|
81084
82658
|
return Boolean(await c["paused"]());
|
|
81085
82659
|
} catch {
|
|
81086
82660
|
return false;
|
|
@@ -81089,16 +82663,16 @@ var RealUpstreamPlugin = class {
|
|
|
81089
82663
|
async readPositionDetails(id) {
|
|
81090
82664
|
const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
|
|
81091
82665
|
if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
|
|
81092
|
-
const c = new
|
|
82666
|
+
const c = new import_ethers48.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
|
|
81093
82667
|
let d;
|
|
81094
82668
|
try {
|
|
81095
|
-
d = await c["getPositionDetails"](
|
|
82669
|
+
d = await c["getPositionDetails"](import_ethers48.ethers.zeroPadValue(id, 32));
|
|
81096
82670
|
} catch (e) {
|
|
81097
82671
|
if (e.code === "CALL_EXCEPTION") return null;
|
|
81098
82672
|
throw e;
|
|
81099
82673
|
}
|
|
81100
82674
|
const borrower = String(d["borrower"]);
|
|
81101
|
-
if (borrower ===
|
|
82675
|
+
if (borrower === import_ethers48.ethers.ZeroAddress) return null;
|
|
81102
82676
|
return {
|
|
81103
82677
|
positionId: String(d["positionId"]),
|
|
81104
82678
|
pkpId: String(d["pkpId"]),
|
|
@@ -82728,8 +84302,8 @@ async function buildBoundary(configResult, overrides) {
|
|
|
82728
84302
|
);
|
|
82729
84303
|
}
|
|
82730
84304
|
try {
|
|
82731
|
-
const decrypted = await
|
|
82732
|
-
if (!(decrypted instanceof
|
|
84305
|
+
const decrypted = await import_ethers49.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
|
|
84306
|
+
if (!(decrypted instanceof import_ethers49.ethers.Wallet)) {
|
|
82733
84307
|
return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
|
|
82734
84308
|
}
|
|
82735
84309
|
wallet = decrypted;
|
|
@@ -83221,7 +84795,7 @@ on the real adapter and the mock.
|
|
|
83221
84795
|
| extend | 1 personal-sign + 1 tx |
|
|
83222
84796
|
| allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
|
|
83223
84797
|
| withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
|
|
83224
|
-
| PSM swap/redeem |
|
|
84798
|
+
| PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
|
|
83225
84799
|
|
|
83226
84800
|
**Honesty notes (say these plainly):**
|
|
83227
84801
|
- **Reads never pop the wallet.** If a read needs a login the user does not have, the
|
|
@@ -83365,16 +84939,19 @@ rather than silently deliver less than quoted.
|
|
|
83365
84939
|
|
|
83366
84940
|
${psmStablecoinRealityNote(d)}
|
|
83367
84941
|
|
|
83368
|
-
**Executing (\`psm_swap\`):** an exchange is
|
|
83369
|
-
result. (1)
|
|
84942
|
+
**Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
|
|
84943
|
+
the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
|
|
84944
|
+
planned against the allowance already standing: none when it covers the amount, one when it
|
|
84945
|
+
is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
|
|
83370
84946
|
differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
|
|
83371
84947
|
the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
|
|
83372
84948
|
you approve UCD to the **UCDController** (the PSM burns your UCD through the
|
|
83373
84949
|
controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
|
|
83374
84950
|
tolerance; if fees or the rate drifted beyond that between quote and execution, the
|
|
83375
84951
|
contract refuses \u2014 you never silently receive less. Output always lands at the signer's
|
|
83376
|
-
own address. If you approve
|
|
83377
|
-
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly
|
|
84952
|
+
own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
|
|
84953
|
+
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
|
|
84954
|
+
the next exchange that it covers uses it without asking for another approval.
|
|
83378
84955
|
PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
|
|
83379
84956
|
REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
|
|
83380
84957
|
wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
|
|
@@ -83847,7 +85424,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
|
83847
85424
|
|
|
83848
85425
|
// src/tools/loan.ts
|
|
83849
85426
|
var import_zod = require("zod");
|
|
83850
|
-
var
|
|
85427
|
+
var import_ethers50 = require("ethers");
|
|
83851
85428
|
|
|
83852
85429
|
// src/util/format.ts
|
|
83853
85430
|
function bigintReplacer(_key, value) {
|
|
@@ -84035,7 +85612,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
|
|
|
84035
85612
|
const b = getB();
|
|
84036
85613
|
if (!b.ok) return renderError(b.error);
|
|
84037
85614
|
return renderEnvelope(
|
|
84038
|
-
await b.boundary.mintUcd({ positionId, amountUcdWei: (0,
|
|
85615
|
+
await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers50.parseEther)(amountUcd.toString()).toString() })
|
|
84039
85616
|
);
|
|
84040
85617
|
})
|
|
84041
85618
|
);
|
|
@@ -84073,7 +85650,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
|
|
|
84073
85650
|
if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
|
|
84074
85651
|
amountUcdWei = detail.data.debtUcdWei;
|
|
84075
85652
|
} else {
|
|
84076
|
-
amountUcdWei = (0,
|
|
85653
|
+
amountUcdWei = (0, import_ethers50.parseEther)(amountUcd.toString()).toString();
|
|
84077
85654
|
}
|
|
84078
85655
|
return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
|
|
84079
85656
|
})
|
|
@@ -84474,7 +86051,7 @@ function registerPsmTools(server, getB) {
|
|
|
84474
86051
|
"psm_swap",
|
|
84475
86052
|
{
|
|
84476
86053
|
title: "Exchange UCD \u2194 a stablecoin through the PSM",
|
|
84477
|
-
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
|
|
86054
|
+
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).",
|
|
84478
86055
|
inputSchema: {
|
|
84479
86056
|
stablecoin: import_zod4.z.string().min(1).describe(
|
|
84480
86057
|
"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."
|
|
@@ -84490,7 +86067,7 @@ function registerPsmTools(server, getB) {
|
|
|
84490
86067
|
const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
|
|
84491
86068
|
const gate = requireConfirmation(
|
|
84492
86069
|
confirmed,
|
|
84493
|
-
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (
|
|
86070
|
+
`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"})`
|
|
84494
86071
|
);
|
|
84495
86072
|
if (gate) return gate;
|
|
84496
86073
|
const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
|
|
@@ -84676,7 +86253,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
|
|
|
84676
86253
|
|
|
84677
86254
|
// src/tools/signer.ts
|
|
84678
86255
|
var import_zod6 = require("zod");
|
|
84679
|
-
var
|
|
86256
|
+
var import_ethers51 = require("ethers");
|
|
84680
86257
|
var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
84681
86258
|
var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
|
|
84682
86259
|
var EXTERNAL_ONLY_MODES = ["external"];
|
|
@@ -84718,7 +86295,7 @@ function registerSignerTool(server, getRuntime, opts) {
|
|
|
84718
86295
|
if (mode !== void 0 && !offeredModes.includes(mode)) {
|
|
84719
86296
|
return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
|
|
84720
86297
|
}
|
|
84721
|
-
if (safeAddress !== void 0 && !
|
|
86298
|
+
if (safeAddress !== void 0 && !import_ethers51.ethers.isAddress(safeAddress)) {
|
|
84722
86299
|
return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
|
|
84723
86300
|
}
|
|
84724
86301
|
if (action === "status") {
|
|
@@ -85129,7 +86706,7 @@ function registerBoundaryInfoResource(server, getB) {
|
|
|
85129
86706
|
}
|
|
85130
86707
|
|
|
85131
86708
|
// src/version.ts
|
|
85132
|
-
var SERVER_VERSION = "0.5.
|
|
86709
|
+
var SERVER_VERSION = "0.5.18";
|
|
85133
86710
|
|
|
85134
86711
|
// src/server.ts
|
|
85135
86712
|
var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
|