@gvnrdao/dh-mcp 0.5.16 → 0.5.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -3
- package/dist/boundary.js +1907 -351
- package/dist/connector-embed.js +1926 -367
- package/dist/connector.js +1926 -367
- package/dist/index.js +1926 -367
- package/package.json +2 -2
package/dist/connector-embed.js
CHANGED
|
@@ -15552,7 +15552,7 @@ ${errorReport}`);
|
|
|
15552
15552
|
}
|
|
15553
15553
|
init_debug_logger();
|
|
15554
15554
|
init_session_signature_cache();
|
|
15555
|
-
var
|
|
15555
|
+
var import_ethers53 = require("ethers");
|
|
15556
15556
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
15557
15557
|
var GRACE_PERIOD_DAYS = 30;
|
|
15558
15558
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -18468,12 +18468,12 @@ ${auth.clientId}`;
|
|
|
18468
18468
|
}
|
|
18469
18469
|
async function executeVaultSnapshot(params) {
|
|
18470
18470
|
global.ethers = {
|
|
18471
|
-
...
|
|
18471
|
+
...import_ethers53.ethers,
|
|
18472
18472
|
providers: {
|
|
18473
|
-
StaticJsonRpcProvider:
|
|
18473
|
+
StaticJsonRpcProvider: import_ethers53.ethers.JsonRpcProvider
|
|
18474
18474
|
},
|
|
18475
|
-
Contract:
|
|
18476
|
-
utils:
|
|
18475
|
+
Contract: import_ethers53.ethers.Contract,
|
|
18476
|
+
utils: import_ethers53.ethers
|
|
18477
18477
|
// v6 moved utils to top level
|
|
18478
18478
|
};
|
|
18479
18479
|
global.Lit = {
|
|
@@ -25682,7 +25682,10 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25682
25682
|
"node_modules/@gvnrdao/dh-lit-ops/dist/utils/lit-core-lit-action-client.js"(exports2) {
|
|
25683
25683
|
"use strict";
|
|
25684
25684
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
25685
|
+
exports2.CORE_API_TRANSPORT_FAILURE_MARKER = void 0;
|
|
25685
25686
|
exports2.normalizeCoreLitActionResult = normalizeCoreLitActionResult;
|
|
25687
|
+
exports2.describeErrorWithCause = describeErrorWithCause;
|
|
25688
|
+
exports2.isCoreApiTransportError = isCoreApiTransportError;
|
|
25686
25689
|
exports2.executeLitActionViaCoreApi = executeLitActionViaCoreApi;
|
|
25687
25690
|
var fetch_lit_action_from_ipfs_1 = require_fetch_lit_action_from_ipfs();
|
|
25688
25691
|
function parseResponsePayload(raw) {
|
|
@@ -25733,6 +25736,27 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25733
25736
|
const fromEnv = process.env.LIT_CORE_API_BASE_URL;
|
|
25734
25737
|
return (explicit || fromEnv || "https://api.chipotle.litprotocol.com").replace(/\/$/, "");
|
|
25735
25738
|
}
|
|
25739
|
+
exports2.CORE_API_TRANSPORT_FAILURE_MARKER = "Lit Core lit_action transport failure";
|
|
25740
|
+
function describeErrorWithCause(e) {
|
|
25741
|
+
const parts = [];
|
|
25742
|
+
let current = e;
|
|
25743
|
+
const seen = /* @__PURE__ */ new Set();
|
|
25744
|
+
while (current != null && !seen.has(current) && parts.length < 5) {
|
|
25745
|
+
seen.add(current);
|
|
25746
|
+
if (current instanceof Error) {
|
|
25747
|
+
const code = current.code;
|
|
25748
|
+
parts.push(typeof code === "string" && !current.message.includes(code) ? `${code}: ${current.message}` : current.message);
|
|
25749
|
+
current = current.cause;
|
|
25750
|
+
} else {
|
|
25751
|
+
parts.push(String(current));
|
|
25752
|
+
break;
|
|
25753
|
+
}
|
|
25754
|
+
}
|
|
25755
|
+
return parts.length === 0 ? String(e) : parts.join(" <- ");
|
|
25756
|
+
}
|
|
25757
|
+
function isCoreApiTransportError(message) {
|
|
25758
|
+
return message.includes(exports2.CORE_API_TRANSPORT_FAILURE_MARKER);
|
|
25759
|
+
}
|
|
25736
25760
|
async function executeLitActionViaCoreApi(options) {
|
|
25737
25761
|
let resolvedCode = options.code || "";
|
|
25738
25762
|
if (!resolvedCode.trim()) {
|
|
@@ -25794,13 +25818,11 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25794
25818
|
return normalizeCoreLitActionResult(body);
|
|
25795
25819
|
} catch (e) {
|
|
25796
25820
|
const msg = e instanceof Error ? e.message : String(e);
|
|
25821
|
+
const error = msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : `${exports2.CORE_API_TRANSPORT_FAILURE_MARKER}: ${describeErrorWithCause(e)}`;
|
|
25797
25822
|
if (options.debug) {
|
|
25798
|
-
console.error("\u274C [executeLitActionViaCoreApi]",
|
|
25823
|
+
console.error("\u274C [executeLitActionViaCoreApi]", error);
|
|
25799
25824
|
}
|
|
25800
|
-
return {
|
|
25801
|
-
success: false,
|
|
25802
|
-
error: msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : msg
|
|
25803
|
-
};
|
|
25825
|
+
return { success: false, error };
|
|
25804
25826
|
} finally {
|
|
25805
25827
|
clearTimeout(timer);
|
|
25806
25828
|
}
|
|
@@ -26782,7 +26804,8 @@ var require_lit_ops_module = __commonJS({
|
|
|
26782
26804
|
const borrowerAddress = borrowerOverride ?? this.config.serverAddress ?? await this.config.signer.getAddress();
|
|
26783
26805
|
const pkpValidatorInfo = DH_LIT_ACTIONS_CHIPOTLE.pkpValidator;
|
|
26784
26806
|
const validatorWalletAddress = process.env.LIT_PKP_VALIDATOR_WALLET_OVERRIDE || pkpValidatorInfo?.validatorWalletAddress;
|
|
26785
|
-
const
|
|
26807
|
+
const errorMessage = (e) => e instanceof Error ? e.message : String(e);
|
|
26808
|
+
const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(errorMessage(e));
|
|
26786
26809
|
const propagationRetries = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_RETRIES) || 8;
|
|
26787
26810
|
const propagationDelayMs = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_DELAY_MS) || 15e3;
|
|
26788
26811
|
let coreResponse;
|
|
@@ -26803,10 +26826,12 @@ var require_lit_ops_module = __commonJS({
|
|
|
26803
26826
|
coreResponse = exec.response;
|
|
26804
26827
|
break;
|
|
26805
26828
|
} catch (e) {
|
|
26806
|
-
|
|
26829
|
+
const propagating = isWalletPropagationError(e);
|
|
26830
|
+
const transport = (0, lit_core_lit_action_client_1.isCoreApiTransportError)(errorMessage(e));
|
|
26831
|
+
if (!propagating && !transport || attempt === propagationRetries) {
|
|
26807
26832
|
throw e;
|
|
26808
26833
|
}
|
|
26809
|
-
console.log(`[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
|
|
26834
|
+
console.log(propagating ? `[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms` : `[ChipotlePKP] vault PKP ${pkpId} validator call failed in transport (${errorMessage(e)}); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
|
|
26810
26835
|
await new Promise((r) => setTimeout(r, propagationDelayMs));
|
|
26811
26836
|
}
|
|
26812
26837
|
}
|
|
@@ -40531,7 +40556,7 @@ var require_dist3 = __commonJS({
|
|
|
40531
40556
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
|
|
40532
40557
|
};
|
|
40533
40558
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
40534
|
-
exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
|
|
40559
|
+
exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
|
|
40535
40560
|
__exportStar(require_interfaces(), exports2);
|
|
40536
40561
|
var dh_lit_actions_1 = require_pkg_src();
|
|
40537
40562
|
Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
|
|
@@ -40601,6 +40626,15 @@ var require_dist3 = __commonJS({
|
|
|
40601
40626
|
Object.defineProperty(exports2, "normalizeCoreLitActionResult", { enumerable: true, get: function() {
|
|
40602
40627
|
return lit_core_lit_action_client_1.normalizeCoreLitActionResult;
|
|
40603
40628
|
} });
|
|
40629
|
+
Object.defineProperty(exports2, "describeErrorWithCause", { enumerable: true, get: function() {
|
|
40630
|
+
return lit_core_lit_action_client_1.describeErrorWithCause;
|
|
40631
|
+
} });
|
|
40632
|
+
Object.defineProperty(exports2, "isCoreApiTransportError", { enumerable: true, get: function() {
|
|
40633
|
+
return lit_core_lit_action_client_1.isCoreApiTransportError;
|
|
40634
|
+
} });
|
|
40635
|
+
Object.defineProperty(exports2, "CORE_API_TRANSPORT_FAILURE_MARKER", { enumerable: true, get: function() {
|
|
40636
|
+
return lit_core_lit_action_client_1.CORE_API_TRANSPORT_FAILURE_MARKER;
|
|
40637
|
+
} });
|
|
40604
40638
|
var bitcoin_signature_1 = require_bitcoin_signature();
|
|
40605
40639
|
Object.defineProperty(exports2, "convertEthereumSignatureToBitcoinDER", { enumerable: true, get: function() {
|
|
40606
40640
|
return bitcoin_signature_1.convertEthereumSignatureToBitcoinDER;
|
|
@@ -41038,7 +41072,7 @@ function htmlPageSecurityHeaders(extra) {
|
|
|
41038
41072
|
}
|
|
41039
41073
|
|
|
41040
41074
|
// src/version.ts
|
|
41041
|
-
var SERVER_VERSION = "0.5.
|
|
41075
|
+
var SERVER_VERSION = "0.5.17";
|
|
41042
41076
|
|
|
41043
41077
|
// src/connector/siwe-oauth.ts
|
|
41044
41078
|
var import_node_crypto2 = require("crypto");
|
|
@@ -41756,7 +41790,7 @@ function resolveRealConfig(env) {
|
|
|
41756
41790
|
|
|
41757
41791
|
// src/boot.ts
|
|
41758
41792
|
var fs6 = __toESM(require("fs"));
|
|
41759
|
-
var
|
|
41793
|
+
var import_ethers50 = require("ethers");
|
|
41760
41794
|
|
|
41761
41795
|
// src/boundary/index.ts
|
|
41762
41796
|
var import_node_crypto9 = require("crypto");
|
|
@@ -42173,7 +42207,7 @@ var BoundaryCore = class {
|
|
|
42173
42207
|
const inToken = toUcd ? s.stablecoinSymbol : "UCD";
|
|
42174
42208
|
const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
|
|
42175
42209
|
const amountIn = parseDecimalUnits(p.amount, inDecimals);
|
|
42176
|
-
const
|
|
42210
|
+
const refuse3 = (refusal, message, details) => ({
|
|
42177
42211
|
env: errEnvelope(
|
|
42178
42212
|
boundaryError("UPSTREAM_REJECTED", message, {
|
|
42179
42213
|
source: statusR.source.id,
|
|
@@ -42184,13 +42218,13 @@ var BoundaryCore = class {
|
|
|
42184
42218
|
});
|
|
42185
42219
|
const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
|
|
42186
42220
|
if (s.paused) {
|
|
42187
|
-
return
|
|
42221
|
+
return refuse3(
|
|
42188
42222
|
"psm-paused",
|
|
42189
42223
|
"the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
|
|
42190
42224
|
);
|
|
42191
42225
|
}
|
|
42192
42226
|
if (!toUcd && !s.redeemEnabled) {
|
|
42193
|
-
return
|
|
42227
|
+
return refuse3(
|
|
42194
42228
|
"redeem-disabled",
|
|
42195
42229
|
`redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
|
|
42196
42230
|
);
|
|
@@ -42201,20 +42235,20 @@ var BoundaryCore = class {
|
|
|
42201
42235
|
const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
|
|
42202
42236
|
const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
|
|
42203
42237
|
if (amountIn < min) {
|
|
42204
|
-
return
|
|
42238
|
+
return refuse3(
|
|
42205
42239
|
"below-min",
|
|
42206
42240
|
`${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
|
|
42207
42241
|
{ amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
|
|
42208
42242
|
);
|
|
42209
42243
|
}
|
|
42210
42244
|
if (max === 0n) {
|
|
42211
|
-
return
|
|
42245
|
+
return refuse3(
|
|
42212
42246
|
"direction-disabled",
|
|
42213
42247
|
`the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
|
|
42214
42248
|
);
|
|
42215
42249
|
}
|
|
42216
42250
|
if (amountIn > max) {
|
|
42217
|
-
return
|
|
42251
|
+
return refuse3(
|
|
42218
42252
|
"above-max",
|
|
42219
42253
|
`${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
|
|
42220
42254
|
{ amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
|
|
@@ -42234,7 +42268,7 @@ var BoundaryCore = class {
|
|
|
42234
42268
|
if (!toUcd) {
|
|
42235
42269
|
const available = BigInt(s.availableReserves);
|
|
42236
42270
|
if (available < amountOut) {
|
|
42237
|
-
return
|
|
42271
|
+
return refuse3(
|
|
42238
42272
|
"insufficient-reserves",
|
|
42239
42273
|
`the PSM cannot pay this redemption: available reserves ${formatDecimalUnits(available, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${available} smallest units), required ${formatDecimalUnits(amountOut, s.stablecoinDecimals)} ${s.stablecoinSymbol} (${amountOut} smallest units).`,
|
|
42240
42274
|
{ available: available.toString(), required: amountOut.toString(), unit: outUnit }
|
|
@@ -42310,20 +42344,31 @@ var BoundaryCore = class {
|
|
|
42310
42344
|
const inDecimals = toUcd ? s.stablecoinDecimals : 18;
|
|
42311
42345
|
const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
|
|
42312
42346
|
const viaSafe = this.deps.signer?.mode() === "safe";
|
|
42347
|
+
const a = v.allowance;
|
|
42348
|
+
const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
|
|
42349
|
+
const approvalsHuman = v.approvals.length === 0 ? `No approval was needed: the standing ${a.tokenSymbol} allowance to ${a.spenderContract} (${fmtIn(a.before)}) already covered the amount.` : v.approvals.map(
|
|
42350
|
+
(leg) => leg.step === "reset-approve" ? `reset the partial ${a.tokenSymbol} allowance to ${a.spenderContract} (${fmtIn(a.before)}) to 0` : `approved EXACTLY ${fmtIn(leg.amount)} to ${a.spenderContract}`
|
|
42351
|
+
).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
|
|
42313
42352
|
const data = {
|
|
42314
42353
|
direction: p.direction,
|
|
42315
42354
|
contractCall: q.contractCall,
|
|
42316
|
-
|
|
42317
|
-
|
|
42318
|
-
|
|
42319
|
-
|
|
42320
|
-
|
|
42321
|
-
|
|
42322
|
-
|
|
42323
|
-
amount: v.approve.amount,
|
|
42355
|
+
allowance: {
|
|
42356
|
+
token: a.tokenSymbol,
|
|
42357
|
+
tokenAddress: a.tokenAddress,
|
|
42358
|
+
spenderAddress: a.spenderAddress,
|
|
42359
|
+
spenderContract: a.spenderContract,
|
|
42360
|
+
spenderReason: a.spenderContract === "SimplePSMV2" ? "the PSM contract itself pulls the USDC it converts (transferFrom), so the USDC allowance goes to the PSM" : "the PSM burns your UCD THROUGH the UCDController (controller.burnFromPsm), so the UCD allowance goes to the UCDController \u2014 a different contract than the PSM, by design",
|
|
42361
|
+
before: a.before,
|
|
42324
42362
|
amountUnit: q.amountInUnit,
|
|
42325
|
-
|
|
42363
|
+
basis: "approvals are planned against the allowance read before signing: none when it already covers the amount; an exact approve when it is 0; a partial allowance is reset to 0 first (some tokens refuse a non-zero \u2192 non-zero approve). Every approve is EXACTLY the input amount \u2014 never unlimited."
|
|
42326
42364
|
},
|
|
42365
|
+
approvals: v.approvals.map((leg) => ({
|
|
42366
|
+
step: leg.step,
|
|
42367
|
+
txRef: leg.txRef,
|
|
42368
|
+
amount: leg.amount,
|
|
42369
|
+
amountUnit: q.amountInUnit,
|
|
42370
|
+
authorization: leg.authorization
|
|
42371
|
+
})),
|
|
42327
42372
|
execute: {
|
|
42328
42373
|
txRef: v.execute.txRef,
|
|
42329
42374
|
amountIn: v.execute.amountIn,
|
|
@@ -42345,7 +42390,7 @@ var BoundaryCore = class {
|
|
|
42345
42390
|
note: viaSafe ? "output lands AT THE SAFE \u2014 both transactions execute BY the Safe (the Safe is msg.sender, and the contract pays msg.sender only; there is no recipient parameter)" : "output goes to the signer's own address \u2014 the contract pays msg.sender only; there is no recipient parameter"
|
|
42346
42391
|
},
|
|
42347
42392
|
balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
|
|
42348
|
-
human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}).
|
|
42393
|
+
human: `${formatDecimalUnits(BigInt(q.amountIn), inDecimals)} ${q.amountInToken} -> ${formatDecimalUnits(BigInt(v.execute.amountOut), outDecimals)} ${q.amountOutToken} (fee ${formatDecimalUnits(BigInt(v.execute.feeAmount), outDecimals)} ${q.fee.token}). ${approvalsHuman} Ceremony ${v.approvals.length + 1}: ${q.contractCall} executed with floor ${formatDecimalUnits(BigInt(v.execute.minOut), outDecimals)} ${q.amountOutToken} (quote \u2212 ${PSM_FLOOR_TOLERANCE_BPS} bps). ` + (viaSafe ? `All executed BY the Safe as consecutive Safe transactions; output to the Safe: ${auth.borrower}.` : `Output to the signer: ${auth.borrower}.`)
|
|
42349
42394
|
};
|
|
42350
42395
|
return okEnvelope(data, r.source, warnings);
|
|
42351
42396
|
}
|
|
@@ -44204,6 +44249,16 @@ function buildExtendTx(ctx, p) {
|
|
|
44204
44249
|
);
|
|
44205
44250
|
}
|
|
44206
44251
|
|
|
44252
|
+
// src/boundary/upstream/shared/psm-approval-steps.ts
|
|
44253
|
+
function psmApprovalSteps(allowanceBefore, amountIn) {
|
|
44254
|
+
if (allowanceBefore >= amountIn) return [];
|
|
44255
|
+
if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
|
|
44256
|
+
return [
|
|
44257
|
+
{ step: "reset-approve", amount: 0n },
|
|
44258
|
+
{ step: "approve", amount: amountIn }
|
|
44259
|
+
];
|
|
44260
|
+
}
|
|
44261
|
+
|
|
44207
44262
|
// src/boundary/upstream/mock/sink-contracts.ts
|
|
44208
44263
|
var import_ethers6 = require("ethers");
|
|
44209
44264
|
function sinkAddress(label) {
|
|
@@ -45039,8 +45094,9 @@ var MockUpstreamPlugin = class {
|
|
|
45039
45094
|
return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
|
|
45040
45095
|
});
|
|
45041
45096
|
}
|
|
45042
|
-
/** PSM exchange
|
|
45043
|
-
* approve
|
|
45097
|
+
/** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
|
|
45098
|
+
* or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
|
|
45099
|
+
* asymmetric by direction, contract truth), then the swap/redeem with
|
|
45044
45100
|
* its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
|
|
45045
45101
|
* AFTER the approve reports the step that declined AND the residual exact-amount
|
|
45046
45102
|
* allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
|
|
@@ -45059,55 +45115,75 @@ var MockUpstreamPlugin = class {
|
|
|
45059
45115
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
45060
45116
|
const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
|
|
45061
45117
|
const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
|
|
45062
|
-
const
|
|
45063
|
-
const
|
|
45118
|
+
const standing = this.world.psmAllowancesOf(p.borrower);
|
|
45119
|
+
const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
|
|
45120
|
+
const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
|
|
45121
|
+
const landed = [];
|
|
45122
|
+
const residualNote = () => {
|
|
45123
|
+
const last = landed[landed.length - 1];
|
|
45124
|
+
const state = !last ? `no approve ran \u2014 the pre-existing allowance of ${allowanceBefore} ${tokenUnit} to ${spenderContract} is unchanged` : last === "reset-approve" ? `the reset step already completed \u2014 the allowance to ${spenderContract} is now 0; nothing is authorized` : `the approve step already completed \u2014 an exact-amount allowance of ${p.amountIn} ${tokenUnit} to ${spenderContract} remains standing; it authorizes only that amount and nothing else`;
|
|
45125
|
+
return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
45126
|
+
};
|
|
45064
45127
|
const executeCard = `${isSwap ? "exchange" : "redeem"} ${p.amountIn} ${tokenUnit} via the PSM (contract ${p.direction}): quote ${plan.value.out} ${outUnit} (fee ${plan.value.fee} ${outUnit}), floor ${p.minOut} ${outUnit} \u2014 output to ${p.borrower}`;
|
|
45065
45128
|
const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
|
|
45066
45129
|
const cer = this.ceremonyNow();
|
|
45067
|
-
|
|
45068
|
-
|
|
45069
|
-
const
|
|
45070
|
-
const
|
|
45071
|
-
const
|
|
45072
|
-
|
|
45073
|
-
|
|
45074
|
-
|
|
45075
|
-
|
|
45076
|
-
|
|
45077
|
-
|
|
45078
|
-
|
|
45079
|
-
|
|
45080
|
-
|
|
45081
|
-
|
|
45130
|
+
const approvals = [];
|
|
45131
|
+
for (const s of steps) {
|
|
45132
|
+
const amount = s.amount.toString();
|
|
45133
|
+
const isReset = s.step === "reset-approve";
|
|
45134
|
+
const label = isReset ? "RESET-APPROVE" : "APPROVE";
|
|
45135
|
+
const stopNote = landed.length > 0 ? residualNote() : isReset ? `the partial allowance of ${allowanceBefore} ${tokenUnit} to ${spenderContract} is unchanged and no funds moved` : "no allowance was granted and no funds moved";
|
|
45136
|
+
const card = isReset ? `reset the standing allowance of ${allowanceBefore} ${tokenUnit} to ${spenderContract} to 0 (required before an exact-amount approve; ${spenderReason})` : `approve exactly ${amount} ${tokenUnit} to ${spenderContract} (${spenderReason})`;
|
|
45137
|
+
let legAuth = null;
|
|
45138
|
+
if (cer) {
|
|
45139
|
+
const chainId = cer.txContext().chainId;
|
|
45140
|
+
const r = await cer.authorizeTx({
|
|
45141
|
+
action: "psm-approve",
|
|
45142
|
+
borrower: p.borrower,
|
|
45143
|
+
tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
|
|
45144
|
+
expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
|
|
45082
45145
|
});
|
|
45146
|
+
if (!r.ok) {
|
|
45147
|
+
return upFail({
|
|
45148
|
+
kind: "rejected",
|
|
45149
|
+
source: "mock-ops",
|
|
45150
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
|
|
45151
|
+
});
|
|
45152
|
+
}
|
|
45153
|
+
this.bindIfDiscovering(r.authorization);
|
|
45154
|
+
legAuth = r.authorization;
|
|
45083
45155
|
}
|
|
45084
|
-
this.
|
|
45085
|
-
|
|
45086
|
-
|
|
45087
|
-
|
|
45088
|
-
|
|
45089
|
-
|
|
45090
|
-
|
|
45091
|
-
|
|
45092
|
-
|
|
45093
|
-
|
|
45156
|
+
const leg = await this.write("psmSwap", () => {
|
|
45157
|
+
const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
|
|
45158
|
+
if (!sig.ok) {
|
|
45159
|
+
return upFail({
|
|
45160
|
+
kind: "rejected",
|
|
45161
|
+
source: "mock-ops",
|
|
45162
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
|
|
45163
|
+
});
|
|
45164
|
+
}
|
|
45165
|
+
const applied = this.applyAuthorized(sig.authorization, () => {
|
|
45166
|
+
this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
|
|
45167
|
+
return { ok: true, value: void 0 };
|
|
45094
45168
|
});
|
|
45095
|
-
|
|
45096
|
-
|
|
45097
|
-
|
|
45098
|
-
|
|
45169
|
+
if (!applied.ok) {
|
|
45170
|
+
return upFail({
|
|
45171
|
+
kind: "rejected",
|
|
45172
|
+
source: "mock-ops",
|
|
45173
|
+
message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
|
|
45174
|
+
});
|
|
45175
|
+
}
|
|
45176
|
+
return upOk(sig.authorization, this.src("mock-ops"));
|
|
45099
45177
|
});
|
|
45100
|
-
if (!
|
|
45101
|
-
|
|
45102
|
-
|
|
45103
|
-
|
|
45104
|
-
|
|
45105
|
-
|
|
45106
|
-
|
|
45107
|
-
|
|
45108
|
-
}
|
|
45109
|
-
if (!step1.ok) return step1;
|
|
45110
|
-
const aAuth = step1.value;
|
|
45178
|
+
if (!leg.ok) return leg;
|
|
45179
|
+
landed.push(s.step);
|
|
45180
|
+
approvals.push({
|
|
45181
|
+
step: s.step,
|
|
45182
|
+
txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
|
|
45183
|
+
amount,
|
|
45184
|
+
authorization: leg.value
|
|
45185
|
+
});
|
|
45186
|
+
}
|
|
45111
45187
|
let executeAuth = null;
|
|
45112
45188
|
if (cer) {
|
|
45113
45189
|
const chainId = cer.txContext().chainId;
|
|
@@ -45122,7 +45198,7 @@ var MockUpstreamPlugin = class {
|
|
|
45122
45198
|
return upFail({
|
|
45123
45199
|
kind: "rejected",
|
|
45124
45200
|
source: "mock-ops",
|
|
45125
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
|
|
45201
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
|
|
45126
45202
|
});
|
|
45127
45203
|
}
|
|
45128
45204
|
executeAuth = r.authorization;
|
|
@@ -45133,23 +45209,16 @@ var MockUpstreamPlugin = class {
|
|
|
45133
45209
|
return upFail({
|
|
45134
45210
|
kind: "rejected",
|
|
45135
45211
|
source: "mock-ops",
|
|
45136
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
|
|
45212
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
|
|
45137
45213
|
});
|
|
45138
45214
|
}
|
|
45139
45215
|
const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
|
|
45140
|
-
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
|
|
45216
|
+
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
|
|
45141
45217
|
const bal = this.world.balancesOf(p.borrower);
|
|
45142
45218
|
return upOk(
|
|
45143
45219
|
{
|
|
45144
|
-
|
|
45145
|
-
|
|
45146
|
-
tokenSymbol,
|
|
45147
|
-
tokenAddress,
|
|
45148
|
-
spenderAddress,
|
|
45149
|
-
spenderContract,
|
|
45150
|
-
amount: p.amountIn,
|
|
45151
|
-
authorization: aAuth
|
|
45152
|
-
},
|
|
45220
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
45221
|
+
approvals,
|
|
45153
45222
|
execute: {
|
|
45154
45223
|
txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
|
|
45155
45224
|
amountIn: p.amountIn,
|
|
@@ -46330,7 +46399,7 @@ var SafeModuleCeremony = class {
|
|
|
46330
46399
|
};
|
|
46331
46400
|
|
|
46332
46401
|
// src/boundary/upstream/real/plugin.ts
|
|
46333
|
-
var
|
|
46402
|
+
var import_ethers49 = require("ethers");
|
|
46334
46403
|
|
|
46335
46404
|
// node_modules/@gvnrdao/dh-sdk/dist/index.mjs
|
|
46336
46405
|
var import_ethers14 = require("ethers");
|
|
@@ -52421,8 +52490,12 @@ var {
|
|
|
52421
52490
|
var import_ethers28 = require("ethers");
|
|
52422
52491
|
var import_ethers29 = require("ethers");
|
|
52423
52492
|
var import_ethers30 = require("ethers");
|
|
52424
|
-
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
52425
52493
|
var import_ethers31 = require("ethers");
|
|
52494
|
+
var import_ethers32 = require("ethers");
|
|
52495
|
+
var import_ethers33 = require("ethers");
|
|
52496
|
+
var import_ethers34 = require("ethers");
|
|
52497
|
+
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
52498
|
+
var import_ethers35 = require("ethers");
|
|
52426
52499
|
var __create2 = Object.create;
|
|
52427
52500
|
var __defProp2 = Object.defineProperty;
|
|
52428
52501
|
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
@@ -54785,7 +54858,7 @@ ${errorReport}`);
|
|
|
54785
54858
|
}
|
|
54786
54859
|
init_debug_logger();
|
|
54787
54860
|
init_session_signature_cache();
|
|
54788
|
-
var
|
|
54861
|
+
var import_ethers232 = __require("ethers");
|
|
54789
54862
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
54790
54863
|
var GRACE_PERIOD_DAYS = 30;
|
|
54791
54864
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -57713,12 +57786,12 @@ ${auth.clientId}`;
|
|
|
57713
57786
|
}
|
|
57714
57787
|
async function executeVaultSnapshot(params) {
|
|
57715
57788
|
global.ethers = {
|
|
57716
|
-
...
|
|
57789
|
+
...import_ethers232.ethers,
|
|
57717
57790
|
providers: {
|
|
57718
|
-
StaticJsonRpcProvider:
|
|
57791
|
+
StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
|
|
57719
57792
|
},
|
|
57720
|
-
Contract:
|
|
57721
|
-
utils:
|
|
57793
|
+
Contract: import_ethers232.ethers.Contract,
|
|
57794
|
+
utils: import_ethers232.ethers
|
|
57722
57795
|
// v6 moved utils to top level
|
|
57723
57796
|
};
|
|
57724
57797
|
global.Lit = {
|
|
@@ -57972,8 +58045,8 @@ function getSepoliaConfig() {
|
|
|
57972
58045
|
positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
|
|
57973
58046
|
positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
|
|
57974
58047
|
simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
|
|
57975
|
-
mockUsdcToken: SEPOLIA_CONTRACTS
|
|
57976
|
-
mockUsdtToken: SEPOLIA_CONTRACTS
|
|
58048
|
+
mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
|
|
58049
|
+
mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
|
|
57977
58050
|
loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
|
|
57978
58051
|
termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
|
|
57979
58052
|
circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
|
|
@@ -58049,14 +58122,17 @@ function getMainnetConfig() {
|
|
|
58049
58122
|
agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
|
|
58050
58123
|
},
|
|
58051
58124
|
subgraphs: {
|
|
58052
|
-
//
|
|
58053
|
-
//
|
|
58054
|
-
//
|
|
58055
|
-
//
|
|
58056
|
-
//
|
|
58057
|
-
//
|
|
58058
|
-
//
|
|
58059
|
-
|
|
58125
|
+
// The MAINNET subgraph on The Graph's decentralized network — the same id
|
|
58126
|
+
// lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
|
|
58127
|
+
// the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
|
|
58128
|
+
// chainId-1 config: unusable as shipped, but a caller who added their own key would have
|
|
58129
|
+
// read Sepolia data as mainnet.
|
|
58130
|
+
//
|
|
58131
|
+
// The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
|
|
58132
|
+
// not) hold, so this URL only works for a standalone caller supplying their own key.
|
|
58133
|
+
// Service mode never uses it — queries go through the lit-ops-server proxy, which adds
|
|
58134
|
+
// the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
|
|
58135
|
+
diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
|
|
58060
58136
|
},
|
|
58061
58137
|
litNetwork: "chipotle",
|
|
58062
58138
|
debug: false
|
|
@@ -59077,6 +59153,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
|
|
|
59077
59153
|
}
|
|
59078
59154
|
return { timestamp: result.timestamp, signature: result.signature };
|
|
59079
59155
|
}
|
|
59156
|
+
function baseMintFeeWei(mintAmountWei, originationFeeBps) {
|
|
59157
|
+
if (mintAmountWei < 0n)
|
|
59158
|
+
throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
|
|
59159
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
59160
|
+
throw new Error(
|
|
59161
|
+
`baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
59162
|
+
);
|
|
59163
|
+
}
|
|
59164
|
+
return mintAmountWei * BigInt(originationFeeBps) / 10000n;
|
|
59165
|
+
}
|
|
59166
|
+
function debtAfterMintExceedsLoanCap(params) {
|
|
59167
|
+
const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
|
|
59168
|
+
for (const [name, v] of Object.entries(params)) {
|
|
59169
|
+
if (v < 0n)
|
|
59170
|
+
throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
|
|
59171
|
+
}
|
|
59172
|
+
return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
|
|
59173
|
+
}
|
|
59174
|
+
function maxPrincipalWithinLoanCap(params) {
|
|
59175
|
+
const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
|
|
59176
|
+
if (maxLoanWei < 0n || currentDebtWei < 0n) {
|
|
59177
|
+
throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
|
|
59178
|
+
}
|
|
59179
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
59180
|
+
throw new Error(
|
|
59181
|
+
`maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
59182
|
+
);
|
|
59183
|
+
}
|
|
59184
|
+
const room = maxLoanWei - currentDebtWei;
|
|
59185
|
+
if (room <= 0n)
|
|
59186
|
+
return 0n;
|
|
59187
|
+
return room * 10000n / (10000n + BigInt(originationFeeBps));
|
|
59188
|
+
}
|
|
59080
59189
|
function buildLoginDomain(chainId) {
|
|
59081
59190
|
return {
|
|
59082
59191
|
name: "Diamond Hands",
|
|
@@ -60486,23 +60595,37 @@ var BitcoinUtils = class {
|
|
|
60486
60595
|
return getBitcoinAddressesFromPkp(pkpPublicKey);
|
|
60487
60596
|
}
|
|
60488
60597
|
};
|
|
60489
|
-
function
|
|
60598
|
+
function networksOfValidAddress(address) {
|
|
60599
|
+
const lower2 = address.toLowerCase();
|
|
60600
|
+
if (lower2.startsWith("bcrt1"))
|
|
60601
|
+
return ["regtest"];
|
|
60602
|
+
if (lower2.startsWith("bc1"))
|
|
60603
|
+
return ["mainnet"];
|
|
60604
|
+
if (lower2.startsWith("tb1"))
|
|
60605
|
+
return ["testnet"];
|
|
60606
|
+
if (address.startsWith("1") || address.startsWith("3"))
|
|
60607
|
+
return ["mainnet"];
|
|
60608
|
+
return ["testnet", "regtest"];
|
|
60609
|
+
}
|
|
60610
|
+
function safeValidateBitcoinAddress(address, network) {
|
|
60490
60611
|
if (!address || typeof address !== "string") {
|
|
60491
60612
|
throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
|
|
60492
60613
|
}
|
|
60493
|
-
|
|
60494
|
-
|
|
60495
|
-
|
|
60496
|
-
|
|
60614
|
+
if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
|
|
60615
|
+
throw new Error(
|
|
60616
|
+
`Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
|
|
60617
|
+
);
|
|
60497
60618
|
}
|
|
60498
|
-
if (
|
|
60499
|
-
|
|
60500
|
-
|
|
60501
|
-
|
|
60502
|
-
}
|
|
60503
|
-
|
|
60504
|
-
|
|
60505
|
-
|
|
60619
|
+
if (!BitcoinUtils.validateAddress(address)) {
|
|
60620
|
+
throw new Error(
|
|
60621
|
+
`Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
|
|
60622
|
+
);
|
|
60623
|
+
}
|
|
60624
|
+
const belongsTo = networksOfValidAddress(address);
|
|
60625
|
+
if (!belongsTo.includes(network)) {
|
|
60626
|
+
throw new Error(
|
|
60627
|
+
`Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
|
|
60628
|
+
);
|
|
60506
60629
|
}
|
|
60507
60630
|
return address;
|
|
60508
60631
|
}
|
|
@@ -62611,6 +62734,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
|
|
|
62611
62734
|
LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
|
|
62612
62735
|
return LoanStatus2;
|
|
62613
62736
|
})(LoanStatus || {});
|
|
62737
|
+
var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
|
|
62738
|
+
var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
|
|
62739
|
+
var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
|
|
62740
|
+
async function collectBorrowerDebtRows(fetchPage) {
|
|
62741
|
+
const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
|
|
62742
|
+
const rows = [];
|
|
62743
|
+
for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
|
|
62744
|
+
const batch = await fetchPage(page * pageSize, pageSize);
|
|
62745
|
+
if (batch.length > pageSize) {
|
|
62746
|
+
throw new Error(
|
|
62747
|
+
`Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
|
|
62748
|
+
);
|
|
62749
|
+
}
|
|
62750
|
+
rows.push(...batch);
|
|
62751
|
+
if (batch.length < pageSize) {
|
|
62752
|
+
return rows;
|
|
62753
|
+
}
|
|
62754
|
+
}
|
|
62755
|
+
throw new Error(
|
|
62756
|
+
`Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
|
|
62757
|
+
);
|
|
62758
|
+
}
|
|
62759
|
+
function parseSubgraphLoanStatus(label) {
|
|
62760
|
+
if (typeof label !== "string") {
|
|
62761
|
+
throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
|
|
62762
|
+
}
|
|
62763
|
+
const value = LoanStatus[label];
|
|
62764
|
+
if (typeof value !== "number") {
|
|
62765
|
+
throw new Error(`Unknown subgraph loan status label: "${label}"`);
|
|
62766
|
+
}
|
|
62767
|
+
return value;
|
|
62768
|
+
}
|
|
62769
|
+
function parseSubgraphWei(row) {
|
|
62770
|
+
const raw = row.ucdDebt || "0";
|
|
62771
|
+
if (typeof raw !== "string") {
|
|
62772
|
+
throw new Error(
|
|
62773
|
+
`ucdDebt on position ${row.id} is not a string: ${String(raw)}`
|
|
62774
|
+
);
|
|
62775
|
+
}
|
|
62776
|
+
let wei;
|
|
62777
|
+
try {
|
|
62778
|
+
wei = BigInt(raw);
|
|
62779
|
+
} catch (error) {
|
|
62780
|
+
throw new Error(
|
|
62781
|
+
`ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
|
|
62782
|
+
{ cause: error }
|
|
62783
|
+
);
|
|
62784
|
+
}
|
|
62785
|
+
if (wei < 0n) {
|
|
62786
|
+
throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
|
|
62787
|
+
}
|
|
62788
|
+
return wei;
|
|
62789
|
+
}
|
|
62790
|
+
var WEI_PER_UCD = 10n ** 18n;
|
|
62791
|
+
function weiToHumanUcdString(wei) {
|
|
62792
|
+
if (wei < 0n) {
|
|
62793
|
+
throw new Error(`Cannot render negative wei: ${wei}`);
|
|
62794
|
+
}
|
|
62795
|
+
const whole = wei / WEI_PER_UCD;
|
|
62796
|
+
const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
|
|
62797
|
+
return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
|
|
62798
|
+
}
|
|
62799
|
+
var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
|
|
62800
|
+
function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
|
|
62801
|
+
let totalWei = 0n;
|
|
62802
|
+
const counts = /* @__PURE__ */ new Map();
|
|
62803
|
+
for (const row of rows) {
|
|
62804
|
+
totalWei += parseSubgraphWei(row);
|
|
62805
|
+
const status = parseSubgraphLoanStatus(row.status);
|
|
62806
|
+
counts.set(status, (counts.get(status) ?? 0) + 1);
|
|
62807
|
+
}
|
|
62808
|
+
const byStatus = [];
|
|
62809
|
+
for (const status of STATUS_ORDINALS) {
|
|
62810
|
+
const count = counts.get(status);
|
|
62811
|
+
if (count === void 0) {
|
|
62812
|
+
continue;
|
|
62813
|
+
}
|
|
62814
|
+
byStatus.push({ status, statusLabel: LoanStatus[status], count });
|
|
62815
|
+
}
|
|
62816
|
+
return {
|
|
62817
|
+
borrower: borrower.toLowerCase(),
|
|
62818
|
+
loanCount: rows.length,
|
|
62819
|
+
totalUcdDebt: totalWei.toString(),
|
|
62820
|
+
totalUcdDebtHuman: weiToHumanUcdString(totalWei),
|
|
62821
|
+
byStatus,
|
|
62822
|
+
source: "subgraph",
|
|
62823
|
+
fetchedAt
|
|
62824
|
+
};
|
|
62825
|
+
}
|
|
62614
62826
|
var POSITION_CORE_ABI = [
|
|
62615
62827
|
"function getPositionDetails(bytes32) view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status, uint40 previousExpiryAt, uint16 totalTerm))"
|
|
62616
62828
|
];
|
|
@@ -63003,6 +63215,43 @@ var LoanQuery = class {
|
|
|
63003
63215
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
63004
63216
|
return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
|
|
63005
63217
|
}
|
|
63218
|
+
/**
|
|
63219
|
+
* Combined UCD debt + by-status counts for a borrower from ONE pass over the
|
|
63220
|
+
* subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
|
|
63221
|
+
* status labels, `source: "subgraph"`.
|
|
63222
|
+
*
|
|
63223
|
+
* INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
|
|
63224
|
+
* sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
|
|
63225
|
+
* failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
|
|
63226
|
+
* is no partial total.
|
|
63227
|
+
*/
|
|
63228
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
63229
|
+
const trimmed = typeof borrower === "string" ? borrower.trim() : "";
|
|
63230
|
+
if (!(0, import_ethers26.isAddress)(trimmed)) {
|
|
63231
|
+
return failure(
|
|
63232
|
+
new SDKError({
|
|
63233
|
+
message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
|
|
63234
|
+
category: "VALIDATION",
|
|
63235
|
+
severity: "LOW",
|
|
63236
|
+
context: { borrower: trimmed }
|
|
63237
|
+
})
|
|
63238
|
+
);
|
|
63239
|
+
}
|
|
63240
|
+
return tryCatchAsync(
|
|
63241
|
+
async () => {
|
|
63242
|
+
const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
|
|
63243
|
+
return buildBorrowerUcdDebtSummary(trimmed, rows);
|
|
63244
|
+
},
|
|
63245
|
+
(error) => error instanceof SDKError ? error : new SDKError({
|
|
63246
|
+
message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
|
|
63247
|
+
category: "SUBGRAPH",
|
|
63248
|
+
severity: "MEDIUM",
|
|
63249
|
+
originalError: error instanceof Error ? error : void 0,
|
|
63250
|
+
cause: error,
|
|
63251
|
+
context: { borrower: trimmed }
|
|
63252
|
+
})
|
|
63253
|
+
);
|
|
63254
|
+
}
|
|
63006
63255
|
/**
|
|
63007
63256
|
* Get active loans (status = ACTIVE)
|
|
63008
63257
|
*
|
|
@@ -64528,7 +64777,35 @@ var GraphClient = class {
|
|
|
64528
64777
|
await new Promise((r) => setTimeout(r, ms));
|
|
64529
64778
|
}
|
|
64530
64779
|
};
|
|
64531
|
-
var
|
|
64780
|
+
var GET_USER_POSITIONS_DOCUMENT = `
|
|
64781
|
+
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
64782
|
+
user(id: $borrower) {
|
|
64783
|
+
id
|
|
64784
|
+
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
64785
|
+
id
|
|
64786
|
+
pkpId
|
|
64787
|
+
borrower {
|
|
64788
|
+
createdAt
|
|
64789
|
+
id
|
|
64790
|
+
}
|
|
64791
|
+
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
64792
|
+
ucdMinted
|
|
64793
|
+
ucdPaid
|
|
64794
|
+
ucdDebt
|
|
64795
|
+
collateralRatio
|
|
64796
|
+
requestedCollateralRatio
|
|
64797
|
+
selectedTerm
|
|
64798
|
+
status
|
|
64799
|
+
createdAt
|
|
64800
|
+
createdAtBlock
|
|
64801
|
+
lastUpdated
|
|
64802
|
+
originalTerm
|
|
64803
|
+
remainingDebt
|
|
64804
|
+
expiryAt
|
|
64805
|
+
}
|
|
64806
|
+
}
|
|
64807
|
+
}
|
|
64808
|
+
`;
|
|
64532
64809
|
function normalizePkpId2(pkpId) {
|
|
64533
64810
|
const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
|
|
64534
64811
|
if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
|
|
@@ -64846,35 +65123,7 @@ var DiamondHandsGraph = class {
|
|
|
64846
65123
|
* Get user positions from subgraph
|
|
64847
65124
|
*/
|
|
64848
65125
|
async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
|
|
64849
|
-
const query =
|
|
64850
|
-
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
64851
|
-
user(id: $borrower) {
|
|
64852
|
-
id
|
|
64853
|
-
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
64854
|
-
id
|
|
64855
|
-
pkpId
|
|
64856
|
-
borrower {
|
|
64857
|
-
createdAt
|
|
64858
|
-
id
|
|
64859
|
-
}
|
|
64860
|
-
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
64861
|
-
ucdMinted
|
|
64862
|
-
ucdPaid
|
|
64863
|
-
ucdDebt
|
|
64864
|
-
collateralRatio
|
|
64865
|
-
requestedCollateralRatio
|
|
64866
|
-
selectedTerm
|
|
64867
|
-
status
|
|
64868
|
-
createdAt
|
|
64869
|
-
createdAtBlock
|
|
64870
|
-
lastUpdated
|
|
64871
|
-
originalTerm
|
|
64872
|
-
remainingDebt
|
|
64873
|
-
expiryAt
|
|
64874
|
-
}
|
|
64875
|
-
}
|
|
64876
|
-
}
|
|
64877
|
-
`;
|
|
65126
|
+
const query = GET_USER_POSITIONS_DOCUMENT;
|
|
64878
65127
|
const variables = {
|
|
64879
65128
|
borrower: userAddress.toLowerCase(),
|
|
64880
65129
|
first: first || void 0,
|
|
@@ -64892,6 +65141,45 @@ var DiamondHandsGraph = class {
|
|
|
64892
65141
|
}
|
|
64893
65142
|
return positions;
|
|
64894
65143
|
}
|
|
65144
|
+
/**
|
|
65145
|
+
* Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
|
|
65146
|
+
* 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
|
|
65147
|
+
* coerces wei to a float and leaves `status` a string cast to the numeric enum).
|
|
65148
|
+
*
|
|
65149
|
+
* Deliberately issues the `GetUserPositions` document rather than a leaner one: the
|
|
65150
|
+
* lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
|
|
65151
|
+
* and that one is already listed, so this needs no server change. The extra fields
|
|
65152
|
+
* cost bytes, not round trips.
|
|
65153
|
+
*
|
|
65154
|
+
* Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
|
|
65155
|
+
*/
|
|
65156
|
+
async getBorrowerDebtRows(borrower) {
|
|
65157
|
+
const borrowerId = borrower.toLowerCase();
|
|
65158
|
+
return collectBorrowerDebtRows(async (skip, first) => {
|
|
65159
|
+
const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
|
|
65160
|
+
borrower: borrowerId,
|
|
65161
|
+
first,
|
|
65162
|
+
skip,
|
|
65163
|
+
orderBy: "id",
|
|
65164
|
+
orderDirection: "asc"
|
|
65165
|
+
});
|
|
65166
|
+
if (result?.user == null) {
|
|
65167
|
+
if (skip > 0) {
|
|
65168
|
+
throw new Error(
|
|
65169
|
+
`getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
|
|
65170
|
+
);
|
|
65171
|
+
}
|
|
65172
|
+
return [];
|
|
65173
|
+
}
|
|
65174
|
+
const positions = result.user.positions;
|
|
65175
|
+
if (!Array.isArray(positions)) {
|
|
65176
|
+
throw new Error(
|
|
65177
|
+
`getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
|
|
65178
|
+
);
|
|
65179
|
+
}
|
|
65180
|
+
return positions.filter((p) => p != null);
|
|
65181
|
+
});
|
|
65182
|
+
}
|
|
64895
65183
|
/**
|
|
64896
65184
|
* Get user positions, plus an accurate total count.
|
|
64897
65185
|
*
|
|
@@ -71060,6 +71348,603 @@ async function mintAgentPkp(params) {
|
|
|
71060
71348
|
clearTimeout(timeout);
|
|
71061
71349
|
}
|
|
71062
71350
|
}
|
|
71351
|
+
var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
|
|
71352
|
+
function planAgentBinding(params) {
|
|
71353
|
+
const { isActive, record, nowSeconds } = params;
|
|
71354
|
+
if (isActive)
|
|
71355
|
+
return { kind: "reuse", agent: record.agent };
|
|
71356
|
+
const status = Number(record.status);
|
|
71357
|
+
if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
|
|
71358
|
+
return { kind: "register" };
|
|
71359
|
+
}
|
|
71360
|
+
if (status !== AGENT_STATUS.Active) {
|
|
71361
|
+
throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
|
|
71362
|
+
}
|
|
71363
|
+
if (Number(record.validUntil) > nowSeconds) {
|
|
71364
|
+
throw new Error(
|
|
71365
|
+
"AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
|
|
71366
|
+
);
|
|
71367
|
+
}
|
|
71368
|
+
return { kind: "rotate" };
|
|
71369
|
+
}
|
|
71370
|
+
async function describeProviderChainMismatch(provider, chainId) {
|
|
71371
|
+
const actual = Number((await provider.getNetwork()).chainId);
|
|
71372
|
+
if (actual === chainId)
|
|
71373
|
+
return null;
|
|
71374
|
+
return `Network mismatch: the SDK was configured for chainId ${chainId}, but the provider is connected to chainId ${actual}. Switch the wallet/RPC to chainId ${chainId}, or configure the SDK for chainId ${actual}. Nothing was signed.`;
|
|
71375
|
+
}
|
|
71376
|
+
var TxValidationError2 = class extends Error {
|
|
71377
|
+
/**
|
|
71378
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
71379
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
71380
|
+
*/
|
|
71381
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
71382
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
71383
|
+
this.name = "TxValidationError";
|
|
71384
|
+
}
|
|
71385
|
+
};
|
|
71386
|
+
var SIGNABLE_FUNCTIONS2 = [
|
|
71387
|
+
"function mintUCD(bytes32 positionId, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractHash, uint256 quantumTimestamp, bytes calldata mintValidatorSignature) external returns (bool)",
|
|
71388
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
71389
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
71390
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
71391
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
71392
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
71393
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
71394
|
+
// protocol cannot execute.
|
|
71395
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
71396
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
71397
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
71398
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
71399
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
71400
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
71401
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
71402
|
+
"function withdrawBTC((bytes32 positionId, bytes32 actionHash, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractBundleHash, string withdrawalAddress, uint256 totalDeduction, uint256 newCollateral, uint256 quantumTimestamp, uint256 btcPrice, string utxoTxid, uint32 utxoVout) params, bytes withdrawalValidatorSignature, bytes btcSpendAuthSignature) external returns (bool)",
|
|
71403
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
71404
|
+
// function reverts permanently. The trustless replacement
|
|
71405
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
71406
|
+
// entry when its LIT Action ships.
|
|
71407
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
71408
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
71409
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
71410
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
71411
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
71412
|
+
// collateral had no client-side pin at all.
|
|
71413
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
71414
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
71415
|
+
// AgentModule; the parity test documents them as client-only.
|
|
71416
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
71417
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
71418
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
71419
|
+
// this too is client-only and never module-whitelisted.
|
|
71420
|
+
"function addAddress(string btcAddress) external"
|
|
71421
|
+
];
|
|
71422
|
+
var IFACE2 = new import_ethers32.ethers.Interface(SIGNABLE_FUNCTIONS2);
|
|
71423
|
+
function encodeSignable2(fn, args) {
|
|
71424
|
+
return IFACE2.encodeFunctionData(fn, args);
|
|
71425
|
+
}
|
|
71426
|
+
function decodeSignable2(data) {
|
|
71427
|
+
try {
|
|
71428
|
+
const parsed = IFACE2.parseTransaction({ data });
|
|
71429
|
+
if (!parsed) {
|
|
71430
|
+
throw new TxValidationError2(
|
|
71431
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
71432
|
+
);
|
|
71433
|
+
}
|
|
71434
|
+
return { name: parsed.name, args: parsed.args };
|
|
71435
|
+
} catch (e) {
|
|
71436
|
+
if (e instanceof TxValidationError2)
|
|
71437
|
+
throw e;
|
|
71438
|
+
throw new TxValidationError2(
|
|
71439
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
71440
|
+
);
|
|
71441
|
+
}
|
|
71442
|
+
}
|
|
71443
|
+
var MAX_GAS_LIMIT = 5000000n;
|
|
71444
|
+
var MAX_FEE_PER_GAS_WEI = 2000000000000n;
|
|
71445
|
+
var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
|
|
71446
|
+
var DEFAULT_FEE_CEILING = {
|
|
71447
|
+
maxGasLimit: MAX_GAS_LIMIT,
|
|
71448
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
|
|
71449
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
|
|
71450
|
+
};
|
|
71451
|
+
function fmtEth(wei) {
|
|
71452
|
+
return `${import_ethers34.ethers.formatEther(wei)} ETH`;
|
|
71453
|
+
}
|
|
71454
|
+
function fmtGwei(wei) {
|
|
71455
|
+
return `${import_ethers34.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
71456
|
+
}
|
|
71457
|
+
function worstCaseFeeWei(gasLimit, maxFeePerGas) {
|
|
71458
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
71459
|
+
return null;
|
|
71460
|
+
return gasLimit * maxFeePerGas;
|
|
71461
|
+
}
|
|
71462
|
+
function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
|
|
71463
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
71464
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
71465
|
+
}
|
|
71466
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
71467
|
+
raise(
|
|
71468
|
+
`maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
|
|
71469
|
+
);
|
|
71470
|
+
}
|
|
71471
|
+
const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
|
|
71472
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
71473
|
+
raise(
|
|
71474
|
+
`worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
71475
|
+
);
|
|
71476
|
+
}
|
|
71477
|
+
}
|
|
71478
|
+
function eqAddr2(a, b) {
|
|
71479
|
+
if (!a || !b)
|
|
71480
|
+
return false;
|
|
71481
|
+
try {
|
|
71482
|
+
return import_ethers33.ethers.getAddress(a) === import_ethers33.ethers.getAddress(b);
|
|
71483
|
+
} catch {
|
|
71484
|
+
return false;
|
|
71485
|
+
}
|
|
71486
|
+
}
|
|
71487
|
+
function readToAddress2(tx2) {
|
|
71488
|
+
const to = tx2["to"];
|
|
71489
|
+
if (typeof to !== "string") {
|
|
71490
|
+
throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
|
|
71491
|
+
}
|
|
71492
|
+
return to;
|
|
71493
|
+
}
|
|
71494
|
+
function readData2(tx2) {
|
|
71495
|
+
const data = tx2["data"];
|
|
71496
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
71497
|
+
throw new TxValidationError2(`unsignedTx.data missing or malformed`);
|
|
71498
|
+
}
|
|
71499
|
+
return data;
|
|
71500
|
+
}
|
|
71501
|
+
function readChainId2(tx2) {
|
|
71502
|
+
const c = tx2["chainId"];
|
|
71503
|
+
if (c == null)
|
|
71504
|
+
return null;
|
|
71505
|
+
if (typeof c === "number")
|
|
71506
|
+
return c;
|
|
71507
|
+
if (typeof c === "string")
|
|
71508
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
71509
|
+
if (typeof c === "bigint")
|
|
71510
|
+
return Number(c);
|
|
71511
|
+
return null;
|
|
71512
|
+
}
|
|
71513
|
+
function readOptionalBigInt(tx2, key) {
|
|
71514
|
+
const v = tx2[key];
|
|
71515
|
+
if (v == null)
|
|
71516
|
+
return null;
|
|
71517
|
+
try {
|
|
71518
|
+
if (typeof v === "bigint")
|
|
71519
|
+
return v;
|
|
71520
|
+
if (typeof v === "number")
|
|
71521
|
+
return BigInt(v);
|
|
71522
|
+
if (typeof v === "string")
|
|
71523
|
+
return BigInt(v);
|
|
71524
|
+
return BigInt(v.toString());
|
|
71525
|
+
} catch {
|
|
71526
|
+
throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
|
|
71527
|
+
}
|
|
71528
|
+
}
|
|
71529
|
+
function readValue2(tx2) {
|
|
71530
|
+
const v = tx2["value"];
|
|
71531
|
+
if (v == null)
|
|
71532
|
+
return 0n;
|
|
71533
|
+
if (typeof v === "string")
|
|
71534
|
+
return BigInt(v);
|
|
71535
|
+
if (typeof v === "number")
|
|
71536
|
+
return BigInt(v);
|
|
71537
|
+
if (typeof v === "bigint")
|
|
71538
|
+
return v;
|
|
71539
|
+
const maybe = v;
|
|
71540
|
+
if (typeof maybe.toBigInt === "function")
|
|
71541
|
+
return maybe.toBigInt();
|
|
71542
|
+
if (typeof maybe.toString === "function")
|
|
71543
|
+
return BigInt(maybe.toString());
|
|
71544
|
+
throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
|
|
71545
|
+
}
|
|
71546
|
+
function normalizePositionId2(id) {
|
|
71547
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
71548
|
+
return import_ethers33.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
71549
|
+
}
|
|
71550
|
+
function requirePositionId(actual, expected) {
|
|
71551
|
+
const txPositionId = String(actual).toLowerCase();
|
|
71552
|
+
if (txPositionId !== normalizePositionId2(expected)) {
|
|
71553
|
+
throw new TxValidationError2(
|
|
71554
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
|
|
71555
|
+
);
|
|
71556
|
+
}
|
|
71557
|
+
}
|
|
71558
|
+
function validateUnsignedTx2(unsignedTx, expected, vctx) {
|
|
71559
|
+
const txChainId = readChainId2(unsignedTx);
|
|
71560
|
+
if (txChainId == null) {
|
|
71561
|
+
throw new TxValidationError2(
|
|
71562
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
71563
|
+
);
|
|
71564
|
+
}
|
|
71565
|
+
if (txChainId !== vctx.chainId) {
|
|
71566
|
+
throw new TxValidationError2(
|
|
71567
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
71568
|
+
);
|
|
71569
|
+
}
|
|
71570
|
+
const value = readValue2(unsignedTx);
|
|
71571
|
+
if (value !== 0n) {
|
|
71572
|
+
throw new TxValidationError2(
|
|
71573
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
71574
|
+
);
|
|
71575
|
+
}
|
|
71576
|
+
assertFeeCeiling(
|
|
71577
|
+
readOptionalBigInt(unsignedTx, "gasLimit"),
|
|
71578
|
+
readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
|
|
71579
|
+
(msg) => {
|
|
71580
|
+
throw new TxValidationError2(msg);
|
|
71581
|
+
},
|
|
71582
|
+
vctx.feeCeiling
|
|
71583
|
+
);
|
|
71584
|
+
const to = readToAddress2(unsignedTx);
|
|
71585
|
+
const data = readData2(unsignedTx);
|
|
71586
|
+
const { name, args } = decodeSignable2(data);
|
|
71587
|
+
const pm = vctx.contracts.PositionManager;
|
|
71588
|
+
switch (expected.kind) {
|
|
71589
|
+
case "mint": {
|
|
71590
|
+
if (name !== "mintUCD") {
|
|
71591
|
+
throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
|
|
71592
|
+
}
|
|
71593
|
+
if (!eqAddr2(to, pm)) {
|
|
71594
|
+
throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
71595
|
+
}
|
|
71596
|
+
requirePositionId(args[0], expected.positionId);
|
|
71597
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
71598
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
71599
|
+
throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
71600
|
+
}
|
|
71601
|
+
const txMintFee = BigInt(String(args[2]));
|
|
71602
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
71603
|
+
throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
71604
|
+
}
|
|
71605
|
+
break;
|
|
71606
|
+
}
|
|
71607
|
+
case "repay": {
|
|
71608
|
+
if (name !== "makePayment") {
|
|
71609
|
+
throw new TxValidationError2(`expected makePayment, server returned ${name}`);
|
|
71610
|
+
}
|
|
71611
|
+
if (!eqAddr2(to, pm)) {
|
|
71612
|
+
throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
71613
|
+
}
|
|
71614
|
+
requirePositionId(args[0], expected.positionId);
|
|
71615
|
+
const txAmount = BigInt(String(args[1]));
|
|
71616
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
71617
|
+
throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
71618
|
+
}
|
|
71619
|
+
break;
|
|
71620
|
+
}
|
|
71621
|
+
case "extend": {
|
|
71622
|
+
if (name !== "extendPosition") {
|
|
71623
|
+
throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
|
|
71624
|
+
}
|
|
71625
|
+
if (!eqAddr2(to, pm)) {
|
|
71626
|
+
throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
71627
|
+
}
|
|
71628
|
+
requirePositionId(args[0], expected.positionId);
|
|
71629
|
+
const txTerm = Number(args[1]);
|
|
71630
|
+
if (txTerm !== expected.selectedTerm) {
|
|
71631
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
71632
|
+
}
|
|
71633
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
71634
|
+
const txFee = BigInt(String(args[5]));
|
|
71635
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
71636
|
+
if (txFee > upper) {
|
|
71637
|
+
throw new TxValidationError2(
|
|
71638
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
71639
|
+
);
|
|
71640
|
+
}
|
|
71641
|
+
}
|
|
71642
|
+
break;
|
|
71643
|
+
}
|
|
71644
|
+
case "withdraw-btc": {
|
|
71645
|
+
if (name !== "withdrawBTC") {
|
|
71646
|
+
throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
|
|
71647
|
+
}
|
|
71648
|
+
if (!eqAddr2(to, pm)) {
|
|
71649
|
+
throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
71650
|
+
}
|
|
71651
|
+
const paramsTuple = args[0];
|
|
71652
|
+
requirePositionId(paramsTuple[0], expected.positionId);
|
|
71653
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
71654
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
71655
|
+
throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
71656
|
+
}
|
|
71657
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
71658
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
71659
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
71660
|
+
if (txDeduction > upper) {
|
|
71661
|
+
throw new TxValidationError2(
|
|
71662
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
71663
|
+
);
|
|
71664
|
+
}
|
|
71665
|
+
}
|
|
71666
|
+
break;
|
|
71667
|
+
}
|
|
71668
|
+
case "ucd-approve": {
|
|
71669
|
+
if (name !== "approve") {
|
|
71670
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
71671
|
+
}
|
|
71672
|
+
const ucd = vctx.contracts.UCDToken;
|
|
71673
|
+
if (!eqAddr2(to, ucd)) {
|
|
71674
|
+
throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
71675
|
+
}
|
|
71676
|
+
const spender = String(args[0]);
|
|
71677
|
+
const ok2 = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
|
|
71678
|
+
if (!ok2) {
|
|
71679
|
+
throw new TxValidationError2(
|
|
71680
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
71681
|
+
);
|
|
71682
|
+
}
|
|
71683
|
+
const amt = BigInt(String(args[1]));
|
|
71684
|
+
const min = BigInt(expected.minAmountWei);
|
|
71685
|
+
if (amt < min) {
|
|
71686
|
+
throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
|
|
71687
|
+
}
|
|
71688
|
+
const SANITY_MAX = min * 1000n;
|
|
71689
|
+
if (amt > SANITY_MAX) {
|
|
71690
|
+
throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
71691
|
+
}
|
|
71692
|
+
break;
|
|
71693
|
+
}
|
|
71694
|
+
case "create-position": {
|
|
71695
|
+
if (name !== "createPosition") {
|
|
71696
|
+
throw new TxValidationError2(`expected createPosition, server returned ${name}`);
|
|
71697
|
+
}
|
|
71698
|
+
if (!eqAddr2(to, pm)) {
|
|
71699
|
+
throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
71700
|
+
}
|
|
71701
|
+
const txTerm = BigInt(String(args[4]));
|
|
71702
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
71703
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
71704
|
+
}
|
|
71705
|
+
break;
|
|
71706
|
+
}
|
|
71707
|
+
case "set-position-delegate": {
|
|
71708
|
+
if (name !== "setPositionDelegate") {
|
|
71709
|
+
throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
|
|
71710
|
+
}
|
|
71711
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
71712
|
+
throw new TxValidationError2(
|
|
71713
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
71714
|
+
);
|
|
71715
|
+
}
|
|
71716
|
+
requirePositionId(args[0], expected.positionId);
|
|
71717
|
+
const txDelegate = String(args[1]);
|
|
71718
|
+
if (!eqAddr2(txDelegate, expected.delegate)) {
|
|
71719
|
+
throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
71720
|
+
}
|
|
71721
|
+
break;
|
|
71722
|
+
}
|
|
71723
|
+
case "bwar-add-address": {
|
|
71724
|
+
if (name !== "addAddress") {
|
|
71725
|
+
throw new TxValidationError2(`expected addAddress, decoded ${name}`);
|
|
71726
|
+
}
|
|
71727
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
71728
|
+
throw new TxValidationError2(
|
|
71729
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
71730
|
+
);
|
|
71731
|
+
}
|
|
71732
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
71733
|
+
throw new TxValidationError2(
|
|
71734
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
71735
|
+
);
|
|
71736
|
+
}
|
|
71737
|
+
break;
|
|
71738
|
+
}
|
|
71739
|
+
case "stablecoin-approve": {
|
|
71740
|
+
if (name !== "approve") {
|
|
71741
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
71742
|
+
}
|
|
71743
|
+
if (!eqAddr2(to, expected.tokenAddress)) {
|
|
71744
|
+
throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
71745
|
+
}
|
|
71746
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
71747
|
+
throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
71748
|
+
}
|
|
71749
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
71750
|
+
throw new TxValidationError2(
|
|
71751
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
71752
|
+
);
|
|
71753
|
+
}
|
|
71754
|
+
break;
|
|
71755
|
+
}
|
|
71756
|
+
case "ucd-approve-controller": {
|
|
71757
|
+
if (name !== "approve") {
|
|
71758
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
71759
|
+
}
|
|
71760
|
+
if (!eqAddr2(to, expected.ucdTokenAddress)) {
|
|
71761
|
+
throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
71762
|
+
}
|
|
71763
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
71764
|
+
throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
71765
|
+
}
|
|
71766
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
71767
|
+
throw new TxValidationError2(
|
|
71768
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
71769
|
+
);
|
|
71770
|
+
}
|
|
71771
|
+
break;
|
|
71772
|
+
}
|
|
71773
|
+
case "psm-swap": {
|
|
71774
|
+
if (name !== "swap")
|
|
71775
|
+
throw new TxValidationError2(`expected swap, server returned ${name}`);
|
|
71776
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
71777
|
+
throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
71778
|
+
}
|
|
71779
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
71780
|
+
throw new TxValidationError2(`swap stablecoin mismatch`);
|
|
71781
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
71782
|
+
throw new TxValidationError2(`swap amountIn mismatch`);
|
|
71783
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
71784
|
+
throw new TxValidationError2(`swap minUcdOut mismatch`);
|
|
71785
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
71786
|
+
throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
71787
|
+
}
|
|
71788
|
+
break;
|
|
71789
|
+
}
|
|
71790
|
+
case "psm-redeem": {
|
|
71791
|
+
if (name !== "redeem")
|
|
71792
|
+
throw new TxValidationError2(`expected redeem, server returned ${name}`);
|
|
71793
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
71794
|
+
throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
71795
|
+
}
|
|
71796
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
71797
|
+
throw new TxValidationError2(`redeem stablecoin mismatch`);
|
|
71798
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
71799
|
+
throw new TxValidationError2(`redeem ucdAmount mismatch`);
|
|
71800
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
71801
|
+
throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
|
|
71802
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
71803
|
+
throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
71804
|
+
}
|
|
71805
|
+
break;
|
|
71806
|
+
}
|
|
71807
|
+
default: {
|
|
71808
|
+
const _exhaustive = expected;
|
|
71809
|
+
throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
71810
|
+
}
|
|
71811
|
+
}
|
|
71812
|
+
}
|
|
71813
|
+
function buildPsmApproveTx(p) {
|
|
71814
|
+
return {
|
|
71815
|
+
to: p.token,
|
|
71816
|
+
data: encodeSignable2("approve", [p.spender, p.amount]),
|
|
71817
|
+
value: "0x0",
|
|
71818
|
+
chainId: p.chainId
|
|
71819
|
+
};
|
|
71820
|
+
}
|
|
71821
|
+
function buildPsmSwapTx2(p) {
|
|
71822
|
+
return {
|
|
71823
|
+
to: p.psm,
|
|
71824
|
+
data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
71825
|
+
value: "0x0",
|
|
71826
|
+
chainId: p.chainId
|
|
71827
|
+
};
|
|
71828
|
+
}
|
|
71829
|
+
function buildPsmRedeemTx2(p) {
|
|
71830
|
+
return {
|
|
71831
|
+
to: p.psm,
|
|
71832
|
+
data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
71833
|
+
value: "0x0",
|
|
71834
|
+
chainId: p.chainId
|
|
71835
|
+
};
|
|
71836
|
+
}
|
|
71837
|
+
var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
|
|
71838
|
+
var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
71839
|
+
function psmExchangeReadsFromProvider(provider, psmAddress) {
|
|
71840
|
+
const psm = new import_ethers31.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
|
|
71841
|
+
return {
|
|
71842
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
71843
|
+
allowance: async (token, owner, spender) => await new import_ethers31.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
|
|
71844
|
+
};
|
|
71845
|
+
}
|
|
71846
|
+
var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
|
|
71847
|
+
function requireAddress(direction, label, value) {
|
|
71848
|
+
if (!value || !import_ethers31.ethers.isAddress(value)) {
|
|
71849
|
+
throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
71850
|
+
}
|
|
71851
|
+
return import_ethers31.ethers.getAddress(value);
|
|
71852
|
+
}
|
|
71853
|
+
async function planPsmExchange(params) {
|
|
71854
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
71855
|
+
const chainId = vctx.chainId;
|
|
71856
|
+
if (amountIn <= 0n) {
|
|
71857
|
+
throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
71858
|
+
}
|
|
71859
|
+
if (minOut <= 0n) {
|
|
71860
|
+
throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
71861
|
+
}
|
|
71862
|
+
const owner = requireAddress(direction, "owner", params.owner);
|
|
71863
|
+
const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
|
|
71864
|
+
const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
|
|
71865
|
+
const isSwap = direction === "swap";
|
|
71866
|
+
const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
|
|
71867
|
+
const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
|
|
71868
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
71869
|
+
throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
71870
|
+
}
|
|
71871
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
71872
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
71873
|
+
const approvals = [];
|
|
71874
|
+
if (allowanceBefore < amountIn) {
|
|
71875
|
+
if (allowanceBefore > 0n) {
|
|
71876
|
+
approvals.push({
|
|
71877
|
+
step: "reset-approve",
|
|
71878
|
+
tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
|
|
71879
|
+
expected: approveExpected(0n)
|
|
71880
|
+
});
|
|
71881
|
+
}
|
|
71882
|
+
approvals.push({
|
|
71883
|
+
step: "approve",
|
|
71884
|
+
tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
|
|
71885
|
+
expected: approveExpected(amountIn)
|
|
71886
|
+
});
|
|
71887
|
+
}
|
|
71888
|
+
const exec = isSwap ? {
|
|
71889
|
+
step: "swap",
|
|
71890
|
+
tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
71891
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
71892
|
+
} : {
|
|
71893
|
+
step: "redeem",
|
|
71894
|
+
tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
71895
|
+
expected: {
|
|
71896
|
+
kind: "psm-redeem",
|
|
71897
|
+
psmAddress: psm,
|
|
71898
|
+
stablecoin,
|
|
71899
|
+
amountUcdWei: amountIn.toString(),
|
|
71900
|
+
minOut: minOut.toString()
|
|
71901
|
+
}
|
|
71902
|
+
};
|
|
71903
|
+
for (const leg of [...approvals, exec]) {
|
|
71904
|
+
validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
|
|
71905
|
+
}
|
|
71906
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
71907
|
+
}
|
|
71908
|
+
async function executePsmPlan(plan, signer, vctx) {
|
|
71909
|
+
const approvalHashes = [];
|
|
71910
|
+
const residual = () => approvalHashes.length === 0 ? "" : ` An approval already landed (tx ${approvalHashes[approvalHashes.length - 1]}): an allowance of exactly ${plan.amountIn} to ${plan.spender} stands. It authorizes only that amount; the next exchange uses or replaces it.`;
|
|
71911
|
+
const sendLeg = async (leg) => {
|
|
71912
|
+
const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
|
|
71913
|
+
validateUnsignedTx2({ ...request }, leg.expected, vctx);
|
|
71914
|
+
const sent = await signer.sendTransaction(request);
|
|
71915
|
+
const receipt = await sent.wait();
|
|
71916
|
+
if (!receipt)
|
|
71917
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
|
|
71918
|
+
if (receipt.status !== 1)
|
|
71919
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
|
|
71920
|
+
return { hash: sent.hash, blockNumber: receipt.blockNumber };
|
|
71921
|
+
};
|
|
71922
|
+
for (const leg of plan.approvals) {
|
|
71923
|
+
const landed = await sendLeg(leg).catch((e) => {
|
|
71924
|
+
throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
71925
|
+
});
|
|
71926
|
+
approvalHashes.push(landed.hash);
|
|
71927
|
+
}
|
|
71928
|
+
const exec = await sendLeg(plan.exec).catch((e) => {
|
|
71929
|
+
throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
71930
|
+
});
|
|
71931
|
+
return { ...exec, approvalHashes };
|
|
71932
|
+
}
|
|
71933
|
+
var LIT_ACTION_CHAIN_NAMES = Object.freeze({
|
|
71934
|
+
1: "ethereum",
|
|
71935
|
+
11155111: "sepolia",
|
|
71936
|
+
1337: "hardhat",
|
|
71937
|
+
31337: "hardhat"
|
|
71938
|
+
});
|
|
71939
|
+
function litActionChainNameForChainId(chainId) {
|
|
71940
|
+
const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
|
|
71941
|
+
if (!name) {
|
|
71942
|
+
throw new Error(
|
|
71943
|
+
`Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
|
|
71944
|
+
);
|
|
71945
|
+
}
|
|
71946
|
+
return name;
|
|
71947
|
+
}
|
|
71063
71948
|
var MockTokenManager = class {
|
|
71064
71949
|
config;
|
|
71065
71950
|
constructor(config) {
|
|
@@ -72033,6 +72918,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
72033
72918
|
*/
|
|
72034
72919
|
static async create(config) {
|
|
72035
72920
|
const userProvidedServiceEndpoint = config.serviceEndpoint;
|
|
72921
|
+
if (typeof config.chainId === "number" && config.provider) {
|
|
72922
|
+
const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
|
|
72923
|
+
if (mismatch) {
|
|
72924
|
+
return failure(
|
|
72925
|
+
new SDKError({
|
|
72926
|
+
message: mismatch,
|
|
72927
|
+
category: "CONFIGURATION",
|
|
72928
|
+
severity: "HIGH"
|
|
72929
|
+
/* HIGH */
|
|
72930
|
+
})
|
|
72931
|
+
);
|
|
72932
|
+
}
|
|
72933
|
+
}
|
|
72036
72934
|
const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
|
|
72037
72935
|
if (userProvidedServiceEndpoint) {
|
|
72038
72936
|
enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
|
|
@@ -72683,6 +73581,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
72683
73581
|
if (this.config.debug) {
|
|
72684
73582
|
log.info(` Position PKP ID: ${position2.pkpId}`);
|
|
72685
73583
|
}
|
|
73584
|
+
const termsResult = await this.getTermsWithFees();
|
|
73585
|
+
if (!termsResult.success) {
|
|
73586
|
+
return {
|
|
73587
|
+
success: false,
|
|
73588
|
+
error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
|
|
73589
|
+
};
|
|
73590
|
+
}
|
|
73591
|
+
const positionTermMonths = Number(position2.selectedTerm);
|
|
73592
|
+
const positionTerm = termsResult.value.terms.find(
|
|
73593
|
+
(term) => term.termMonths === positionTermMonths
|
|
73594
|
+
);
|
|
73595
|
+
if (!positionTerm) {
|
|
73596
|
+
return {
|
|
73597
|
+
success: false,
|
|
73598
|
+
error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
|
|
73599
|
+
};
|
|
73600
|
+
}
|
|
73601
|
+
const currentDebtWei = BigInt(position2.ucdDebt);
|
|
73602
|
+
const baseFeeWei = baseMintFeeWei(
|
|
73603
|
+
requestAmountWei,
|
|
73604
|
+
positionTerm.originationFeeBps
|
|
73605
|
+
);
|
|
73606
|
+
if (debtAfterMintExceedsLoanCap({
|
|
73607
|
+
currentDebtWei,
|
|
73608
|
+
mintAmountWei: requestAmountWei,
|
|
73609
|
+
mintFeeWei: baseFeeWei,
|
|
73610
|
+
maxLoanWei: maxLoanValueWei
|
|
73611
|
+
})) {
|
|
73612
|
+
const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
|
|
73613
|
+
const maxPrincipalUcd = Number(
|
|
73614
|
+
maxPrincipalWithinLoanCap({
|
|
73615
|
+
maxLoanWei: maxLoanValueWei,
|
|
73616
|
+
currentDebtWei,
|
|
73617
|
+
originationFeeBps: positionTerm.originationFeeBps
|
|
73618
|
+
}) / BigInt(10 ** 18)
|
|
73619
|
+
);
|
|
73620
|
+
return {
|
|
73621
|
+
success: false,
|
|
73622
|
+
error: `Amount ${request.amount} UCD plus the ${positionTerm.originationFeeBps / 100}% origination fee (${(0, import_ethers14.formatEther)(baseFeeWei)} UCD) would take this loan's debt to ${(0, import_ethers14.formatEther)(debtAfterWei)} UCD, above the protocol maximum of ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD. The largest amount you can mint now is ${maxPrincipalUcd} UCD.`
|
|
73623
|
+
};
|
|
73624
|
+
}
|
|
73625
|
+
if (this.config.debug) {
|
|
73626
|
+
log.info(
|
|
73627
|
+
`\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers14.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD`,
|
|
73628
|
+
{}
|
|
73629
|
+
);
|
|
73630
|
+
}
|
|
72686
73631
|
let pkpPublicKey;
|
|
72687
73632
|
let pkpEthAddress;
|
|
72688
73633
|
const pkpCache = this.cacheManager.getCache("pkp-data", {
|
|
@@ -72772,7 +73717,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
72772
73717
|
` UCDController: ${contracts?.UCDController || "MISSING"}`
|
|
72773
73718
|
);
|
|
72774
73719
|
}
|
|
72775
|
-
const chain = this.config.chain || (
|
|
73720
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
72776
73721
|
const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
|
|
72777
73722
|
if (this.config.debug) {
|
|
72778
73723
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -73372,6 +74317,25 @@ Error data: none`
|
|
|
73372
74317
|
}
|
|
73373
74318
|
const selector = simError.selector;
|
|
73374
74319
|
const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
|
|
74320
|
+
const MINT_GUARD_CODES = {
|
|
74321
|
+
"1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
|
|
74322
|
+
"2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
|
|
74323
|
+
"3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
|
|
74324
|
+
};
|
|
74325
|
+
let loanCapDiagnostics = "";
|
|
74326
|
+
if (selector === "0xe6dd4d41") {
|
|
74327
|
+
const guardCode = BigInt(
|
|
74328
|
+
"0x" + String(simError.data).slice(10).padStart(64, "0")
|
|
74329
|
+
).toString();
|
|
74330
|
+
const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
|
|
74331
|
+
loanCapDiagnostics = `
|
|
74332
|
+
|
|
74333
|
+
MintGuardFailed(${guardCode}): ${guardMeaning}
|
|
74334
|
+
Lit mintAmount: ${validationResponse.mintAmount}
|
|
74335
|
+
Lit mintFee: ${validationResponse.mintFee}
|
|
74336
|
+
Lit newDebt: ${validationResponse.newDebt}
|
|
74337
|
+
Protocol maximum: ${(0, import_ethers14.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
|
|
74338
|
+
}
|
|
73375
74339
|
const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
|
|
73376
74340
|
selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
|
|
73377
74341
|
selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
|
|
@@ -73417,7 +74381,7 @@ Quantum Timing Analysis:
|
|
|
73417
74381
|
Error selector: ${selector}
|
|
73418
74382
|
Error data: ${simError.data}
|
|
73419
74383
|
Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
|
|
73420
|
-
Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
74384
|
+
Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
|
|
73421
74385
|
);
|
|
73422
74386
|
}
|
|
73423
74387
|
const tx2 = await sendEip1559Transaction({
|
|
@@ -76025,7 +76989,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76025
76989
|
` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
|
|
76026
76990
|
);
|
|
76027
76991
|
}
|
|
76028
|
-
const chain = this.config.chain || (
|
|
76992
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
76029
76993
|
const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
|
|
76030
76994
|
if (this.config.debug) {
|
|
76031
76995
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -76580,13 +77544,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76580
77544
|
return { success: false, error: "Failed to resolve PKP public key" };
|
|
76581
77545
|
}
|
|
76582
77546
|
const chipotlePkpAddress = (0, import_ethers14.computeAddress)(publicKey);
|
|
76583
|
-
const
|
|
76584
|
-
1: "ethereum",
|
|
76585
|
-
11155111: "sepolia",
|
|
76586
|
-
1337: "hardhat",
|
|
76587
|
-
31337: "hardhat"
|
|
76588
|
-
};
|
|
76589
|
-
const chainName = STANDALONE_CHAIN_NAMES[chainId];
|
|
77547
|
+
const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
|
|
76590
77548
|
if (!chainName) {
|
|
76591
77549
|
return {
|
|
76592
77550
|
success: false,
|
|
@@ -77808,6 +78766,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77808
78766
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
77809
78767
|
return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
|
|
77810
78768
|
}
|
|
78769
|
+
/**
|
|
78770
|
+
* Combined UCD debt (canonical wei string + display string) and by-status loan
|
|
78771
|
+
* counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
|
|
78772
|
+
* an INDEXED, informational figure that lags writes; never size a transaction
|
|
78773
|
+
* from it (repayments read the chain via `getPositionDetailsView`).
|
|
78774
|
+
*
|
|
78775
|
+
* Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
|
|
78776
|
+
* failure or past 10,000 positions; never returns a partial total.
|
|
78777
|
+
*/
|
|
78778
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
78779
|
+
return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
|
|
78780
|
+
}
|
|
77811
78781
|
/**
|
|
77812
78782
|
* Get all active loans
|
|
77813
78783
|
*
|
|
@@ -77933,11 +78903,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77933
78903
|
}
|
|
77934
78904
|
/**
|
|
77935
78905
|
* Execute a PSM stablecoin → UCD swap.
|
|
77936
|
-
*
|
|
78906
|
+
* Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
|
|
78907
|
+
* partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
|
|
77937
78908
|
*
|
|
77938
78909
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
|
|
77939
78910
|
* @param params.amountWei - Stablecoin amount in native decimals (bigint)
|
|
77940
|
-
* @param params.minUcdOutWei - Minimum UCD to receive;
|
|
78911
|
+
* @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
|
|
77941
78912
|
* @param params.signer - Connected signer for the approval and swap transactions
|
|
77942
78913
|
*/
|
|
77943
78914
|
async psmSwap(params) {
|
|
@@ -77947,32 +78918,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77947
78918
|
"SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
|
|
77948
78919
|
);
|
|
77949
78920
|
}
|
|
77950
|
-
|
|
77951
|
-
|
|
77952
|
-
|
|
77953
|
-
|
|
77954
|
-
|
|
77955
|
-
|
|
77956
|
-
|
|
77957
|
-
if (allowance < params.amountWei) {
|
|
77958
|
-
const approveTx = await stablecoin.approve(psmAddress, import_ethers14.MaxUint256);
|
|
77959
|
-
await approveTx.wait();
|
|
77960
|
-
}
|
|
77961
|
-
const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
|
|
77962
|
-
const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
|
|
77963
|
-
const receipt = await tx2.wait();
|
|
77964
|
-
if (!receipt)
|
|
77965
|
-
throw new Error("PSM swap transaction receipt unavailable");
|
|
77966
|
-
return { hash: tx2.hash, blockNumber: receipt.blockNumber };
|
|
78921
|
+
return this.runPsmExchange({
|
|
78922
|
+
direction: "swap",
|
|
78923
|
+
signer: params.signer,
|
|
78924
|
+
addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
|
|
78925
|
+
amountIn: params.amountWei,
|
|
78926
|
+
minOut: params.minUcdOutWei
|
|
78927
|
+
});
|
|
77967
78928
|
}
|
|
77968
78929
|
/**
|
|
77969
78930
|
* Execute a PSM UCD → stablecoin redeem.
|
|
77970
|
-
*
|
|
77971
|
-
* UCDToken.burn(from, amount) calls
|
|
78931
|
+
* Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
|
|
78932
|
+
* M-4 burn allowance guard: UCDToken.burn(from, amount) calls
|
|
78933
|
+
* _spendAllowance(from, msg.sender=ucdController, amount).
|
|
77972
78934
|
*
|
|
77973
78935
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
|
|
77974
78936
|
* @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
|
|
77975
|
-
* @param params.minStablecoinOutWei - Minimum stablecoin to receive
|
|
78937
|
+
* @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
|
|
77976
78938
|
* @param params.signer - Connected signer
|
|
77977
78939
|
*/
|
|
77978
78940
|
async psmRedeem(params) {
|
|
@@ -77985,23 +78947,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77985
78947
|
throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
|
|
77986
78948
|
if (!ucdControllerAddress)
|
|
77987
78949
|
throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
|
|
77988
|
-
|
|
77989
|
-
|
|
77990
|
-
|
|
77991
|
-
|
|
77992
|
-
|
|
77993
|
-
|
|
77994
|
-
|
|
77995
|
-
|
|
77996
|
-
|
|
77997
|
-
|
|
77998
|
-
|
|
77999
|
-
|
|
78000
|
-
|
|
78001
|
-
|
|
78002
|
-
|
|
78003
|
-
|
|
78004
|
-
|
|
78950
|
+
return this.runPsmExchange({
|
|
78951
|
+
direction: "redeem",
|
|
78952
|
+
signer: params.signer,
|
|
78953
|
+
addresses: {
|
|
78954
|
+
psm: psmAddress,
|
|
78955
|
+
stablecoin: params.stablecoinAddress,
|
|
78956
|
+
ucdToken: ucdAddress,
|
|
78957
|
+
ucdController: ucdControllerAddress
|
|
78958
|
+
},
|
|
78959
|
+
amountIn: params.ucdAmountWei,
|
|
78960
|
+
minOut: params.minStablecoinOutWei
|
|
78961
|
+
});
|
|
78962
|
+
}
|
|
78963
|
+
/**
|
|
78964
|
+
* Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
|
|
78965
|
+
* The signer's chain must match the SDK's configured chain — the addresses came from it.
|
|
78966
|
+
*/
|
|
78967
|
+
async runPsmExchange(params) {
|
|
78968
|
+
const provider = params.signer.provider;
|
|
78969
|
+
if (!provider) {
|
|
78970
|
+
throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
|
|
78971
|
+
}
|
|
78972
|
+
const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
|
|
78973
|
+
if (typeof configuredChainId !== "number") {
|
|
78974
|
+
throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
|
|
78975
|
+
}
|
|
78976
|
+
const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
|
|
78977
|
+
if (mismatch)
|
|
78978
|
+
throw new Error(mismatch);
|
|
78979
|
+
const vctx = {
|
|
78980
|
+
chainId: configuredChainId,
|
|
78981
|
+
network: String(configuredChainId),
|
|
78982
|
+
contracts: {}
|
|
78983
|
+
};
|
|
78984
|
+
const plan = await planPsmExchange({
|
|
78985
|
+
direction: params.direction,
|
|
78986
|
+
owner: await params.signer.getAddress(),
|
|
78987
|
+
addresses: params.addresses,
|
|
78988
|
+
amountIn: params.amountIn,
|
|
78989
|
+
minOut: params.minOut,
|
|
78990
|
+
vctx,
|
|
78991
|
+
reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
|
|
78992
|
+
});
|
|
78993
|
+
const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
|
|
78994
|
+
return { hash, blockNumber };
|
|
78005
78995
|
}
|
|
78006
78996
|
/**
|
|
78007
78997
|
* Wait for the subgraph to index up to (and including) the given block number.
|
|
@@ -78182,18 +79172,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
78182
79172
|
const user = await signer.getAddress();
|
|
78183
79173
|
const registry = AgentDelegationRegistry__factory.connect(addr, signer);
|
|
78184
79174
|
let agentAddress;
|
|
78185
|
-
const
|
|
78186
|
-
|
|
78187
|
-
|
|
79175
|
+
const [isActive, record, latestBlock] = await Promise.all([
|
|
79176
|
+
registry.isAgentActive(user),
|
|
79177
|
+
registry.agentOf(user),
|
|
79178
|
+
this.getProviderOrThrow().getBlock("latest")
|
|
79179
|
+
]);
|
|
79180
|
+
if (!latestBlock) {
|
|
79181
|
+
throw new SDKError({
|
|
79182
|
+
message: "Could not read the latest block to check the agent registration's expiry",
|
|
79183
|
+
category: "NETWORK",
|
|
79184
|
+
severity: "HIGH"
|
|
79185
|
+
/* HIGH */
|
|
79186
|
+
});
|
|
79187
|
+
}
|
|
79188
|
+
const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
|
|
79189
|
+
if (plan.kind === "reuse") {
|
|
79190
|
+
agentAddress = plan.agent;
|
|
78188
79191
|
} else {
|
|
78189
79192
|
agentAddress = await mintAgentPkp({
|
|
78190
79193
|
serviceEndpoint: this.config.serviceEndpoint,
|
|
78191
79194
|
authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
|
|
78192
79195
|
});
|
|
78193
79196
|
const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
|
|
78194
|
-
const validUntil =
|
|
78195
|
-
const
|
|
78196
|
-
await
|
|
79197
|
+
const validUntil = latestBlock.timestamp + validitySeconds;
|
|
79198
|
+
const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
|
|
79199
|
+
await bindTx.wait();
|
|
78197
79200
|
}
|
|
78198
79201
|
const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
|
|
78199
79202
|
() => null
|
|
@@ -79585,7 +80588,552 @@ var SUPPORTED_STABLECOINS = `
|
|
|
79585
80588
|
}`;
|
|
79586
80589
|
|
|
79587
80590
|
// src/boundary/upstream/real/psm-calls.ts
|
|
79588
|
-
var
|
|
80591
|
+
var import_ethers42 = require("ethers");
|
|
80592
|
+
|
|
80593
|
+
// node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
|
|
80594
|
+
var import_ethers36 = require("ethers");
|
|
80595
|
+
var import_ethers37 = require("ethers");
|
|
80596
|
+
var import_ethers38 = require("ethers");
|
|
80597
|
+
var import_ethers39 = require("ethers");
|
|
80598
|
+
var import_ethers40 = require("ethers");
|
|
80599
|
+
var import_ethers41 = require("ethers");
|
|
80600
|
+
var TxValidationError3 = class extends Error {
|
|
80601
|
+
/**
|
|
80602
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
80603
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
80604
|
+
*/
|
|
80605
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
80606
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
80607
|
+
this.name = "TxValidationError";
|
|
80608
|
+
}
|
|
80609
|
+
};
|
|
80610
|
+
var SIGNABLE_FUNCTIONS3 = [
|
|
80611
|
+
"function mintUCD(bytes32 positionId, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractHash, uint256 quantumTimestamp, bytes calldata mintValidatorSignature) external returns (bool)",
|
|
80612
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
80613
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
80614
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
80615
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
80616
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
80617
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
80618
|
+
// protocol cannot execute.
|
|
80619
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
80620
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
80621
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
80622
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
80623
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
80624
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
80625
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
80626
|
+
"function withdrawBTC((bytes32 positionId, bytes32 actionHash, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractBundleHash, string withdrawalAddress, uint256 totalDeduction, uint256 newCollateral, uint256 quantumTimestamp, uint256 btcPrice, string utxoTxid, uint32 utxoVout) params, bytes withdrawalValidatorSignature, bytes btcSpendAuthSignature) external returns (bool)",
|
|
80627
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
80628
|
+
// function reverts permanently. The trustless replacement
|
|
80629
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
80630
|
+
// entry when its LIT Action ships.
|
|
80631
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
80632
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
80633
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
80634
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
80635
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
80636
|
+
// collateral had no client-side pin at all.
|
|
80637
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
80638
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
80639
|
+
// AgentModule; the parity test documents them as client-only.
|
|
80640
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
80641
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
80642
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
80643
|
+
// this too is client-only and never module-whitelisted.
|
|
80644
|
+
"function addAddress(string btcAddress) external"
|
|
80645
|
+
];
|
|
80646
|
+
var IFACE3 = new import_ethers36.ethers.Interface(SIGNABLE_FUNCTIONS3);
|
|
80647
|
+
function encodeSignable3(fn, args) {
|
|
80648
|
+
return IFACE3.encodeFunctionData(fn, args);
|
|
80649
|
+
}
|
|
80650
|
+
function decodeSignable3(data) {
|
|
80651
|
+
try {
|
|
80652
|
+
const parsed = IFACE3.parseTransaction({ data });
|
|
80653
|
+
if (!parsed) {
|
|
80654
|
+
throw new TxValidationError3(
|
|
80655
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
80656
|
+
);
|
|
80657
|
+
}
|
|
80658
|
+
return { name: parsed.name, args: parsed.args };
|
|
80659
|
+
} catch (e) {
|
|
80660
|
+
if (e instanceof TxValidationError3)
|
|
80661
|
+
throw e;
|
|
80662
|
+
throw new TxValidationError3(
|
|
80663
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
80664
|
+
);
|
|
80665
|
+
}
|
|
80666
|
+
}
|
|
80667
|
+
var MAX_GAS_LIMIT2 = 5000000n;
|
|
80668
|
+
var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
|
|
80669
|
+
var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
|
|
80670
|
+
var DEFAULT_FEE_CEILING2 = {
|
|
80671
|
+
maxGasLimit: MAX_GAS_LIMIT2,
|
|
80672
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
|
|
80673
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
|
|
80674
|
+
};
|
|
80675
|
+
function fmtEth2(wei) {
|
|
80676
|
+
return `${import_ethers37.ethers.formatEther(wei)} ETH`;
|
|
80677
|
+
}
|
|
80678
|
+
function fmtGwei2(wei) {
|
|
80679
|
+
return `${import_ethers37.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
80680
|
+
}
|
|
80681
|
+
function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
|
|
80682
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
80683
|
+
return null;
|
|
80684
|
+
return gasLimit * maxFeePerGas;
|
|
80685
|
+
}
|
|
80686
|
+
function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
|
|
80687
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
80688
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
80689
|
+
}
|
|
80690
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
80691
|
+
raise(
|
|
80692
|
+
`maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
|
|
80693
|
+
);
|
|
80694
|
+
}
|
|
80695
|
+
const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
|
|
80696
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
80697
|
+
raise(
|
|
80698
|
+
`worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
80699
|
+
);
|
|
80700
|
+
}
|
|
80701
|
+
}
|
|
80702
|
+
function eqAddr3(a, b) {
|
|
80703
|
+
if (!a || !b)
|
|
80704
|
+
return false;
|
|
80705
|
+
try {
|
|
80706
|
+
return import_ethers38.ethers.getAddress(a) === import_ethers38.ethers.getAddress(b);
|
|
80707
|
+
} catch {
|
|
80708
|
+
return false;
|
|
80709
|
+
}
|
|
80710
|
+
}
|
|
80711
|
+
function readToAddress3(tx2) {
|
|
80712
|
+
const to = tx2["to"];
|
|
80713
|
+
if (typeof to !== "string") {
|
|
80714
|
+
throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
|
|
80715
|
+
}
|
|
80716
|
+
return to;
|
|
80717
|
+
}
|
|
80718
|
+
function readData3(tx2) {
|
|
80719
|
+
const data = tx2["data"];
|
|
80720
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
80721
|
+
throw new TxValidationError3(`unsignedTx.data missing or malformed`);
|
|
80722
|
+
}
|
|
80723
|
+
return data;
|
|
80724
|
+
}
|
|
80725
|
+
function readChainId3(tx2) {
|
|
80726
|
+
const c = tx2["chainId"];
|
|
80727
|
+
if (c == null)
|
|
80728
|
+
return null;
|
|
80729
|
+
if (typeof c === "number")
|
|
80730
|
+
return c;
|
|
80731
|
+
if (typeof c === "string")
|
|
80732
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
80733
|
+
if (typeof c === "bigint")
|
|
80734
|
+
return Number(c);
|
|
80735
|
+
return null;
|
|
80736
|
+
}
|
|
80737
|
+
function readOptionalBigInt2(tx2, key) {
|
|
80738
|
+
const v = tx2[key];
|
|
80739
|
+
if (v == null)
|
|
80740
|
+
return null;
|
|
80741
|
+
try {
|
|
80742
|
+
if (typeof v === "bigint")
|
|
80743
|
+
return v;
|
|
80744
|
+
if (typeof v === "number")
|
|
80745
|
+
return BigInt(v);
|
|
80746
|
+
if (typeof v === "string")
|
|
80747
|
+
return BigInt(v);
|
|
80748
|
+
return BigInt(v.toString());
|
|
80749
|
+
} catch {
|
|
80750
|
+
throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
|
|
80751
|
+
}
|
|
80752
|
+
}
|
|
80753
|
+
function readValue3(tx2) {
|
|
80754
|
+
const v = tx2["value"];
|
|
80755
|
+
if (v == null)
|
|
80756
|
+
return 0n;
|
|
80757
|
+
if (typeof v === "string")
|
|
80758
|
+
return BigInt(v);
|
|
80759
|
+
if (typeof v === "number")
|
|
80760
|
+
return BigInt(v);
|
|
80761
|
+
if (typeof v === "bigint")
|
|
80762
|
+
return v;
|
|
80763
|
+
const maybe = v;
|
|
80764
|
+
if (typeof maybe.toBigInt === "function")
|
|
80765
|
+
return maybe.toBigInt();
|
|
80766
|
+
if (typeof maybe.toString === "function")
|
|
80767
|
+
return BigInt(maybe.toString());
|
|
80768
|
+
throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
|
|
80769
|
+
}
|
|
80770
|
+
function normalizePositionId3(id) {
|
|
80771
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
80772
|
+
return import_ethers38.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
80773
|
+
}
|
|
80774
|
+
function requirePositionId2(actual, expected) {
|
|
80775
|
+
const txPositionId = String(actual).toLowerCase();
|
|
80776
|
+
if (txPositionId !== normalizePositionId3(expected)) {
|
|
80777
|
+
throw new TxValidationError3(
|
|
80778
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
|
|
80779
|
+
);
|
|
80780
|
+
}
|
|
80781
|
+
}
|
|
80782
|
+
function validateUnsignedTx3(unsignedTx, expected, vctx) {
|
|
80783
|
+
const txChainId = readChainId3(unsignedTx);
|
|
80784
|
+
if (txChainId == null) {
|
|
80785
|
+
throw new TxValidationError3(
|
|
80786
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
80787
|
+
);
|
|
80788
|
+
}
|
|
80789
|
+
if (txChainId !== vctx.chainId) {
|
|
80790
|
+
throw new TxValidationError3(
|
|
80791
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
80792
|
+
);
|
|
80793
|
+
}
|
|
80794
|
+
const value = readValue3(unsignedTx);
|
|
80795
|
+
if (value !== 0n) {
|
|
80796
|
+
throw new TxValidationError3(
|
|
80797
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
80798
|
+
);
|
|
80799
|
+
}
|
|
80800
|
+
assertFeeCeiling2(
|
|
80801
|
+
readOptionalBigInt2(unsignedTx, "gasLimit"),
|
|
80802
|
+
readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
|
|
80803
|
+
(msg) => {
|
|
80804
|
+
throw new TxValidationError3(msg);
|
|
80805
|
+
},
|
|
80806
|
+
vctx.feeCeiling
|
|
80807
|
+
);
|
|
80808
|
+
const to = readToAddress3(unsignedTx);
|
|
80809
|
+
const data = readData3(unsignedTx);
|
|
80810
|
+
const { name, args } = decodeSignable3(data);
|
|
80811
|
+
const pm = vctx.contracts.PositionManager;
|
|
80812
|
+
switch (expected.kind) {
|
|
80813
|
+
case "mint": {
|
|
80814
|
+
if (name !== "mintUCD") {
|
|
80815
|
+
throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
|
|
80816
|
+
}
|
|
80817
|
+
if (!eqAddr3(to, pm)) {
|
|
80818
|
+
throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
80819
|
+
}
|
|
80820
|
+
requirePositionId2(args[0], expected.positionId);
|
|
80821
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
80822
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
80823
|
+
throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
80824
|
+
}
|
|
80825
|
+
const txMintFee = BigInt(String(args[2]));
|
|
80826
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
80827
|
+
throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
80828
|
+
}
|
|
80829
|
+
break;
|
|
80830
|
+
}
|
|
80831
|
+
case "repay": {
|
|
80832
|
+
if (name !== "makePayment") {
|
|
80833
|
+
throw new TxValidationError3(`expected makePayment, server returned ${name}`);
|
|
80834
|
+
}
|
|
80835
|
+
if (!eqAddr3(to, pm)) {
|
|
80836
|
+
throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
80837
|
+
}
|
|
80838
|
+
requirePositionId2(args[0], expected.positionId);
|
|
80839
|
+
const txAmount = BigInt(String(args[1]));
|
|
80840
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
80841
|
+
throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
80842
|
+
}
|
|
80843
|
+
break;
|
|
80844
|
+
}
|
|
80845
|
+
case "extend": {
|
|
80846
|
+
if (name !== "extendPosition") {
|
|
80847
|
+
throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
|
|
80848
|
+
}
|
|
80849
|
+
if (!eqAddr3(to, pm)) {
|
|
80850
|
+
throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
80851
|
+
}
|
|
80852
|
+
requirePositionId2(args[0], expected.positionId);
|
|
80853
|
+
const txTerm = Number(args[1]);
|
|
80854
|
+
if (txTerm !== expected.selectedTerm) {
|
|
80855
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
80856
|
+
}
|
|
80857
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
80858
|
+
const txFee = BigInt(String(args[5]));
|
|
80859
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
80860
|
+
if (txFee > upper) {
|
|
80861
|
+
throw new TxValidationError3(
|
|
80862
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
80863
|
+
);
|
|
80864
|
+
}
|
|
80865
|
+
}
|
|
80866
|
+
break;
|
|
80867
|
+
}
|
|
80868
|
+
case "withdraw-btc": {
|
|
80869
|
+
if (name !== "withdrawBTC") {
|
|
80870
|
+
throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
|
|
80871
|
+
}
|
|
80872
|
+
if (!eqAddr3(to, pm)) {
|
|
80873
|
+
throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
80874
|
+
}
|
|
80875
|
+
const paramsTuple = args[0];
|
|
80876
|
+
requirePositionId2(paramsTuple[0], expected.positionId);
|
|
80877
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
80878
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
80879
|
+
throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
80880
|
+
}
|
|
80881
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
80882
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
80883
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
80884
|
+
if (txDeduction > upper) {
|
|
80885
|
+
throw new TxValidationError3(
|
|
80886
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
80887
|
+
);
|
|
80888
|
+
}
|
|
80889
|
+
}
|
|
80890
|
+
break;
|
|
80891
|
+
}
|
|
80892
|
+
case "ucd-approve": {
|
|
80893
|
+
if (name !== "approve") {
|
|
80894
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
80895
|
+
}
|
|
80896
|
+
const ucd = vctx.contracts.UCDToken;
|
|
80897
|
+
if (!eqAddr3(to, ucd)) {
|
|
80898
|
+
throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
80899
|
+
}
|
|
80900
|
+
const spender = String(args[0]);
|
|
80901
|
+
const ok2 = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
|
|
80902
|
+
if (!ok2) {
|
|
80903
|
+
throw new TxValidationError3(
|
|
80904
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
80905
|
+
);
|
|
80906
|
+
}
|
|
80907
|
+
const amt = BigInt(String(args[1]));
|
|
80908
|
+
const min = BigInt(expected.minAmountWei);
|
|
80909
|
+
if (amt < min) {
|
|
80910
|
+
throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
|
|
80911
|
+
}
|
|
80912
|
+
const SANITY_MAX = min * 1000n;
|
|
80913
|
+
if (amt > SANITY_MAX) {
|
|
80914
|
+
throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
80915
|
+
}
|
|
80916
|
+
break;
|
|
80917
|
+
}
|
|
80918
|
+
case "create-position": {
|
|
80919
|
+
if (name !== "createPosition") {
|
|
80920
|
+
throw new TxValidationError3(`expected createPosition, server returned ${name}`);
|
|
80921
|
+
}
|
|
80922
|
+
if (!eqAddr3(to, pm)) {
|
|
80923
|
+
throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
80924
|
+
}
|
|
80925
|
+
const txTerm = BigInt(String(args[4]));
|
|
80926
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
80927
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
80928
|
+
}
|
|
80929
|
+
break;
|
|
80930
|
+
}
|
|
80931
|
+
case "set-position-delegate": {
|
|
80932
|
+
if (name !== "setPositionDelegate") {
|
|
80933
|
+
throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
|
|
80934
|
+
}
|
|
80935
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
80936
|
+
throw new TxValidationError3(
|
|
80937
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
80938
|
+
);
|
|
80939
|
+
}
|
|
80940
|
+
requirePositionId2(args[0], expected.positionId);
|
|
80941
|
+
const txDelegate = String(args[1]);
|
|
80942
|
+
if (!eqAddr3(txDelegate, expected.delegate)) {
|
|
80943
|
+
throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
80944
|
+
}
|
|
80945
|
+
break;
|
|
80946
|
+
}
|
|
80947
|
+
case "bwar-add-address": {
|
|
80948
|
+
if (name !== "addAddress") {
|
|
80949
|
+
throw new TxValidationError3(`expected addAddress, decoded ${name}`);
|
|
80950
|
+
}
|
|
80951
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
80952
|
+
throw new TxValidationError3(
|
|
80953
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
80954
|
+
);
|
|
80955
|
+
}
|
|
80956
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
80957
|
+
throw new TxValidationError3(
|
|
80958
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
80959
|
+
);
|
|
80960
|
+
}
|
|
80961
|
+
break;
|
|
80962
|
+
}
|
|
80963
|
+
case "stablecoin-approve": {
|
|
80964
|
+
if (name !== "approve") {
|
|
80965
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
80966
|
+
}
|
|
80967
|
+
if (!eqAddr3(to, expected.tokenAddress)) {
|
|
80968
|
+
throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
80969
|
+
}
|
|
80970
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
80971
|
+
throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
80972
|
+
}
|
|
80973
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
80974
|
+
throw new TxValidationError3(
|
|
80975
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
80976
|
+
);
|
|
80977
|
+
}
|
|
80978
|
+
break;
|
|
80979
|
+
}
|
|
80980
|
+
case "ucd-approve-controller": {
|
|
80981
|
+
if (name !== "approve") {
|
|
80982
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
80983
|
+
}
|
|
80984
|
+
if (!eqAddr3(to, expected.ucdTokenAddress)) {
|
|
80985
|
+
throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
80986
|
+
}
|
|
80987
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
80988
|
+
throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
80989
|
+
}
|
|
80990
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
80991
|
+
throw new TxValidationError3(
|
|
80992
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
80993
|
+
);
|
|
80994
|
+
}
|
|
80995
|
+
break;
|
|
80996
|
+
}
|
|
80997
|
+
case "psm-swap": {
|
|
80998
|
+
if (name !== "swap")
|
|
80999
|
+
throw new TxValidationError3(`expected swap, server returned ${name}`);
|
|
81000
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
81001
|
+
throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
81002
|
+
}
|
|
81003
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
81004
|
+
throw new TxValidationError3(`swap stablecoin mismatch`);
|
|
81005
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
81006
|
+
throw new TxValidationError3(`swap amountIn mismatch`);
|
|
81007
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
81008
|
+
throw new TxValidationError3(`swap minUcdOut mismatch`);
|
|
81009
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
81010
|
+
throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
81011
|
+
}
|
|
81012
|
+
break;
|
|
81013
|
+
}
|
|
81014
|
+
case "psm-redeem": {
|
|
81015
|
+
if (name !== "redeem")
|
|
81016
|
+
throw new TxValidationError3(`expected redeem, server returned ${name}`);
|
|
81017
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
81018
|
+
throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
81019
|
+
}
|
|
81020
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
81021
|
+
throw new TxValidationError3(`redeem stablecoin mismatch`);
|
|
81022
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
81023
|
+
throw new TxValidationError3(`redeem ucdAmount mismatch`);
|
|
81024
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
81025
|
+
throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
|
|
81026
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
81027
|
+
throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
81028
|
+
}
|
|
81029
|
+
break;
|
|
81030
|
+
}
|
|
81031
|
+
default: {
|
|
81032
|
+
const _exhaustive = expected;
|
|
81033
|
+
throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
81034
|
+
}
|
|
81035
|
+
}
|
|
81036
|
+
}
|
|
81037
|
+
var SLOT_SECONDS2 = 12;
|
|
81038
|
+
var INCLUSION_SLOT_TOLERANCE2 = 3;
|
|
81039
|
+
var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
|
|
81040
|
+
function buildPsmApproveTx2(p) {
|
|
81041
|
+
return {
|
|
81042
|
+
to: p.token,
|
|
81043
|
+
data: encodeSignable3("approve", [p.spender, p.amount]),
|
|
81044
|
+
value: "0x0",
|
|
81045
|
+
chainId: p.chainId
|
|
81046
|
+
};
|
|
81047
|
+
}
|
|
81048
|
+
function buildPsmSwapTx3(p) {
|
|
81049
|
+
return {
|
|
81050
|
+
to: p.psm,
|
|
81051
|
+
data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
81052
|
+
value: "0x0",
|
|
81053
|
+
chainId: p.chainId
|
|
81054
|
+
};
|
|
81055
|
+
}
|
|
81056
|
+
function buildPsmRedeemTx3(p) {
|
|
81057
|
+
return {
|
|
81058
|
+
to: p.psm,
|
|
81059
|
+
data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
81060
|
+
value: "0x0",
|
|
81061
|
+
chainId: p.chainId
|
|
81062
|
+
};
|
|
81063
|
+
}
|
|
81064
|
+
var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
|
|
81065
|
+
var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
81066
|
+
function psmExchangeReadsFromProvider2(provider, psmAddress) {
|
|
81067
|
+
const psm = new import_ethers41.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
|
|
81068
|
+
return {
|
|
81069
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
81070
|
+
allowance: async (token, owner, spender) => await new import_ethers41.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
|
|
81071
|
+
};
|
|
81072
|
+
}
|
|
81073
|
+
var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
|
|
81074
|
+
function requireAddress2(direction, label, value) {
|
|
81075
|
+
if (!value || !import_ethers41.ethers.isAddress(value)) {
|
|
81076
|
+
throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
81077
|
+
}
|
|
81078
|
+
return import_ethers41.ethers.getAddress(value);
|
|
81079
|
+
}
|
|
81080
|
+
async function planPsmExchange2(params) {
|
|
81081
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
81082
|
+
const chainId = vctx.chainId;
|
|
81083
|
+
if (amountIn <= 0n) {
|
|
81084
|
+
throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
81085
|
+
}
|
|
81086
|
+
if (minOut <= 0n) {
|
|
81087
|
+
throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
81088
|
+
}
|
|
81089
|
+
const owner = requireAddress2(direction, "owner", params.owner);
|
|
81090
|
+
const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
|
|
81091
|
+
const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
|
|
81092
|
+
const isSwap = direction === "swap";
|
|
81093
|
+
const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
|
|
81094
|
+
const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
|
|
81095
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
81096
|
+
throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
81097
|
+
}
|
|
81098
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
81099
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
81100
|
+
const approvals = [];
|
|
81101
|
+
if (allowanceBefore < amountIn) {
|
|
81102
|
+
if (allowanceBefore > 0n) {
|
|
81103
|
+
approvals.push({
|
|
81104
|
+
step: "reset-approve",
|
|
81105
|
+
tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
|
|
81106
|
+
expected: approveExpected(0n)
|
|
81107
|
+
});
|
|
81108
|
+
}
|
|
81109
|
+
approvals.push({
|
|
81110
|
+
step: "approve",
|
|
81111
|
+
tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
|
|
81112
|
+
expected: approveExpected(amountIn)
|
|
81113
|
+
});
|
|
81114
|
+
}
|
|
81115
|
+
const exec = isSwap ? {
|
|
81116
|
+
step: "swap",
|
|
81117
|
+
tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
81118
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
81119
|
+
} : {
|
|
81120
|
+
step: "redeem",
|
|
81121
|
+
tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
81122
|
+
expected: {
|
|
81123
|
+
kind: "psm-redeem",
|
|
81124
|
+
psmAddress: psm,
|
|
81125
|
+
stablecoin,
|
|
81126
|
+
amountUcdWei: amountIn.toString(),
|
|
81127
|
+
minOut: minOut.toString()
|
|
81128
|
+
}
|
|
81129
|
+
};
|
|
81130
|
+
for (const leg of [...approvals, exec]) {
|
|
81131
|
+
validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
|
|
81132
|
+
}
|
|
81133
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
81134
|
+
}
|
|
81135
|
+
|
|
81136
|
+
// src/boundary/upstream/real/psm-calls.ts
|
|
79589
81137
|
var PSM_VIEW_FRAGMENTS = [
|
|
79590
81138
|
"function VERSION() view returns (string)",
|
|
79591
81139
|
"function supportedStablecoins(address) view returns (bool)",
|
|
@@ -79605,15 +81153,7 @@ var PSM_VIEW_FRAGMENTS = [
|
|
|
79605
81153
|
"function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
|
|
79606
81154
|
"function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
|
|
79607
81155
|
];
|
|
79608
|
-
var
|
|
79609
|
-
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
|
|
79610
|
-
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
|
|
79611
|
-
];
|
|
79612
|
-
var ERC20_FRAGMENTS = [
|
|
79613
|
-
"function approve(address spender, uint256 amount) returns (bool)",
|
|
79614
|
-
"function balanceOf(address holder) view returns (uint256)"
|
|
79615
|
-
];
|
|
79616
|
-
var ERC20_IFACE = new import_ethers32.ethers.Interface(ERC20_FRAGMENTS);
|
|
81156
|
+
var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
|
|
79617
81157
|
var PSM_ERROR_FRAGMENTS = [
|
|
79618
81158
|
"error StablecoinNotSupported(address stablecoin)",
|
|
79619
81159
|
"error InvalidAmount()",
|
|
@@ -79661,9 +81201,9 @@ var RENDERERS = {
|
|
|
79661
81201
|
var PsmCalls = class {
|
|
79662
81202
|
constructor(deps) {
|
|
79663
81203
|
this.deps = deps;
|
|
79664
|
-
const abi = [...PSM_VIEW_FRAGMENTS, ...
|
|
79665
|
-
this.iface = new
|
|
79666
|
-
this.psm = new
|
|
81204
|
+
const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
|
|
81205
|
+
this.iface = new import_ethers42.ethers.Interface(abi);
|
|
81206
|
+
this.psm = new import_ethers42.ethers.Contract(deps.psmAddress, abi, deps.provider);
|
|
79667
81207
|
}
|
|
79668
81208
|
psm;
|
|
79669
81209
|
iface;
|
|
@@ -79676,34 +81216,10 @@ var PsmCalls = class {
|
|
|
79676
81216
|
...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
|
|
79677
81217
|
};
|
|
79678
81218
|
}
|
|
79679
|
-
|
|
79680
|
-
|
|
79681
|
-
|
|
79682
|
-
|
|
79683
|
-
return {
|
|
79684
|
-
to: p.token,
|
|
79685
|
-
data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
|
|
79686
|
-
value: "0x0",
|
|
79687
|
-
chainId: p.chainId
|
|
79688
|
-
};
|
|
79689
|
-
}
|
|
79690
|
-
/** Step 2, stablecoin → UCD (contract `swap`). */
|
|
79691
|
-
buildSwap(p) {
|
|
79692
|
-
return {
|
|
79693
|
-
to: this.deps.psmAddress,
|
|
79694
|
-
data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
|
|
79695
|
-
value: "0x0",
|
|
79696
|
-
chainId: p.chainId
|
|
79697
|
-
};
|
|
79698
|
-
}
|
|
79699
|
-
/** Step 2, UCD → stablecoin (contract `redeem`). */
|
|
79700
|
-
buildRedeem(p) {
|
|
79701
|
-
return {
|
|
79702
|
-
to: this.deps.psmAddress,
|
|
79703
|
-
data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
|
|
79704
|
-
value: "0x0",
|
|
79705
|
-
chainId: p.chainId
|
|
79706
|
-
};
|
|
81219
|
+
/** The two live reads the SDK's exchange planner depends on (supported set + allowance),
|
|
81220
|
+
* over this wrapper's provider and PSM. */
|
|
81221
|
+
exchangeReads() {
|
|
81222
|
+
return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
|
|
79707
81223
|
}
|
|
79708
81224
|
/** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
|
|
79709
81225
|
async balances(holder) {
|
|
@@ -79716,8 +81232,8 @@ var PsmCalls = class {
|
|
|
79716
81232
|
});
|
|
79717
81233
|
}
|
|
79718
81234
|
return this.call(async () => {
|
|
79719
|
-
const ucd = new
|
|
79720
|
-
const stable = new
|
|
81235
|
+
const ucd = new import_ethers42.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
|
|
81236
|
+
const stable = new import_ethers42.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
|
|
79721
81237
|
const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
|
|
79722
81238
|
return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
|
|
79723
81239
|
});
|
|
@@ -79835,7 +81351,7 @@ var PsmCalls = class {
|
|
|
79835
81351
|
};
|
|
79836
81352
|
|
|
79837
81353
|
// src/boundary/upstream/real/session.ts
|
|
79838
|
-
var
|
|
81354
|
+
var import_ethers43 = require("ethers");
|
|
79839
81355
|
var REFRESH_LEEWAY_SEC = 30;
|
|
79840
81356
|
var LOGIN_TYPES_WITH_AUDIENCE3 = {
|
|
79841
81357
|
DiamondHands: [
|
|
@@ -79883,7 +81399,7 @@ var LitOpsSession = class {
|
|
|
79883
81399
|
const message = {
|
|
79884
81400
|
address: this.wallet.address,
|
|
79885
81401
|
issuedAt: Math.floor(Date.now() / 1e3),
|
|
79886
|
-
nonce: "0x" + Buffer.from(
|
|
81402
|
+
nonce: "0x" + Buffer.from(import_ethers43.ethers.randomBytes(32)).toString("hex"),
|
|
79887
81403
|
audience: this.serviceEndpoint
|
|
79888
81404
|
};
|
|
79889
81405
|
const signature = await this.wallet.signTypedData(
|
|
@@ -79925,7 +81441,7 @@ function decodeJwtExp(token) {
|
|
|
79925
81441
|
}
|
|
79926
81442
|
|
|
79927
81443
|
// src/boundary/upstream/real/write-ops.ts
|
|
79928
|
-
var
|
|
81444
|
+
var import_ethers45 = require("ethers");
|
|
79929
81445
|
|
|
79930
81446
|
// src/signer/types.ts
|
|
79931
81447
|
var OperationDeclined = class extends Error {
|
|
@@ -79935,7 +81451,7 @@ var OperationDeclined = class extends Error {
|
|
|
79935
81451
|
init_tx_validator();
|
|
79936
81452
|
|
|
79937
81453
|
// src/boundary/upstream/shared/external-bridge/page-crypto.ts
|
|
79938
|
-
var
|
|
81454
|
+
var import_ethers44 = require("ethers");
|
|
79939
81455
|
var PERSONAL_SIGN_LAYOUTS = {
|
|
79940
81456
|
"dh-op-envelope-v1": {
|
|
79941
81457
|
types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
|
|
@@ -79956,9 +81472,9 @@ function hashForLayout(layout, fields) {
|
|
|
79956
81472
|
const values = def.fieldOrder.map((name) => {
|
|
79957
81473
|
const raw = fields[name];
|
|
79958
81474
|
if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
|
|
79959
|
-
return hashUtf8.has(name) ?
|
|
81475
|
+
return hashUtf8.has(name) ? import_ethers44.ethers.keccak256(import_ethers44.ethers.toUtf8Bytes(raw)) : raw;
|
|
79960
81476
|
});
|
|
79961
|
-
return
|
|
81477
|
+
return import_ethers44.ethers.solidityPackedKeccak256(def.types, values);
|
|
79962
81478
|
}
|
|
79963
81479
|
var PAGE_CRYPTO_JS = `"use strict";
|
|
79964
81480
|
(function () {
|
|
@@ -80187,9 +81703,21 @@ function buildValidationContext(network, chainId) {
|
|
|
80187
81703
|
|
|
80188
81704
|
// src/boundary/upstream/real/write-ops.ts
|
|
80189
81705
|
var SOURCE5 = "real-ops";
|
|
81706
|
+
function mcpExpected(leg) {
|
|
81707
|
+
const e = leg.expected;
|
|
81708
|
+
switch (e.kind) {
|
|
81709
|
+
case "stablecoin-approve":
|
|
81710
|
+
case "ucd-approve-controller":
|
|
81711
|
+
case "psm-swap":
|
|
81712
|
+
case "psm-redeem":
|
|
81713
|
+
return e;
|
|
81714
|
+
default:
|
|
81715
|
+
throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
|
|
81716
|
+
}
|
|
81717
|
+
}
|
|
80190
81718
|
var OP_LAYOUT = "dh-op-envelope-v1";
|
|
80191
81719
|
function randomNonceHex() {
|
|
80192
|
-
return "0x" + Buffer.from(
|
|
81720
|
+
return "0x" + Buffer.from(import_ethers45.ethers.randomBytes(16)).toString("hex");
|
|
80193
81721
|
}
|
|
80194
81722
|
async function postJson(url2, body, headers) {
|
|
80195
81723
|
const res = await fetch(url2, {
|
|
@@ -80250,7 +81778,7 @@ function buildWriteOps(deps) {
|
|
|
80250
81778
|
return {
|
|
80251
81779
|
to: String(tx2["to"] ?? ""),
|
|
80252
81780
|
data: String(tx2["data"] ?? "0x"),
|
|
80253
|
-
value: tx2["value"] != null ?
|
|
81781
|
+
value: tx2["value"] != null ? import_ethers45.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
|
|
80254
81782
|
chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
|
|
80255
81783
|
};
|
|
80256
81784
|
}
|
|
@@ -80335,8 +81863,9 @@ function buildWriteOps(deps) {
|
|
|
80335
81863
|
}
|
|
80336
81864
|
return {
|
|
80337
81865
|
createPosition: async (p) => {
|
|
80338
|
-
const
|
|
80339
|
-
if (!
|
|
81866
|
+
const built = await deps.getWriteSdk();
|
|
81867
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81868
|
+
const sdk = built.sdk;
|
|
80340
81869
|
try {
|
|
80341
81870
|
await deps.assertValidatorConfigured();
|
|
80342
81871
|
} catch (e) {
|
|
@@ -80415,7 +81944,7 @@ function buildWriteOps(deps) {
|
|
|
80415
81944
|
mintedUcdWei: minted,
|
|
80416
81945
|
feeUcdWei: mintFee,
|
|
80417
81946
|
echoedAmountUcdWei: minted,
|
|
80418
|
-
authorization: auth(action, `mint ${
|
|
81947
|
+
authorization: auth(action, `mint ${import_ethers45.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
|
|
80419
81948
|
},
|
|
80420
81949
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
80421
81950
|
);
|
|
@@ -80456,7 +81985,7 @@ function buildWriteOps(deps) {
|
|
|
80456
81985
|
txRef: { kind: "eth-tx", id: r.value.txHash },
|
|
80457
81986
|
paidUcdWei: paid,
|
|
80458
81987
|
echoedAmountUcdWei: paid,
|
|
80459
|
-
authorization: auth(action, `repay ${
|
|
81988
|
+
authorization: auth(action, `repay ${import_ethers45.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
|
|
80460
81989
|
},
|
|
80461
81990
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
80462
81991
|
);
|
|
@@ -80496,8 +82025,9 @@ function buildWriteOps(deps) {
|
|
|
80496
82025
|
);
|
|
80497
82026
|
},
|
|
80498
82027
|
withdraw: async (p) => {
|
|
80499
|
-
const
|
|
80500
|
-
if (!
|
|
82028
|
+
const built = await deps.getWriteSdk();
|
|
82029
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
82030
|
+
const sdk = built.sdk;
|
|
80501
82031
|
const amountSats = Number(p.amountSats);
|
|
80502
82032
|
const feeSats = Number(p.networkFeeSats);
|
|
80503
82033
|
let result;
|
|
@@ -80526,12 +82056,13 @@ function buildWriteOps(deps) {
|
|
|
80526
82056
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
80527
82057
|
);
|
|
80528
82058
|
},
|
|
80529
|
-
/** PSM exchange
|
|
80530
|
-
* orchestration.
|
|
80531
|
-
*
|
|
80532
|
-
*
|
|
80533
|
-
*
|
|
80534
|
-
*
|
|
82059
|
+
/** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
|
|
82060
|
+
* orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
|
|
82061
|
+
* builder every client shares (it replaced this file's own builders and the SDK's old
|
|
82062
|
+
* MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
|
|
82063
|
+
* allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
|
|
82064
|
+
* validated again here by the MCP's own whitelist (the one the approval card decodes
|
|
82065
|
+
* with), then signed through the session signer and broadcast — one at a time. */
|
|
80535
82066
|
psmSwap: async (p) => {
|
|
80536
82067
|
const pr = await deps.psm(p.stablecoin);
|
|
80537
82068
|
if (!pr.ok) return upFail(pr.failure);
|
|
@@ -80545,11 +82076,7 @@ function buildWriteOps(deps) {
|
|
|
80545
82076
|
message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
|
|
80546
82077
|
});
|
|
80547
82078
|
}
|
|
80548
|
-
const amountIn = BigInt(p.amountIn);
|
|
80549
|
-
const minOut = BigInt(p.minOut);
|
|
80550
82079
|
const vctx = buildValidationContext(config.network, chainId);
|
|
80551
|
-
const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
|
|
80552
|
-
const spenderAddress = isSwap ? addr.psm : addr.ucdController;
|
|
80553
82080
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
80554
82081
|
const tokenSymbol = isSwap ? calls.symbol() : "UCD";
|
|
80555
82082
|
const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
|
|
@@ -80566,49 +82093,66 @@ function buildWriteOps(deps) {
|
|
|
80566
82093
|
return submitFailure(leg, e);
|
|
80567
82094
|
}
|
|
80568
82095
|
};
|
|
80569
|
-
|
|
82096
|
+
let plan;
|
|
80570
82097
|
try {
|
|
80571
|
-
|
|
80572
|
-
|
|
80573
|
-
|
|
80574
|
-
|
|
80575
|
-
|
|
80576
|
-
|
|
80577
|
-
|
|
80578
|
-
|
|
80579
|
-
|
|
80580
|
-
const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
|
|
80581
|
-
if (!approveHashR.ok) return approveHashR;
|
|
80582
|
-
const approveHash = approveHashR.value;
|
|
80583
|
-
const residualNote = `the approve ALREADY broadcast (tx ${approveHash}) \u2014 an exact-amount allowance of ${p.amountIn} ${tokenSymbol} smallest units to ${spenderContract} stands; it authorizes only that amount and nothing else. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
80584
|
-
const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
|
|
80585
|
-
try {
|
|
80586
|
-
validateUnsignedTx(
|
|
80587
|
-
{ ...execTx },
|
|
80588
|
-
isSwap ? { kind: "psm-swap", psmAddress: addr.psm, stablecoin: addr.stablecoin, amountIn: p.amountIn, minOut: p.minOut } : { kind: "psm-redeem", psmAddress: addr.psm, stablecoin: addr.stablecoin, amountUcdWei: p.amountIn, minOut: p.minOut },
|
|
80589
|
-
vctx
|
|
80590
|
-
);
|
|
82098
|
+
plan = await planPsmExchange2({
|
|
82099
|
+
direction: p.direction,
|
|
82100
|
+
owner: p.borrower,
|
|
82101
|
+
addresses: addr,
|
|
82102
|
+
amountIn: BigInt(p.amountIn),
|
|
82103
|
+
minOut: BigInt(p.minOut),
|
|
82104
|
+
vctx,
|
|
82105
|
+
reads: calls.exchangeReads()
|
|
82106
|
+
});
|
|
80591
82107
|
} catch (e) {
|
|
80592
|
-
return upFail({ kind: "rejected", source: SOURCE5, message:
|
|
82108
|
+
return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
|
|
82109
|
+
kind: "unavailable",
|
|
82110
|
+
source: SOURCE5,
|
|
82111
|
+
message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
|
|
82112
|
+
raw: String(e)
|
|
82113
|
+
});
|
|
80593
82114
|
}
|
|
80594
|
-
const
|
|
80595
|
-
const
|
|
80596
|
-
|
|
80597
|
-
|
|
80598
|
-
|
|
82115
|
+
const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
|
|
82116
|
+
const unit = `${tokenSymbol} smallest units`;
|
|
82117
|
+
const landed = [];
|
|
82118
|
+
const residualNote = () => {
|
|
82119
|
+
const last = landed[landed.length - 1];
|
|
82120
|
+
const standing = !last ? `no approve ran \u2014 the pre-existing allowance of ${allowanceBefore} ${unit} to ${spenderContract} is unchanged` : last.step === "reset-approve" ? `the reset ALREADY broadcast (tx ${last.hash}) \u2014 the allowance to ${spenderContract} is now 0; nothing is authorized` : `the approve ALREADY broadcast (tx ${last.hash}) \u2014 an exact-amount allowance of ${p.amountIn} ${unit} to ${spenderContract} stands; it authorizes only that amount and nothing else`;
|
|
82121
|
+
return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
82122
|
+
};
|
|
82123
|
+
const runLeg = async (leg) => {
|
|
82124
|
+
const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
|
|
82125
|
+
try {
|
|
82126
|
+
validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
|
|
82127
|
+
} catch (e) {
|
|
82128
|
+
return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
|
|
82129
|
+
}
|
|
82130
|
+
const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
|
|
82131
|
+
const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
|
|
82132
|
+
return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
|
|
82133
|
+
};
|
|
82134
|
+
const approvals = [];
|
|
82135
|
+
for (const leg of plan.approvals) {
|
|
82136
|
+
const card = leg.step === "reset-approve" ? `reset the standing allowance of ${allowanceBefore} ${unit} to ${spenderContract} (${spenderAddress}) to 0 \u2014 required before an exact-amount approve` : `approve exactly ${p.amountIn} ${unit} to ${spenderContract} (${spenderAddress})`;
|
|
82137
|
+
const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
|
|
82138
|
+
const r = await runLeg(leg);
|
|
82139
|
+
if (!r.ok) return r;
|
|
82140
|
+
landed.push({ step, hash: r.value });
|
|
82141
|
+
approvals.push({
|
|
82142
|
+
step,
|
|
82143
|
+
txRef: { kind: "eth-tx", id: r.value },
|
|
82144
|
+
amount: leg.step === "reset-approve" ? "0" : p.amountIn,
|
|
82145
|
+
authorization: auth("psm-approve", card, r.value)
|
|
82146
|
+
});
|
|
80599
82147
|
}
|
|
82148
|
+
const execCard = `${p.direction} ${p.amountIn} ${isSwap ? unit : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
|
|
82149
|
+
const execHashR = await runLeg(plan.exec);
|
|
82150
|
+
if (!execHashR.ok) return execHashR;
|
|
80600
82151
|
const execHash = execHashR.value;
|
|
80601
82152
|
const balancesR = await calls.balances(p.borrower);
|
|
80602
82153
|
const row = {
|
|
80603
|
-
|
|
80604
|
-
|
|
80605
|
-
tokenSymbol,
|
|
80606
|
-
tokenAddress,
|
|
80607
|
-
spenderAddress,
|
|
80608
|
-
spenderContract,
|
|
80609
|
-
amount: p.amountIn,
|
|
80610
|
-
authorization: auth("psm-approve", approveCard, approveHash)
|
|
80611
|
-
},
|
|
82154
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
82155
|
+
approvals,
|
|
80612
82156
|
execute: {
|
|
80613
82157
|
txRef: { kind: "eth-tx", id: execHash },
|
|
80614
82158
|
amountIn: p.amountIn,
|
|
@@ -80625,8 +82169,9 @@ function buildWriteOps(deps) {
|
|
|
80625
82169
|
// registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
|
|
80626
82170
|
// msg.sender, so their path is a SafeTx — never this keystore leg.
|
|
80627
82171
|
allowlistWithdrawalAddress: async (p) => {
|
|
80628
|
-
const
|
|
80629
|
-
if (!
|
|
82172
|
+
const built = await deps.getWriteSdk();
|
|
82173
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
82174
|
+
const sdk = built.sdk;
|
|
80630
82175
|
let result;
|
|
80631
82176
|
try {
|
|
80632
82177
|
result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
|
|
@@ -80673,8 +82218,9 @@ function buildWriteOps(deps) {
|
|
|
80673
82218
|
message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
|
|
80674
82219
|
}),
|
|
80675
82220
|
retryWithdrawExecute: async (p) => {
|
|
80676
|
-
const
|
|
80677
|
-
if (!
|
|
82221
|
+
const built = await deps.getWriteSdk();
|
|
82222
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
82223
|
+
const sdk = built.sdk;
|
|
80678
82224
|
let rows;
|
|
80679
82225
|
try {
|
|
80680
82226
|
rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
|
|
@@ -80702,7 +82248,7 @@ function buildWriteOps(deps) {
|
|
|
80702
82248
|
}
|
|
80703
82249
|
|
|
80704
82250
|
// src/signer/eoa-dh.ts
|
|
80705
|
-
var
|
|
82251
|
+
var import_ethers46 = require("ethers");
|
|
80706
82252
|
var EoaDHSigner = class {
|
|
80707
82253
|
constructor(wallet, broadcast, clock = Date.now) {
|
|
80708
82254
|
this.wallet = wallet;
|
|
@@ -80719,7 +82265,7 @@ var EoaDHSigner = class {
|
|
|
80719
82265
|
async signAuthorization(spec) {
|
|
80720
82266
|
const quantumTs = nextQuantumTimestamp(this.clock());
|
|
80721
82267
|
const { fields, hashHex } = spec.stamp(quantumTs);
|
|
80722
|
-
const signature = await this.wallet.signMessage(
|
|
82268
|
+
const signature = await this.wallet.signMessage(import_ethers46.ethers.getBytes(hashHex));
|
|
80723
82269
|
return { signature, quantumTs, fields };
|
|
80724
82270
|
}
|
|
80725
82271
|
async wrapInnerTx(innerTx) {
|
|
@@ -80737,10 +82283,10 @@ var EoaDHSigner = class {
|
|
|
80737
82283
|
|
|
80738
82284
|
// src/signer/external-eoa.ts
|
|
80739
82285
|
var import_node_crypto7 = require("crypto");
|
|
80740
|
-
var
|
|
82286
|
+
var import_ethers48 = require("ethers");
|
|
80741
82287
|
|
|
80742
82288
|
// src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
|
|
80743
|
-
var
|
|
82289
|
+
var import_ethers47 = require("ethers");
|
|
80744
82290
|
function eq2(a, b) {
|
|
80745
82291
|
return a.toLowerCase() === b.toLowerCase();
|
|
80746
82292
|
}
|
|
@@ -80763,7 +82309,7 @@ function compareLandedTx(landed, approved, borrower) {
|
|
|
80763
82309
|
return { status: "verified", from: landed.from, hash: landed.hash };
|
|
80764
82310
|
}
|
|
80765
82311
|
function verifyRawSignedTx(rawSignedTx, approved, borrower) {
|
|
80766
|
-
const parsed =
|
|
82312
|
+
const parsed = import_ethers47.ethers.Transaction.from(rawSignedTx);
|
|
80767
82313
|
if (!parsed.from || !parsed.to || !parsed.hash) {
|
|
80768
82314
|
return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
|
|
80769
82315
|
}
|
|
@@ -80801,7 +82347,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
|
|
|
80801
82347
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
80802
82348
|
try {
|
|
80803
82349
|
const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
|
|
80804
|
-
return
|
|
82350
|
+
return import_ethers48.ethers.toBeHex(est * 15n / 10n);
|
|
80805
82351
|
} catch (e) {
|
|
80806
82352
|
lastErr = e;
|
|
80807
82353
|
await new Promise((r) => setTimeout(r, 13e3));
|
|
@@ -80851,7 +82397,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80851
82397
|
throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
|
|
80852
82398
|
}
|
|
80853
82399
|
const finalHash = spec.stamp(used.quantumTs).hashHex;
|
|
80854
|
-
const recovered =
|
|
82400
|
+
const recovered = import_ethers48.ethers.verifyMessage(import_ethers48.ethers.getBytes(finalHash), outcome.signature);
|
|
80855
82401
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
80856
82402
|
throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
80857
82403
|
}
|
|
@@ -80862,7 +82408,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80862
82408
|
}
|
|
80863
82409
|
async submitValidatedTx(outerTx, ctx) {
|
|
80864
82410
|
const approved = toApprovedTx(outerTx, this.deps.chainId);
|
|
80865
|
-
const gas = outerTx.gasLimit != null ?
|
|
82411
|
+
const gas = outerTx.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
|
|
80866
82412
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80867
82413
|
id: (0, import_node_crypto7.randomUUID)(),
|
|
80868
82414
|
kind: "transaction",
|
|
@@ -80896,7 +82442,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80896
82442
|
return new BridgeEthersSigner(this.deps);
|
|
80897
82443
|
}
|
|
80898
82444
|
};
|
|
80899
|
-
var BridgeEthersSigner = class _BridgeEthersSigner extends
|
|
82445
|
+
var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers48.ethers.AbstractSigner {
|
|
80900
82446
|
constructor(deps) {
|
|
80901
82447
|
super(deps.provider);
|
|
80902
82448
|
this.deps = deps;
|
|
@@ -80907,13 +82453,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80907
82453
|
return this.deps.borrower;
|
|
80908
82454
|
}
|
|
80909
82455
|
async signMessage(message) {
|
|
80910
|
-
const bytes = typeof message === "string" ?
|
|
82456
|
+
const bytes = typeof message === "string" ? import_ethers48.ethers.toUtf8Bytes(message) : message;
|
|
80911
82457
|
if (bytes.length !== 32) {
|
|
80912
82458
|
throw new Error(
|
|
80913
82459
|
`external-wallet signMessage accepts only the SDK's bare 32-byte auth hashes (got ${bytes.length} bytes) \u2014 no other raw-message signing rides this path.`
|
|
80914
82460
|
);
|
|
80915
82461
|
}
|
|
80916
|
-
const hashHex =
|
|
82462
|
+
const hashHex = import_ethers48.ethers.hexlify(bytes).toLowerCase();
|
|
80917
82463
|
const nowMs = (this.deps.clock ?? Date.now)();
|
|
80918
82464
|
const expiresAtSec = nextQuantumTimestamp(nowMs);
|
|
80919
82465
|
const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
|
|
@@ -80943,7 +82489,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80943
82489
|
if (outcome.status !== "approved" || !outcome.signature) {
|
|
80944
82490
|
throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
|
|
80945
82491
|
}
|
|
80946
|
-
const recovered =
|
|
82492
|
+
const recovered = import_ethers48.ethers.verifyMessage(bytes, outcome.signature);
|
|
80947
82493
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
80948
82494
|
throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
80949
82495
|
}
|
|
@@ -80977,11 +82523,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80977
82523
|
const approved = {
|
|
80978
82524
|
to: tx2.to,
|
|
80979
82525
|
data: tx2.data,
|
|
80980
|
-
value: tx2.value != null ?
|
|
82526
|
+
value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
80981
82527
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
|
|
80982
82528
|
};
|
|
80983
82529
|
const card = cardForTx(approved);
|
|
80984
|
-
const gas = tx2.gasLimit != null ?
|
|
82530
|
+
const gas = tx2.gasLimit != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
|
|
80985
82531
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80986
82532
|
id: (0, import_node_crypto7.randomUUID)(),
|
|
80987
82533
|
kind: "transaction",
|
|
@@ -81023,14 +82569,14 @@ function toApprovedTx(tx2, fallbackChainId) {
|
|
|
81023
82569
|
return {
|
|
81024
82570
|
to: tx2.to,
|
|
81025
82571
|
data: tx2.data,
|
|
81026
|
-
value: tx2.value != null ?
|
|
82572
|
+
value: tx2.value != null ? import_ethers48.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
81027
82573
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
|
|
81028
82574
|
};
|
|
81029
82575
|
}
|
|
81030
82576
|
function describeFn(data) {
|
|
81031
82577
|
try {
|
|
81032
|
-
const { decodeSignable:
|
|
81033
|
-
return
|
|
82578
|
+
const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
|
|
82579
|
+
return decodeSignable4(data).name;
|
|
81034
82580
|
} catch {
|
|
81035
82581
|
return "operation";
|
|
81036
82582
|
}
|
|
@@ -81067,7 +82613,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
|
|
|
81067
82613
|
var RealUpstreamPlugin = class {
|
|
81068
82614
|
constructor(config, wallet, runtime) {
|
|
81069
82615
|
this.config = config;
|
|
81070
|
-
this.provider = new
|
|
82616
|
+
this.provider = new import_ethers49.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
|
|
81071
82617
|
this.wallet = wallet ?? null;
|
|
81072
82618
|
this.runtime = runtime ?? null;
|
|
81073
82619
|
this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
|
|
@@ -81260,18 +82806,24 @@ var RealUpstreamPlugin = class {
|
|
|
81260
82806
|
* the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
|
|
81261
82807
|
* and the service-mode SDK routes its own subgraph reads through the same proxy — so
|
|
81262
82808
|
* writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
|
|
81263
|
-
* Safe to call repeatedly
|
|
81264
|
-
*
|
|
82809
|
+
* Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
|
|
82810
|
+
* first write builds again (see ensureSdk). */
|
|
81265
82811
|
async initWriteSdk() {
|
|
81266
82812
|
if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
|
|
81267
82813
|
const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
|
|
81268
82814
|
if (!wallet) return;
|
|
81269
82815
|
await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
|
|
81270
82816
|
}
|
|
81271
|
-
/**
|
|
81272
|
-
*
|
|
82817
|
+
/** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
|
|
82818
|
+
*
|
|
82819
|
+
* A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
|
|
82820
|
+
* life of the process and drop the error, which was survivable only while `create` never
|
|
82821
|
+
* touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
|
|
82822
|
+
* RPC blip at boot would have disabled every later write with no reason given. Now each write
|
|
82823
|
+
* retries, and a persistent failure says what it is. Concurrent callers share one build. */
|
|
81273
82824
|
async ensureSdk(key, signer) {
|
|
81274
|
-
|
|
82825
|
+
const cached = this.sdkCache.get(key);
|
|
82826
|
+
if (cached) return { ok: true, sdk: cached };
|
|
81275
82827
|
const inFlight = this.sdkInFlight.get(key);
|
|
81276
82828
|
if (inFlight) return inFlight;
|
|
81277
82829
|
const build = (async () => {
|
|
@@ -81291,17 +82843,23 @@ var RealUpstreamPlugin = class {
|
|
|
81291
82843
|
// nesting writes under indexer discovery (the M8B-4 coupling this removes).
|
|
81292
82844
|
...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
|
|
81293
82845
|
});
|
|
81294
|
-
|
|
81295
|
-
|
|
81296
|
-
|
|
82846
|
+
if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
|
|
82847
|
+
return { ok: false, reason: builtWrite.error.message };
|
|
82848
|
+
} catch (e) {
|
|
82849
|
+
return { ok: false, reason: e instanceof Error ? e.message : String(e) };
|
|
81297
82850
|
}
|
|
81298
82851
|
})();
|
|
81299
82852
|
this.sdkInFlight.set(key, build);
|
|
81300
82853
|
const built = await build;
|
|
81301
82854
|
this.sdkInFlight.delete(key);
|
|
81302
|
-
this.sdkCache.set(key, built);
|
|
82855
|
+
if (built.ok) this.sdkCache.set(key, built.sdk);
|
|
81303
82856
|
return built;
|
|
81304
82857
|
}
|
|
82858
|
+
/** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
|
|
82859
|
+
async writeSdkFor(key, signer) {
|
|
82860
|
+
const built = await this.ensureSdk(key, signer);
|
|
82861
|
+
return built.ok ? { ok: true, sdk: built.sdk } : built;
|
|
82862
|
+
}
|
|
81305
82863
|
wallet;
|
|
81306
82864
|
// ---- per-call signer resolution (plan 10 A3) ----
|
|
81307
82865
|
/** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
|
|
@@ -81341,7 +82899,7 @@ var RealUpstreamPlugin = class {
|
|
|
81341
82899
|
chainId: this.config.chainId,
|
|
81342
82900
|
dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
|
|
81343
82901
|
session,
|
|
81344
|
-
getWriteSdk: () => this.
|
|
82902
|
+
getWriteSdk: () => this.writeSdkFor(key, wallet),
|
|
81345
82903
|
readDetails: (id) => this.readPositionDetails(id),
|
|
81346
82904
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
81347
82905
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
@@ -81357,14 +82915,14 @@ var RealUpstreamPlugin = class {
|
|
|
81357
82915
|
if (!pkpValidation) {
|
|
81358
82916
|
throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
|
|
81359
82917
|
}
|
|
81360
|
-
const registry = new
|
|
82918
|
+
const registry = new import_ethers49.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
|
|
81361
82919
|
let validator;
|
|
81362
82920
|
try {
|
|
81363
82921
|
validator = await registry.validatorForVersion(version2);
|
|
81364
82922
|
} catch (e) {
|
|
81365
82923
|
throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
|
|
81366
82924
|
}
|
|
81367
|
-
if (validator ===
|
|
82925
|
+
if (validator === import_ethers49.ethers.ZeroAddress) {
|
|
81368
82926
|
throw new Error(
|
|
81369
82927
|
`validator version ${version2} is NOT registered on ${this.config.network} (PKPValidation ${pkpValidation} returns the zero address) \u2014 the transaction would revert ValidatorNotConfigured. Set DH_VALIDATOR_VERSION to the network's registered generation.`
|
|
81370
82928
|
);
|
|
@@ -81438,7 +82996,6 @@ var RealUpstreamPlugin = class {
|
|
|
81438
82996
|
gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
|
|
81439
82997
|
this.opsGatewayCache.set(key, gateway);
|
|
81440
82998
|
}
|
|
81441
|
-
await this.ensureSdk(key, wallet.connect(this.provider));
|
|
81442
82999
|
return { ok: true, gateway };
|
|
81443
83000
|
}
|
|
81444
83001
|
if (mode === "external") {
|
|
@@ -81475,14 +83032,13 @@ var RealUpstreamPlugin = class {
|
|
|
81475
83032
|
chainId: this.config.chainId,
|
|
81476
83033
|
dhSigner: new ExternalEoaDHSigner(deps),
|
|
81477
83034
|
session,
|
|
81478
|
-
getWriteSdk: () => this.
|
|
83035
|
+
getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
|
|
81479
83036
|
readDetails: (id) => this.readPositionDetails(id),
|
|
81480
83037
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
81481
83038
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
81482
83039
|
});
|
|
81483
83040
|
this.opsGatewayCache.set(key, gateway);
|
|
81484
83041
|
}
|
|
81485
|
-
await this.ensureSdk(key, this.externalSigners.get(key));
|
|
81486
83042
|
return { ok: true, gateway };
|
|
81487
83043
|
}
|
|
81488
83044
|
return {
|
|
@@ -81642,7 +83198,7 @@ var RealUpstreamPlugin = class {
|
|
|
81642
83198
|
);
|
|
81643
83199
|
if (!r.ok) return r;
|
|
81644
83200
|
const raw = r.value.data.supportedStablecoins ?? [];
|
|
81645
|
-
const bad = raw.find((x) => !
|
|
83201
|
+
const bad = raw.find((x) => !import_ethers49.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
|
|
81646
83202
|
if (bad) {
|
|
81647
83203
|
return {
|
|
81648
83204
|
ok: false,
|
|
@@ -81725,7 +83281,7 @@ var RealUpstreamPlugin = class {
|
|
|
81725
83281
|
};
|
|
81726
83282
|
}
|
|
81727
83283
|
const symbol = raw.toLowerCase();
|
|
81728
|
-
if (
|
|
83284
|
+
if (import_ethers49.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
|
|
81729
83285
|
const verified = await this.verifiedStablecoins();
|
|
81730
83286
|
if (!verified.ok) return { ok: false, failure: verified.failure };
|
|
81731
83287
|
const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
|
|
@@ -81763,7 +83319,7 @@ var RealUpstreamPlugin = class {
|
|
|
81763
83319
|
* chain, then sign.
|
|
81764
83320
|
*/
|
|
81765
83321
|
async psmCallsFor(stablecoinAddress) {
|
|
81766
|
-
if (!
|
|
83322
|
+
if (!import_ethers49.ethers.isAddress(stablecoinAddress)) {
|
|
81767
83323
|
throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
|
|
81768
83324
|
}
|
|
81769
83325
|
const key = stablecoinAddress.toLowerCase();
|
|
@@ -81783,9 +83339,9 @@ var RealUpstreamPlugin = class {
|
|
|
81783
83339
|
let supported;
|
|
81784
83340
|
let symbol;
|
|
81785
83341
|
try {
|
|
81786
|
-
const psm = new
|
|
83342
|
+
const psm = new import_ethers49.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
|
|
81787
83343
|
supported = await psm["supportedStablecoins"](key);
|
|
81788
|
-
const erc20 = new
|
|
83344
|
+
const erc20 = new import_ethers49.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
|
|
81789
83345
|
symbol = await erc20["symbol"]();
|
|
81790
83346
|
} catch (e) {
|
|
81791
83347
|
return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
|
|
@@ -81998,7 +83554,7 @@ var RealUpstreamPlugin = class {
|
|
|
81998
83554
|
const pm = this.contracts["PositionManager"];
|
|
81999
83555
|
if (!pm) return false;
|
|
82000
83556
|
try {
|
|
82001
|
-
const c = new
|
|
83557
|
+
const c = new import_ethers49.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
|
|
82002
83558
|
return Boolean(await c["paused"]());
|
|
82003
83559
|
} catch {
|
|
82004
83560
|
return false;
|
|
@@ -82007,16 +83563,16 @@ var RealUpstreamPlugin = class {
|
|
|
82007
83563
|
async readPositionDetails(id) {
|
|
82008
83564
|
const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
|
|
82009
83565
|
if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
|
|
82010
|
-
const c = new
|
|
83566
|
+
const c = new import_ethers49.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
|
|
82011
83567
|
let d;
|
|
82012
83568
|
try {
|
|
82013
|
-
d = await c["getPositionDetails"](
|
|
83569
|
+
d = await c["getPositionDetails"](import_ethers49.ethers.zeroPadValue(id, 32));
|
|
82014
83570
|
} catch (e) {
|
|
82015
83571
|
if (e.code === "CALL_EXCEPTION") return null;
|
|
82016
83572
|
throw e;
|
|
82017
83573
|
}
|
|
82018
83574
|
const borrower = String(d["borrower"]);
|
|
82019
|
-
if (borrower ===
|
|
83575
|
+
if (borrower === import_ethers49.ethers.ZeroAddress) return null;
|
|
82020
83576
|
return {
|
|
82021
83577
|
positionId: String(d["positionId"]),
|
|
82022
83578
|
pkpId: String(d["pkpId"]),
|
|
@@ -83618,8 +85174,8 @@ async function buildBoundary(configResult, overrides) {
|
|
|
83618
85174
|
);
|
|
83619
85175
|
}
|
|
83620
85176
|
try {
|
|
83621
|
-
const decrypted = await
|
|
83622
|
-
if (!(decrypted instanceof
|
|
85177
|
+
const decrypted = await import_ethers50.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
|
|
85178
|
+
if (!(decrypted instanceof import_ethers50.ethers.Wallet)) {
|
|
83623
85179
|
return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
|
|
83624
85180
|
}
|
|
83625
85181
|
wallet = decrypted;
|
|
@@ -84111,7 +85667,7 @@ on the real adapter and the mock.
|
|
|
84111
85667
|
| extend | 1 personal-sign + 1 tx |
|
|
84112
85668
|
| allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
|
|
84113
85669
|
| withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
|
|
84114
|
-
| PSM swap/redeem |
|
|
85670
|
+
| PSM swap/redeem | 1\u20133 tx (0\u20132 exact-amount approve legs, by standing allowance + swap/redeem) |
|
|
84115
85671
|
|
|
84116
85672
|
**Honesty notes (say these plainly):**
|
|
84117
85673
|
- **Reads never pop the wallet.** If a read needs a login the user does not have, the
|
|
@@ -84255,16 +85811,19 @@ rather than silently deliver less than quoted.
|
|
|
84255
85811
|
|
|
84256
85812
|
${psmStablecoinRealityNote(d)}
|
|
84257
85813
|
|
|
84258
|
-
**Executing (\`psm_swap\`):** an exchange is
|
|
84259
|
-
result. (1)
|
|
85814
|
+
**Executing (\`psm_swap\`):** an exchange is up to THREE on-chain ceremonies, all shown in
|
|
85815
|
+
the result. (1) The **exact-amount approval** the input token needs \u2014 never unlimited, and
|
|
85816
|
+
planned against the allowance already standing: none when it covers the amount, one when it
|
|
85817
|
+
is 0, and a reset to 0 before the approval when a partial allowance is left over. The spender
|
|
84260
85818
|
differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
|
|
84261
85819
|
the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
|
|
84262
85820
|
you approve UCD to the **UCDController** (the PSM burns your UCD through the
|
|
84263
85821
|
controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
|
|
84264
85822
|
tolerance; if fees or the rate drifted beyond that between quote and execution, the
|
|
84265
85823
|
contract refuses \u2014 you never silently receive less. Output always lands at the signer's
|
|
84266
|
-
own address. If you approve
|
|
84267
|
-
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly
|
|
85824
|
+
own address. If you approve but decline the swap/redeem, the exact-amount allowance remains
|
|
85825
|
+
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly, and
|
|
85826
|
+
the next exchange that it covers uses it without asking for another approval.
|
|
84268
85827
|
PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
|
|
84269
85828
|
REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
|
|
84270
85829
|
wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
|
|
@@ -84737,7 +86296,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
|
84737
86296
|
|
|
84738
86297
|
// src/tools/loan.ts
|
|
84739
86298
|
var import_zod = require("zod");
|
|
84740
|
-
var
|
|
86299
|
+
var import_ethers51 = require("ethers");
|
|
84741
86300
|
|
|
84742
86301
|
// src/util/format.ts
|
|
84743
86302
|
function bigintReplacer(_key, value) {
|
|
@@ -84925,7 +86484,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
|
|
|
84925
86484
|
const b = getB();
|
|
84926
86485
|
if (!b.ok) return renderError(b.error);
|
|
84927
86486
|
return renderEnvelope(
|
|
84928
|
-
await b.boundary.mintUcd({ positionId, amountUcdWei: (0,
|
|
86487
|
+
await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers51.parseEther)(amountUcd.toString()).toString() })
|
|
84929
86488
|
);
|
|
84930
86489
|
})
|
|
84931
86490
|
);
|
|
@@ -84963,7 +86522,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
|
|
|
84963
86522
|
if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
|
|
84964
86523
|
amountUcdWei = detail.data.debtUcdWei;
|
|
84965
86524
|
} else {
|
|
84966
|
-
amountUcdWei = (0,
|
|
86525
|
+
amountUcdWei = (0, import_ethers51.parseEther)(amountUcd.toString()).toString();
|
|
84967
86526
|
}
|
|
84968
86527
|
return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
|
|
84969
86528
|
})
|
|
@@ -85364,7 +86923,7 @@ function registerPsmTools(server, getB) {
|
|
|
85364
86923
|
"psm_swap",
|
|
85365
86924
|
{
|
|
85366
86925
|
title: "Exchange UCD \u2194 a stablecoin through the PSM",
|
|
85367
|
-
description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as
|
|
86926
|
+
description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as explicit on-chain ceremonies, each signed by the session signer and all reported in the result: (1) the approvals the input token NEEDS, planned against its standing allowance \u2014 none when the allowance already covers the amount; one EXACT-AMOUNT approval when it is 0; a reset to 0 followed by the exact approval when a partial allowance stands. to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
|
|
85368
86927
|
inputSchema: {
|
|
85369
86928
|
stablecoin: import_zod4.z.string().min(1).describe(
|
|
85370
86929
|
"The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
|
|
@@ -85380,7 +86939,7 @@ function registerPsmTools(server, getB) {
|
|
|
85380
86939
|
const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
|
|
85381
86940
|
const gate = requireConfirmation(
|
|
85382
86941
|
confirmed,
|
|
85383
|
-
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (
|
|
86942
|
+
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (exact-amount approval if the standing allowance does not cover it, then ${direction === "to-ucd" ? "swap" : "redeem"})`
|
|
85384
86943
|
);
|
|
85385
86944
|
if (gate) return gate;
|
|
85386
86945
|
const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
|
|
@@ -85566,7 +87125,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
|
|
|
85566
87125
|
|
|
85567
87126
|
// src/tools/signer.ts
|
|
85568
87127
|
var import_zod6 = require("zod");
|
|
85569
|
-
var
|
|
87128
|
+
var import_ethers52 = require("ethers");
|
|
85570
87129
|
var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
85571
87130
|
var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
|
|
85572
87131
|
var EXTERNAL_ONLY_MODES = ["external"];
|
|
@@ -85608,7 +87167,7 @@ function registerSignerTool(server, getRuntime, opts) {
|
|
|
85608
87167
|
if (mode !== void 0 && !offeredModes.includes(mode)) {
|
|
85609
87168
|
return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
|
|
85610
87169
|
}
|
|
85611
|
-
if (safeAddress !== void 0 && !
|
|
87170
|
+
if (safeAddress !== void 0 && !import_ethers52.ethers.isAddress(safeAddress)) {
|
|
85612
87171
|
return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
|
|
85613
87172
|
}
|
|
85614
87173
|
if (action === "status") {
|