@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/boundary.js
CHANGED
|
@@ -15431,7 +15431,7 @@ ${errorReport}`);
|
|
|
15431
15431
|
}
|
|
15432
15432
|
init_debug_logger();
|
|
15433
15433
|
init_session_signature_cache();
|
|
15434
|
-
var
|
|
15434
|
+
var import_ethers49 = require("ethers");
|
|
15435
15435
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
15436
15436
|
var GRACE_PERIOD_DAYS = 30;
|
|
15437
15437
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -18347,12 +18347,12 @@ ${auth.clientId}`;
|
|
|
18347
18347
|
}
|
|
18348
18348
|
async function executeVaultSnapshot(params) {
|
|
18349
18349
|
global.ethers = {
|
|
18350
|
-
...
|
|
18350
|
+
...import_ethers49.ethers,
|
|
18351
18351
|
providers: {
|
|
18352
|
-
StaticJsonRpcProvider:
|
|
18352
|
+
StaticJsonRpcProvider: import_ethers49.ethers.JsonRpcProvider
|
|
18353
18353
|
},
|
|
18354
|
-
Contract:
|
|
18355
|
-
utils:
|
|
18354
|
+
Contract: import_ethers49.ethers.Contract,
|
|
18355
|
+
utils: import_ethers49.ethers
|
|
18356
18356
|
// v6 moved utils to top level
|
|
18357
18357
|
};
|
|
18358
18358
|
global.Lit = {
|
|
@@ -25561,7 +25561,10 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25561
25561
|
"node_modules/@gvnrdao/dh-lit-ops/dist/utils/lit-core-lit-action-client.js"(exports2) {
|
|
25562
25562
|
"use strict";
|
|
25563
25563
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
25564
|
+
exports2.CORE_API_TRANSPORT_FAILURE_MARKER = void 0;
|
|
25564
25565
|
exports2.normalizeCoreLitActionResult = normalizeCoreLitActionResult;
|
|
25566
|
+
exports2.describeErrorWithCause = describeErrorWithCause;
|
|
25567
|
+
exports2.isCoreApiTransportError = isCoreApiTransportError;
|
|
25565
25568
|
exports2.executeLitActionViaCoreApi = executeLitActionViaCoreApi;
|
|
25566
25569
|
var fetch_lit_action_from_ipfs_1 = require_fetch_lit_action_from_ipfs();
|
|
25567
25570
|
function parseResponsePayload(raw) {
|
|
@@ -25612,6 +25615,27 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25612
25615
|
const fromEnv = process.env.LIT_CORE_API_BASE_URL;
|
|
25613
25616
|
return (explicit || fromEnv || "https://api.chipotle.litprotocol.com").replace(/\/$/, "");
|
|
25614
25617
|
}
|
|
25618
|
+
exports2.CORE_API_TRANSPORT_FAILURE_MARKER = "Lit Core lit_action transport failure";
|
|
25619
|
+
function describeErrorWithCause(e) {
|
|
25620
|
+
const parts = [];
|
|
25621
|
+
let current = e;
|
|
25622
|
+
const seen = /* @__PURE__ */ new Set();
|
|
25623
|
+
while (current != null && !seen.has(current) && parts.length < 5) {
|
|
25624
|
+
seen.add(current);
|
|
25625
|
+
if (current instanceof Error) {
|
|
25626
|
+
const code = current.code;
|
|
25627
|
+
parts.push(typeof code === "string" && !current.message.includes(code) ? `${code}: ${current.message}` : current.message);
|
|
25628
|
+
current = current.cause;
|
|
25629
|
+
} else {
|
|
25630
|
+
parts.push(String(current));
|
|
25631
|
+
break;
|
|
25632
|
+
}
|
|
25633
|
+
}
|
|
25634
|
+
return parts.length === 0 ? String(e) : parts.join(" <- ");
|
|
25635
|
+
}
|
|
25636
|
+
function isCoreApiTransportError(message) {
|
|
25637
|
+
return message.includes(exports2.CORE_API_TRANSPORT_FAILURE_MARKER);
|
|
25638
|
+
}
|
|
25615
25639
|
async function executeLitActionViaCoreApi(options) {
|
|
25616
25640
|
let resolvedCode = options.code || "";
|
|
25617
25641
|
if (!resolvedCode.trim()) {
|
|
@@ -25673,13 +25697,11 @@ var require_lit_core_lit_action_client = __commonJS({
|
|
|
25673
25697
|
return normalizeCoreLitActionResult(body);
|
|
25674
25698
|
} catch (e) {
|
|
25675
25699
|
const msg = e instanceof Error ? e.message : String(e);
|
|
25700
|
+
const error = msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : `${exports2.CORE_API_TRANSPORT_FAILURE_MARKER}: ${describeErrorWithCause(e)}`;
|
|
25676
25701
|
if (options.debug) {
|
|
25677
|
-
console.error("\u274C [executeLitActionViaCoreApi]",
|
|
25702
|
+
console.error("\u274C [executeLitActionViaCoreApi]", error);
|
|
25678
25703
|
}
|
|
25679
|
-
return {
|
|
25680
|
-
success: false,
|
|
25681
|
-
error: msg.includes("abort") ? `Lit Core lit_action timed out after ${timeoutMs}ms` : msg
|
|
25682
|
-
};
|
|
25704
|
+
return { success: false, error };
|
|
25683
25705
|
} finally {
|
|
25684
25706
|
clearTimeout(timer);
|
|
25685
25707
|
}
|
|
@@ -26661,7 +26683,8 @@ var require_lit_ops_module = __commonJS({
|
|
|
26661
26683
|
const borrowerAddress = borrowerOverride ?? this.config.serverAddress ?? await this.config.signer.getAddress();
|
|
26662
26684
|
const pkpValidatorInfo = DH_LIT_ACTIONS_CHIPOTLE.pkpValidator;
|
|
26663
26685
|
const validatorWalletAddress = process.env.LIT_PKP_VALIDATOR_WALLET_OVERRIDE || pkpValidatorInfo?.validatorWalletAddress;
|
|
26664
|
-
const
|
|
26686
|
+
const errorMessage = (e) => e instanceof Error ? e.message : String(e);
|
|
26687
|
+
const isWalletPropagationError = (e) => /cannot use selected wallet in selected action/i.test(errorMessage(e));
|
|
26665
26688
|
const propagationRetries = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_RETRIES) || 8;
|
|
26666
26689
|
const propagationDelayMs = Number(process.env.LIT_PKP_VALIDATOR_PROPAGATION_DELAY_MS) || 15e3;
|
|
26667
26690
|
let coreResponse;
|
|
@@ -26682,10 +26705,12 @@ var require_lit_ops_module = __commonJS({
|
|
|
26682
26705
|
coreResponse = exec.response;
|
|
26683
26706
|
break;
|
|
26684
26707
|
} catch (e) {
|
|
26685
|
-
|
|
26708
|
+
const propagating = isWalletPropagationError(e);
|
|
26709
|
+
const transport = (0, lit_core_lit_action_client_1.isCoreApiTransportError)(errorMessage(e));
|
|
26710
|
+
if (!propagating && !transport || attempt === propagationRetries) {
|
|
26686
26711
|
throw e;
|
|
26687
26712
|
}
|
|
26688
|
-
console.log(`[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
|
|
26713
|
+
console.log(propagating ? `[ChipotlePKP] vault PKP ${pkpId} not yet authorized on Chipotle (Base\u2192TEE propagation); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms` : `[ChipotlePKP] vault PKP ${pkpId} validator call failed in transport (${errorMessage(e)}); retry ${attempt}/${propagationRetries} in ${propagationDelayMs}ms`);
|
|
26689
26714
|
await new Promise((r) => setTimeout(r, propagationDelayMs));
|
|
26690
26715
|
}
|
|
26691
26716
|
}
|
|
@@ -40410,7 +40435,7 @@ var require_dist3 = __commonJS({
|
|
|
40410
40435
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
|
|
40411
40436
|
};
|
|
40412
40437
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
40413
|
-
exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
|
|
40438
|
+
exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
|
|
40414
40439
|
__exportStar(require_interfaces(), exports2);
|
|
40415
40440
|
var dh_lit_actions_1 = require_pkg_src();
|
|
40416
40441
|
Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
|
|
@@ -40480,6 +40505,15 @@ var require_dist3 = __commonJS({
|
|
|
40480
40505
|
Object.defineProperty(exports2, "normalizeCoreLitActionResult", { enumerable: true, get: function() {
|
|
40481
40506
|
return lit_core_lit_action_client_1.normalizeCoreLitActionResult;
|
|
40482
40507
|
} });
|
|
40508
|
+
Object.defineProperty(exports2, "describeErrorWithCause", { enumerable: true, get: function() {
|
|
40509
|
+
return lit_core_lit_action_client_1.describeErrorWithCause;
|
|
40510
|
+
} });
|
|
40511
|
+
Object.defineProperty(exports2, "isCoreApiTransportError", { enumerable: true, get: function() {
|
|
40512
|
+
return lit_core_lit_action_client_1.isCoreApiTransportError;
|
|
40513
|
+
} });
|
|
40514
|
+
Object.defineProperty(exports2, "CORE_API_TRANSPORT_FAILURE_MARKER", { enumerable: true, get: function() {
|
|
40515
|
+
return lit_core_lit_action_client_1.CORE_API_TRANSPORT_FAILURE_MARKER;
|
|
40516
|
+
} });
|
|
40483
40517
|
var bitcoin_signature_1 = require_bitcoin_signature();
|
|
40484
40518
|
Object.defineProperty(exports2, "convertEthereumSignatureToBitcoinDER", { enumerable: true, get: function() {
|
|
40485
40519
|
return bitcoin_signature_1.convertEthereumSignatureToBitcoinDER;
|
|
@@ -41043,7 +41077,7 @@ var BoundaryCore = class {
|
|
|
41043
41077
|
const inToken = toUcd ? s.stablecoinSymbol : "UCD";
|
|
41044
41078
|
const inUnit = toUcd ? `${s.stablecoinSymbol} smallest units (${s.stablecoinDecimals} decimals)` : "UCD wei (18 decimals)";
|
|
41045
41079
|
const amountIn = parseDecimalUnits(p.amount, inDecimals);
|
|
41046
|
-
const
|
|
41080
|
+
const refuse3 = (refusal, message, details) => ({
|
|
41047
41081
|
env: errEnvelope(
|
|
41048
41082
|
boundaryError("UPSTREAM_REJECTED", message, {
|
|
41049
41083
|
source: statusR.source.id,
|
|
@@ -41054,13 +41088,13 @@ var BoundaryCore = class {
|
|
|
41054
41088
|
});
|
|
41055
41089
|
const named = (units) => `${formatDecimalUnits(units, inDecimals)} ${inToken} (${units} ${inUnit})`;
|
|
41056
41090
|
if (s.paused) {
|
|
41057
|
-
return
|
|
41091
|
+
return refuse3(
|
|
41058
41092
|
"psm-paused",
|
|
41059
41093
|
"the PSM is paused \u2014 BOTH exchange directions are disabled until an operator unpauses it (this is the PSM's own pause switch)."
|
|
41060
41094
|
);
|
|
41061
41095
|
}
|
|
41062
41096
|
if (!toUcd && !s.redeemEnabled) {
|
|
41063
|
-
return
|
|
41097
|
+
return refuse3(
|
|
41064
41098
|
"redeem-disabled",
|
|
41065
41099
|
`redemptions are disabled (redeemEnabled = false) \u2014 UCD -> ${s.stablecoinSymbol} is refused; ${s.stablecoinSymbol} -> UCD swaps are unaffected.`
|
|
41066
41100
|
);
|
|
@@ -41071,20 +41105,20 @@ var BoundaryCore = class {
|
|
|
41071
41105
|
const min = BigInt(toUcd ? s.minSwapAmount : s.minRedeemAmount);
|
|
41072
41106
|
const max = BigInt(toUcd ? s.maxSwapAmount : s.maxRedeemAmount);
|
|
41073
41107
|
if (amountIn < min) {
|
|
41074
|
-
return
|
|
41108
|
+
return refuse3(
|
|
41075
41109
|
"below-min",
|
|
41076
41110
|
`${named(amountIn)} is below the minimum of ${named(min)} for the ${p.direction} direction.`,
|
|
41077
41111
|
{ amount: amountIn.toString(), minimum: min.toString(), unit: inUnit }
|
|
41078
41112
|
);
|
|
41079
41113
|
}
|
|
41080
41114
|
if (max === 0n) {
|
|
41081
|
-
return
|
|
41115
|
+
return refuse3(
|
|
41082
41116
|
"direction-disabled",
|
|
41083
41117
|
`the ${p.direction} direction is DISABLED by configuration (${toUcd ? "maxSwapAmount" : "maxRedeemAmount"} is 0).`
|
|
41084
41118
|
);
|
|
41085
41119
|
}
|
|
41086
41120
|
if (amountIn > max) {
|
|
41087
|
-
return
|
|
41121
|
+
return refuse3(
|
|
41088
41122
|
"above-max",
|
|
41089
41123
|
`${named(amountIn)} is above the maximum of ${named(max)} per operation for the ${p.direction} direction.`,
|
|
41090
41124
|
{ amount: amountIn.toString(), maximum: max.toString(), unit: inUnit }
|
|
@@ -41104,7 +41138,7 @@ var BoundaryCore = class {
|
|
|
41104
41138
|
if (!toUcd) {
|
|
41105
41139
|
const available = BigInt(s.availableReserves);
|
|
41106
41140
|
if (available < amountOut) {
|
|
41107
|
-
return
|
|
41141
|
+
return refuse3(
|
|
41108
41142
|
"insufficient-reserves",
|
|
41109
41143
|
`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).`,
|
|
41110
41144
|
{ available: available.toString(), required: amountOut.toString(), unit: outUnit }
|
|
@@ -41180,20 +41214,31 @@ var BoundaryCore = class {
|
|
|
41180
41214
|
const inDecimals = toUcd ? s.stablecoinDecimals : 18;
|
|
41181
41215
|
const outDecimals = toUcd ? 18 : s.stablecoinDecimals;
|
|
41182
41216
|
const viaSafe = this.deps.signer?.mode() === "safe";
|
|
41217
|
+
const a = v.allowance;
|
|
41218
|
+
const fmtIn = (units) => `${formatDecimalUnits(BigInt(units), inDecimals)} ${a.tokenSymbol}`;
|
|
41219
|
+
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(
|
|
41220
|
+
(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}`
|
|
41221
|
+
).map((text, i) => `Ceremony ${i + 1}: ${text}.`).join(" ");
|
|
41183
41222
|
const data = {
|
|
41184
41223
|
direction: p.direction,
|
|
41185
41224
|
contractCall: q.contractCall,
|
|
41186
|
-
|
|
41187
|
-
|
|
41188
|
-
|
|
41189
|
-
|
|
41190
|
-
|
|
41191
|
-
|
|
41192
|
-
|
|
41193
|
-
amount: v.approve.amount,
|
|
41225
|
+
allowance: {
|
|
41226
|
+
token: a.tokenSymbol,
|
|
41227
|
+
tokenAddress: a.tokenAddress,
|
|
41228
|
+
spenderAddress: a.spenderAddress,
|
|
41229
|
+
spenderContract: a.spenderContract,
|
|
41230
|
+
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",
|
|
41231
|
+
before: a.before,
|
|
41194
41232
|
amountUnit: q.amountInUnit,
|
|
41195
|
-
|
|
41233
|
+
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."
|
|
41196
41234
|
},
|
|
41235
|
+
approvals: v.approvals.map((leg) => ({
|
|
41236
|
+
step: leg.step,
|
|
41237
|
+
txRef: leg.txRef,
|
|
41238
|
+
amount: leg.amount,
|
|
41239
|
+
amountUnit: q.amountInUnit,
|
|
41240
|
+
authorization: leg.authorization
|
|
41241
|
+
})),
|
|
41197
41242
|
execute: {
|
|
41198
41243
|
txRef: v.execute.txRef,
|
|
41199
41244
|
amountIn: v.execute.amountIn,
|
|
@@ -41215,7 +41260,7 @@ var BoundaryCore = class {
|
|
|
41215
41260
|
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"
|
|
41216
41261
|
},
|
|
41217
41262
|
balancesAfter: v.balancesAfter ? { ucdWei: v.balancesAfter.ucdWei, usdcUnits: v.balancesAfter.stablecoinUnits } : null,
|
|
41218
|
-
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}).
|
|
41263
|
+
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}.`)
|
|
41219
41264
|
};
|
|
41220
41265
|
return okEnvelope(data, r.source, warnings);
|
|
41221
41266
|
}
|
|
@@ -43074,6 +43119,16 @@ function buildExtendTx(ctx, p) {
|
|
|
43074
43119
|
);
|
|
43075
43120
|
}
|
|
43076
43121
|
|
|
43122
|
+
// src/boundary/upstream/shared/psm-approval-steps.ts
|
|
43123
|
+
function psmApprovalSteps(allowanceBefore, amountIn) {
|
|
43124
|
+
if (allowanceBefore >= amountIn) return [];
|
|
43125
|
+
if (allowanceBefore === 0n) return [{ step: "approve", amount: amountIn }];
|
|
43126
|
+
return [
|
|
43127
|
+
{ step: "reset-approve", amount: 0n },
|
|
43128
|
+
{ step: "approve", amount: amountIn }
|
|
43129
|
+
];
|
|
43130
|
+
}
|
|
43131
|
+
|
|
43077
43132
|
// src/boundary/upstream/mock/sink-contracts.ts
|
|
43078
43133
|
var import_ethers5 = require("ethers");
|
|
43079
43134
|
function sinkAddress(label) {
|
|
@@ -43900,8 +43955,9 @@ var MockUpstreamPlugin = class {
|
|
|
43900
43955
|
return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
|
|
43901
43956
|
});
|
|
43902
43957
|
}
|
|
43903
|
-
/** PSM exchange
|
|
43904
|
-
* approve
|
|
43958
|
+
/** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
|
|
43959
|
+
* or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
|
|
43960
|
+
* asymmetric by direction, contract truth), then the swap/redeem with
|
|
43905
43961
|
* its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
|
|
43906
43962
|
* AFTER the approve reports the step that declined AND the residual exact-amount
|
|
43907
43963
|
* allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
|
|
@@ -43920,55 +43976,75 @@ var MockUpstreamPlugin = class {
|
|
|
43920
43976
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
43921
43977
|
const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
|
|
43922
43978
|
const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
|
|
43923
|
-
const
|
|
43924
|
-
const
|
|
43979
|
+
const standing = this.world.psmAllowancesOf(p.borrower);
|
|
43980
|
+
const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
|
|
43981
|
+
const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
|
|
43982
|
+
const landed = [];
|
|
43983
|
+
const residualNote = () => {
|
|
43984
|
+
const last = landed[landed.length - 1];
|
|
43985
|
+
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`;
|
|
43986
|
+
return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
43987
|
+
};
|
|
43925
43988
|
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}`;
|
|
43926
43989
|
const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
|
|
43927
43990
|
const cer = this.ceremonyNow();
|
|
43928
|
-
|
|
43929
|
-
|
|
43930
|
-
const
|
|
43931
|
-
const
|
|
43932
|
-
const
|
|
43933
|
-
|
|
43934
|
-
|
|
43935
|
-
|
|
43936
|
-
|
|
43937
|
-
|
|
43938
|
-
|
|
43939
|
-
|
|
43940
|
-
|
|
43941
|
-
|
|
43942
|
-
|
|
43991
|
+
const approvals = [];
|
|
43992
|
+
for (const s of steps) {
|
|
43993
|
+
const amount = s.amount.toString();
|
|
43994
|
+
const isReset = s.step === "reset-approve";
|
|
43995
|
+
const label = isReset ? "RESET-APPROVE" : "APPROVE";
|
|
43996
|
+
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";
|
|
43997
|
+
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})`;
|
|
43998
|
+
let legAuth = null;
|
|
43999
|
+
if (cer) {
|
|
44000
|
+
const chainId = cer.txContext().chainId;
|
|
44001
|
+
const r = await cer.authorizeTx({
|
|
44002
|
+
action: "psm-approve",
|
|
44003
|
+
borrower: p.borrower,
|
|
44004
|
+
tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
|
|
44005
|
+
expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
|
|
43943
44006
|
});
|
|
44007
|
+
if (!r.ok) {
|
|
44008
|
+
return upFail({
|
|
44009
|
+
kind: "rejected",
|
|
44010
|
+
source: "mock-ops",
|
|
44011
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
|
|
44012
|
+
});
|
|
44013
|
+
}
|
|
44014
|
+
this.bindIfDiscovering(r.authorization);
|
|
44015
|
+
legAuth = r.authorization;
|
|
43944
44016
|
}
|
|
43945
|
-
this.
|
|
43946
|
-
|
|
43947
|
-
|
|
43948
|
-
|
|
43949
|
-
|
|
43950
|
-
|
|
43951
|
-
|
|
43952
|
-
|
|
43953
|
-
|
|
43954
|
-
|
|
44017
|
+
const leg = await this.write("psmSwap", () => {
|
|
44018
|
+
const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
|
|
44019
|
+
if (!sig.ok) {
|
|
44020
|
+
return upFail({
|
|
44021
|
+
kind: "rejected",
|
|
44022
|
+
source: "mock-ops",
|
|
44023
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
|
|
44024
|
+
});
|
|
44025
|
+
}
|
|
44026
|
+
const applied = this.applyAuthorized(sig.authorization, () => {
|
|
44027
|
+
this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
|
|
44028
|
+
return { ok: true, value: void 0 };
|
|
43955
44029
|
});
|
|
43956
|
-
|
|
43957
|
-
|
|
43958
|
-
|
|
43959
|
-
|
|
44030
|
+
if (!applied.ok) {
|
|
44031
|
+
return upFail({
|
|
44032
|
+
kind: "rejected",
|
|
44033
|
+
source: "mock-ops",
|
|
44034
|
+
message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
|
|
44035
|
+
});
|
|
44036
|
+
}
|
|
44037
|
+
return upOk(sig.authorization, this.src("mock-ops"));
|
|
43960
44038
|
});
|
|
43961
|
-
if (!
|
|
43962
|
-
|
|
43963
|
-
|
|
43964
|
-
|
|
43965
|
-
|
|
43966
|
-
|
|
43967
|
-
|
|
43968
|
-
|
|
43969
|
-
}
|
|
43970
|
-
if (!step1.ok) return step1;
|
|
43971
|
-
const aAuth = step1.value;
|
|
44039
|
+
if (!leg.ok) return leg;
|
|
44040
|
+
landed.push(s.step);
|
|
44041
|
+
approvals.push({
|
|
44042
|
+
step: s.step,
|
|
44043
|
+
txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
|
|
44044
|
+
amount,
|
|
44045
|
+
authorization: leg.value
|
|
44046
|
+
});
|
|
44047
|
+
}
|
|
43972
44048
|
let executeAuth = null;
|
|
43973
44049
|
if (cer) {
|
|
43974
44050
|
const chainId = cer.txContext().chainId;
|
|
@@ -43983,7 +44059,7 @@ var MockUpstreamPlugin = class {
|
|
|
43983
44059
|
return upFail({
|
|
43984
44060
|
kind: "rejected",
|
|
43985
44061
|
source: "mock-ops",
|
|
43986
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
|
|
44062
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
|
|
43987
44063
|
});
|
|
43988
44064
|
}
|
|
43989
44065
|
executeAuth = r.authorization;
|
|
@@ -43994,23 +44070,16 @@ var MockUpstreamPlugin = class {
|
|
|
43994
44070
|
return upFail({
|
|
43995
44071
|
kind: "rejected",
|
|
43996
44072
|
source: "mock-ops",
|
|
43997
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
|
|
44073
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
|
|
43998
44074
|
});
|
|
43999
44075
|
}
|
|
44000
44076
|
const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
|
|
44001
|
-
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
|
|
44077
|
+
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
|
|
44002
44078
|
const bal = this.world.balancesOf(p.borrower);
|
|
44003
44079
|
return upOk(
|
|
44004
44080
|
{
|
|
44005
|
-
|
|
44006
|
-
|
|
44007
|
-
tokenSymbol,
|
|
44008
|
-
tokenAddress,
|
|
44009
|
-
spenderAddress,
|
|
44010
|
-
spenderContract,
|
|
44011
|
-
amount: p.amountIn,
|
|
44012
|
-
authorization: aAuth
|
|
44013
|
-
},
|
|
44081
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
44082
|
+
approvals,
|
|
44014
44083
|
execute: {
|
|
44015
44084
|
txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
|
|
44016
44085
|
amountIn: p.amountIn,
|
|
@@ -45191,7 +45260,7 @@ var SafeModuleCeremony = class {
|
|
|
45191
45260
|
};
|
|
45192
45261
|
|
|
45193
45262
|
// src/boundary/upstream/real/plugin.ts
|
|
45194
|
-
var
|
|
45263
|
+
var import_ethers48 = require("ethers");
|
|
45195
45264
|
|
|
45196
45265
|
// node_modules/@gvnrdao/dh-sdk/dist/index.mjs
|
|
45197
45266
|
var import_ethers13 = require("ethers");
|
|
@@ -51282,8 +51351,12 @@ var {
|
|
|
51282
51351
|
var import_ethers27 = require("ethers");
|
|
51283
51352
|
var import_ethers28 = require("ethers");
|
|
51284
51353
|
var import_ethers29 = require("ethers");
|
|
51285
|
-
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
51286
51354
|
var import_ethers30 = require("ethers");
|
|
51355
|
+
var import_ethers31 = require("ethers");
|
|
51356
|
+
var import_ethers32 = require("ethers");
|
|
51357
|
+
var import_ethers33 = require("ethers");
|
|
51358
|
+
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
51359
|
+
var import_ethers34 = require("ethers");
|
|
51287
51360
|
var __create2 = Object.create;
|
|
51288
51361
|
var __defProp2 = Object.defineProperty;
|
|
51289
51362
|
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
@@ -53646,7 +53719,7 @@ ${errorReport}`);
|
|
|
53646
53719
|
}
|
|
53647
53720
|
init_debug_logger();
|
|
53648
53721
|
init_session_signature_cache();
|
|
53649
|
-
var
|
|
53722
|
+
var import_ethers232 = __require("ethers");
|
|
53650
53723
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
53651
53724
|
var GRACE_PERIOD_DAYS = 30;
|
|
53652
53725
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -56574,12 +56647,12 @@ ${auth.clientId}`;
|
|
|
56574
56647
|
}
|
|
56575
56648
|
async function executeVaultSnapshot(params) {
|
|
56576
56649
|
global.ethers = {
|
|
56577
|
-
...
|
|
56650
|
+
...import_ethers232.ethers,
|
|
56578
56651
|
providers: {
|
|
56579
|
-
StaticJsonRpcProvider:
|
|
56652
|
+
StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
|
|
56580
56653
|
},
|
|
56581
|
-
Contract:
|
|
56582
|
-
utils:
|
|
56654
|
+
Contract: import_ethers232.ethers.Contract,
|
|
56655
|
+
utils: import_ethers232.ethers
|
|
56583
56656
|
// v6 moved utils to top level
|
|
56584
56657
|
};
|
|
56585
56658
|
global.Lit = {
|
|
@@ -56833,8 +56906,8 @@ function getSepoliaConfig() {
|
|
|
56833
56906
|
positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
|
|
56834
56907
|
positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
|
|
56835
56908
|
simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
|
|
56836
|
-
mockUsdcToken: SEPOLIA_CONTRACTS
|
|
56837
|
-
mockUsdtToken: SEPOLIA_CONTRACTS
|
|
56909
|
+
mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
|
|
56910
|
+
mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
|
|
56838
56911
|
loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
|
|
56839
56912
|
termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
|
|
56840
56913
|
circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
|
|
@@ -56910,14 +56983,17 @@ function getMainnetConfig() {
|
|
|
56910
56983
|
agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
|
|
56911
56984
|
},
|
|
56912
56985
|
subgraphs: {
|
|
56913
|
-
//
|
|
56914
|
-
//
|
|
56915
|
-
//
|
|
56916
|
-
//
|
|
56917
|
-
//
|
|
56918
|
-
//
|
|
56919
|
-
//
|
|
56920
|
-
|
|
56986
|
+
// The MAINNET subgraph on The Graph's decentralized network — the same id
|
|
56987
|
+
// lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
|
|
56988
|
+
// the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
|
|
56989
|
+
// chainId-1 config: unusable as shipped, but a caller who added their own key would have
|
|
56990
|
+
// read Sepolia data as mainnet.
|
|
56991
|
+
//
|
|
56992
|
+
// The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
|
|
56993
|
+
// not) hold, so this URL only works for a standalone caller supplying their own key.
|
|
56994
|
+
// Service mode never uses it — queries go through the lit-ops-server proxy, which adds
|
|
56995
|
+
// the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
|
|
56996
|
+
diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
|
|
56921
56997
|
},
|
|
56922
56998
|
litNetwork: "chipotle",
|
|
56923
56999
|
debug: false
|
|
@@ -57938,6 +58014,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
|
|
|
57938
58014
|
}
|
|
57939
58015
|
return { timestamp: result.timestamp, signature: result.signature };
|
|
57940
58016
|
}
|
|
58017
|
+
function baseMintFeeWei(mintAmountWei, originationFeeBps) {
|
|
58018
|
+
if (mintAmountWei < 0n)
|
|
58019
|
+
throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
|
|
58020
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
58021
|
+
throw new Error(
|
|
58022
|
+
`baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
58023
|
+
);
|
|
58024
|
+
}
|
|
58025
|
+
return mintAmountWei * BigInt(originationFeeBps) / 10000n;
|
|
58026
|
+
}
|
|
58027
|
+
function debtAfterMintExceedsLoanCap(params) {
|
|
58028
|
+
const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
|
|
58029
|
+
for (const [name, v] of Object.entries(params)) {
|
|
58030
|
+
if (v < 0n)
|
|
58031
|
+
throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
|
|
58032
|
+
}
|
|
58033
|
+
return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
|
|
58034
|
+
}
|
|
58035
|
+
function maxPrincipalWithinLoanCap(params) {
|
|
58036
|
+
const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
|
|
58037
|
+
if (maxLoanWei < 0n || currentDebtWei < 0n) {
|
|
58038
|
+
throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
|
|
58039
|
+
}
|
|
58040
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
58041
|
+
throw new Error(
|
|
58042
|
+
`maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
58043
|
+
);
|
|
58044
|
+
}
|
|
58045
|
+
const room = maxLoanWei - currentDebtWei;
|
|
58046
|
+
if (room <= 0n)
|
|
58047
|
+
return 0n;
|
|
58048
|
+
return room * 10000n / (10000n + BigInt(originationFeeBps));
|
|
58049
|
+
}
|
|
57941
58050
|
function buildLoginDomain(chainId) {
|
|
57942
58051
|
return {
|
|
57943
58052
|
name: "Diamond Hands",
|
|
@@ -59347,23 +59456,37 @@ var BitcoinUtils = class {
|
|
|
59347
59456
|
return getBitcoinAddressesFromPkp(pkpPublicKey);
|
|
59348
59457
|
}
|
|
59349
59458
|
};
|
|
59350
|
-
function
|
|
59459
|
+
function networksOfValidAddress(address) {
|
|
59460
|
+
const lower2 = address.toLowerCase();
|
|
59461
|
+
if (lower2.startsWith("bcrt1"))
|
|
59462
|
+
return ["regtest"];
|
|
59463
|
+
if (lower2.startsWith("bc1"))
|
|
59464
|
+
return ["mainnet"];
|
|
59465
|
+
if (lower2.startsWith("tb1"))
|
|
59466
|
+
return ["testnet"];
|
|
59467
|
+
if (address.startsWith("1") || address.startsWith("3"))
|
|
59468
|
+
return ["mainnet"];
|
|
59469
|
+
return ["testnet", "regtest"];
|
|
59470
|
+
}
|
|
59471
|
+
function safeValidateBitcoinAddress(address, network) {
|
|
59351
59472
|
if (!address || typeof address !== "string") {
|
|
59352
59473
|
throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
|
|
59353
59474
|
}
|
|
59354
|
-
|
|
59355
|
-
|
|
59356
|
-
|
|
59357
|
-
|
|
59475
|
+
if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
|
|
59476
|
+
throw new Error(
|
|
59477
|
+
`Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
|
|
59478
|
+
);
|
|
59358
59479
|
}
|
|
59359
|
-
if (
|
|
59360
|
-
|
|
59361
|
-
|
|
59362
|
-
|
|
59363
|
-
}
|
|
59364
|
-
|
|
59365
|
-
|
|
59366
|
-
|
|
59480
|
+
if (!BitcoinUtils.validateAddress(address)) {
|
|
59481
|
+
throw new Error(
|
|
59482
|
+
`Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
|
|
59483
|
+
);
|
|
59484
|
+
}
|
|
59485
|
+
const belongsTo = networksOfValidAddress(address);
|
|
59486
|
+
if (!belongsTo.includes(network)) {
|
|
59487
|
+
throw new Error(
|
|
59488
|
+
`Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
|
|
59489
|
+
);
|
|
59367
59490
|
}
|
|
59368
59491
|
return address;
|
|
59369
59492
|
}
|
|
@@ -61472,6 +61595,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
|
|
|
61472
61595
|
LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
|
|
61473
61596
|
return LoanStatus2;
|
|
61474
61597
|
})(LoanStatus || {});
|
|
61598
|
+
var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
|
|
61599
|
+
var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
|
|
61600
|
+
var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
|
|
61601
|
+
async function collectBorrowerDebtRows(fetchPage) {
|
|
61602
|
+
const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
|
|
61603
|
+
const rows = [];
|
|
61604
|
+
for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
|
|
61605
|
+
const batch = await fetchPage(page * pageSize, pageSize);
|
|
61606
|
+
if (batch.length > pageSize) {
|
|
61607
|
+
throw new Error(
|
|
61608
|
+
`Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
|
|
61609
|
+
);
|
|
61610
|
+
}
|
|
61611
|
+
rows.push(...batch);
|
|
61612
|
+
if (batch.length < pageSize) {
|
|
61613
|
+
return rows;
|
|
61614
|
+
}
|
|
61615
|
+
}
|
|
61616
|
+
throw new Error(
|
|
61617
|
+
`Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
|
|
61618
|
+
);
|
|
61619
|
+
}
|
|
61620
|
+
function parseSubgraphLoanStatus(label) {
|
|
61621
|
+
if (typeof label !== "string") {
|
|
61622
|
+
throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
|
|
61623
|
+
}
|
|
61624
|
+
const value = LoanStatus[label];
|
|
61625
|
+
if (typeof value !== "number") {
|
|
61626
|
+
throw new Error(`Unknown subgraph loan status label: "${label}"`);
|
|
61627
|
+
}
|
|
61628
|
+
return value;
|
|
61629
|
+
}
|
|
61630
|
+
function parseSubgraphWei(row) {
|
|
61631
|
+
const raw = row.ucdDebt || "0";
|
|
61632
|
+
if (typeof raw !== "string") {
|
|
61633
|
+
throw new Error(
|
|
61634
|
+
`ucdDebt on position ${row.id} is not a string: ${String(raw)}`
|
|
61635
|
+
);
|
|
61636
|
+
}
|
|
61637
|
+
let wei;
|
|
61638
|
+
try {
|
|
61639
|
+
wei = BigInt(raw);
|
|
61640
|
+
} catch (error) {
|
|
61641
|
+
throw new Error(
|
|
61642
|
+
`ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
|
|
61643
|
+
{ cause: error }
|
|
61644
|
+
);
|
|
61645
|
+
}
|
|
61646
|
+
if (wei < 0n) {
|
|
61647
|
+
throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
|
|
61648
|
+
}
|
|
61649
|
+
return wei;
|
|
61650
|
+
}
|
|
61651
|
+
var WEI_PER_UCD = 10n ** 18n;
|
|
61652
|
+
function weiToHumanUcdString(wei) {
|
|
61653
|
+
if (wei < 0n) {
|
|
61654
|
+
throw new Error(`Cannot render negative wei: ${wei}`);
|
|
61655
|
+
}
|
|
61656
|
+
const whole = wei / WEI_PER_UCD;
|
|
61657
|
+
const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
|
|
61658
|
+
return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
|
|
61659
|
+
}
|
|
61660
|
+
var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
|
|
61661
|
+
function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
|
|
61662
|
+
let totalWei = 0n;
|
|
61663
|
+
const counts = /* @__PURE__ */ new Map();
|
|
61664
|
+
for (const row of rows) {
|
|
61665
|
+
totalWei += parseSubgraphWei(row);
|
|
61666
|
+
const status = parseSubgraphLoanStatus(row.status);
|
|
61667
|
+
counts.set(status, (counts.get(status) ?? 0) + 1);
|
|
61668
|
+
}
|
|
61669
|
+
const byStatus = [];
|
|
61670
|
+
for (const status of STATUS_ORDINALS) {
|
|
61671
|
+
const count = counts.get(status);
|
|
61672
|
+
if (count === void 0) {
|
|
61673
|
+
continue;
|
|
61674
|
+
}
|
|
61675
|
+
byStatus.push({ status, statusLabel: LoanStatus[status], count });
|
|
61676
|
+
}
|
|
61677
|
+
return {
|
|
61678
|
+
borrower: borrower.toLowerCase(),
|
|
61679
|
+
loanCount: rows.length,
|
|
61680
|
+
totalUcdDebt: totalWei.toString(),
|
|
61681
|
+
totalUcdDebtHuman: weiToHumanUcdString(totalWei),
|
|
61682
|
+
byStatus,
|
|
61683
|
+
source: "subgraph",
|
|
61684
|
+
fetchedAt
|
|
61685
|
+
};
|
|
61686
|
+
}
|
|
61475
61687
|
var POSITION_CORE_ABI = [
|
|
61476
61688
|
"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))"
|
|
61477
61689
|
];
|
|
@@ -61864,6 +62076,43 @@ var LoanQuery = class {
|
|
|
61864
62076
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
61865
62077
|
return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
|
|
61866
62078
|
}
|
|
62079
|
+
/**
|
|
62080
|
+
* Combined UCD debt + by-status counts for a borrower from ONE pass over the
|
|
62081
|
+
* subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
|
|
62082
|
+
* status labels, `source: "subgraph"`.
|
|
62083
|
+
*
|
|
62084
|
+
* INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
|
|
62085
|
+
* sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
|
|
62086
|
+
* failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
|
|
62087
|
+
* is no partial total.
|
|
62088
|
+
*/
|
|
62089
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
62090
|
+
const trimmed = typeof borrower === "string" ? borrower.trim() : "";
|
|
62091
|
+
if (!(0, import_ethers25.isAddress)(trimmed)) {
|
|
62092
|
+
return failure(
|
|
62093
|
+
new SDKError({
|
|
62094
|
+
message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
|
|
62095
|
+
category: "VALIDATION",
|
|
62096
|
+
severity: "LOW",
|
|
62097
|
+
context: { borrower: trimmed }
|
|
62098
|
+
})
|
|
62099
|
+
);
|
|
62100
|
+
}
|
|
62101
|
+
return tryCatchAsync(
|
|
62102
|
+
async () => {
|
|
62103
|
+
const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
|
|
62104
|
+
return buildBorrowerUcdDebtSummary(trimmed, rows);
|
|
62105
|
+
},
|
|
62106
|
+
(error) => error instanceof SDKError ? error : new SDKError({
|
|
62107
|
+
message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
|
|
62108
|
+
category: "SUBGRAPH",
|
|
62109
|
+
severity: "MEDIUM",
|
|
62110
|
+
originalError: error instanceof Error ? error : void 0,
|
|
62111
|
+
cause: error,
|
|
62112
|
+
context: { borrower: trimmed }
|
|
62113
|
+
})
|
|
62114
|
+
);
|
|
62115
|
+
}
|
|
61867
62116
|
/**
|
|
61868
62117
|
* Get active loans (status = ACTIVE)
|
|
61869
62118
|
*
|
|
@@ -63389,7 +63638,35 @@ var GraphClient = class {
|
|
|
63389
63638
|
await new Promise((r) => setTimeout(r, ms));
|
|
63390
63639
|
}
|
|
63391
63640
|
};
|
|
63392
|
-
var
|
|
63641
|
+
var GET_USER_POSITIONS_DOCUMENT = `
|
|
63642
|
+
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
63643
|
+
user(id: $borrower) {
|
|
63644
|
+
id
|
|
63645
|
+
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
63646
|
+
id
|
|
63647
|
+
pkpId
|
|
63648
|
+
borrower {
|
|
63649
|
+
createdAt
|
|
63650
|
+
id
|
|
63651
|
+
}
|
|
63652
|
+
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
63653
|
+
ucdMinted
|
|
63654
|
+
ucdPaid
|
|
63655
|
+
ucdDebt
|
|
63656
|
+
collateralRatio
|
|
63657
|
+
requestedCollateralRatio
|
|
63658
|
+
selectedTerm
|
|
63659
|
+
status
|
|
63660
|
+
createdAt
|
|
63661
|
+
createdAtBlock
|
|
63662
|
+
lastUpdated
|
|
63663
|
+
originalTerm
|
|
63664
|
+
remainingDebt
|
|
63665
|
+
expiryAt
|
|
63666
|
+
}
|
|
63667
|
+
}
|
|
63668
|
+
}
|
|
63669
|
+
`;
|
|
63393
63670
|
function normalizePkpId2(pkpId) {
|
|
63394
63671
|
const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
|
|
63395
63672
|
if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
|
|
@@ -63707,35 +63984,7 @@ var DiamondHandsGraph = class {
|
|
|
63707
63984
|
* Get user positions from subgraph
|
|
63708
63985
|
*/
|
|
63709
63986
|
async getUserPositionsOnly(userAddress, first, skip, orderBy, orderDirection) {
|
|
63710
|
-
const query =
|
|
63711
|
-
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
63712
|
-
user(id: $borrower) {
|
|
63713
|
-
id
|
|
63714
|
-
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
63715
|
-
id
|
|
63716
|
-
pkpId
|
|
63717
|
-
borrower {
|
|
63718
|
-
createdAt
|
|
63719
|
-
id
|
|
63720
|
-
}
|
|
63721
|
-
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
63722
|
-
ucdMinted
|
|
63723
|
-
ucdPaid
|
|
63724
|
-
ucdDebt
|
|
63725
|
-
collateralRatio
|
|
63726
|
-
requestedCollateralRatio
|
|
63727
|
-
selectedTerm
|
|
63728
|
-
status
|
|
63729
|
-
createdAt
|
|
63730
|
-
createdAtBlock
|
|
63731
|
-
lastUpdated
|
|
63732
|
-
originalTerm
|
|
63733
|
-
remainingDebt
|
|
63734
|
-
expiryAt
|
|
63735
|
-
}
|
|
63736
|
-
}
|
|
63737
|
-
}
|
|
63738
|
-
`;
|
|
63987
|
+
const query = GET_USER_POSITIONS_DOCUMENT;
|
|
63739
63988
|
const variables = {
|
|
63740
63989
|
borrower: userAddress.toLowerCase(),
|
|
63741
63990
|
first: first || void 0,
|
|
@@ -63753,6 +64002,45 @@ var DiamondHandsGraph = class {
|
|
|
63753
64002
|
}
|
|
63754
64003
|
return positions;
|
|
63755
64004
|
}
|
|
64005
|
+
/**
|
|
64006
|
+
* Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
|
|
64007
|
+
* 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
|
|
64008
|
+
* coerces wei to a float and leaves `status` a string cast to the numeric enum).
|
|
64009
|
+
*
|
|
64010
|
+
* Deliberately issues the `GetUserPositions` document rather than a leaner one: the
|
|
64011
|
+
* lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
|
|
64012
|
+
* and that one is already listed, so this needs no server change. The extra fields
|
|
64013
|
+
* cost bytes, not round trips.
|
|
64014
|
+
*
|
|
64015
|
+
* Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
|
|
64016
|
+
*/
|
|
64017
|
+
async getBorrowerDebtRows(borrower) {
|
|
64018
|
+
const borrowerId = borrower.toLowerCase();
|
|
64019
|
+
return collectBorrowerDebtRows(async (skip, first) => {
|
|
64020
|
+
const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
|
|
64021
|
+
borrower: borrowerId,
|
|
64022
|
+
first,
|
|
64023
|
+
skip,
|
|
64024
|
+
orderBy: "id",
|
|
64025
|
+
orderDirection: "asc"
|
|
64026
|
+
});
|
|
64027
|
+
if (result?.user == null) {
|
|
64028
|
+
if (skip > 0) {
|
|
64029
|
+
throw new Error(
|
|
64030
|
+
`getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
|
|
64031
|
+
);
|
|
64032
|
+
}
|
|
64033
|
+
return [];
|
|
64034
|
+
}
|
|
64035
|
+
const positions = result.user.positions;
|
|
64036
|
+
if (!Array.isArray(positions)) {
|
|
64037
|
+
throw new Error(
|
|
64038
|
+
`getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
|
|
64039
|
+
);
|
|
64040
|
+
}
|
|
64041
|
+
return positions.filter((p) => p != null);
|
|
64042
|
+
});
|
|
64043
|
+
}
|
|
63756
64044
|
/**
|
|
63757
64045
|
* Get user positions, plus an accurate total count.
|
|
63758
64046
|
*
|
|
@@ -69921,6 +70209,603 @@ async function mintAgentPkp(params) {
|
|
|
69921
70209
|
clearTimeout(timeout);
|
|
69922
70210
|
}
|
|
69923
70211
|
}
|
|
70212
|
+
var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
|
|
70213
|
+
function planAgentBinding(params) {
|
|
70214
|
+
const { isActive, record, nowSeconds } = params;
|
|
70215
|
+
if (isActive)
|
|
70216
|
+
return { kind: "reuse", agent: record.agent };
|
|
70217
|
+
const status = Number(record.status);
|
|
70218
|
+
if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
|
|
70219
|
+
return { kind: "register" };
|
|
70220
|
+
}
|
|
70221
|
+
if (status !== AGENT_STATUS.Active) {
|
|
70222
|
+
throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
|
|
70223
|
+
}
|
|
70224
|
+
if (Number(record.validUntil) > nowSeconds) {
|
|
70225
|
+
throw new Error(
|
|
70226
|
+
"AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
|
|
70227
|
+
);
|
|
70228
|
+
}
|
|
70229
|
+
return { kind: "rotate" };
|
|
70230
|
+
}
|
|
70231
|
+
async function describeProviderChainMismatch(provider, chainId) {
|
|
70232
|
+
const actual = Number((await provider.getNetwork()).chainId);
|
|
70233
|
+
if (actual === chainId)
|
|
70234
|
+
return null;
|
|
70235
|
+
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.`;
|
|
70236
|
+
}
|
|
70237
|
+
var TxValidationError2 = class extends Error {
|
|
70238
|
+
/**
|
|
70239
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
70240
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
70241
|
+
*/
|
|
70242
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
70243
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
70244
|
+
this.name = "TxValidationError";
|
|
70245
|
+
}
|
|
70246
|
+
};
|
|
70247
|
+
var SIGNABLE_FUNCTIONS2 = [
|
|
70248
|
+
"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)",
|
|
70249
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
70250
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
70251
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
70252
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
70253
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
70254
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
70255
|
+
// protocol cannot execute.
|
|
70256
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
70257
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
70258
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
70259
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
70260
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
70261
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
70262
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
70263
|
+
"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)",
|
|
70264
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
70265
|
+
// function reverts permanently. The trustless replacement
|
|
70266
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
70267
|
+
// entry when its LIT Action ships.
|
|
70268
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
70269
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
70270
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
70271
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
70272
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
70273
|
+
// collateral had no client-side pin at all.
|
|
70274
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
70275
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
70276
|
+
// AgentModule; the parity test documents them as client-only.
|
|
70277
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
70278
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
70279
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
70280
|
+
// this too is client-only and never module-whitelisted.
|
|
70281
|
+
"function addAddress(string btcAddress) external"
|
|
70282
|
+
];
|
|
70283
|
+
var IFACE2 = new import_ethers31.ethers.Interface(SIGNABLE_FUNCTIONS2);
|
|
70284
|
+
function encodeSignable2(fn, args) {
|
|
70285
|
+
return IFACE2.encodeFunctionData(fn, args);
|
|
70286
|
+
}
|
|
70287
|
+
function decodeSignable2(data) {
|
|
70288
|
+
try {
|
|
70289
|
+
const parsed = IFACE2.parseTransaction({ data });
|
|
70290
|
+
if (!parsed) {
|
|
70291
|
+
throw new TxValidationError2(
|
|
70292
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
70293
|
+
);
|
|
70294
|
+
}
|
|
70295
|
+
return { name: parsed.name, args: parsed.args };
|
|
70296
|
+
} catch (e) {
|
|
70297
|
+
if (e instanceof TxValidationError2)
|
|
70298
|
+
throw e;
|
|
70299
|
+
throw new TxValidationError2(
|
|
70300
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
70301
|
+
);
|
|
70302
|
+
}
|
|
70303
|
+
}
|
|
70304
|
+
var MAX_GAS_LIMIT = 5000000n;
|
|
70305
|
+
var MAX_FEE_PER_GAS_WEI = 2000000000000n;
|
|
70306
|
+
var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
|
|
70307
|
+
var DEFAULT_FEE_CEILING = {
|
|
70308
|
+
maxGasLimit: MAX_GAS_LIMIT,
|
|
70309
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
|
|
70310
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
|
|
70311
|
+
};
|
|
70312
|
+
function fmtEth(wei) {
|
|
70313
|
+
return `${import_ethers33.ethers.formatEther(wei)} ETH`;
|
|
70314
|
+
}
|
|
70315
|
+
function fmtGwei(wei) {
|
|
70316
|
+
return `${import_ethers33.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
70317
|
+
}
|
|
70318
|
+
function worstCaseFeeWei(gasLimit, maxFeePerGas) {
|
|
70319
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
70320
|
+
return null;
|
|
70321
|
+
return gasLimit * maxFeePerGas;
|
|
70322
|
+
}
|
|
70323
|
+
function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
|
|
70324
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
70325
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
70326
|
+
}
|
|
70327
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
70328
|
+
raise(
|
|
70329
|
+
`maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
|
|
70330
|
+
);
|
|
70331
|
+
}
|
|
70332
|
+
const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
|
|
70333
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
70334
|
+
raise(
|
|
70335
|
+
`worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
70336
|
+
);
|
|
70337
|
+
}
|
|
70338
|
+
}
|
|
70339
|
+
function eqAddr2(a, b) {
|
|
70340
|
+
if (!a || !b)
|
|
70341
|
+
return false;
|
|
70342
|
+
try {
|
|
70343
|
+
return import_ethers32.ethers.getAddress(a) === import_ethers32.ethers.getAddress(b);
|
|
70344
|
+
} catch {
|
|
70345
|
+
return false;
|
|
70346
|
+
}
|
|
70347
|
+
}
|
|
70348
|
+
function readToAddress2(tx2) {
|
|
70349
|
+
const to = tx2["to"];
|
|
70350
|
+
if (typeof to !== "string") {
|
|
70351
|
+
throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
|
|
70352
|
+
}
|
|
70353
|
+
return to;
|
|
70354
|
+
}
|
|
70355
|
+
function readData2(tx2) {
|
|
70356
|
+
const data = tx2["data"];
|
|
70357
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
70358
|
+
throw new TxValidationError2(`unsignedTx.data missing or malformed`);
|
|
70359
|
+
}
|
|
70360
|
+
return data;
|
|
70361
|
+
}
|
|
70362
|
+
function readChainId2(tx2) {
|
|
70363
|
+
const c = tx2["chainId"];
|
|
70364
|
+
if (c == null)
|
|
70365
|
+
return null;
|
|
70366
|
+
if (typeof c === "number")
|
|
70367
|
+
return c;
|
|
70368
|
+
if (typeof c === "string")
|
|
70369
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
70370
|
+
if (typeof c === "bigint")
|
|
70371
|
+
return Number(c);
|
|
70372
|
+
return null;
|
|
70373
|
+
}
|
|
70374
|
+
function readOptionalBigInt(tx2, key) {
|
|
70375
|
+
const v = tx2[key];
|
|
70376
|
+
if (v == null)
|
|
70377
|
+
return null;
|
|
70378
|
+
try {
|
|
70379
|
+
if (typeof v === "bigint")
|
|
70380
|
+
return v;
|
|
70381
|
+
if (typeof v === "number")
|
|
70382
|
+
return BigInt(v);
|
|
70383
|
+
if (typeof v === "string")
|
|
70384
|
+
return BigInt(v);
|
|
70385
|
+
return BigInt(v.toString());
|
|
70386
|
+
} catch {
|
|
70387
|
+
throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
|
|
70388
|
+
}
|
|
70389
|
+
}
|
|
70390
|
+
function readValue2(tx2) {
|
|
70391
|
+
const v = tx2["value"];
|
|
70392
|
+
if (v == null)
|
|
70393
|
+
return 0n;
|
|
70394
|
+
if (typeof v === "string")
|
|
70395
|
+
return BigInt(v);
|
|
70396
|
+
if (typeof v === "number")
|
|
70397
|
+
return BigInt(v);
|
|
70398
|
+
if (typeof v === "bigint")
|
|
70399
|
+
return v;
|
|
70400
|
+
const maybe = v;
|
|
70401
|
+
if (typeof maybe.toBigInt === "function")
|
|
70402
|
+
return maybe.toBigInt();
|
|
70403
|
+
if (typeof maybe.toString === "function")
|
|
70404
|
+
return BigInt(maybe.toString());
|
|
70405
|
+
throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
|
|
70406
|
+
}
|
|
70407
|
+
function normalizePositionId2(id) {
|
|
70408
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
70409
|
+
return import_ethers32.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
70410
|
+
}
|
|
70411
|
+
function requirePositionId(actual, expected) {
|
|
70412
|
+
const txPositionId = String(actual).toLowerCase();
|
|
70413
|
+
if (txPositionId !== normalizePositionId2(expected)) {
|
|
70414
|
+
throw new TxValidationError2(
|
|
70415
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
|
|
70416
|
+
);
|
|
70417
|
+
}
|
|
70418
|
+
}
|
|
70419
|
+
function validateUnsignedTx2(unsignedTx, expected, vctx) {
|
|
70420
|
+
const txChainId = readChainId2(unsignedTx);
|
|
70421
|
+
if (txChainId == null) {
|
|
70422
|
+
throw new TxValidationError2(
|
|
70423
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
70424
|
+
);
|
|
70425
|
+
}
|
|
70426
|
+
if (txChainId !== vctx.chainId) {
|
|
70427
|
+
throw new TxValidationError2(
|
|
70428
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
70429
|
+
);
|
|
70430
|
+
}
|
|
70431
|
+
const value = readValue2(unsignedTx);
|
|
70432
|
+
if (value !== 0n) {
|
|
70433
|
+
throw new TxValidationError2(
|
|
70434
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
70435
|
+
);
|
|
70436
|
+
}
|
|
70437
|
+
assertFeeCeiling(
|
|
70438
|
+
readOptionalBigInt(unsignedTx, "gasLimit"),
|
|
70439
|
+
readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
|
|
70440
|
+
(msg) => {
|
|
70441
|
+
throw new TxValidationError2(msg);
|
|
70442
|
+
},
|
|
70443
|
+
vctx.feeCeiling
|
|
70444
|
+
);
|
|
70445
|
+
const to = readToAddress2(unsignedTx);
|
|
70446
|
+
const data = readData2(unsignedTx);
|
|
70447
|
+
const { name, args } = decodeSignable2(data);
|
|
70448
|
+
const pm = vctx.contracts.PositionManager;
|
|
70449
|
+
switch (expected.kind) {
|
|
70450
|
+
case "mint": {
|
|
70451
|
+
if (name !== "mintUCD") {
|
|
70452
|
+
throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
|
|
70453
|
+
}
|
|
70454
|
+
if (!eqAddr2(to, pm)) {
|
|
70455
|
+
throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
70456
|
+
}
|
|
70457
|
+
requirePositionId(args[0], expected.positionId);
|
|
70458
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
70459
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
70460
|
+
throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
70461
|
+
}
|
|
70462
|
+
const txMintFee = BigInt(String(args[2]));
|
|
70463
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
70464
|
+
throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
70465
|
+
}
|
|
70466
|
+
break;
|
|
70467
|
+
}
|
|
70468
|
+
case "repay": {
|
|
70469
|
+
if (name !== "makePayment") {
|
|
70470
|
+
throw new TxValidationError2(`expected makePayment, server returned ${name}`);
|
|
70471
|
+
}
|
|
70472
|
+
if (!eqAddr2(to, pm)) {
|
|
70473
|
+
throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
70474
|
+
}
|
|
70475
|
+
requirePositionId(args[0], expected.positionId);
|
|
70476
|
+
const txAmount = BigInt(String(args[1]));
|
|
70477
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
70478
|
+
throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
70479
|
+
}
|
|
70480
|
+
break;
|
|
70481
|
+
}
|
|
70482
|
+
case "extend": {
|
|
70483
|
+
if (name !== "extendPosition") {
|
|
70484
|
+
throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
|
|
70485
|
+
}
|
|
70486
|
+
if (!eqAddr2(to, pm)) {
|
|
70487
|
+
throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
70488
|
+
}
|
|
70489
|
+
requirePositionId(args[0], expected.positionId);
|
|
70490
|
+
const txTerm = Number(args[1]);
|
|
70491
|
+
if (txTerm !== expected.selectedTerm) {
|
|
70492
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
70493
|
+
}
|
|
70494
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
70495
|
+
const txFee = BigInt(String(args[5]));
|
|
70496
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
70497
|
+
if (txFee > upper) {
|
|
70498
|
+
throw new TxValidationError2(
|
|
70499
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
70500
|
+
);
|
|
70501
|
+
}
|
|
70502
|
+
}
|
|
70503
|
+
break;
|
|
70504
|
+
}
|
|
70505
|
+
case "withdraw-btc": {
|
|
70506
|
+
if (name !== "withdrawBTC") {
|
|
70507
|
+
throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
|
|
70508
|
+
}
|
|
70509
|
+
if (!eqAddr2(to, pm)) {
|
|
70510
|
+
throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
70511
|
+
}
|
|
70512
|
+
const paramsTuple = args[0];
|
|
70513
|
+
requirePositionId(paramsTuple[0], expected.positionId);
|
|
70514
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
70515
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
70516
|
+
throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
70517
|
+
}
|
|
70518
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
70519
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
70520
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
70521
|
+
if (txDeduction > upper) {
|
|
70522
|
+
throw new TxValidationError2(
|
|
70523
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
70524
|
+
);
|
|
70525
|
+
}
|
|
70526
|
+
}
|
|
70527
|
+
break;
|
|
70528
|
+
}
|
|
70529
|
+
case "ucd-approve": {
|
|
70530
|
+
if (name !== "approve") {
|
|
70531
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70532
|
+
}
|
|
70533
|
+
const ucd = vctx.contracts.UCDToken;
|
|
70534
|
+
if (!eqAddr2(to, ucd)) {
|
|
70535
|
+
throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
70536
|
+
}
|
|
70537
|
+
const spender = String(args[0]);
|
|
70538
|
+
const ok = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
|
|
70539
|
+
if (!ok) {
|
|
70540
|
+
throw new TxValidationError2(
|
|
70541
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
70542
|
+
);
|
|
70543
|
+
}
|
|
70544
|
+
const amt = BigInt(String(args[1]));
|
|
70545
|
+
const min = BigInt(expected.minAmountWei);
|
|
70546
|
+
if (amt < min) {
|
|
70547
|
+
throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
|
|
70548
|
+
}
|
|
70549
|
+
const SANITY_MAX = min * 1000n;
|
|
70550
|
+
if (amt > SANITY_MAX) {
|
|
70551
|
+
throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
70552
|
+
}
|
|
70553
|
+
break;
|
|
70554
|
+
}
|
|
70555
|
+
case "create-position": {
|
|
70556
|
+
if (name !== "createPosition") {
|
|
70557
|
+
throw new TxValidationError2(`expected createPosition, server returned ${name}`);
|
|
70558
|
+
}
|
|
70559
|
+
if (!eqAddr2(to, pm)) {
|
|
70560
|
+
throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
70561
|
+
}
|
|
70562
|
+
const txTerm = BigInt(String(args[4]));
|
|
70563
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
70564
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
70565
|
+
}
|
|
70566
|
+
break;
|
|
70567
|
+
}
|
|
70568
|
+
case "set-position-delegate": {
|
|
70569
|
+
if (name !== "setPositionDelegate") {
|
|
70570
|
+
throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
|
|
70571
|
+
}
|
|
70572
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
70573
|
+
throw new TxValidationError2(
|
|
70574
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
70575
|
+
);
|
|
70576
|
+
}
|
|
70577
|
+
requirePositionId(args[0], expected.positionId);
|
|
70578
|
+
const txDelegate = String(args[1]);
|
|
70579
|
+
if (!eqAddr2(txDelegate, expected.delegate)) {
|
|
70580
|
+
throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
70581
|
+
}
|
|
70582
|
+
break;
|
|
70583
|
+
}
|
|
70584
|
+
case "bwar-add-address": {
|
|
70585
|
+
if (name !== "addAddress") {
|
|
70586
|
+
throw new TxValidationError2(`expected addAddress, decoded ${name}`);
|
|
70587
|
+
}
|
|
70588
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
70589
|
+
throw new TxValidationError2(
|
|
70590
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
70591
|
+
);
|
|
70592
|
+
}
|
|
70593
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
70594
|
+
throw new TxValidationError2(
|
|
70595
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
70596
|
+
);
|
|
70597
|
+
}
|
|
70598
|
+
break;
|
|
70599
|
+
}
|
|
70600
|
+
case "stablecoin-approve": {
|
|
70601
|
+
if (name !== "approve") {
|
|
70602
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70603
|
+
}
|
|
70604
|
+
if (!eqAddr2(to, expected.tokenAddress)) {
|
|
70605
|
+
throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
70606
|
+
}
|
|
70607
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
70608
|
+
throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
70609
|
+
}
|
|
70610
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
70611
|
+
throw new TxValidationError2(
|
|
70612
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
70613
|
+
);
|
|
70614
|
+
}
|
|
70615
|
+
break;
|
|
70616
|
+
}
|
|
70617
|
+
case "ucd-approve-controller": {
|
|
70618
|
+
if (name !== "approve") {
|
|
70619
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70620
|
+
}
|
|
70621
|
+
if (!eqAddr2(to, expected.ucdTokenAddress)) {
|
|
70622
|
+
throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
70623
|
+
}
|
|
70624
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
70625
|
+
throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
70626
|
+
}
|
|
70627
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
70628
|
+
throw new TxValidationError2(
|
|
70629
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
70630
|
+
);
|
|
70631
|
+
}
|
|
70632
|
+
break;
|
|
70633
|
+
}
|
|
70634
|
+
case "psm-swap": {
|
|
70635
|
+
if (name !== "swap")
|
|
70636
|
+
throw new TxValidationError2(`expected swap, server returned ${name}`);
|
|
70637
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
70638
|
+
throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
70639
|
+
}
|
|
70640
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
70641
|
+
throw new TxValidationError2(`swap stablecoin mismatch`);
|
|
70642
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
70643
|
+
throw new TxValidationError2(`swap amountIn mismatch`);
|
|
70644
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
70645
|
+
throw new TxValidationError2(`swap minUcdOut mismatch`);
|
|
70646
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
70647
|
+
throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
70648
|
+
}
|
|
70649
|
+
break;
|
|
70650
|
+
}
|
|
70651
|
+
case "psm-redeem": {
|
|
70652
|
+
if (name !== "redeem")
|
|
70653
|
+
throw new TxValidationError2(`expected redeem, server returned ${name}`);
|
|
70654
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
70655
|
+
throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
70656
|
+
}
|
|
70657
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
70658
|
+
throw new TxValidationError2(`redeem stablecoin mismatch`);
|
|
70659
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
70660
|
+
throw new TxValidationError2(`redeem ucdAmount mismatch`);
|
|
70661
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
70662
|
+
throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
|
|
70663
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
70664
|
+
throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
70665
|
+
}
|
|
70666
|
+
break;
|
|
70667
|
+
}
|
|
70668
|
+
default: {
|
|
70669
|
+
const _exhaustive = expected;
|
|
70670
|
+
throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
70671
|
+
}
|
|
70672
|
+
}
|
|
70673
|
+
}
|
|
70674
|
+
function buildPsmApproveTx(p) {
|
|
70675
|
+
return {
|
|
70676
|
+
to: p.token,
|
|
70677
|
+
data: encodeSignable2("approve", [p.spender, p.amount]),
|
|
70678
|
+
value: "0x0",
|
|
70679
|
+
chainId: p.chainId
|
|
70680
|
+
};
|
|
70681
|
+
}
|
|
70682
|
+
function buildPsmSwapTx2(p) {
|
|
70683
|
+
return {
|
|
70684
|
+
to: p.psm,
|
|
70685
|
+
data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
70686
|
+
value: "0x0",
|
|
70687
|
+
chainId: p.chainId
|
|
70688
|
+
};
|
|
70689
|
+
}
|
|
70690
|
+
function buildPsmRedeemTx2(p) {
|
|
70691
|
+
return {
|
|
70692
|
+
to: p.psm,
|
|
70693
|
+
data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
70694
|
+
value: "0x0",
|
|
70695
|
+
chainId: p.chainId
|
|
70696
|
+
};
|
|
70697
|
+
}
|
|
70698
|
+
var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
|
|
70699
|
+
var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
70700
|
+
function psmExchangeReadsFromProvider(provider, psmAddress) {
|
|
70701
|
+
const psm = new import_ethers30.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
|
|
70702
|
+
return {
|
|
70703
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
70704
|
+
allowance: async (token, owner, spender) => await new import_ethers30.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
|
|
70705
|
+
};
|
|
70706
|
+
}
|
|
70707
|
+
var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
|
|
70708
|
+
function requireAddress(direction, label, value) {
|
|
70709
|
+
if (!value || !import_ethers30.ethers.isAddress(value)) {
|
|
70710
|
+
throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
70711
|
+
}
|
|
70712
|
+
return import_ethers30.ethers.getAddress(value);
|
|
70713
|
+
}
|
|
70714
|
+
async function planPsmExchange(params) {
|
|
70715
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
70716
|
+
const chainId = vctx.chainId;
|
|
70717
|
+
if (amountIn <= 0n) {
|
|
70718
|
+
throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
70719
|
+
}
|
|
70720
|
+
if (minOut <= 0n) {
|
|
70721
|
+
throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
70722
|
+
}
|
|
70723
|
+
const owner = requireAddress(direction, "owner", params.owner);
|
|
70724
|
+
const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
|
|
70725
|
+
const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
|
|
70726
|
+
const isSwap = direction === "swap";
|
|
70727
|
+
const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
|
|
70728
|
+
const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
|
|
70729
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
70730
|
+
throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
70731
|
+
}
|
|
70732
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
70733
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
70734
|
+
const approvals = [];
|
|
70735
|
+
if (allowanceBefore < amountIn) {
|
|
70736
|
+
if (allowanceBefore > 0n) {
|
|
70737
|
+
approvals.push({
|
|
70738
|
+
step: "reset-approve",
|
|
70739
|
+
tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
|
|
70740
|
+
expected: approveExpected(0n)
|
|
70741
|
+
});
|
|
70742
|
+
}
|
|
70743
|
+
approvals.push({
|
|
70744
|
+
step: "approve",
|
|
70745
|
+
tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
|
|
70746
|
+
expected: approveExpected(amountIn)
|
|
70747
|
+
});
|
|
70748
|
+
}
|
|
70749
|
+
const exec = isSwap ? {
|
|
70750
|
+
step: "swap",
|
|
70751
|
+
tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
70752
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
70753
|
+
} : {
|
|
70754
|
+
step: "redeem",
|
|
70755
|
+
tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
70756
|
+
expected: {
|
|
70757
|
+
kind: "psm-redeem",
|
|
70758
|
+
psmAddress: psm,
|
|
70759
|
+
stablecoin,
|
|
70760
|
+
amountUcdWei: amountIn.toString(),
|
|
70761
|
+
minOut: minOut.toString()
|
|
70762
|
+
}
|
|
70763
|
+
};
|
|
70764
|
+
for (const leg of [...approvals, exec]) {
|
|
70765
|
+
validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
|
|
70766
|
+
}
|
|
70767
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
70768
|
+
}
|
|
70769
|
+
async function executePsmPlan(plan, signer, vctx) {
|
|
70770
|
+
const approvalHashes = [];
|
|
70771
|
+
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.`;
|
|
70772
|
+
const sendLeg = async (leg) => {
|
|
70773
|
+
const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
|
|
70774
|
+
validateUnsignedTx2({ ...request }, leg.expected, vctx);
|
|
70775
|
+
const sent = await signer.sendTransaction(request);
|
|
70776
|
+
const receipt = await sent.wait();
|
|
70777
|
+
if (!receipt)
|
|
70778
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
|
|
70779
|
+
if (receipt.status !== 1)
|
|
70780
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
|
|
70781
|
+
return { hash: sent.hash, blockNumber: receipt.blockNumber };
|
|
70782
|
+
};
|
|
70783
|
+
for (const leg of plan.approvals) {
|
|
70784
|
+
const landed = await sendLeg(leg).catch((e) => {
|
|
70785
|
+
throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
70786
|
+
});
|
|
70787
|
+
approvalHashes.push(landed.hash);
|
|
70788
|
+
}
|
|
70789
|
+
const exec = await sendLeg(plan.exec).catch((e) => {
|
|
70790
|
+
throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
70791
|
+
});
|
|
70792
|
+
return { ...exec, approvalHashes };
|
|
70793
|
+
}
|
|
70794
|
+
var LIT_ACTION_CHAIN_NAMES = Object.freeze({
|
|
70795
|
+
1: "ethereum",
|
|
70796
|
+
11155111: "sepolia",
|
|
70797
|
+
1337: "hardhat",
|
|
70798
|
+
31337: "hardhat"
|
|
70799
|
+
});
|
|
70800
|
+
function litActionChainNameForChainId(chainId) {
|
|
70801
|
+
const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
|
|
70802
|
+
if (!name) {
|
|
70803
|
+
throw new Error(
|
|
70804
|
+
`Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
|
|
70805
|
+
);
|
|
70806
|
+
}
|
|
70807
|
+
return name;
|
|
70808
|
+
}
|
|
69924
70809
|
var MockTokenManager = class {
|
|
69925
70810
|
config;
|
|
69926
70811
|
constructor(config) {
|
|
@@ -70894,6 +71779,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
70894
71779
|
*/
|
|
70895
71780
|
static async create(config) {
|
|
70896
71781
|
const userProvidedServiceEndpoint = config.serviceEndpoint;
|
|
71782
|
+
if (typeof config.chainId === "number" && config.provider) {
|
|
71783
|
+
const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
|
|
71784
|
+
if (mismatch) {
|
|
71785
|
+
return failure(
|
|
71786
|
+
new SDKError({
|
|
71787
|
+
message: mismatch,
|
|
71788
|
+
category: "CONFIGURATION",
|
|
71789
|
+
severity: "HIGH"
|
|
71790
|
+
/* HIGH */
|
|
71791
|
+
})
|
|
71792
|
+
);
|
|
71793
|
+
}
|
|
71794
|
+
}
|
|
70897
71795
|
const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
|
|
70898
71796
|
if (userProvidedServiceEndpoint) {
|
|
70899
71797
|
enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
|
|
@@ -71544,6 +72442,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71544
72442
|
if (this.config.debug) {
|
|
71545
72443
|
log.info(` Position PKP ID: ${position2.pkpId}`);
|
|
71546
72444
|
}
|
|
72445
|
+
const termsResult = await this.getTermsWithFees();
|
|
72446
|
+
if (!termsResult.success) {
|
|
72447
|
+
return {
|
|
72448
|
+
success: false,
|
|
72449
|
+
error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
|
|
72450
|
+
};
|
|
72451
|
+
}
|
|
72452
|
+
const positionTermMonths = Number(position2.selectedTerm);
|
|
72453
|
+
const positionTerm = termsResult.value.terms.find(
|
|
72454
|
+
(term) => term.termMonths === positionTermMonths
|
|
72455
|
+
);
|
|
72456
|
+
if (!positionTerm) {
|
|
72457
|
+
return {
|
|
72458
|
+
success: false,
|
|
72459
|
+
error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
|
|
72460
|
+
};
|
|
72461
|
+
}
|
|
72462
|
+
const currentDebtWei = BigInt(position2.ucdDebt);
|
|
72463
|
+
const baseFeeWei = baseMintFeeWei(
|
|
72464
|
+
requestAmountWei,
|
|
72465
|
+
positionTerm.originationFeeBps
|
|
72466
|
+
);
|
|
72467
|
+
if (debtAfterMintExceedsLoanCap({
|
|
72468
|
+
currentDebtWei,
|
|
72469
|
+
mintAmountWei: requestAmountWei,
|
|
72470
|
+
mintFeeWei: baseFeeWei,
|
|
72471
|
+
maxLoanWei: maxLoanValueWei
|
|
72472
|
+
})) {
|
|
72473
|
+
const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
|
|
72474
|
+
const maxPrincipalUcd = Number(
|
|
72475
|
+
maxPrincipalWithinLoanCap({
|
|
72476
|
+
maxLoanWei: maxLoanValueWei,
|
|
72477
|
+
currentDebtWei,
|
|
72478
|
+
originationFeeBps: positionTerm.originationFeeBps
|
|
72479
|
+
}) / BigInt(10 ** 18)
|
|
72480
|
+
);
|
|
72481
|
+
return {
|
|
72482
|
+
success: false,
|
|
72483
|
+
error: `Amount ${request.amount} UCD plus the ${positionTerm.originationFeeBps / 100}% origination fee (${(0, import_ethers13.formatEther)(baseFeeWei)} UCD) would take this loan's debt to ${(0, import_ethers13.formatEther)(debtAfterWei)} UCD, above the protocol maximum of ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD. The largest amount you can mint now is ${maxPrincipalUcd} UCD.`
|
|
72484
|
+
};
|
|
72485
|
+
}
|
|
72486
|
+
if (this.config.debug) {
|
|
72487
|
+
log.info(
|
|
72488
|
+
`\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers13.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD`,
|
|
72489
|
+
{}
|
|
72490
|
+
);
|
|
72491
|
+
}
|
|
71547
72492
|
let pkpPublicKey;
|
|
71548
72493
|
let pkpEthAddress;
|
|
71549
72494
|
const pkpCache = this.cacheManager.getCache("pkp-data", {
|
|
@@ -71633,7 +72578,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71633
72578
|
` UCDController: ${contracts?.UCDController || "MISSING"}`
|
|
71634
72579
|
);
|
|
71635
72580
|
}
|
|
71636
|
-
const chain = this.config.chain || (
|
|
72581
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
71637
72582
|
const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
|
|
71638
72583
|
if (this.config.debug) {
|
|
71639
72584
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -72233,6 +73178,25 @@ Error data: none`
|
|
|
72233
73178
|
}
|
|
72234
73179
|
const selector = simError.selector;
|
|
72235
73180
|
const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
|
|
73181
|
+
const MINT_GUARD_CODES = {
|
|
73182
|
+
"1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
|
|
73183
|
+
"2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
|
|
73184
|
+
"3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
|
|
73185
|
+
};
|
|
73186
|
+
let loanCapDiagnostics = "";
|
|
73187
|
+
if (selector === "0xe6dd4d41") {
|
|
73188
|
+
const guardCode = BigInt(
|
|
73189
|
+
"0x" + String(simError.data).slice(10).padStart(64, "0")
|
|
73190
|
+
).toString();
|
|
73191
|
+
const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
|
|
73192
|
+
loanCapDiagnostics = `
|
|
73193
|
+
|
|
73194
|
+
MintGuardFailed(${guardCode}): ${guardMeaning}
|
|
73195
|
+
Lit mintAmount: ${validationResponse.mintAmount}
|
|
73196
|
+
Lit mintFee: ${validationResponse.mintFee}
|
|
73197
|
+
Lit newDebt: ${validationResponse.newDebt}
|
|
73198
|
+
Protocol maximum: ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
|
|
73199
|
+
}
|
|
72236
73200
|
const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
|
|
72237
73201
|
selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
|
|
72238
73202
|
selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
|
|
@@ -72278,7 +73242,7 @@ Quantum Timing Analysis:
|
|
|
72278
73242
|
Error selector: ${selector}
|
|
72279
73243
|
Error data: ${simError.data}
|
|
72280
73244
|
Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
|
|
72281
|
-
Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
73245
|
+
Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
|
|
72282
73246
|
);
|
|
72283
73247
|
}
|
|
72284
73248
|
const tx2 = await sendEip1559Transaction({
|
|
@@ -74886,7 +75850,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
74886
75850
|
` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
|
|
74887
75851
|
);
|
|
74888
75852
|
}
|
|
74889
|
-
const chain = this.config.chain || (
|
|
75853
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
74890
75854
|
const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
|
|
74891
75855
|
if (this.config.debug) {
|
|
74892
75856
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -75441,13 +76405,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
75441
76405
|
return { success: false, error: "Failed to resolve PKP public key" };
|
|
75442
76406
|
}
|
|
75443
76407
|
const chipotlePkpAddress = (0, import_ethers13.computeAddress)(publicKey);
|
|
75444
|
-
const
|
|
75445
|
-
1: "ethereum",
|
|
75446
|
-
11155111: "sepolia",
|
|
75447
|
-
1337: "hardhat",
|
|
75448
|
-
31337: "hardhat"
|
|
75449
|
-
};
|
|
75450
|
-
const chainName = STANDALONE_CHAIN_NAMES[chainId];
|
|
76408
|
+
const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
|
|
75451
76409
|
if (!chainName) {
|
|
75452
76410
|
return {
|
|
75453
76411
|
success: false,
|
|
@@ -76669,6 +77627,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76669
77627
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
76670
77628
|
return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
|
|
76671
77629
|
}
|
|
77630
|
+
/**
|
|
77631
|
+
* Combined UCD debt (canonical wei string + display string) and by-status loan
|
|
77632
|
+
* counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
|
|
77633
|
+
* an INDEXED, informational figure that lags writes; never size a transaction
|
|
77634
|
+
* from it (repayments read the chain via `getPositionDetailsView`).
|
|
77635
|
+
*
|
|
77636
|
+
* Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
|
|
77637
|
+
* failure or past 10,000 positions; never returns a partial total.
|
|
77638
|
+
*/
|
|
77639
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
77640
|
+
return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
|
|
77641
|
+
}
|
|
76672
77642
|
/**
|
|
76673
77643
|
* Get all active loans
|
|
76674
77644
|
*
|
|
@@ -76794,11 +77764,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76794
77764
|
}
|
|
76795
77765
|
/**
|
|
76796
77766
|
* Execute a PSM stablecoin → UCD swap.
|
|
76797
|
-
*
|
|
77767
|
+
* Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
|
|
77768
|
+
* partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
|
|
76798
77769
|
*
|
|
76799
77770
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
|
|
76800
77771
|
* @param params.amountWei - Stablecoin amount in native decimals (bigint)
|
|
76801
|
-
* @param params.minUcdOutWei - Minimum UCD to receive;
|
|
77772
|
+
* @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
|
|
76802
77773
|
* @param params.signer - Connected signer for the approval and swap transactions
|
|
76803
77774
|
*/
|
|
76804
77775
|
async psmSwap(params) {
|
|
@@ -76808,32 +77779,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76808
77779
|
"SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
|
|
76809
77780
|
);
|
|
76810
77781
|
}
|
|
76811
|
-
|
|
76812
|
-
|
|
76813
|
-
|
|
76814
|
-
|
|
76815
|
-
|
|
76816
|
-
|
|
76817
|
-
|
|
76818
|
-
if (allowance < params.amountWei) {
|
|
76819
|
-
const approveTx = await stablecoin.approve(psmAddress, import_ethers13.MaxUint256);
|
|
76820
|
-
await approveTx.wait();
|
|
76821
|
-
}
|
|
76822
|
-
const psm = SimplePSMV2__factory.connect(psmAddress, params.signer);
|
|
76823
|
-
const tx2 = await psm.swap(params.stablecoinAddress, params.amountWei, params.minUcdOutWei);
|
|
76824
|
-
const receipt = await tx2.wait();
|
|
76825
|
-
if (!receipt)
|
|
76826
|
-
throw new Error("PSM swap transaction receipt unavailable");
|
|
76827
|
-
return { hash: tx2.hash, blockNumber: receipt.blockNumber };
|
|
77782
|
+
return this.runPsmExchange({
|
|
77783
|
+
direction: "swap",
|
|
77784
|
+
signer: params.signer,
|
|
77785
|
+
addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
|
|
77786
|
+
amountIn: params.amountWei,
|
|
77787
|
+
minOut: params.minUcdOutWei
|
|
77788
|
+
});
|
|
76828
77789
|
}
|
|
76829
77790
|
/**
|
|
76830
77791
|
* Execute a PSM UCD → stablecoin redeem.
|
|
76831
|
-
*
|
|
76832
|
-
* UCDToken.burn(from, amount) calls
|
|
77792
|
+
* Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
|
|
77793
|
+
* M-4 burn allowance guard: UCDToken.burn(from, amount) calls
|
|
77794
|
+
* _spendAllowance(from, msg.sender=ucdController, amount).
|
|
76833
77795
|
*
|
|
76834
77796
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
|
|
76835
77797
|
* @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
|
|
76836
|
-
* @param params.minStablecoinOutWei - Minimum stablecoin to receive
|
|
77798
|
+
* @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
|
|
76837
77799
|
* @param params.signer - Connected signer
|
|
76838
77800
|
*/
|
|
76839
77801
|
async psmRedeem(params) {
|
|
@@ -76846,23 +77808,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76846
77808
|
throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
|
|
76847
77809
|
if (!ucdControllerAddress)
|
|
76848
77810
|
throw new Error("UCDController address not configured \u2014 provide contractAddresses.ucdController");
|
|
76849
|
-
|
|
76850
|
-
|
|
76851
|
-
|
|
76852
|
-
|
|
76853
|
-
|
|
76854
|
-
|
|
76855
|
-
|
|
76856
|
-
|
|
76857
|
-
|
|
76858
|
-
|
|
76859
|
-
|
|
76860
|
-
|
|
76861
|
-
|
|
76862
|
-
|
|
76863
|
-
|
|
76864
|
-
|
|
76865
|
-
|
|
77811
|
+
return this.runPsmExchange({
|
|
77812
|
+
direction: "redeem",
|
|
77813
|
+
signer: params.signer,
|
|
77814
|
+
addresses: {
|
|
77815
|
+
psm: psmAddress,
|
|
77816
|
+
stablecoin: params.stablecoinAddress,
|
|
77817
|
+
ucdToken: ucdAddress,
|
|
77818
|
+
ucdController: ucdControllerAddress
|
|
77819
|
+
},
|
|
77820
|
+
amountIn: params.ucdAmountWei,
|
|
77821
|
+
minOut: params.minStablecoinOutWei
|
|
77822
|
+
});
|
|
77823
|
+
}
|
|
77824
|
+
/**
|
|
77825
|
+
* Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
|
|
77826
|
+
* The signer's chain must match the SDK's configured chain — the addresses came from it.
|
|
77827
|
+
*/
|
|
77828
|
+
async runPsmExchange(params) {
|
|
77829
|
+
const provider = params.signer.provider;
|
|
77830
|
+
if (!provider) {
|
|
77831
|
+
throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
|
|
77832
|
+
}
|
|
77833
|
+
const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
|
|
77834
|
+
if (typeof configuredChainId !== "number") {
|
|
77835
|
+
throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
|
|
77836
|
+
}
|
|
77837
|
+
const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
|
|
77838
|
+
if (mismatch)
|
|
77839
|
+
throw new Error(mismatch);
|
|
77840
|
+
const vctx = {
|
|
77841
|
+
chainId: configuredChainId,
|
|
77842
|
+
network: String(configuredChainId),
|
|
77843
|
+
contracts: {}
|
|
77844
|
+
};
|
|
77845
|
+
const plan = await planPsmExchange({
|
|
77846
|
+
direction: params.direction,
|
|
77847
|
+
owner: await params.signer.getAddress(),
|
|
77848
|
+
addresses: params.addresses,
|
|
77849
|
+
amountIn: params.amountIn,
|
|
77850
|
+
minOut: params.minOut,
|
|
77851
|
+
vctx,
|
|
77852
|
+
reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
|
|
77853
|
+
});
|
|
77854
|
+
const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
|
|
77855
|
+
return { hash, blockNumber };
|
|
76866
77856
|
}
|
|
76867
77857
|
/**
|
|
76868
77858
|
* Wait for the subgraph to index up to (and including) the given block number.
|
|
@@ -77043,18 +78033,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77043
78033
|
const user = await signer.getAddress();
|
|
77044
78034
|
const registry = AgentDelegationRegistry__factory.connect(addr, signer);
|
|
77045
78035
|
let agentAddress;
|
|
77046
|
-
const
|
|
77047
|
-
|
|
77048
|
-
|
|
78036
|
+
const [isActive, record, latestBlock] = await Promise.all([
|
|
78037
|
+
registry.isAgentActive(user),
|
|
78038
|
+
registry.agentOf(user),
|
|
78039
|
+
this.getProviderOrThrow().getBlock("latest")
|
|
78040
|
+
]);
|
|
78041
|
+
if (!latestBlock) {
|
|
78042
|
+
throw new SDKError({
|
|
78043
|
+
message: "Could not read the latest block to check the agent registration's expiry",
|
|
78044
|
+
category: "NETWORK",
|
|
78045
|
+
severity: "HIGH"
|
|
78046
|
+
/* HIGH */
|
|
78047
|
+
});
|
|
78048
|
+
}
|
|
78049
|
+
const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
|
|
78050
|
+
if (plan.kind === "reuse") {
|
|
78051
|
+
agentAddress = plan.agent;
|
|
77049
78052
|
} else {
|
|
77050
78053
|
agentAddress = await mintAgentPkp({
|
|
77051
78054
|
serviceEndpoint: this.config.serviceEndpoint,
|
|
77052
78055
|
authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
|
|
77053
78056
|
});
|
|
77054
78057
|
const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
|
|
77055
|
-
const validUntil =
|
|
77056
|
-
const
|
|
77057
|
-
await
|
|
78058
|
+
const validUntil = latestBlock.timestamp + validitySeconds;
|
|
78059
|
+
const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
|
|
78060
|
+
await bindTx.wait();
|
|
77058
78061
|
}
|
|
77059
78062
|
const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
|
|
77060
78063
|
() => null
|
|
@@ -78446,7 +79449,552 @@ var SUPPORTED_STABLECOINS = `
|
|
|
78446
79449
|
}`;
|
|
78447
79450
|
|
|
78448
79451
|
// src/boundary/upstream/real/psm-calls.ts
|
|
78449
|
-
var
|
|
79452
|
+
var import_ethers41 = require("ethers");
|
|
79453
|
+
|
|
79454
|
+
// node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
|
|
79455
|
+
var import_ethers35 = require("ethers");
|
|
79456
|
+
var import_ethers36 = require("ethers");
|
|
79457
|
+
var import_ethers37 = require("ethers");
|
|
79458
|
+
var import_ethers38 = require("ethers");
|
|
79459
|
+
var import_ethers39 = require("ethers");
|
|
79460
|
+
var import_ethers40 = require("ethers");
|
|
79461
|
+
var TxValidationError3 = class extends Error {
|
|
79462
|
+
/**
|
|
79463
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
79464
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
79465
|
+
*/
|
|
79466
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
79467
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
79468
|
+
this.name = "TxValidationError";
|
|
79469
|
+
}
|
|
79470
|
+
};
|
|
79471
|
+
var SIGNABLE_FUNCTIONS3 = [
|
|
79472
|
+
"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)",
|
|
79473
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
79474
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
79475
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
79476
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
79477
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
79478
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
79479
|
+
// protocol cannot execute.
|
|
79480
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
79481
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
79482
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
79483
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
79484
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
79485
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
79486
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
79487
|
+
"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)",
|
|
79488
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
79489
|
+
// function reverts permanently. The trustless replacement
|
|
79490
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
79491
|
+
// entry when its LIT Action ships.
|
|
79492
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
79493
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
79494
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
79495
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
79496
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
79497
|
+
// collateral had no client-side pin at all.
|
|
79498
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
79499
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
79500
|
+
// AgentModule; the parity test documents them as client-only.
|
|
79501
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
79502
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
79503
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
79504
|
+
// this too is client-only and never module-whitelisted.
|
|
79505
|
+
"function addAddress(string btcAddress) external"
|
|
79506
|
+
];
|
|
79507
|
+
var IFACE3 = new import_ethers35.ethers.Interface(SIGNABLE_FUNCTIONS3);
|
|
79508
|
+
function encodeSignable3(fn, args) {
|
|
79509
|
+
return IFACE3.encodeFunctionData(fn, args);
|
|
79510
|
+
}
|
|
79511
|
+
function decodeSignable3(data) {
|
|
79512
|
+
try {
|
|
79513
|
+
const parsed = IFACE3.parseTransaction({ data });
|
|
79514
|
+
if (!parsed) {
|
|
79515
|
+
throw new TxValidationError3(
|
|
79516
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
79517
|
+
);
|
|
79518
|
+
}
|
|
79519
|
+
return { name: parsed.name, args: parsed.args };
|
|
79520
|
+
} catch (e) {
|
|
79521
|
+
if (e instanceof TxValidationError3)
|
|
79522
|
+
throw e;
|
|
79523
|
+
throw new TxValidationError3(
|
|
79524
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
79525
|
+
);
|
|
79526
|
+
}
|
|
79527
|
+
}
|
|
79528
|
+
var MAX_GAS_LIMIT2 = 5000000n;
|
|
79529
|
+
var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
|
|
79530
|
+
var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
|
|
79531
|
+
var DEFAULT_FEE_CEILING2 = {
|
|
79532
|
+
maxGasLimit: MAX_GAS_LIMIT2,
|
|
79533
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
|
|
79534
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
|
|
79535
|
+
};
|
|
79536
|
+
function fmtEth2(wei) {
|
|
79537
|
+
return `${import_ethers36.ethers.formatEther(wei)} ETH`;
|
|
79538
|
+
}
|
|
79539
|
+
function fmtGwei2(wei) {
|
|
79540
|
+
return `${import_ethers36.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
79541
|
+
}
|
|
79542
|
+
function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
|
|
79543
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
79544
|
+
return null;
|
|
79545
|
+
return gasLimit * maxFeePerGas;
|
|
79546
|
+
}
|
|
79547
|
+
function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
|
|
79548
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
79549
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
79550
|
+
}
|
|
79551
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
79552
|
+
raise(
|
|
79553
|
+
`maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
|
|
79554
|
+
);
|
|
79555
|
+
}
|
|
79556
|
+
const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
|
|
79557
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
79558
|
+
raise(
|
|
79559
|
+
`worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
79560
|
+
);
|
|
79561
|
+
}
|
|
79562
|
+
}
|
|
79563
|
+
function eqAddr3(a, b) {
|
|
79564
|
+
if (!a || !b)
|
|
79565
|
+
return false;
|
|
79566
|
+
try {
|
|
79567
|
+
return import_ethers37.ethers.getAddress(a) === import_ethers37.ethers.getAddress(b);
|
|
79568
|
+
} catch {
|
|
79569
|
+
return false;
|
|
79570
|
+
}
|
|
79571
|
+
}
|
|
79572
|
+
function readToAddress3(tx2) {
|
|
79573
|
+
const to = tx2["to"];
|
|
79574
|
+
if (typeof to !== "string") {
|
|
79575
|
+
throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
|
|
79576
|
+
}
|
|
79577
|
+
return to;
|
|
79578
|
+
}
|
|
79579
|
+
function readData3(tx2) {
|
|
79580
|
+
const data = tx2["data"];
|
|
79581
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
79582
|
+
throw new TxValidationError3(`unsignedTx.data missing or malformed`);
|
|
79583
|
+
}
|
|
79584
|
+
return data;
|
|
79585
|
+
}
|
|
79586
|
+
function readChainId3(tx2) {
|
|
79587
|
+
const c = tx2["chainId"];
|
|
79588
|
+
if (c == null)
|
|
79589
|
+
return null;
|
|
79590
|
+
if (typeof c === "number")
|
|
79591
|
+
return c;
|
|
79592
|
+
if (typeof c === "string")
|
|
79593
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
79594
|
+
if (typeof c === "bigint")
|
|
79595
|
+
return Number(c);
|
|
79596
|
+
return null;
|
|
79597
|
+
}
|
|
79598
|
+
function readOptionalBigInt2(tx2, key) {
|
|
79599
|
+
const v = tx2[key];
|
|
79600
|
+
if (v == null)
|
|
79601
|
+
return null;
|
|
79602
|
+
try {
|
|
79603
|
+
if (typeof v === "bigint")
|
|
79604
|
+
return v;
|
|
79605
|
+
if (typeof v === "number")
|
|
79606
|
+
return BigInt(v);
|
|
79607
|
+
if (typeof v === "string")
|
|
79608
|
+
return BigInt(v);
|
|
79609
|
+
return BigInt(v.toString());
|
|
79610
|
+
} catch {
|
|
79611
|
+
throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
|
|
79612
|
+
}
|
|
79613
|
+
}
|
|
79614
|
+
function readValue3(tx2) {
|
|
79615
|
+
const v = tx2["value"];
|
|
79616
|
+
if (v == null)
|
|
79617
|
+
return 0n;
|
|
79618
|
+
if (typeof v === "string")
|
|
79619
|
+
return BigInt(v);
|
|
79620
|
+
if (typeof v === "number")
|
|
79621
|
+
return BigInt(v);
|
|
79622
|
+
if (typeof v === "bigint")
|
|
79623
|
+
return v;
|
|
79624
|
+
const maybe = v;
|
|
79625
|
+
if (typeof maybe.toBigInt === "function")
|
|
79626
|
+
return maybe.toBigInt();
|
|
79627
|
+
if (typeof maybe.toString === "function")
|
|
79628
|
+
return BigInt(maybe.toString());
|
|
79629
|
+
throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
|
|
79630
|
+
}
|
|
79631
|
+
function normalizePositionId3(id) {
|
|
79632
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
79633
|
+
return import_ethers37.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
79634
|
+
}
|
|
79635
|
+
function requirePositionId2(actual, expected) {
|
|
79636
|
+
const txPositionId = String(actual).toLowerCase();
|
|
79637
|
+
if (txPositionId !== normalizePositionId3(expected)) {
|
|
79638
|
+
throw new TxValidationError3(
|
|
79639
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
|
|
79640
|
+
);
|
|
79641
|
+
}
|
|
79642
|
+
}
|
|
79643
|
+
function validateUnsignedTx3(unsignedTx, expected, vctx) {
|
|
79644
|
+
const txChainId = readChainId3(unsignedTx);
|
|
79645
|
+
if (txChainId == null) {
|
|
79646
|
+
throw new TxValidationError3(
|
|
79647
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
79648
|
+
);
|
|
79649
|
+
}
|
|
79650
|
+
if (txChainId !== vctx.chainId) {
|
|
79651
|
+
throw new TxValidationError3(
|
|
79652
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
79653
|
+
);
|
|
79654
|
+
}
|
|
79655
|
+
const value = readValue3(unsignedTx);
|
|
79656
|
+
if (value !== 0n) {
|
|
79657
|
+
throw new TxValidationError3(
|
|
79658
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
79659
|
+
);
|
|
79660
|
+
}
|
|
79661
|
+
assertFeeCeiling2(
|
|
79662
|
+
readOptionalBigInt2(unsignedTx, "gasLimit"),
|
|
79663
|
+
readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
|
|
79664
|
+
(msg) => {
|
|
79665
|
+
throw new TxValidationError3(msg);
|
|
79666
|
+
},
|
|
79667
|
+
vctx.feeCeiling
|
|
79668
|
+
);
|
|
79669
|
+
const to = readToAddress3(unsignedTx);
|
|
79670
|
+
const data = readData3(unsignedTx);
|
|
79671
|
+
const { name, args } = decodeSignable3(data);
|
|
79672
|
+
const pm = vctx.contracts.PositionManager;
|
|
79673
|
+
switch (expected.kind) {
|
|
79674
|
+
case "mint": {
|
|
79675
|
+
if (name !== "mintUCD") {
|
|
79676
|
+
throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
|
|
79677
|
+
}
|
|
79678
|
+
if (!eqAddr3(to, pm)) {
|
|
79679
|
+
throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
79680
|
+
}
|
|
79681
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79682
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
79683
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
79684
|
+
throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
79685
|
+
}
|
|
79686
|
+
const txMintFee = BigInt(String(args[2]));
|
|
79687
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
79688
|
+
throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
79689
|
+
}
|
|
79690
|
+
break;
|
|
79691
|
+
}
|
|
79692
|
+
case "repay": {
|
|
79693
|
+
if (name !== "makePayment") {
|
|
79694
|
+
throw new TxValidationError3(`expected makePayment, server returned ${name}`);
|
|
79695
|
+
}
|
|
79696
|
+
if (!eqAddr3(to, pm)) {
|
|
79697
|
+
throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
79698
|
+
}
|
|
79699
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79700
|
+
const txAmount = BigInt(String(args[1]));
|
|
79701
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
79702
|
+
throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
79703
|
+
}
|
|
79704
|
+
break;
|
|
79705
|
+
}
|
|
79706
|
+
case "extend": {
|
|
79707
|
+
if (name !== "extendPosition") {
|
|
79708
|
+
throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
|
|
79709
|
+
}
|
|
79710
|
+
if (!eqAddr3(to, pm)) {
|
|
79711
|
+
throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
79712
|
+
}
|
|
79713
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79714
|
+
const txTerm = Number(args[1]);
|
|
79715
|
+
if (txTerm !== expected.selectedTerm) {
|
|
79716
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
79717
|
+
}
|
|
79718
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
79719
|
+
const txFee = BigInt(String(args[5]));
|
|
79720
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
79721
|
+
if (txFee > upper) {
|
|
79722
|
+
throw new TxValidationError3(
|
|
79723
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
79724
|
+
);
|
|
79725
|
+
}
|
|
79726
|
+
}
|
|
79727
|
+
break;
|
|
79728
|
+
}
|
|
79729
|
+
case "withdraw-btc": {
|
|
79730
|
+
if (name !== "withdrawBTC") {
|
|
79731
|
+
throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
|
|
79732
|
+
}
|
|
79733
|
+
if (!eqAddr3(to, pm)) {
|
|
79734
|
+
throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
79735
|
+
}
|
|
79736
|
+
const paramsTuple = args[0];
|
|
79737
|
+
requirePositionId2(paramsTuple[0], expected.positionId);
|
|
79738
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
79739
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
79740
|
+
throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
79741
|
+
}
|
|
79742
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
79743
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
79744
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
79745
|
+
if (txDeduction > upper) {
|
|
79746
|
+
throw new TxValidationError3(
|
|
79747
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
79748
|
+
);
|
|
79749
|
+
}
|
|
79750
|
+
}
|
|
79751
|
+
break;
|
|
79752
|
+
}
|
|
79753
|
+
case "ucd-approve": {
|
|
79754
|
+
if (name !== "approve") {
|
|
79755
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79756
|
+
}
|
|
79757
|
+
const ucd = vctx.contracts.UCDToken;
|
|
79758
|
+
if (!eqAddr3(to, ucd)) {
|
|
79759
|
+
throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
79760
|
+
}
|
|
79761
|
+
const spender = String(args[0]);
|
|
79762
|
+
const ok = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
|
|
79763
|
+
if (!ok) {
|
|
79764
|
+
throw new TxValidationError3(
|
|
79765
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
79766
|
+
);
|
|
79767
|
+
}
|
|
79768
|
+
const amt = BigInt(String(args[1]));
|
|
79769
|
+
const min = BigInt(expected.minAmountWei);
|
|
79770
|
+
if (amt < min) {
|
|
79771
|
+
throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
|
|
79772
|
+
}
|
|
79773
|
+
const SANITY_MAX = min * 1000n;
|
|
79774
|
+
if (amt > SANITY_MAX) {
|
|
79775
|
+
throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
79776
|
+
}
|
|
79777
|
+
break;
|
|
79778
|
+
}
|
|
79779
|
+
case "create-position": {
|
|
79780
|
+
if (name !== "createPosition") {
|
|
79781
|
+
throw new TxValidationError3(`expected createPosition, server returned ${name}`);
|
|
79782
|
+
}
|
|
79783
|
+
if (!eqAddr3(to, pm)) {
|
|
79784
|
+
throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
79785
|
+
}
|
|
79786
|
+
const txTerm = BigInt(String(args[4]));
|
|
79787
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
79788
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
79789
|
+
}
|
|
79790
|
+
break;
|
|
79791
|
+
}
|
|
79792
|
+
case "set-position-delegate": {
|
|
79793
|
+
if (name !== "setPositionDelegate") {
|
|
79794
|
+
throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
|
|
79795
|
+
}
|
|
79796
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
79797
|
+
throw new TxValidationError3(
|
|
79798
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
79799
|
+
);
|
|
79800
|
+
}
|
|
79801
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79802
|
+
const txDelegate = String(args[1]);
|
|
79803
|
+
if (!eqAddr3(txDelegate, expected.delegate)) {
|
|
79804
|
+
throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
79805
|
+
}
|
|
79806
|
+
break;
|
|
79807
|
+
}
|
|
79808
|
+
case "bwar-add-address": {
|
|
79809
|
+
if (name !== "addAddress") {
|
|
79810
|
+
throw new TxValidationError3(`expected addAddress, decoded ${name}`);
|
|
79811
|
+
}
|
|
79812
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
79813
|
+
throw new TxValidationError3(
|
|
79814
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
79815
|
+
);
|
|
79816
|
+
}
|
|
79817
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
79818
|
+
throw new TxValidationError3(
|
|
79819
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
79820
|
+
);
|
|
79821
|
+
}
|
|
79822
|
+
break;
|
|
79823
|
+
}
|
|
79824
|
+
case "stablecoin-approve": {
|
|
79825
|
+
if (name !== "approve") {
|
|
79826
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79827
|
+
}
|
|
79828
|
+
if (!eqAddr3(to, expected.tokenAddress)) {
|
|
79829
|
+
throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
79830
|
+
}
|
|
79831
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
79832
|
+
throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
79833
|
+
}
|
|
79834
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
79835
|
+
throw new TxValidationError3(
|
|
79836
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
79837
|
+
);
|
|
79838
|
+
}
|
|
79839
|
+
break;
|
|
79840
|
+
}
|
|
79841
|
+
case "ucd-approve-controller": {
|
|
79842
|
+
if (name !== "approve") {
|
|
79843
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79844
|
+
}
|
|
79845
|
+
if (!eqAddr3(to, expected.ucdTokenAddress)) {
|
|
79846
|
+
throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
79847
|
+
}
|
|
79848
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
79849
|
+
throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
79850
|
+
}
|
|
79851
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
79852
|
+
throw new TxValidationError3(
|
|
79853
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
79854
|
+
);
|
|
79855
|
+
}
|
|
79856
|
+
break;
|
|
79857
|
+
}
|
|
79858
|
+
case "psm-swap": {
|
|
79859
|
+
if (name !== "swap")
|
|
79860
|
+
throw new TxValidationError3(`expected swap, server returned ${name}`);
|
|
79861
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
79862
|
+
throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
79863
|
+
}
|
|
79864
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
79865
|
+
throw new TxValidationError3(`swap stablecoin mismatch`);
|
|
79866
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
79867
|
+
throw new TxValidationError3(`swap amountIn mismatch`);
|
|
79868
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
79869
|
+
throw new TxValidationError3(`swap minUcdOut mismatch`);
|
|
79870
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
79871
|
+
throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
79872
|
+
}
|
|
79873
|
+
break;
|
|
79874
|
+
}
|
|
79875
|
+
case "psm-redeem": {
|
|
79876
|
+
if (name !== "redeem")
|
|
79877
|
+
throw new TxValidationError3(`expected redeem, server returned ${name}`);
|
|
79878
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
79879
|
+
throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
79880
|
+
}
|
|
79881
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
79882
|
+
throw new TxValidationError3(`redeem stablecoin mismatch`);
|
|
79883
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
79884
|
+
throw new TxValidationError3(`redeem ucdAmount mismatch`);
|
|
79885
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
79886
|
+
throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
|
|
79887
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
79888
|
+
throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
79889
|
+
}
|
|
79890
|
+
break;
|
|
79891
|
+
}
|
|
79892
|
+
default: {
|
|
79893
|
+
const _exhaustive = expected;
|
|
79894
|
+
throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
79895
|
+
}
|
|
79896
|
+
}
|
|
79897
|
+
}
|
|
79898
|
+
var SLOT_SECONDS2 = 12;
|
|
79899
|
+
var INCLUSION_SLOT_TOLERANCE2 = 3;
|
|
79900
|
+
var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
|
|
79901
|
+
function buildPsmApproveTx2(p) {
|
|
79902
|
+
return {
|
|
79903
|
+
to: p.token,
|
|
79904
|
+
data: encodeSignable3("approve", [p.spender, p.amount]),
|
|
79905
|
+
value: "0x0",
|
|
79906
|
+
chainId: p.chainId
|
|
79907
|
+
};
|
|
79908
|
+
}
|
|
79909
|
+
function buildPsmSwapTx3(p) {
|
|
79910
|
+
return {
|
|
79911
|
+
to: p.psm,
|
|
79912
|
+
data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
79913
|
+
value: "0x0",
|
|
79914
|
+
chainId: p.chainId
|
|
79915
|
+
};
|
|
79916
|
+
}
|
|
79917
|
+
function buildPsmRedeemTx3(p) {
|
|
79918
|
+
return {
|
|
79919
|
+
to: p.psm,
|
|
79920
|
+
data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
79921
|
+
value: "0x0",
|
|
79922
|
+
chainId: p.chainId
|
|
79923
|
+
};
|
|
79924
|
+
}
|
|
79925
|
+
var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
|
|
79926
|
+
var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
79927
|
+
function psmExchangeReadsFromProvider2(provider, psmAddress) {
|
|
79928
|
+
const psm = new import_ethers40.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
|
|
79929
|
+
return {
|
|
79930
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
79931
|
+
allowance: async (token, owner, spender) => await new import_ethers40.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
|
|
79932
|
+
};
|
|
79933
|
+
}
|
|
79934
|
+
var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
|
|
79935
|
+
function requireAddress2(direction, label, value) {
|
|
79936
|
+
if (!value || !import_ethers40.ethers.isAddress(value)) {
|
|
79937
|
+
throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
79938
|
+
}
|
|
79939
|
+
return import_ethers40.ethers.getAddress(value);
|
|
79940
|
+
}
|
|
79941
|
+
async function planPsmExchange2(params) {
|
|
79942
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
79943
|
+
const chainId = vctx.chainId;
|
|
79944
|
+
if (amountIn <= 0n) {
|
|
79945
|
+
throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
79946
|
+
}
|
|
79947
|
+
if (minOut <= 0n) {
|
|
79948
|
+
throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
79949
|
+
}
|
|
79950
|
+
const owner = requireAddress2(direction, "owner", params.owner);
|
|
79951
|
+
const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
|
|
79952
|
+
const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
|
|
79953
|
+
const isSwap = direction === "swap";
|
|
79954
|
+
const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
|
|
79955
|
+
const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
|
|
79956
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
79957
|
+
throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
79958
|
+
}
|
|
79959
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
79960
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
79961
|
+
const approvals = [];
|
|
79962
|
+
if (allowanceBefore < amountIn) {
|
|
79963
|
+
if (allowanceBefore > 0n) {
|
|
79964
|
+
approvals.push({
|
|
79965
|
+
step: "reset-approve",
|
|
79966
|
+
tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
|
|
79967
|
+
expected: approveExpected(0n)
|
|
79968
|
+
});
|
|
79969
|
+
}
|
|
79970
|
+
approvals.push({
|
|
79971
|
+
step: "approve",
|
|
79972
|
+
tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
|
|
79973
|
+
expected: approveExpected(amountIn)
|
|
79974
|
+
});
|
|
79975
|
+
}
|
|
79976
|
+
const exec = isSwap ? {
|
|
79977
|
+
step: "swap",
|
|
79978
|
+
tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
79979
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
79980
|
+
} : {
|
|
79981
|
+
step: "redeem",
|
|
79982
|
+
tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
79983
|
+
expected: {
|
|
79984
|
+
kind: "psm-redeem",
|
|
79985
|
+
psmAddress: psm,
|
|
79986
|
+
stablecoin,
|
|
79987
|
+
amountUcdWei: amountIn.toString(),
|
|
79988
|
+
minOut: minOut.toString()
|
|
79989
|
+
}
|
|
79990
|
+
};
|
|
79991
|
+
for (const leg of [...approvals, exec]) {
|
|
79992
|
+
validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
|
|
79993
|
+
}
|
|
79994
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
79995
|
+
}
|
|
79996
|
+
|
|
79997
|
+
// src/boundary/upstream/real/psm-calls.ts
|
|
78450
79998
|
var PSM_VIEW_FRAGMENTS = [
|
|
78451
79999
|
"function VERSION() view returns (string)",
|
|
78452
80000
|
"function supportedStablecoins(address) view returns (bool)",
|
|
@@ -78466,15 +80014,7 @@ var PSM_VIEW_FRAGMENTS = [
|
|
|
78466
80014
|
"function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
|
|
78467
80015
|
"function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
|
|
78468
80016
|
];
|
|
78469
|
-
var
|
|
78470
|
-
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) returns (uint256)",
|
|
78471
|
-
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) returns (uint256)"
|
|
78472
|
-
];
|
|
78473
|
-
var ERC20_FRAGMENTS = [
|
|
78474
|
-
"function approve(address spender, uint256 amount) returns (bool)",
|
|
78475
|
-
"function balanceOf(address holder) view returns (uint256)"
|
|
78476
|
-
];
|
|
78477
|
-
var ERC20_IFACE = new import_ethers31.ethers.Interface(ERC20_FRAGMENTS);
|
|
80017
|
+
var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
|
|
78478
80018
|
var PSM_ERROR_FRAGMENTS = [
|
|
78479
80019
|
"error StablecoinNotSupported(address stablecoin)",
|
|
78480
80020
|
"error InvalidAmount()",
|
|
@@ -78522,9 +80062,9 @@ var RENDERERS = {
|
|
|
78522
80062
|
var PsmCalls = class {
|
|
78523
80063
|
constructor(deps) {
|
|
78524
80064
|
this.deps = deps;
|
|
78525
|
-
const abi = [...PSM_VIEW_FRAGMENTS, ...
|
|
78526
|
-
this.iface = new
|
|
78527
|
-
this.psm = new
|
|
80065
|
+
const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
|
|
80066
|
+
this.iface = new import_ethers41.ethers.Interface(abi);
|
|
80067
|
+
this.psm = new import_ethers41.ethers.Contract(deps.psmAddress, abi, deps.provider);
|
|
78528
80068
|
}
|
|
78529
80069
|
psm;
|
|
78530
80070
|
iface;
|
|
@@ -78537,34 +80077,10 @@ var PsmCalls = class {
|
|
|
78537
80077
|
...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
|
|
78538
80078
|
};
|
|
78539
80079
|
}
|
|
78540
|
-
|
|
78541
|
-
|
|
78542
|
-
|
|
78543
|
-
|
|
78544
|
-
return {
|
|
78545
|
-
to: p.token,
|
|
78546
|
-
data: ERC20_IFACE.encodeFunctionData("approve", [p.spender, p.amount]),
|
|
78547
|
-
value: "0x0",
|
|
78548
|
-
chainId: p.chainId
|
|
78549
|
-
};
|
|
78550
|
-
}
|
|
78551
|
-
/** Step 2, stablecoin → UCD (contract `swap`). */
|
|
78552
|
-
buildSwap(p) {
|
|
78553
|
-
return {
|
|
78554
|
-
to: this.deps.psmAddress,
|
|
78555
|
-
data: this.iface.encodeFunctionData("swap", [this.deps.stablecoinAddress, p.amountIn, p.minOut]),
|
|
78556
|
-
value: "0x0",
|
|
78557
|
-
chainId: p.chainId
|
|
78558
|
-
};
|
|
78559
|
-
}
|
|
78560
|
-
/** Step 2, UCD → stablecoin (contract `redeem`). */
|
|
78561
|
-
buildRedeem(p) {
|
|
78562
|
-
return {
|
|
78563
|
-
to: this.deps.psmAddress,
|
|
78564
|
-
data: this.iface.encodeFunctionData("redeem", [this.deps.stablecoinAddress, p.ucdAmount, p.minOut]),
|
|
78565
|
-
value: "0x0",
|
|
78566
|
-
chainId: p.chainId
|
|
78567
|
-
};
|
|
80080
|
+
/** The two live reads the SDK's exchange planner depends on (supported set + allowance),
|
|
80081
|
+
* over this wrapper's provider and PSM. */
|
|
80082
|
+
exchangeReads() {
|
|
80083
|
+
return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
|
|
78568
80084
|
}
|
|
78569
80085
|
/** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
|
|
78570
80086
|
async balances(holder) {
|
|
@@ -78577,8 +80093,8 @@ var PsmCalls = class {
|
|
|
78577
80093
|
});
|
|
78578
80094
|
}
|
|
78579
80095
|
return this.call(async () => {
|
|
78580
|
-
const ucd = new
|
|
78581
|
-
const stable = new
|
|
80096
|
+
const ucd = new import_ethers41.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
|
|
80097
|
+
const stable = new import_ethers41.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
|
|
78582
80098
|
const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
|
|
78583
80099
|
return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
|
|
78584
80100
|
});
|
|
@@ -78696,7 +80212,7 @@ var PsmCalls = class {
|
|
|
78696
80212
|
};
|
|
78697
80213
|
|
|
78698
80214
|
// src/boundary/upstream/real/session.ts
|
|
78699
|
-
var
|
|
80215
|
+
var import_ethers42 = require("ethers");
|
|
78700
80216
|
var REFRESH_LEEWAY_SEC = 30;
|
|
78701
80217
|
var LOGIN_TYPES_WITH_AUDIENCE3 = {
|
|
78702
80218
|
DiamondHands: [
|
|
@@ -78744,7 +80260,7 @@ var LitOpsSession = class {
|
|
|
78744
80260
|
const message = {
|
|
78745
80261
|
address: this.wallet.address,
|
|
78746
80262
|
issuedAt: Math.floor(Date.now() / 1e3),
|
|
78747
|
-
nonce: "0x" + Buffer.from(
|
|
80263
|
+
nonce: "0x" + Buffer.from(import_ethers42.ethers.randomBytes(32)).toString("hex"),
|
|
78748
80264
|
audience: this.serviceEndpoint
|
|
78749
80265
|
};
|
|
78750
80266
|
const signature = await this.wallet.signTypedData(
|
|
@@ -78786,7 +80302,7 @@ function decodeJwtExp(token) {
|
|
|
78786
80302
|
}
|
|
78787
80303
|
|
|
78788
80304
|
// src/boundary/upstream/real/write-ops.ts
|
|
78789
|
-
var
|
|
80305
|
+
var import_ethers44 = require("ethers");
|
|
78790
80306
|
|
|
78791
80307
|
// src/signer/types.ts
|
|
78792
80308
|
var OperationDeclined = class extends Error {
|
|
@@ -78796,7 +80312,7 @@ var OperationDeclined = class extends Error {
|
|
|
78796
80312
|
init_tx_validator();
|
|
78797
80313
|
|
|
78798
80314
|
// src/boundary/upstream/shared/external-bridge/page-crypto.ts
|
|
78799
|
-
var
|
|
80315
|
+
var import_ethers43 = require("ethers");
|
|
78800
80316
|
var PERSONAL_SIGN_LAYOUTS = {
|
|
78801
80317
|
"dh-op-envelope-v1": {
|
|
78802
80318
|
types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
|
|
@@ -78817,9 +80333,9 @@ function hashForLayout(layout, fields) {
|
|
|
78817
80333
|
const values = def.fieldOrder.map((name) => {
|
|
78818
80334
|
const raw = fields[name];
|
|
78819
80335
|
if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
|
|
78820
|
-
return hashUtf8.has(name) ?
|
|
80336
|
+
return hashUtf8.has(name) ? import_ethers43.ethers.keccak256(import_ethers43.ethers.toUtf8Bytes(raw)) : raw;
|
|
78821
80337
|
});
|
|
78822
|
-
return
|
|
80338
|
+
return import_ethers43.ethers.solidityPackedKeccak256(def.types, values);
|
|
78823
80339
|
}
|
|
78824
80340
|
var PAGE_CRYPTO_JS = `"use strict";
|
|
78825
80341
|
(function () {
|
|
@@ -79048,9 +80564,21 @@ function buildValidationContext(network, chainId) {
|
|
|
79048
80564
|
|
|
79049
80565
|
// src/boundary/upstream/real/write-ops.ts
|
|
79050
80566
|
var SOURCE5 = "real-ops";
|
|
80567
|
+
function mcpExpected(leg) {
|
|
80568
|
+
const e = leg.expected;
|
|
80569
|
+
switch (e.kind) {
|
|
80570
|
+
case "stablecoin-approve":
|
|
80571
|
+
case "ucd-approve-controller":
|
|
80572
|
+
case "psm-swap":
|
|
80573
|
+
case "psm-redeem":
|
|
80574
|
+
return e;
|
|
80575
|
+
default:
|
|
80576
|
+
throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
|
|
80577
|
+
}
|
|
80578
|
+
}
|
|
79051
80579
|
var OP_LAYOUT = "dh-op-envelope-v1";
|
|
79052
80580
|
function randomNonceHex() {
|
|
79053
|
-
return "0x" + Buffer.from(
|
|
80581
|
+
return "0x" + Buffer.from(import_ethers44.ethers.randomBytes(16)).toString("hex");
|
|
79054
80582
|
}
|
|
79055
80583
|
async function postJson(url2, body, headers) {
|
|
79056
80584
|
const res = await fetch(url2, {
|
|
@@ -79111,7 +80639,7 @@ function buildWriteOps(deps) {
|
|
|
79111
80639
|
return {
|
|
79112
80640
|
to: String(tx2["to"] ?? ""),
|
|
79113
80641
|
data: String(tx2["data"] ?? "0x"),
|
|
79114
|
-
value: tx2["value"] != null ?
|
|
80642
|
+
value: tx2["value"] != null ? import_ethers44.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
|
|
79115
80643
|
chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
|
|
79116
80644
|
};
|
|
79117
80645
|
}
|
|
@@ -79196,8 +80724,9 @@ function buildWriteOps(deps) {
|
|
|
79196
80724
|
}
|
|
79197
80725
|
return {
|
|
79198
80726
|
createPosition: async (p) => {
|
|
79199
|
-
const
|
|
79200
|
-
if (!
|
|
80727
|
+
const built = await deps.getWriteSdk();
|
|
80728
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
80729
|
+
const sdk = built.sdk;
|
|
79201
80730
|
try {
|
|
79202
80731
|
await deps.assertValidatorConfigured();
|
|
79203
80732
|
} catch (e) {
|
|
@@ -79276,7 +80805,7 @@ function buildWriteOps(deps) {
|
|
|
79276
80805
|
mintedUcdWei: minted,
|
|
79277
80806
|
feeUcdWei: mintFee,
|
|
79278
80807
|
echoedAmountUcdWei: minted,
|
|
79279
|
-
authorization: auth(action, `mint ${
|
|
80808
|
+
authorization: auth(action, `mint ${import_ethers44.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
|
|
79280
80809
|
},
|
|
79281
80810
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79282
80811
|
);
|
|
@@ -79317,7 +80846,7 @@ function buildWriteOps(deps) {
|
|
|
79317
80846
|
txRef: { kind: "eth-tx", id: r.value.txHash },
|
|
79318
80847
|
paidUcdWei: paid,
|
|
79319
80848
|
echoedAmountUcdWei: paid,
|
|
79320
|
-
authorization: auth(action, `repay ${
|
|
80849
|
+
authorization: auth(action, `repay ${import_ethers44.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
|
|
79321
80850
|
},
|
|
79322
80851
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79323
80852
|
);
|
|
@@ -79357,8 +80886,9 @@ function buildWriteOps(deps) {
|
|
|
79357
80886
|
);
|
|
79358
80887
|
},
|
|
79359
80888
|
withdraw: async (p) => {
|
|
79360
|
-
const
|
|
79361
|
-
if (!
|
|
80889
|
+
const built = await deps.getWriteSdk();
|
|
80890
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
80891
|
+
const sdk = built.sdk;
|
|
79362
80892
|
const amountSats = Number(p.amountSats);
|
|
79363
80893
|
const feeSats = Number(p.networkFeeSats);
|
|
79364
80894
|
let result;
|
|
@@ -79387,12 +80917,13 @@ function buildWriteOps(deps) {
|
|
|
79387
80917
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79388
80918
|
);
|
|
79389
80919
|
},
|
|
79390
|
-
/** PSM exchange
|
|
79391
|
-
* orchestration.
|
|
79392
|
-
*
|
|
79393
|
-
*
|
|
79394
|
-
*
|
|
79395
|
-
*
|
|
80920
|
+
/** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
|
|
80921
|
+
* orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
|
|
80922
|
+
* builder every client shares (it replaced this file's own builders and the SDK's old
|
|
80923
|
+
* MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
|
|
80924
|
+
* allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
|
|
80925
|
+
* validated again here by the MCP's own whitelist (the one the approval card decodes
|
|
80926
|
+
* with), then signed through the session signer and broadcast — one at a time. */
|
|
79396
80927
|
psmSwap: async (p) => {
|
|
79397
80928
|
const pr = await deps.psm(p.stablecoin);
|
|
79398
80929
|
if (!pr.ok) return upFail(pr.failure);
|
|
@@ -79406,11 +80937,7 @@ function buildWriteOps(deps) {
|
|
|
79406
80937
|
message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
|
|
79407
80938
|
});
|
|
79408
80939
|
}
|
|
79409
|
-
const amountIn = BigInt(p.amountIn);
|
|
79410
|
-
const minOut = BigInt(p.minOut);
|
|
79411
80940
|
const vctx = buildValidationContext(config.network, chainId);
|
|
79412
|
-
const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
|
|
79413
|
-
const spenderAddress = isSwap ? addr.psm : addr.ucdController;
|
|
79414
80941
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
79415
80942
|
const tokenSymbol = isSwap ? calls.symbol() : "UCD";
|
|
79416
80943
|
const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
|
|
@@ -79427,49 +80954,66 @@ function buildWriteOps(deps) {
|
|
|
79427
80954
|
return submitFailure(leg, e);
|
|
79428
80955
|
}
|
|
79429
80956
|
};
|
|
79430
|
-
|
|
80957
|
+
let plan;
|
|
79431
80958
|
try {
|
|
79432
|
-
|
|
79433
|
-
|
|
79434
|
-
|
|
79435
|
-
|
|
79436
|
-
|
|
79437
|
-
|
|
79438
|
-
|
|
79439
|
-
|
|
79440
|
-
|
|
79441
|
-
const approveHashR = await broadcast("psmSwap (approve)", "psm-approve", approveTx);
|
|
79442
|
-
if (!approveHashR.ok) return approveHashR;
|
|
79443
|
-
const approveHash = approveHashR.value;
|
|
79444
|
-
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`;
|
|
79445
|
-
const execTx = isSwap ? calls.buildSwap({ amountIn, minOut, chainId }) : calls.buildRedeem({ ucdAmount: amountIn, minOut, chainId });
|
|
79446
|
-
try {
|
|
79447
|
-
validateUnsignedTx(
|
|
79448
|
-
{ ...execTx },
|
|
79449
|
-
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 },
|
|
79450
|
-
vctx
|
|
79451
|
-
);
|
|
80959
|
+
plan = await planPsmExchange2({
|
|
80960
|
+
direction: p.direction,
|
|
80961
|
+
owner: p.borrower,
|
|
80962
|
+
addresses: addr,
|
|
80963
|
+
amountIn: BigInt(p.amountIn),
|
|
80964
|
+
minOut: BigInt(p.minOut),
|
|
80965
|
+
vctx,
|
|
80966
|
+
reads: calls.exchangeReads()
|
|
80967
|
+
});
|
|
79452
80968
|
} catch (e) {
|
|
79453
|
-
return upFail({ kind: "rejected", source: SOURCE5, message:
|
|
80969
|
+
return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
|
|
80970
|
+
kind: "unavailable",
|
|
80971
|
+
source: SOURCE5,
|
|
80972
|
+
message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
|
|
80973
|
+
raw: String(e)
|
|
80974
|
+
});
|
|
79454
80975
|
}
|
|
79455
|
-
const
|
|
79456
|
-
const
|
|
79457
|
-
|
|
79458
|
-
|
|
79459
|
-
|
|
80976
|
+
const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
|
|
80977
|
+
const unit = `${tokenSymbol} smallest units`;
|
|
80978
|
+
const landed = [];
|
|
80979
|
+
const residualNote = () => {
|
|
80980
|
+
const last = landed[landed.length - 1];
|
|
80981
|
+
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`;
|
|
80982
|
+
return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
80983
|
+
};
|
|
80984
|
+
const runLeg = async (leg) => {
|
|
80985
|
+
const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
|
|
80986
|
+
try {
|
|
80987
|
+
validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
|
|
80988
|
+
} catch (e) {
|
|
80989
|
+
return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
|
|
80990
|
+
}
|
|
80991
|
+
const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
|
|
80992
|
+
const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
|
|
80993
|
+
return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
|
|
80994
|
+
};
|
|
80995
|
+
const approvals = [];
|
|
80996
|
+
for (const leg of plan.approvals) {
|
|
80997
|
+
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})`;
|
|
80998
|
+
const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
|
|
80999
|
+
const r = await runLeg(leg);
|
|
81000
|
+
if (!r.ok) return r;
|
|
81001
|
+
landed.push({ step, hash: r.value });
|
|
81002
|
+
approvals.push({
|
|
81003
|
+
step,
|
|
81004
|
+
txRef: { kind: "eth-tx", id: r.value },
|
|
81005
|
+
amount: leg.step === "reset-approve" ? "0" : p.amountIn,
|
|
81006
|
+
authorization: auth("psm-approve", card, r.value)
|
|
81007
|
+
});
|
|
79460
81008
|
}
|
|
81009
|
+
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}`;
|
|
81010
|
+
const execHashR = await runLeg(plan.exec);
|
|
81011
|
+
if (!execHashR.ok) return execHashR;
|
|
79461
81012
|
const execHash = execHashR.value;
|
|
79462
81013
|
const balancesR = await calls.balances(p.borrower);
|
|
79463
81014
|
const row = {
|
|
79464
|
-
|
|
79465
|
-
|
|
79466
|
-
tokenSymbol,
|
|
79467
|
-
tokenAddress,
|
|
79468
|
-
spenderAddress,
|
|
79469
|
-
spenderContract,
|
|
79470
|
-
amount: p.amountIn,
|
|
79471
|
-
authorization: auth("psm-approve", approveCard, approveHash)
|
|
79472
|
-
},
|
|
81015
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
81016
|
+
approvals,
|
|
79473
81017
|
execute: {
|
|
79474
81018
|
txRef: { kind: "eth-tx", id: execHash },
|
|
79475
81019
|
amountIn: p.amountIn,
|
|
@@ -79486,8 +81030,9 @@ function buildWriteOps(deps) {
|
|
|
79486
81030
|
// registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
|
|
79487
81031
|
// msg.sender, so their path is a SafeTx — never this keystore leg.
|
|
79488
81032
|
allowlistWithdrawalAddress: async (p) => {
|
|
79489
|
-
const
|
|
79490
|
-
if (!
|
|
81033
|
+
const built = await deps.getWriteSdk();
|
|
81034
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81035
|
+
const sdk = built.sdk;
|
|
79491
81036
|
let result;
|
|
79492
81037
|
try {
|
|
79493
81038
|
result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
|
|
@@ -79534,8 +81079,9 @@ function buildWriteOps(deps) {
|
|
|
79534
81079
|
message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
|
|
79535
81080
|
}),
|
|
79536
81081
|
retryWithdrawExecute: async (p) => {
|
|
79537
|
-
const
|
|
79538
|
-
if (!
|
|
81082
|
+
const built = await deps.getWriteSdk();
|
|
81083
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81084
|
+
const sdk = built.sdk;
|
|
79539
81085
|
let rows;
|
|
79540
81086
|
try {
|
|
79541
81087
|
rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
|
|
@@ -79563,7 +81109,7 @@ function buildWriteOps(deps) {
|
|
|
79563
81109
|
}
|
|
79564
81110
|
|
|
79565
81111
|
// src/signer/eoa-dh.ts
|
|
79566
|
-
var
|
|
81112
|
+
var import_ethers45 = require("ethers");
|
|
79567
81113
|
var EoaDHSigner = class {
|
|
79568
81114
|
constructor(wallet, broadcast, clock = Date.now) {
|
|
79569
81115
|
this.wallet = wallet;
|
|
@@ -79580,7 +81126,7 @@ var EoaDHSigner = class {
|
|
|
79580
81126
|
async signAuthorization(spec) {
|
|
79581
81127
|
const quantumTs = nextQuantumTimestamp(this.clock());
|
|
79582
81128
|
const { fields, hashHex } = spec.stamp(quantumTs);
|
|
79583
|
-
const signature = await this.wallet.signMessage(
|
|
81129
|
+
const signature = await this.wallet.signMessage(import_ethers45.ethers.getBytes(hashHex));
|
|
79584
81130
|
return { signature, quantumTs, fields };
|
|
79585
81131
|
}
|
|
79586
81132
|
async wrapInnerTx(innerTx) {
|
|
@@ -79598,10 +81144,10 @@ var EoaDHSigner = class {
|
|
|
79598
81144
|
|
|
79599
81145
|
// src/signer/external-eoa.ts
|
|
79600
81146
|
var import_node_crypto5 = require("crypto");
|
|
79601
|
-
var
|
|
81147
|
+
var import_ethers47 = require("ethers");
|
|
79602
81148
|
|
|
79603
81149
|
// src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
|
|
79604
|
-
var
|
|
81150
|
+
var import_ethers46 = require("ethers");
|
|
79605
81151
|
function eq2(a, b) {
|
|
79606
81152
|
return a.toLowerCase() === b.toLowerCase();
|
|
79607
81153
|
}
|
|
@@ -79624,7 +81170,7 @@ function compareLandedTx(landed, approved, borrower) {
|
|
|
79624
81170
|
return { status: "verified", from: landed.from, hash: landed.hash };
|
|
79625
81171
|
}
|
|
79626
81172
|
function verifyRawSignedTx(rawSignedTx, approved, borrower) {
|
|
79627
|
-
const parsed =
|
|
81173
|
+
const parsed = import_ethers46.ethers.Transaction.from(rawSignedTx);
|
|
79628
81174
|
if (!parsed.from || !parsed.to || !parsed.hash) {
|
|
79629
81175
|
return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
|
|
79630
81176
|
}
|
|
@@ -79662,7 +81208,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
|
|
|
79662
81208
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
79663
81209
|
try {
|
|
79664
81210
|
const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
|
|
79665
|
-
return
|
|
81211
|
+
return import_ethers47.ethers.toBeHex(est * 15n / 10n);
|
|
79666
81212
|
} catch (e) {
|
|
79667
81213
|
lastErr = e;
|
|
79668
81214
|
await new Promise((r) => setTimeout(r, 13e3));
|
|
@@ -79712,7 +81258,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79712
81258
|
throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
|
|
79713
81259
|
}
|
|
79714
81260
|
const finalHash = spec.stamp(used.quantumTs).hashHex;
|
|
79715
|
-
const recovered =
|
|
81261
|
+
const recovered = import_ethers47.ethers.verifyMessage(import_ethers47.ethers.getBytes(finalHash), outcome.signature);
|
|
79716
81262
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
79717
81263
|
throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
79718
81264
|
}
|
|
@@ -79723,7 +81269,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79723
81269
|
}
|
|
79724
81270
|
async submitValidatedTx(outerTx, ctx) {
|
|
79725
81271
|
const approved = toApprovedTx(outerTx, this.deps.chainId);
|
|
79726
|
-
const gas = outerTx.gasLimit != null ?
|
|
81272
|
+
const gas = outerTx.gasLimit != null ? import_ethers47.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
|
|
79727
81273
|
const outcome = await this.deps.bridge.requestSignature({
|
|
79728
81274
|
id: (0, import_node_crypto5.randomUUID)(),
|
|
79729
81275
|
kind: "transaction",
|
|
@@ -79757,7 +81303,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79757
81303
|
return new BridgeEthersSigner(this.deps);
|
|
79758
81304
|
}
|
|
79759
81305
|
};
|
|
79760
|
-
var BridgeEthersSigner = class _BridgeEthersSigner extends
|
|
81306
|
+
var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers47.ethers.AbstractSigner {
|
|
79761
81307
|
constructor(deps) {
|
|
79762
81308
|
super(deps.provider);
|
|
79763
81309
|
this.deps = deps;
|
|
@@ -79768,13 +81314,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79768
81314
|
return this.deps.borrower;
|
|
79769
81315
|
}
|
|
79770
81316
|
async signMessage(message) {
|
|
79771
|
-
const bytes = typeof message === "string" ?
|
|
81317
|
+
const bytes = typeof message === "string" ? import_ethers47.ethers.toUtf8Bytes(message) : message;
|
|
79772
81318
|
if (bytes.length !== 32) {
|
|
79773
81319
|
throw new Error(
|
|
79774
81320
|
`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.`
|
|
79775
81321
|
);
|
|
79776
81322
|
}
|
|
79777
|
-
const hashHex =
|
|
81323
|
+
const hashHex = import_ethers47.ethers.hexlify(bytes).toLowerCase();
|
|
79778
81324
|
const nowMs = (this.deps.clock ?? Date.now)();
|
|
79779
81325
|
const expiresAtSec = nextQuantumTimestamp(nowMs);
|
|
79780
81326
|
const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
|
|
@@ -79804,7 +81350,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79804
81350
|
if (outcome.status !== "approved" || !outcome.signature) {
|
|
79805
81351
|
throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
|
|
79806
81352
|
}
|
|
79807
|
-
const recovered =
|
|
81353
|
+
const recovered = import_ethers47.ethers.verifyMessage(bytes, outcome.signature);
|
|
79808
81354
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
79809
81355
|
throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
79810
81356
|
}
|
|
@@ -79838,11 +81384,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79838
81384
|
const approved = {
|
|
79839
81385
|
to: tx2.to,
|
|
79840
81386
|
data: tx2.data,
|
|
79841
|
-
value: tx2.value != null ?
|
|
81387
|
+
value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
79842
81388
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
|
|
79843
81389
|
};
|
|
79844
81390
|
const card = cardForTx(approved);
|
|
79845
|
-
const gas = tx2.gasLimit != null ?
|
|
81391
|
+
const gas = tx2.gasLimit != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
|
|
79846
81392
|
const outcome = await this.deps.bridge.requestSignature({
|
|
79847
81393
|
id: (0, import_node_crypto5.randomUUID)(),
|
|
79848
81394
|
kind: "transaction",
|
|
@@ -79884,14 +81430,14 @@ function toApprovedTx(tx2, fallbackChainId) {
|
|
|
79884
81430
|
return {
|
|
79885
81431
|
to: tx2.to,
|
|
79886
81432
|
data: tx2.data,
|
|
79887
|
-
value: tx2.value != null ?
|
|
81433
|
+
value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
79888
81434
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
|
|
79889
81435
|
};
|
|
79890
81436
|
}
|
|
79891
81437
|
function describeFn(data) {
|
|
79892
81438
|
try {
|
|
79893
|
-
const { decodeSignable:
|
|
79894
|
-
return
|
|
81439
|
+
const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
|
|
81440
|
+
return decodeSignable4(data).name;
|
|
79895
81441
|
} catch {
|
|
79896
81442
|
return "operation";
|
|
79897
81443
|
}
|
|
@@ -79928,7 +81474,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
|
|
|
79928
81474
|
var RealUpstreamPlugin = class {
|
|
79929
81475
|
constructor(config, wallet, runtime) {
|
|
79930
81476
|
this.config = config;
|
|
79931
|
-
this.provider = new
|
|
81477
|
+
this.provider = new import_ethers48.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
|
|
79932
81478
|
this.wallet = wallet ?? null;
|
|
79933
81479
|
this.runtime = runtime ?? null;
|
|
79934
81480
|
this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
|
|
@@ -80121,18 +81667,24 @@ var RealUpstreamPlugin = class {
|
|
|
80121
81667
|
* the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
|
|
80122
81668
|
* and the service-mode SDK routes its own subgraph reads through the same proxy — so
|
|
80123
81669
|
* writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
|
|
80124
|
-
* Safe to call repeatedly
|
|
80125
|
-
*
|
|
81670
|
+
* Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
|
|
81671
|
+
* first write builds again (see ensureSdk). */
|
|
80126
81672
|
async initWriteSdk() {
|
|
80127
81673
|
if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
|
|
80128
81674
|
const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
|
|
80129
81675
|
if (!wallet) return;
|
|
80130
81676
|
await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
|
|
80131
81677
|
}
|
|
80132
|
-
/**
|
|
80133
|
-
*
|
|
81678
|
+
/** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
|
|
81679
|
+
*
|
|
81680
|
+
* A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
|
|
81681
|
+
* life of the process and drop the error, which was survivable only while `create` never
|
|
81682
|
+
* touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
|
|
81683
|
+
* RPC blip at boot would have disabled every later write with no reason given. Now each write
|
|
81684
|
+
* retries, and a persistent failure says what it is. Concurrent callers share one build. */
|
|
80134
81685
|
async ensureSdk(key, signer) {
|
|
80135
|
-
|
|
81686
|
+
const cached = this.sdkCache.get(key);
|
|
81687
|
+
if (cached) return { ok: true, sdk: cached };
|
|
80136
81688
|
const inFlight = this.sdkInFlight.get(key);
|
|
80137
81689
|
if (inFlight) return inFlight;
|
|
80138
81690
|
const build = (async () => {
|
|
@@ -80152,17 +81704,23 @@ var RealUpstreamPlugin = class {
|
|
|
80152
81704
|
// nesting writes under indexer discovery (the M8B-4 coupling this removes).
|
|
80153
81705
|
...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
|
|
80154
81706
|
});
|
|
80155
|
-
|
|
80156
|
-
|
|
80157
|
-
|
|
81707
|
+
if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
|
|
81708
|
+
return { ok: false, reason: builtWrite.error.message };
|
|
81709
|
+
} catch (e) {
|
|
81710
|
+
return { ok: false, reason: e instanceof Error ? e.message : String(e) };
|
|
80158
81711
|
}
|
|
80159
81712
|
})();
|
|
80160
81713
|
this.sdkInFlight.set(key, build);
|
|
80161
81714
|
const built = await build;
|
|
80162
81715
|
this.sdkInFlight.delete(key);
|
|
80163
|
-
this.sdkCache.set(key, built);
|
|
81716
|
+
if (built.ok) this.sdkCache.set(key, built.sdk);
|
|
80164
81717
|
return built;
|
|
80165
81718
|
}
|
|
81719
|
+
/** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
|
|
81720
|
+
async writeSdkFor(key, signer) {
|
|
81721
|
+
const built = await this.ensureSdk(key, signer);
|
|
81722
|
+
return built.ok ? { ok: true, sdk: built.sdk } : built;
|
|
81723
|
+
}
|
|
80166
81724
|
wallet;
|
|
80167
81725
|
// ---- per-call signer resolution (plan 10 A3) ----
|
|
80168
81726
|
/** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
|
|
@@ -80202,7 +81760,7 @@ var RealUpstreamPlugin = class {
|
|
|
80202
81760
|
chainId: this.config.chainId,
|
|
80203
81761
|
dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
|
|
80204
81762
|
session,
|
|
80205
|
-
getWriteSdk: () => this.
|
|
81763
|
+
getWriteSdk: () => this.writeSdkFor(key, wallet),
|
|
80206
81764
|
readDetails: (id) => this.readPositionDetails(id),
|
|
80207
81765
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
80208
81766
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
@@ -80218,14 +81776,14 @@ var RealUpstreamPlugin = class {
|
|
|
80218
81776
|
if (!pkpValidation) {
|
|
80219
81777
|
throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
|
|
80220
81778
|
}
|
|
80221
|
-
const registry = new
|
|
81779
|
+
const registry = new import_ethers48.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
|
|
80222
81780
|
let validator;
|
|
80223
81781
|
try {
|
|
80224
81782
|
validator = await registry.validatorForVersion(version2);
|
|
80225
81783
|
} catch (e) {
|
|
80226
81784
|
throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
|
|
80227
81785
|
}
|
|
80228
|
-
if (validator ===
|
|
81786
|
+
if (validator === import_ethers48.ethers.ZeroAddress) {
|
|
80229
81787
|
throw new Error(
|
|
80230
81788
|
`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.`
|
|
80231
81789
|
);
|
|
@@ -80299,7 +81857,6 @@ var RealUpstreamPlugin = class {
|
|
|
80299
81857
|
gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
|
|
80300
81858
|
this.opsGatewayCache.set(key, gateway);
|
|
80301
81859
|
}
|
|
80302
|
-
await this.ensureSdk(key, wallet.connect(this.provider));
|
|
80303
81860
|
return { ok: true, gateway };
|
|
80304
81861
|
}
|
|
80305
81862
|
if (mode === "external") {
|
|
@@ -80336,14 +81893,13 @@ var RealUpstreamPlugin = class {
|
|
|
80336
81893
|
chainId: this.config.chainId,
|
|
80337
81894
|
dhSigner: new ExternalEoaDHSigner(deps),
|
|
80338
81895
|
session,
|
|
80339
|
-
getWriteSdk: () => this.
|
|
81896
|
+
getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
|
|
80340
81897
|
readDetails: (id) => this.readPositionDetails(id),
|
|
80341
81898
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
80342
81899
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
80343
81900
|
});
|
|
80344
81901
|
this.opsGatewayCache.set(key, gateway);
|
|
80345
81902
|
}
|
|
80346
|
-
await this.ensureSdk(key, this.externalSigners.get(key));
|
|
80347
81903
|
return { ok: true, gateway };
|
|
80348
81904
|
}
|
|
80349
81905
|
return {
|
|
@@ -80503,7 +82059,7 @@ var RealUpstreamPlugin = class {
|
|
|
80503
82059
|
);
|
|
80504
82060
|
if (!r.ok) return r;
|
|
80505
82061
|
const raw = r.value.data.supportedStablecoins ?? [];
|
|
80506
|
-
const bad = raw.find((x) => !
|
|
82062
|
+
const bad = raw.find((x) => !import_ethers48.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
|
|
80507
82063
|
if (bad) {
|
|
80508
82064
|
return {
|
|
80509
82065
|
ok: false,
|
|
@@ -80586,7 +82142,7 @@ var RealUpstreamPlugin = class {
|
|
|
80586
82142
|
};
|
|
80587
82143
|
}
|
|
80588
82144
|
const symbol = raw.toLowerCase();
|
|
80589
|
-
if (
|
|
82145
|
+
if (import_ethers48.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
|
|
80590
82146
|
const verified = await this.verifiedStablecoins();
|
|
80591
82147
|
if (!verified.ok) return { ok: false, failure: verified.failure };
|
|
80592
82148
|
const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
|
|
@@ -80624,7 +82180,7 @@ var RealUpstreamPlugin = class {
|
|
|
80624
82180
|
* chain, then sign.
|
|
80625
82181
|
*/
|
|
80626
82182
|
async psmCallsFor(stablecoinAddress) {
|
|
80627
|
-
if (!
|
|
82183
|
+
if (!import_ethers48.ethers.isAddress(stablecoinAddress)) {
|
|
80628
82184
|
throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
|
|
80629
82185
|
}
|
|
80630
82186
|
const key = stablecoinAddress.toLowerCase();
|
|
@@ -80644,9 +82200,9 @@ var RealUpstreamPlugin = class {
|
|
|
80644
82200
|
let supported;
|
|
80645
82201
|
let symbol;
|
|
80646
82202
|
try {
|
|
80647
|
-
const psm = new
|
|
82203
|
+
const psm = new import_ethers48.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
|
|
80648
82204
|
supported = await psm["supportedStablecoins"](key);
|
|
80649
|
-
const erc20 = new
|
|
82205
|
+
const erc20 = new import_ethers48.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
|
|
80650
82206
|
symbol = await erc20["symbol"]();
|
|
80651
82207
|
} catch (e) {
|
|
80652
82208
|
return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
|
|
@@ -80859,7 +82415,7 @@ var RealUpstreamPlugin = class {
|
|
|
80859
82415
|
const pm = this.contracts["PositionManager"];
|
|
80860
82416
|
if (!pm) return false;
|
|
80861
82417
|
try {
|
|
80862
|
-
const c = new
|
|
82418
|
+
const c = new import_ethers48.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
|
|
80863
82419
|
return Boolean(await c["paused"]());
|
|
80864
82420
|
} catch {
|
|
80865
82421
|
return false;
|
|
@@ -80868,16 +82424,16 @@ var RealUpstreamPlugin = class {
|
|
|
80868
82424
|
async readPositionDetails(id) {
|
|
80869
82425
|
const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
|
|
80870
82426
|
if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
|
|
80871
|
-
const c = new
|
|
82427
|
+
const c = new import_ethers48.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
|
|
80872
82428
|
let d;
|
|
80873
82429
|
try {
|
|
80874
|
-
d = await c["getPositionDetails"](
|
|
82430
|
+
d = await c["getPositionDetails"](import_ethers48.ethers.zeroPadValue(id, 32));
|
|
80875
82431
|
} catch (e) {
|
|
80876
82432
|
if (e.code === "CALL_EXCEPTION") return null;
|
|
80877
82433
|
throw e;
|
|
80878
82434
|
}
|
|
80879
82435
|
const borrower = String(d["borrower"]);
|
|
80880
|
-
if (borrower ===
|
|
82436
|
+
if (borrower === import_ethers48.ethers.ZeroAddress) return null;
|
|
80881
82437
|
return {
|
|
80882
82438
|
positionId: String(d["positionId"]),
|
|
80883
82439
|
pkpId: String(d["pkpId"]),
|