@gvnrdao/dh-mcp 0.5.16 → 0.5.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -35
- package/dist/boundary.js +1933 -359
- package/dist/connector-embed.js +1969 -512
- package/dist/connector.js +1969 -512
- package/dist/index.js +1952 -375
- package/package.json +2 -2
package/dist/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) {
|
|
@@ -43221,9 +43276,25 @@ var SignerManager = class {
|
|
|
43221
43276
|
pendingCeremonies: this.deps.pendingCeremonies()
|
|
43222
43277
|
};
|
|
43223
43278
|
}
|
|
43224
|
-
/**
|
|
43279
|
+
/**
|
|
43280
|
+
* The conversational first-run text every write answers with under mode `none`.
|
|
43281
|
+
*
|
|
43282
|
+
* It states the SCOPE of the refusal first, because the tool list does not change with
|
|
43283
|
+
* signer mode: an assistant that meets this on `loan_mint` still sees `loan_pay`,
|
|
43284
|
+
* `loan_withdraw` and `psm_swap` advertised, and its natural next move is to try one
|
|
43285
|
+
* rather than to run setup. Every one of them refuses identically here
|
|
43286
|
+
* (`BoundaryCore.requireBorrower`), so without that sentence the model rediscovers the
|
|
43287
|
+
* same wall N times and the user watches it flail. Naming the scope converts N refusals
|
|
43288
|
+
* into one instruction.
|
|
43289
|
+
*
|
|
43290
|
+
* It also says reads still work, so "no signer" is not misread as "server broken", and
|
|
43291
|
+
* it offers ONLY the modes this composition can actually construct — a build with no
|
|
43292
|
+
* keystore runtime must not suggest one (the same rule G-CONN-14 holds the guide to).
|
|
43293
|
+
*/
|
|
43225
43294
|
invitation() {
|
|
43226
|
-
|
|
43295
|
+
const keystoreOffered = this.deps.keystore !== null;
|
|
43296
|
+
const options = keystoreOffered ? "(1) 'use my own wallet' \u2014 you approve each operation in YOUR wallet (MetaMask popup, or a mobile wallet via WalletConnect); (2) 'sign automatically' \u2014 a local keystore signs after each confirmation. " : "'use my own wallet' \u2014 you approve each operation in YOUR wallet. It is the only mode this build offers. ";
|
|
43297
|
+
return `No authorization mode is chosen yet, so EVERY fund-moving tool will refuse with this same message until one is \u2014 trying a different write tool will not get past it. Reading is unaffected: prices, protocol terms and position data all work right now. To move funds, choose how to approve it: ${options}Tell the agent which you prefer (it calls signer_setup), or ask for 'guide first-setup'.`;
|
|
43227
43298
|
}
|
|
43228
43299
|
};
|
|
43229
43300
|
var KeystoreProvider = class {
|
|
@@ -43900,8 +43971,9 @@ var MockUpstreamPlugin = class {
|
|
|
43900
43971
|
return upOk({ grant: r.value, authorization: sig.authorization }, this.src("mock-ops"));
|
|
43901
43972
|
});
|
|
43902
43973
|
}
|
|
43903
|
-
/** PSM exchange
|
|
43904
|
-
* approve
|
|
43974
|
+
/** PSM exchange (plan 08 W1; seam 1.4): the approve legs the standing allowance needs (0, 1
|
|
43975
|
+
* or reset + approve — `psmApprovalSteps`) in ONE ops call, each exact-amount (spender
|
|
43976
|
+
* asymmetric by direction, contract truth), then the swap/redeem with
|
|
43905
43977
|
* its mandatory floor. Doomed pairs refuse BEFORE any ceremony (planPsmSwap); a decline
|
|
43906
43978
|
* AFTER the approve reports the step that declined AND the residual exact-amount
|
|
43907
43979
|
* allowance honestly (it stands in the world, as it would on-chain). No retry loops. */
|
|
@@ -43920,55 +43992,75 @@ var MockUpstreamPlugin = class {
|
|
|
43920
43992
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
43921
43993
|
const spenderAddress = isSwap ? psmAddress : SINK_CONTRACTS["UCDController"];
|
|
43922
43994
|
const spenderReason = isSwap ? "the PSM pulls the USDC it converts" : "the PSM burns your UCD through the UCDController";
|
|
43923
|
-
const
|
|
43924
|
-
const
|
|
43995
|
+
const standing = this.world.psmAllowancesOf(p.borrower);
|
|
43996
|
+
const allowanceBefore = BigInt(isSwap ? standing.usdcToPsm : standing.ucdToController);
|
|
43997
|
+
const steps = psmApprovalSteps(allowanceBefore, BigInt(p.amountIn));
|
|
43998
|
+
const landed = [];
|
|
43999
|
+
const residualNote = () => {
|
|
44000
|
+
const last = landed[landed.length - 1];
|
|
44001
|
+
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`;
|
|
44002
|
+
return `${state}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
44003
|
+
};
|
|
43925
44004
|
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
44005
|
const declinedMessage = (leg) => leg.ok ? "" : leg.failure.message;
|
|
43927
44006
|
const cer = this.ceremonyNow();
|
|
43928
|
-
|
|
43929
|
-
|
|
43930
|
-
const
|
|
43931
|
-
const
|
|
43932
|
-
const
|
|
43933
|
-
|
|
43934
|
-
|
|
43935
|
-
|
|
43936
|
-
|
|
43937
|
-
|
|
43938
|
-
|
|
43939
|
-
|
|
43940
|
-
|
|
43941
|
-
|
|
43942
|
-
|
|
44007
|
+
const approvals = [];
|
|
44008
|
+
for (const s of steps) {
|
|
44009
|
+
const amount = s.amount.toString();
|
|
44010
|
+
const isReset = s.step === "reset-approve";
|
|
44011
|
+
const label = isReset ? "RESET-APPROVE" : "APPROVE";
|
|
44012
|
+
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";
|
|
44013
|
+
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})`;
|
|
44014
|
+
let legAuth = null;
|
|
44015
|
+
if (cer) {
|
|
44016
|
+
const chainId = cer.txContext().chainId;
|
|
44017
|
+
const r = await cer.authorizeTx({
|
|
44018
|
+
action: "psm-approve",
|
|
44019
|
+
borrower: p.borrower,
|
|
44020
|
+
tx: buildApproveTx(chainId, { token: tokenAddress, spender: spenderAddress, amount }),
|
|
44021
|
+
expected: isSwap ? { kind: "stablecoin-approve", tokenAddress, spender: spenderAddress, amountUnits: amount } : { kind: "ucd-approve-controller", ucdTokenAddress: tokenAddress, spender: spenderAddress, amountWei: amount }
|
|
43943
44022
|
});
|
|
44023
|
+
if (!r.ok) {
|
|
44024
|
+
return upFail({
|
|
44025
|
+
kind: "rejected",
|
|
44026
|
+
source: "mock-ops",
|
|
44027
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(r.failure)} \u2014 ${stopNote}`
|
|
44028
|
+
});
|
|
44029
|
+
}
|
|
44030
|
+
this.bindIfDiscovering(r.authorization);
|
|
44031
|
+
legAuth = r.authorization;
|
|
43944
44032
|
}
|
|
43945
|
-
this.
|
|
43946
|
-
|
|
43947
|
-
|
|
43948
|
-
|
|
43949
|
-
|
|
43950
|
-
|
|
43951
|
-
|
|
43952
|
-
|
|
43953
|
-
|
|
43954
|
-
|
|
44033
|
+
const leg = await this.write("psmSwap", () => {
|
|
44034
|
+
const sig = legAuth ? { ok: true, authorization: legAuth } : this.sign("psm-approve", p.borrower, card);
|
|
44035
|
+
if (!sig.ok) {
|
|
44036
|
+
return upFail({
|
|
44037
|
+
kind: "rejected",
|
|
44038
|
+
source: "mock-ops",
|
|
44039
|
+
message: `psmSwap declined at the ${label} step: ${declinedMessage(sig.failure)} \u2014 ${stopNote}`
|
|
44040
|
+
});
|
|
44041
|
+
}
|
|
44042
|
+
const applied = this.applyAuthorized(sig.authorization, () => {
|
|
44043
|
+
this.world.psmApprove({ direction: p.direction, owner: p.borrower, amount });
|
|
44044
|
+
return { ok: true, value: void 0 };
|
|
43955
44045
|
});
|
|
43956
|
-
|
|
43957
|
-
|
|
43958
|
-
|
|
43959
|
-
|
|
44046
|
+
if (!applied.ok) {
|
|
44047
|
+
return upFail({
|
|
44048
|
+
kind: "rejected",
|
|
44049
|
+
source: "mock-ops",
|
|
44050
|
+
message: `psmSwap failed at the ${label} step: ${applied.reason} \u2014 ${stopNote}`
|
|
44051
|
+
});
|
|
44052
|
+
}
|
|
44053
|
+
return upOk(sig.authorization, this.src("mock-ops"));
|
|
43960
44054
|
});
|
|
43961
|
-
if (!
|
|
43962
|
-
|
|
43963
|
-
|
|
43964
|
-
|
|
43965
|
-
|
|
43966
|
-
|
|
43967
|
-
|
|
43968
|
-
|
|
43969
|
-
}
|
|
43970
|
-
if (!step1.ok) return step1;
|
|
43971
|
-
const aAuth = step1.value;
|
|
44055
|
+
if (!leg.ok) return leg;
|
|
44056
|
+
landed.push(s.step);
|
|
44057
|
+
approvals.push({
|
|
44058
|
+
step: s.step,
|
|
44059
|
+
txRef: legAuth ? { kind: "eth-tx", id: leg.value.digest } : this.world.nextTxRef(),
|
|
44060
|
+
amount,
|
|
44061
|
+
authorization: leg.value
|
|
44062
|
+
});
|
|
44063
|
+
}
|
|
43972
44064
|
let executeAuth = null;
|
|
43973
44065
|
if (cer) {
|
|
43974
44066
|
const chainId = cer.txContext().chainId;
|
|
@@ -43983,7 +44075,7 @@ var MockUpstreamPlugin = class {
|
|
|
43983
44075
|
return upFail({
|
|
43984
44076
|
kind: "rejected",
|
|
43985
44077
|
source: "mock-ops",
|
|
43986
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote}`
|
|
44078
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(r.failure)} \u2014 ${residualNote()}`
|
|
43987
44079
|
});
|
|
43988
44080
|
}
|
|
43989
44081
|
executeAuth = r.authorization;
|
|
@@ -43994,23 +44086,16 @@ var MockUpstreamPlugin = class {
|
|
|
43994
44086
|
return upFail({
|
|
43995
44087
|
kind: "rejected",
|
|
43996
44088
|
source: "mock-ops",
|
|
43997
|
-
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote}`
|
|
44089
|
+
message: `psmSwap declined at the ${isSwap ? "SWAP" : "REDEEM"} step: ${declinedMessage(sig.failure)} \u2014 ${residualNote()}`
|
|
43998
44090
|
});
|
|
43999
44091
|
}
|
|
44000
44092
|
const r = this.applyAuthorized(sig.authorization, () => this.world.psmExecute(p));
|
|
44001
|
-
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote}`);
|
|
44093
|
+
if (!r.ok) return this.rejected("psmSwap", `${r.reason} \u2014 ${residualNote()}`);
|
|
44002
44094
|
const bal = this.world.balancesOf(p.borrower);
|
|
44003
44095
|
return upOk(
|
|
44004
44096
|
{
|
|
44005
|
-
|
|
44006
|
-
|
|
44007
|
-
tokenSymbol,
|
|
44008
|
-
tokenAddress,
|
|
44009
|
-
spenderAddress,
|
|
44010
|
-
spenderContract,
|
|
44011
|
-
amount: p.amountIn,
|
|
44012
|
-
authorization: aAuth
|
|
44013
|
-
},
|
|
44097
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
44098
|
+
approvals,
|
|
44014
44099
|
execute: {
|
|
44015
44100
|
txRef: executeAuth ? { kind: "eth-tx", id: sig.authorization.digest } : this.world.nextTxRef(),
|
|
44016
44101
|
amountIn: p.amountIn,
|
|
@@ -45191,7 +45276,7 @@ var SafeModuleCeremony = class {
|
|
|
45191
45276
|
};
|
|
45192
45277
|
|
|
45193
45278
|
// src/boundary/upstream/real/plugin.ts
|
|
45194
|
-
var
|
|
45279
|
+
var import_ethers48 = require("ethers");
|
|
45195
45280
|
|
|
45196
45281
|
// node_modules/@gvnrdao/dh-sdk/dist/index.mjs
|
|
45197
45282
|
var import_ethers13 = require("ethers");
|
|
@@ -51282,8 +51367,12 @@ var {
|
|
|
51282
51367
|
var import_ethers27 = require("ethers");
|
|
51283
51368
|
var import_ethers28 = require("ethers");
|
|
51284
51369
|
var import_ethers29 = require("ethers");
|
|
51285
|
-
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
51286
51370
|
var import_ethers30 = require("ethers");
|
|
51371
|
+
var import_ethers31 = require("ethers");
|
|
51372
|
+
var import_ethers32 = require("ethers");
|
|
51373
|
+
var import_ethers33 = require("ethers");
|
|
51374
|
+
var import_dh_lit_ops = __toESM(require_dist3(), 1);
|
|
51375
|
+
var import_ethers34 = require("ethers");
|
|
51287
51376
|
var __create2 = Object.create;
|
|
51288
51377
|
var __defProp2 = Object.defineProperty;
|
|
51289
51378
|
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
@@ -53646,7 +53735,7 @@ ${errorReport}`);
|
|
|
53646
53735
|
}
|
|
53647
53736
|
init_debug_logger();
|
|
53648
53737
|
init_session_signature_cache();
|
|
53649
|
-
var
|
|
53738
|
+
var import_ethers232 = __require("ethers");
|
|
53650
53739
|
var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
|
|
53651
53740
|
var GRACE_PERIOD_DAYS = 30;
|
|
53652
53741
|
var SATOSHIS_PER_BITCOIN = 100000000n;
|
|
@@ -56574,12 +56663,12 @@ ${auth.clientId}`;
|
|
|
56574
56663
|
}
|
|
56575
56664
|
async function executeVaultSnapshot(params) {
|
|
56576
56665
|
global.ethers = {
|
|
56577
|
-
...
|
|
56666
|
+
...import_ethers232.ethers,
|
|
56578
56667
|
providers: {
|
|
56579
|
-
StaticJsonRpcProvider:
|
|
56668
|
+
StaticJsonRpcProvider: import_ethers232.ethers.JsonRpcProvider
|
|
56580
56669
|
},
|
|
56581
|
-
Contract:
|
|
56582
|
-
utils:
|
|
56670
|
+
Contract: import_ethers232.ethers.Contract,
|
|
56671
|
+
utils: import_ethers232.ethers
|
|
56583
56672
|
// v6 moved utils to top level
|
|
56584
56673
|
};
|
|
56585
56674
|
global.Lit = {
|
|
@@ -56833,8 +56922,8 @@ function getSepoliaConfig() {
|
|
|
56833
56922
|
positionManagerCore: SEPOLIA_CONTRACTS.PositionManagerCoreModule || "",
|
|
56834
56923
|
positionManagerViews: SEPOLIA_CONTRACTS.PositionManagerViews || "",
|
|
56835
56924
|
simplePsmV2: SEPOLIA_CONTRACTS.SimplePSMV2 || "",
|
|
56836
|
-
mockUsdcToken: SEPOLIA_CONTRACTS
|
|
56837
|
-
mockUsdtToken: SEPOLIA_CONTRACTS
|
|
56925
|
+
mockUsdcToken: SEPOLIA_CONTRACTS.mockUsdcToken || "",
|
|
56926
|
+
mockUsdtToken: SEPOLIA_CONTRACTS.mockUsdtToken || "",
|
|
56838
56927
|
loanOperationsManager: SEPOLIA_CONTRACTS.LoanOperationsManagerModule || "",
|
|
56839
56928
|
termManager: SEPOLIA_CONTRACTS.TermManagerModule || "",
|
|
56840
56929
|
circuitBreaker: SEPOLIA_CONTRACTS.CircuitBreakerModule || "",
|
|
@@ -56910,14 +56999,17 @@ function getMainnetConfig() {
|
|
|
56910
56999
|
agentModuleFactory: MAINNET_CONTRACTS.AgentModuleFactory || ""
|
|
56911
57000
|
},
|
|
56912
57001
|
subgraphs: {
|
|
56913
|
-
//
|
|
56914
|
-
//
|
|
56915
|
-
//
|
|
56916
|
-
//
|
|
56917
|
-
//
|
|
56918
|
-
//
|
|
56919
|
-
//
|
|
56920
|
-
|
|
57002
|
+
// The MAINNET subgraph on The Graph's decentralized network — the same id
|
|
57003
|
+
// lit-ops-server's ETHEREUM_SUBGRAPH_URL points at (infra/terraform). The path segment is
|
|
57004
|
+
// the subgraph's PUBLIC ID, not a credential. This used to be a SEPOLIA id under a
|
|
57005
|
+
// chainId-1 config: unusable as shipped, but a caller who added their own key would have
|
|
57006
|
+
// read Sepolia data as mainnet.
|
|
57007
|
+
//
|
|
57008
|
+
// The gateway needs an `Authorization: Bearer <query key>` the SDK does not (and must
|
|
57009
|
+
// not) hold, so this URL only works for a standalone caller supplying their own key.
|
|
57010
|
+
// Service mode never uses it — queries go through the lit-ops-server proxy, which adds
|
|
57011
|
+
// the key server-side. Same rule as rpcUrls above: never ship a keyed URL in a client config.
|
|
57012
|
+
diamondHandsUrl: "https://gateway.thegraph.com/api/subgraphs/id/8Gt9zaSCgkxxSiLMGaKVj7qU3ds1heGVGxgWcXXpwbPd"
|
|
56921
57013
|
},
|
|
56922
57014
|
litNetwork: "chipotle",
|
|
56923
57015
|
debug: false
|
|
@@ -57938,6 +58030,39 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
|
|
|
57938
58030
|
}
|
|
57939
58031
|
return { timestamp: result.timestamp, signature: result.signature };
|
|
57940
58032
|
}
|
|
58033
|
+
function baseMintFeeWei(mintAmountWei, originationFeeBps) {
|
|
58034
|
+
if (mintAmountWei < 0n)
|
|
58035
|
+
throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
|
|
58036
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
58037
|
+
throw new Error(
|
|
58038
|
+
`baseMintFeeWei: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
58039
|
+
);
|
|
58040
|
+
}
|
|
58041
|
+
return mintAmountWei * BigInt(originationFeeBps) / 10000n;
|
|
58042
|
+
}
|
|
58043
|
+
function debtAfterMintExceedsLoanCap(params) {
|
|
58044
|
+
const { currentDebtWei, mintAmountWei, mintFeeWei, maxLoanWei } = params;
|
|
58045
|
+
for (const [name, v] of Object.entries(params)) {
|
|
58046
|
+
if (v < 0n)
|
|
58047
|
+
throw new Error(`debtAfterMintExceedsLoanCap: ${name} cannot be negative`);
|
|
58048
|
+
}
|
|
58049
|
+
return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
|
|
58050
|
+
}
|
|
58051
|
+
function maxPrincipalWithinLoanCap(params) {
|
|
58052
|
+
const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
|
|
58053
|
+
if (maxLoanWei < 0n || currentDebtWei < 0n) {
|
|
58054
|
+
throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
|
|
58055
|
+
}
|
|
58056
|
+
if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
|
|
58057
|
+
throw new Error(
|
|
58058
|
+
`maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
|
|
58059
|
+
);
|
|
58060
|
+
}
|
|
58061
|
+
const room = maxLoanWei - currentDebtWei;
|
|
58062
|
+
if (room <= 0n)
|
|
58063
|
+
return 0n;
|
|
58064
|
+
return room * 10000n / (10000n + BigInt(originationFeeBps));
|
|
58065
|
+
}
|
|
57941
58066
|
function buildLoginDomain(chainId) {
|
|
57942
58067
|
return {
|
|
57943
58068
|
name: "Diamond Hands",
|
|
@@ -59347,23 +59472,37 @@ var BitcoinUtils = class {
|
|
|
59347
59472
|
return getBitcoinAddressesFromPkp(pkpPublicKey);
|
|
59348
59473
|
}
|
|
59349
59474
|
};
|
|
59350
|
-
function
|
|
59475
|
+
function networksOfValidAddress(address) {
|
|
59476
|
+
const lower2 = address.toLowerCase();
|
|
59477
|
+
if (lower2.startsWith("bcrt1"))
|
|
59478
|
+
return ["regtest"];
|
|
59479
|
+
if (lower2.startsWith("bc1"))
|
|
59480
|
+
return ["mainnet"];
|
|
59481
|
+
if (lower2.startsWith("tb1"))
|
|
59482
|
+
return ["testnet"];
|
|
59483
|
+
if (address.startsWith("1") || address.startsWith("3"))
|
|
59484
|
+
return ["mainnet"];
|
|
59485
|
+
return ["testnet", "regtest"];
|
|
59486
|
+
}
|
|
59487
|
+
function safeValidateBitcoinAddress(address, network) {
|
|
59351
59488
|
if (!address || typeof address !== "string") {
|
|
59352
59489
|
throw new Error(`Invalid Bitcoin address: must be a non-empty string`);
|
|
59353
59490
|
}
|
|
59354
|
-
|
|
59355
|
-
|
|
59356
|
-
|
|
59357
|
-
|
|
59491
|
+
if (network !== "mainnet" && network !== "testnet" && network !== "regtest") {
|
|
59492
|
+
throw new Error(
|
|
59493
|
+
`Bitcoin network is required to validate an address (got ${JSON.stringify(network)})`
|
|
59494
|
+
);
|
|
59358
59495
|
}
|
|
59359
|
-
if (
|
|
59360
|
-
|
|
59361
|
-
|
|
59362
|
-
|
|
59363
|
-
}
|
|
59364
|
-
|
|
59365
|
-
|
|
59366
|
-
|
|
59496
|
+
if (!BitcoinUtils.validateAddress(address)) {
|
|
59497
|
+
throw new Error(
|
|
59498
|
+
`Invalid Bitcoin address: ${address} (malformed or failed its checksum \u2014 check for a typo)`
|
|
59499
|
+
);
|
|
59500
|
+
}
|
|
59501
|
+
const belongsTo = networksOfValidAddress(address);
|
|
59502
|
+
if (!belongsTo.includes(network)) {
|
|
59503
|
+
throw new Error(
|
|
59504
|
+
`Bitcoin address ${address} is not a ${network} address \u2014 it is a ${belongsTo.join("/")} address. Sending across networks would lose the funds.`
|
|
59505
|
+
);
|
|
59367
59506
|
}
|
|
59368
59507
|
return address;
|
|
59369
59508
|
}
|
|
@@ -61472,6 +61611,95 @@ var LoanStatus = /* @__PURE__ */ ((LoanStatus2) => {
|
|
|
61472
61611
|
LoanStatus2[LoanStatus2["CLOSED"] = 7] = "CLOSED";
|
|
61473
61612
|
return LoanStatus2;
|
|
61474
61613
|
})(LoanStatus || {});
|
|
61614
|
+
var THE_GRAPH_MAX_BATCH_SIZE = 1e3;
|
|
61615
|
+
var BORROWER_DEBT_ROWS_PAGE_SIZE = THE_GRAPH_MAX_BATCH_SIZE;
|
|
61616
|
+
var BORROWER_DEBT_ROWS_MAX_PAGES = 10;
|
|
61617
|
+
async function collectBorrowerDebtRows(fetchPage) {
|
|
61618
|
+
const pageSize = BORROWER_DEBT_ROWS_PAGE_SIZE;
|
|
61619
|
+
const rows = [];
|
|
61620
|
+
for (let page = 0; page < BORROWER_DEBT_ROWS_MAX_PAGES; page++) {
|
|
61621
|
+
const batch = await fetchPage(page * pageSize, pageSize);
|
|
61622
|
+
if (batch.length > pageSize) {
|
|
61623
|
+
throw new Error(
|
|
61624
|
+
`Borrower debt page ${page} returned ${batch.length} rows for first: ${pageSize}`
|
|
61625
|
+
);
|
|
61626
|
+
}
|
|
61627
|
+
rows.push(...batch);
|
|
61628
|
+
if (batch.length < pageSize) {
|
|
61629
|
+
return rows;
|
|
61630
|
+
}
|
|
61631
|
+
}
|
|
61632
|
+
throw new Error(
|
|
61633
|
+
`Borrower debt rows exceeded ${BORROWER_DEBT_ROWS_MAX_PAGES} pages of ${pageSize} (${rows.length} rows so far); refusing to return a partial total`
|
|
61634
|
+
);
|
|
61635
|
+
}
|
|
61636
|
+
function parseSubgraphLoanStatus(label) {
|
|
61637
|
+
if (typeof label !== "string") {
|
|
61638
|
+
throw new Error(`Subgraph loan status is not a string: ${String(label)}`);
|
|
61639
|
+
}
|
|
61640
|
+
const value = LoanStatus[label];
|
|
61641
|
+
if (typeof value !== "number") {
|
|
61642
|
+
throw new Error(`Unknown subgraph loan status label: "${label}"`);
|
|
61643
|
+
}
|
|
61644
|
+
return value;
|
|
61645
|
+
}
|
|
61646
|
+
function parseSubgraphWei(row) {
|
|
61647
|
+
const raw = row.ucdDebt || "0";
|
|
61648
|
+
if (typeof raw !== "string") {
|
|
61649
|
+
throw new Error(
|
|
61650
|
+
`ucdDebt on position ${row.id} is not a string: ${String(raw)}`
|
|
61651
|
+
);
|
|
61652
|
+
}
|
|
61653
|
+
let wei;
|
|
61654
|
+
try {
|
|
61655
|
+
wei = BigInt(raw);
|
|
61656
|
+
} catch (error) {
|
|
61657
|
+
throw new Error(
|
|
61658
|
+
`ucdDebt on position ${row.id} is not an integer wei string: "${raw}"`,
|
|
61659
|
+
{ cause: error }
|
|
61660
|
+
);
|
|
61661
|
+
}
|
|
61662
|
+
if (wei < 0n) {
|
|
61663
|
+
throw new Error(`Negative ucdDebt on position ${row.id}: ${raw}`);
|
|
61664
|
+
}
|
|
61665
|
+
return wei;
|
|
61666
|
+
}
|
|
61667
|
+
var WEI_PER_UCD = 10n ** 18n;
|
|
61668
|
+
function weiToHumanUcdString(wei) {
|
|
61669
|
+
if (wei < 0n) {
|
|
61670
|
+
throw new Error(`Cannot render negative wei: ${wei}`);
|
|
61671
|
+
}
|
|
61672
|
+
const whole = wei / WEI_PER_UCD;
|
|
61673
|
+
const frac = (wei % WEI_PER_UCD).toString().padStart(18, "0").replace(/0+$/, "");
|
|
61674
|
+
return frac.length > 0 ? `${whole}.${frac}` : `${whole}`;
|
|
61675
|
+
}
|
|
61676
|
+
var STATUS_ORDINALS = Object.values(LoanStatus).filter((v) => typeof v === "number").sort((a, b) => a - b);
|
|
61677
|
+
function buildBorrowerUcdDebtSummary(borrower, rows, fetchedAt = Date.now()) {
|
|
61678
|
+
let totalWei = 0n;
|
|
61679
|
+
const counts = /* @__PURE__ */ new Map();
|
|
61680
|
+
for (const row of rows) {
|
|
61681
|
+
totalWei += parseSubgraphWei(row);
|
|
61682
|
+
const status = parseSubgraphLoanStatus(row.status);
|
|
61683
|
+
counts.set(status, (counts.get(status) ?? 0) + 1);
|
|
61684
|
+
}
|
|
61685
|
+
const byStatus = [];
|
|
61686
|
+
for (const status of STATUS_ORDINALS) {
|
|
61687
|
+
const count = counts.get(status);
|
|
61688
|
+
if (count === void 0) {
|
|
61689
|
+
continue;
|
|
61690
|
+
}
|
|
61691
|
+
byStatus.push({ status, statusLabel: LoanStatus[status], count });
|
|
61692
|
+
}
|
|
61693
|
+
return {
|
|
61694
|
+
borrower: borrower.toLowerCase(),
|
|
61695
|
+
loanCount: rows.length,
|
|
61696
|
+
totalUcdDebt: totalWei.toString(),
|
|
61697
|
+
totalUcdDebtHuman: weiToHumanUcdString(totalWei),
|
|
61698
|
+
byStatus,
|
|
61699
|
+
source: "subgraph",
|
|
61700
|
+
fetchedAt
|
|
61701
|
+
};
|
|
61702
|
+
}
|
|
61475
61703
|
var POSITION_CORE_ABI = [
|
|
61476
61704
|
"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
61705
|
];
|
|
@@ -61864,6 +62092,43 @@ var LoanQuery = class {
|
|
|
61864
62092
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
61865
62093
|
return this.getLoans({ borrower, orderBy, orderDirection }, pagination);
|
|
61866
62094
|
}
|
|
62095
|
+
/**
|
|
62096
|
+
* Combined UCD debt + by-status counts for a borrower from ONE pass over the
|
|
62097
|
+
* subgraph's raw rows (`graphClient.getBorrowerDebtRows`): BigInt wei sum, strict
|
|
62098
|
+
* status labels, `source: "subgraph"`.
|
|
62099
|
+
*
|
|
62100
|
+
* INDEXED figure, not a transaction input — the subgraph lags writes. Anything that
|
|
62101
|
+
* sizes a repayment reads the chain (`getPositionDetailsView`). Fails loud: a page
|
|
62102
|
+
* failure or the page cap is a SUBGRAPH-category failure carrying the cause; there
|
|
62103
|
+
* is no partial total.
|
|
62104
|
+
*/
|
|
62105
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
62106
|
+
const trimmed = typeof borrower === "string" ? borrower.trim() : "";
|
|
62107
|
+
if (!(0, import_ethers25.isAddress)(trimmed)) {
|
|
62108
|
+
return failure(
|
|
62109
|
+
new SDKError({
|
|
62110
|
+
message: `Borrower must be an EVM address for a UCD debt summary, got "${trimmed}"`,
|
|
62111
|
+
category: "VALIDATION",
|
|
62112
|
+
severity: "LOW",
|
|
62113
|
+
context: { borrower: trimmed }
|
|
62114
|
+
})
|
|
62115
|
+
);
|
|
62116
|
+
}
|
|
62117
|
+
return tryCatchAsync(
|
|
62118
|
+
async () => {
|
|
62119
|
+
const rows = await this.config.graphClient.getBorrowerDebtRows(trimmed);
|
|
62120
|
+
return buildBorrowerUcdDebtSummary(trimmed, rows);
|
|
62121
|
+
},
|
|
62122
|
+
(error) => error instanceof SDKError ? error : new SDKError({
|
|
62123
|
+
message: `Borrower UCD debt summary failed for ${trimmed}: ${error instanceof Error ? error.message : String(error)}`,
|
|
62124
|
+
category: "SUBGRAPH",
|
|
62125
|
+
severity: "MEDIUM",
|
|
62126
|
+
originalError: error instanceof Error ? error : void 0,
|
|
62127
|
+
cause: error,
|
|
62128
|
+
context: { borrower: trimmed }
|
|
62129
|
+
})
|
|
62130
|
+
);
|
|
62131
|
+
}
|
|
61867
62132
|
/**
|
|
61868
62133
|
* Get active loans (status = ACTIVE)
|
|
61869
62134
|
*
|
|
@@ -63389,7 +63654,35 @@ var GraphClient = class {
|
|
|
63389
63654
|
await new Promise((r) => setTimeout(r, ms));
|
|
63390
63655
|
}
|
|
63391
63656
|
};
|
|
63392
|
-
var
|
|
63657
|
+
var GET_USER_POSITIONS_DOCUMENT = `
|
|
63658
|
+
query GetUserPositions($borrower: Bytes!, $first: Int, $skip: Int, $orderBy: Position_orderBy, $orderDirection: OrderDirection) {
|
|
63659
|
+
user(id: $borrower) {
|
|
63660
|
+
id
|
|
63661
|
+
positions(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDirection) {
|
|
63662
|
+
id
|
|
63663
|
+
pkpId
|
|
63664
|
+
borrower {
|
|
63665
|
+
createdAt
|
|
63666
|
+
id
|
|
63667
|
+
}
|
|
63668
|
+
# btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
|
|
63669
|
+
ucdMinted
|
|
63670
|
+
ucdPaid
|
|
63671
|
+
ucdDebt
|
|
63672
|
+
collateralRatio
|
|
63673
|
+
requestedCollateralRatio
|
|
63674
|
+
selectedTerm
|
|
63675
|
+
status
|
|
63676
|
+
createdAt
|
|
63677
|
+
createdAtBlock
|
|
63678
|
+
lastUpdated
|
|
63679
|
+
originalTerm
|
|
63680
|
+
remainingDebt
|
|
63681
|
+
expiryAt
|
|
63682
|
+
}
|
|
63683
|
+
}
|
|
63684
|
+
}
|
|
63685
|
+
`;
|
|
63393
63686
|
function normalizePkpId2(pkpId) {
|
|
63394
63687
|
const raw = pkpId.startsWith("0x") ? pkpId.slice(2) : pkpId;
|
|
63395
63688
|
if (raw.length === 64 && raw.startsWith("000000000000000000000000") && raw !== "0".repeat(64)) {
|
|
@@ -63707,35 +64000,7 @@ var DiamondHandsGraph = class {
|
|
|
63707
64000
|
* Get user positions from subgraph
|
|
63708
64001
|
*/
|
|
63709
64002
|
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
|
-
`;
|
|
64003
|
+
const query = GET_USER_POSITIONS_DOCUMENT;
|
|
63739
64004
|
const variables = {
|
|
63740
64005
|
borrower: userAddress.toLowerCase(),
|
|
63741
64006
|
first: first || void 0,
|
|
@@ -63753,6 +64018,45 @@ var DiamondHandsGraph = class {
|
|
|
63753
64018
|
}
|
|
63754
64019
|
return positions;
|
|
63755
64020
|
}
|
|
64021
|
+
/**
|
|
64022
|
+
* Raw `{ id, status, ucdDebt }` for EVERY position of a borrower: one round trip per
|
|
64023
|
+
* 1000 positions, no count walk, no vault RPCs, and no `LoanData` transform (which
|
|
64024
|
+
* coerces wei to a float and leaves `status` a string cast to the numeric enum).
|
|
64025
|
+
*
|
|
64026
|
+
* Deliberately issues the `GetUserPositions` document rather than a leaner one: the
|
|
64027
|
+
* lit-ops graph proxy only passes allowlisted documents (graph-document-policy.ts),
|
|
64028
|
+
* and that one is already listed, so this needs no server change. The extra fields
|
|
64029
|
+
* cost bytes, not round trips.
|
|
64030
|
+
*
|
|
64031
|
+
* Throws past `BORROWER_DEBT_ROWS_MAX_PAGES` — never a partial set.
|
|
64032
|
+
*/
|
|
64033
|
+
async getBorrowerDebtRows(borrower) {
|
|
64034
|
+
const borrowerId = borrower.toLowerCase();
|
|
64035
|
+
return collectBorrowerDebtRows(async (skip, first) => {
|
|
64036
|
+
const result = await this.client.execute(GET_USER_POSITIONS_DOCUMENT, {
|
|
64037
|
+
borrower: borrowerId,
|
|
64038
|
+
first,
|
|
64039
|
+
skip,
|
|
64040
|
+
orderBy: "id",
|
|
64041
|
+
orderDirection: "asc"
|
|
64042
|
+
});
|
|
64043
|
+
if (result?.user == null) {
|
|
64044
|
+
if (skip > 0) {
|
|
64045
|
+
throw new Error(
|
|
64046
|
+
`getBorrowerDebtRows: user ${borrowerId} vanished from the subgraph at skip ${skip}`
|
|
64047
|
+
);
|
|
64048
|
+
}
|
|
64049
|
+
return [];
|
|
64050
|
+
}
|
|
64051
|
+
const positions = result.user.positions;
|
|
64052
|
+
if (!Array.isArray(positions)) {
|
|
64053
|
+
throw new Error(
|
|
64054
|
+
`getBorrowerDebtRows: subgraph returned no positions array for ${borrowerId} at skip ${skip}`
|
|
64055
|
+
);
|
|
64056
|
+
}
|
|
64057
|
+
return positions.filter((p) => p != null);
|
|
64058
|
+
});
|
|
64059
|
+
}
|
|
63756
64060
|
/**
|
|
63757
64061
|
* Get user positions, plus an accurate total count.
|
|
63758
64062
|
*
|
|
@@ -69921,6 +70225,603 @@ async function mintAgentPkp(params) {
|
|
|
69921
70225
|
clearTimeout(timeout);
|
|
69922
70226
|
}
|
|
69923
70227
|
}
|
|
70228
|
+
var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
|
|
70229
|
+
function planAgentBinding(params) {
|
|
70230
|
+
const { isActive, record, nowSeconds } = params;
|
|
70231
|
+
if (isActive)
|
|
70232
|
+
return { kind: "reuse", agent: record.agent };
|
|
70233
|
+
const status = Number(record.status);
|
|
70234
|
+
if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
|
|
70235
|
+
return { kind: "register" };
|
|
70236
|
+
}
|
|
70237
|
+
if (status !== AGENT_STATUS.Active) {
|
|
70238
|
+
throw new Error(`Unknown agent status ${status} in AgentDelegationRegistry`);
|
|
70239
|
+
}
|
|
70240
|
+
if (Number(record.validUntil) > nowSeconds) {
|
|
70241
|
+
throw new Error(
|
|
70242
|
+
"AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
|
|
70243
|
+
);
|
|
70244
|
+
}
|
|
70245
|
+
return { kind: "rotate" };
|
|
70246
|
+
}
|
|
70247
|
+
async function describeProviderChainMismatch(provider, chainId) {
|
|
70248
|
+
const actual = Number((await provider.getNetwork()).chainId);
|
|
70249
|
+
if (actual === chainId)
|
|
70250
|
+
return null;
|
|
70251
|
+
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.`;
|
|
70252
|
+
}
|
|
70253
|
+
var TxValidationError2 = class extends Error {
|
|
70254
|
+
/**
|
|
70255
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
70256
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
70257
|
+
*/
|
|
70258
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
70259
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
70260
|
+
this.name = "TxValidationError";
|
|
70261
|
+
}
|
|
70262
|
+
};
|
|
70263
|
+
var SIGNABLE_FUNCTIONS2 = [
|
|
70264
|
+
"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)",
|
|
70265
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
70266
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
70267
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
70268
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
70269
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
70270
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
70271
|
+
// protocol cannot execute.
|
|
70272
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
70273
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
70274
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
70275
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
70276
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
70277
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
70278
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
70279
|
+
"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)",
|
|
70280
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
70281
|
+
// function reverts permanently. The trustless replacement
|
|
70282
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
70283
|
+
// entry when its LIT Action ships.
|
|
70284
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
70285
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
70286
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
70287
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
70288
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
70289
|
+
// collateral had no client-side pin at all.
|
|
70290
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
70291
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
70292
|
+
// AgentModule; the parity test documents them as client-only.
|
|
70293
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
70294
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
70295
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
70296
|
+
// this too is client-only and never module-whitelisted.
|
|
70297
|
+
"function addAddress(string btcAddress) external"
|
|
70298
|
+
];
|
|
70299
|
+
var IFACE2 = new import_ethers31.ethers.Interface(SIGNABLE_FUNCTIONS2);
|
|
70300
|
+
function encodeSignable2(fn, args) {
|
|
70301
|
+
return IFACE2.encodeFunctionData(fn, args);
|
|
70302
|
+
}
|
|
70303
|
+
function decodeSignable2(data) {
|
|
70304
|
+
try {
|
|
70305
|
+
const parsed = IFACE2.parseTransaction({ data });
|
|
70306
|
+
if (!parsed) {
|
|
70307
|
+
throw new TxValidationError2(
|
|
70308
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
70309
|
+
);
|
|
70310
|
+
}
|
|
70311
|
+
return { name: parsed.name, args: parsed.args };
|
|
70312
|
+
} catch (e) {
|
|
70313
|
+
if (e instanceof TxValidationError2)
|
|
70314
|
+
throw e;
|
|
70315
|
+
throw new TxValidationError2(
|
|
70316
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
70317
|
+
);
|
|
70318
|
+
}
|
|
70319
|
+
}
|
|
70320
|
+
var MAX_GAS_LIMIT = 5000000n;
|
|
70321
|
+
var MAX_FEE_PER_GAS_WEI = 2000000000000n;
|
|
70322
|
+
var DEFAULT_MAX_TX_FEE_WEI = 250000000000000000n;
|
|
70323
|
+
var DEFAULT_FEE_CEILING = {
|
|
70324
|
+
maxGasLimit: MAX_GAS_LIMIT,
|
|
70325
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI,
|
|
70326
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI
|
|
70327
|
+
};
|
|
70328
|
+
function fmtEth(wei) {
|
|
70329
|
+
return `${import_ethers33.ethers.formatEther(wei)} ETH`;
|
|
70330
|
+
}
|
|
70331
|
+
function fmtGwei(wei) {
|
|
70332
|
+
return `${import_ethers33.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
70333
|
+
}
|
|
70334
|
+
function worstCaseFeeWei(gasLimit, maxFeePerGas) {
|
|
70335
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
70336
|
+
return null;
|
|
70337
|
+
return gasLimit * maxFeePerGas;
|
|
70338
|
+
}
|
|
70339
|
+
function assertFeeCeiling(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING) {
|
|
70340
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
70341
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
70342
|
+
}
|
|
70343
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
70344
|
+
raise(
|
|
70345
|
+
`maxFeePerGas ${fmtGwei(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei(ceiling.maxFeePerGasWei)}`
|
|
70346
|
+
);
|
|
70347
|
+
}
|
|
70348
|
+
const worst = worstCaseFeeWei(gasLimit, maxFeePerGas);
|
|
70349
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
70350
|
+
raise(
|
|
70351
|
+
`worst-case transaction fee ${fmtEth(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
70352
|
+
);
|
|
70353
|
+
}
|
|
70354
|
+
}
|
|
70355
|
+
function eqAddr2(a, b) {
|
|
70356
|
+
if (!a || !b)
|
|
70357
|
+
return false;
|
|
70358
|
+
try {
|
|
70359
|
+
return import_ethers32.ethers.getAddress(a) === import_ethers32.ethers.getAddress(b);
|
|
70360
|
+
} catch {
|
|
70361
|
+
return false;
|
|
70362
|
+
}
|
|
70363
|
+
}
|
|
70364
|
+
function readToAddress2(tx2) {
|
|
70365
|
+
const to = tx2["to"];
|
|
70366
|
+
if (typeof to !== "string") {
|
|
70367
|
+
throw new TxValidationError2(`unsignedTx.to is missing or not a string`);
|
|
70368
|
+
}
|
|
70369
|
+
return to;
|
|
70370
|
+
}
|
|
70371
|
+
function readData2(tx2) {
|
|
70372
|
+
const data = tx2["data"];
|
|
70373
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
70374
|
+
throw new TxValidationError2(`unsignedTx.data missing or malformed`);
|
|
70375
|
+
}
|
|
70376
|
+
return data;
|
|
70377
|
+
}
|
|
70378
|
+
function readChainId2(tx2) {
|
|
70379
|
+
const c = tx2["chainId"];
|
|
70380
|
+
if (c == null)
|
|
70381
|
+
return null;
|
|
70382
|
+
if (typeof c === "number")
|
|
70383
|
+
return c;
|
|
70384
|
+
if (typeof c === "string")
|
|
70385
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
70386
|
+
if (typeof c === "bigint")
|
|
70387
|
+
return Number(c);
|
|
70388
|
+
return null;
|
|
70389
|
+
}
|
|
70390
|
+
function readOptionalBigInt(tx2, key) {
|
|
70391
|
+
const v = tx2[key];
|
|
70392
|
+
if (v == null)
|
|
70393
|
+
return null;
|
|
70394
|
+
try {
|
|
70395
|
+
if (typeof v === "bigint")
|
|
70396
|
+
return v;
|
|
70397
|
+
if (typeof v === "number")
|
|
70398
|
+
return BigInt(v);
|
|
70399
|
+
if (typeof v === "string")
|
|
70400
|
+
return BigInt(v);
|
|
70401
|
+
return BigInt(v.toString());
|
|
70402
|
+
} catch {
|
|
70403
|
+
throw new TxValidationError2(`unsignedTx.${key} is present but not a valid integer`);
|
|
70404
|
+
}
|
|
70405
|
+
}
|
|
70406
|
+
function readValue2(tx2) {
|
|
70407
|
+
const v = tx2["value"];
|
|
70408
|
+
if (v == null)
|
|
70409
|
+
return 0n;
|
|
70410
|
+
if (typeof v === "string")
|
|
70411
|
+
return BigInt(v);
|
|
70412
|
+
if (typeof v === "number")
|
|
70413
|
+
return BigInt(v);
|
|
70414
|
+
if (typeof v === "bigint")
|
|
70415
|
+
return v;
|
|
70416
|
+
const maybe = v;
|
|
70417
|
+
if (typeof maybe.toBigInt === "function")
|
|
70418
|
+
return maybe.toBigInt();
|
|
70419
|
+
if (typeof maybe.toString === "function")
|
|
70420
|
+
return BigInt(maybe.toString());
|
|
70421
|
+
throw new TxValidationError2(`unsignedTx.value has unrecognized type`);
|
|
70422
|
+
}
|
|
70423
|
+
function normalizePositionId2(id) {
|
|
70424
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
70425
|
+
return import_ethers32.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
70426
|
+
}
|
|
70427
|
+
function requirePositionId(actual, expected) {
|
|
70428
|
+
const txPositionId = String(actual).toLowerCase();
|
|
70429
|
+
if (txPositionId !== normalizePositionId2(expected)) {
|
|
70430
|
+
throw new TxValidationError2(
|
|
70431
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId2(expected)}`
|
|
70432
|
+
);
|
|
70433
|
+
}
|
|
70434
|
+
}
|
|
70435
|
+
function validateUnsignedTx2(unsignedTx, expected, vctx) {
|
|
70436
|
+
const txChainId = readChainId2(unsignedTx);
|
|
70437
|
+
if (txChainId == null) {
|
|
70438
|
+
throw new TxValidationError2(
|
|
70439
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
70440
|
+
);
|
|
70441
|
+
}
|
|
70442
|
+
if (txChainId !== vctx.chainId) {
|
|
70443
|
+
throw new TxValidationError2(
|
|
70444
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
70445
|
+
);
|
|
70446
|
+
}
|
|
70447
|
+
const value = readValue2(unsignedTx);
|
|
70448
|
+
if (value !== 0n) {
|
|
70449
|
+
throw new TxValidationError2(
|
|
70450
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
70451
|
+
);
|
|
70452
|
+
}
|
|
70453
|
+
assertFeeCeiling(
|
|
70454
|
+
readOptionalBigInt(unsignedTx, "gasLimit"),
|
|
70455
|
+
readOptionalBigInt(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt(unsignedTx, "gasPrice"),
|
|
70456
|
+
(msg) => {
|
|
70457
|
+
throw new TxValidationError2(msg);
|
|
70458
|
+
},
|
|
70459
|
+
vctx.feeCeiling
|
|
70460
|
+
);
|
|
70461
|
+
const to = readToAddress2(unsignedTx);
|
|
70462
|
+
const data = readData2(unsignedTx);
|
|
70463
|
+
const { name, args } = decodeSignable2(data);
|
|
70464
|
+
const pm = vctx.contracts.PositionManager;
|
|
70465
|
+
switch (expected.kind) {
|
|
70466
|
+
case "mint": {
|
|
70467
|
+
if (name !== "mintUCD") {
|
|
70468
|
+
throw new TxValidationError2(`expected mintUCD, server returned ${name}`);
|
|
70469
|
+
}
|
|
70470
|
+
if (!eqAddr2(to, pm)) {
|
|
70471
|
+
throw new TxValidationError2(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
70472
|
+
}
|
|
70473
|
+
requirePositionId(args[0], expected.positionId);
|
|
70474
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
70475
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
70476
|
+
throw new TxValidationError2(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
70477
|
+
}
|
|
70478
|
+
const txMintFee = BigInt(String(args[2]));
|
|
70479
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
70480
|
+
throw new TxValidationError2(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
70481
|
+
}
|
|
70482
|
+
break;
|
|
70483
|
+
}
|
|
70484
|
+
case "repay": {
|
|
70485
|
+
if (name !== "makePayment") {
|
|
70486
|
+
throw new TxValidationError2(`expected makePayment, server returned ${name}`);
|
|
70487
|
+
}
|
|
70488
|
+
if (!eqAddr2(to, pm)) {
|
|
70489
|
+
throw new TxValidationError2(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
70490
|
+
}
|
|
70491
|
+
requirePositionId(args[0], expected.positionId);
|
|
70492
|
+
const txAmount = BigInt(String(args[1]));
|
|
70493
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
70494
|
+
throw new TxValidationError2(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
70495
|
+
}
|
|
70496
|
+
break;
|
|
70497
|
+
}
|
|
70498
|
+
case "extend": {
|
|
70499
|
+
if (name !== "extendPosition") {
|
|
70500
|
+
throw new TxValidationError2(`expected extendPosition, server returned ${name}`);
|
|
70501
|
+
}
|
|
70502
|
+
if (!eqAddr2(to, pm)) {
|
|
70503
|
+
throw new TxValidationError2(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
70504
|
+
}
|
|
70505
|
+
requirePositionId(args[0], expected.positionId);
|
|
70506
|
+
const txTerm = Number(args[1]);
|
|
70507
|
+
if (txTerm !== expected.selectedTerm) {
|
|
70508
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
70509
|
+
}
|
|
70510
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
70511
|
+
const txFee = BigInt(String(args[5]));
|
|
70512
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
70513
|
+
if (txFee > upper) {
|
|
70514
|
+
throw new TxValidationError2(
|
|
70515
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
70516
|
+
);
|
|
70517
|
+
}
|
|
70518
|
+
}
|
|
70519
|
+
break;
|
|
70520
|
+
}
|
|
70521
|
+
case "withdraw-btc": {
|
|
70522
|
+
if (name !== "withdrawBTC") {
|
|
70523
|
+
throw new TxValidationError2(`expected withdrawBTC, server returned ${name}`);
|
|
70524
|
+
}
|
|
70525
|
+
if (!eqAddr2(to, pm)) {
|
|
70526
|
+
throw new TxValidationError2(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
70527
|
+
}
|
|
70528
|
+
const paramsTuple = args[0];
|
|
70529
|
+
requirePositionId(paramsTuple[0], expected.positionId);
|
|
70530
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
70531
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
70532
|
+
throw new TxValidationError2(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
70533
|
+
}
|
|
70534
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
70535
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
70536
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
70537
|
+
if (txDeduction > upper) {
|
|
70538
|
+
throw new TxValidationError2(
|
|
70539
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
70540
|
+
);
|
|
70541
|
+
}
|
|
70542
|
+
}
|
|
70543
|
+
break;
|
|
70544
|
+
}
|
|
70545
|
+
case "ucd-approve": {
|
|
70546
|
+
if (name !== "approve") {
|
|
70547
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70548
|
+
}
|
|
70549
|
+
const ucd = vctx.contracts.UCDToken;
|
|
70550
|
+
if (!eqAddr2(to, ucd)) {
|
|
70551
|
+
throw new TxValidationError2(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
70552
|
+
}
|
|
70553
|
+
const spender = String(args[0]);
|
|
70554
|
+
const ok = expected.spenderCandidates.some((s) => eqAddr2(spender, s));
|
|
70555
|
+
if (!ok) {
|
|
70556
|
+
throw new TxValidationError2(
|
|
70557
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
70558
|
+
);
|
|
70559
|
+
}
|
|
70560
|
+
const amt = BigInt(String(args[1]));
|
|
70561
|
+
const min = BigInt(expected.minAmountWei);
|
|
70562
|
+
if (amt < min) {
|
|
70563
|
+
throw new TxValidationError2(`approve amount ${amt} is less than required ${min}`);
|
|
70564
|
+
}
|
|
70565
|
+
const SANITY_MAX = min * 1000n;
|
|
70566
|
+
if (amt > SANITY_MAX) {
|
|
70567
|
+
throw new TxValidationError2(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
70568
|
+
}
|
|
70569
|
+
break;
|
|
70570
|
+
}
|
|
70571
|
+
case "create-position": {
|
|
70572
|
+
if (name !== "createPosition") {
|
|
70573
|
+
throw new TxValidationError2(`expected createPosition, server returned ${name}`);
|
|
70574
|
+
}
|
|
70575
|
+
if (!eqAddr2(to, pm)) {
|
|
70576
|
+
throw new TxValidationError2(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
70577
|
+
}
|
|
70578
|
+
const txTerm = BigInt(String(args[4]));
|
|
70579
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
70580
|
+
throw new TxValidationError2(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
70581
|
+
}
|
|
70582
|
+
break;
|
|
70583
|
+
}
|
|
70584
|
+
case "set-position-delegate": {
|
|
70585
|
+
if (name !== "setPositionDelegate") {
|
|
70586
|
+
throw new TxValidationError2(`expected setPositionDelegate, server returned ${name}`);
|
|
70587
|
+
}
|
|
70588
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
70589
|
+
throw new TxValidationError2(
|
|
70590
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
70591
|
+
);
|
|
70592
|
+
}
|
|
70593
|
+
requirePositionId(args[0], expected.positionId);
|
|
70594
|
+
const txDelegate = String(args[1]);
|
|
70595
|
+
if (!eqAddr2(txDelegate, expected.delegate)) {
|
|
70596
|
+
throw new TxValidationError2(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
70597
|
+
}
|
|
70598
|
+
break;
|
|
70599
|
+
}
|
|
70600
|
+
case "bwar-add-address": {
|
|
70601
|
+
if (name !== "addAddress") {
|
|
70602
|
+
throw new TxValidationError2(`expected addAddress, decoded ${name}`);
|
|
70603
|
+
}
|
|
70604
|
+
if (!eqAddr2(to, expected.registryAddress)) {
|
|
70605
|
+
throw new TxValidationError2(
|
|
70606
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
70607
|
+
);
|
|
70608
|
+
}
|
|
70609
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
70610
|
+
throw new TxValidationError2(
|
|
70611
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
70612
|
+
);
|
|
70613
|
+
}
|
|
70614
|
+
break;
|
|
70615
|
+
}
|
|
70616
|
+
case "stablecoin-approve": {
|
|
70617
|
+
if (name !== "approve") {
|
|
70618
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70619
|
+
}
|
|
70620
|
+
if (!eqAddr2(to, expected.tokenAddress)) {
|
|
70621
|
+
throw new TxValidationError2(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
70622
|
+
}
|
|
70623
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
70624
|
+
throw new TxValidationError2(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
70625
|
+
}
|
|
70626
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
70627
|
+
throw new TxValidationError2(
|
|
70628
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
70629
|
+
);
|
|
70630
|
+
}
|
|
70631
|
+
break;
|
|
70632
|
+
}
|
|
70633
|
+
case "ucd-approve-controller": {
|
|
70634
|
+
if (name !== "approve") {
|
|
70635
|
+
throw new TxValidationError2(`expected ERC-20 approve, server returned ${name}`);
|
|
70636
|
+
}
|
|
70637
|
+
if (!eqAddr2(to, expected.ucdTokenAddress)) {
|
|
70638
|
+
throw new TxValidationError2(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
70639
|
+
}
|
|
70640
|
+
if (!eqAddr2(String(args[0]), expected.spender)) {
|
|
70641
|
+
throw new TxValidationError2(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
70642
|
+
}
|
|
70643
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
70644
|
+
throw new TxValidationError2(
|
|
70645
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
70646
|
+
);
|
|
70647
|
+
}
|
|
70648
|
+
break;
|
|
70649
|
+
}
|
|
70650
|
+
case "psm-swap": {
|
|
70651
|
+
if (name !== "swap")
|
|
70652
|
+
throw new TxValidationError2(`expected swap, server returned ${name}`);
|
|
70653
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
70654
|
+
throw new TxValidationError2(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
70655
|
+
}
|
|
70656
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
70657
|
+
throw new TxValidationError2(`swap stablecoin mismatch`);
|
|
70658
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
70659
|
+
throw new TxValidationError2(`swap amountIn mismatch`);
|
|
70660
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
70661
|
+
throw new TxValidationError2(`swap minUcdOut mismatch`);
|
|
70662
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
70663
|
+
throw new TxValidationError2(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
70664
|
+
}
|
|
70665
|
+
break;
|
|
70666
|
+
}
|
|
70667
|
+
case "psm-redeem": {
|
|
70668
|
+
if (name !== "redeem")
|
|
70669
|
+
throw new TxValidationError2(`expected redeem, server returned ${name}`);
|
|
70670
|
+
if (!eqAddr2(to, expected.psmAddress)) {
|
|
70671
|
+
throw new TxValidationError2(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
70672
|
+
}
|
|
70673
|
+
if (!eqAddr2(String(args[0]), expected.stablecoin))
|
|
70674
|
+
throw new TxValidationError2(`redeem stablecoin mismatch`);
|
|
70675
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
70676
|
+
throw new TxValidationError2(`redeem ucdAmount mismatch`);
|
|
70677
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
70678
|
+
throw new TxValidationError2(`redeem minStablecoinOut mismatch`);
|
|
70679
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
70680
|
+
throw new TxValidationError2(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
70681
|
+
}
|
|
70682
|
+
break;
|
|
70683
|
+
}
|
|
70684
|
+
default: {
|
|
70685
|
+
const _exhaustive = expected;
|
|
70686
|
+
throw new TxValidationError2(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
70687
|
+
}
|
|
70688
|
+
}
|
|
70689
|
+
}
|
|
70690
|
+
function buildPsmApproveTx(p) {
|
|
70691
|
+
return {
|
|
70692
|
+
to: p.token,
|
|
70693
|
+
data: encodeSignable2("approve", [p.spender, p.amount]),
|
|
70694
|
+
value: "0x0",
|
|
70695
|
+
chainId: p.chainId
|
|
70696
|
+
};
|
|
70697
|
+
}
|
|
70698
|
+
function buildPsmSwapTx2(p) {
|
|
70699
|
+
return {
|
|
70700
|
+
to: p.psm,
|
|
70701
|
+
data: encodeSignable2("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
70702
|
+
value: "0x0",
|
|
70703
|
+
chainId: p.chainId
|
|
70704
|
+
};
|
|
70705
|
+
}
|
|
70706
|
+
function buildPsmRedeemTx2(p) {
|
|
70707
|
+
return {
|
|
70708
|
+
to: p.psm,
|
|
70709
|
+
data: encodeSignable2("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
70710
|
+
value: "0x0",
|
|
70711
|
+
chainId: p.chainId
|
|
70712
|
+
};
|
|
70713
|
+
}
|
|
70714
|
+
var PSM_READS_ABI = ["function supportedStablecoins(address) view returns (bool)"];
|
|
70715
|
+
var ERC20_READS_ABI = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
70716
|
+
function psmExchangeReadsFromProvider(provider, psmAddress) {
|
|
70717
|
+
const psm = new import_ethers30.ethers.Contract(psmAddress, PSM_READS_ABI, provider);
|
|
70718
|
+
return {
|
|
70719
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
70720
|
+
allowance: async (token, owner, spender) => await new import_ethers30.ethers.Contract(token, ERC20_READS_ABI, provider).getFunction("allowance")(owner, spender)
|
|
70721
|
+
};
|
|
70722
|
+
}
|
|
70723
|
+
var refuse = (direction, msg) => new TxValidationError2(msg, `PSM ${direction}`);
|
|
70724
|
+
function requireAddress(direction, label, value) {
|
|
70725
|
+
if (!value || !import_ethers30.ethers.isAddress(value)) {
|
|
70726
|
+
throw refuse(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
70727
|
+
}
|
|
70728
|
+
return import_ethers30.ethers.getAddress(value);
|
|
70729
|
+
}
|
|
70730
|
+
async function planPsmExchange(params) {
|
|
70731
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
70732
|
+
const chainId = vctx.chainId;
|
|
70733
|
+
if (amountIn <= 0n) {
|
|
70734
|
+
throw refuse(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
70735
|
+
}
|
|
70736
|
+
if (minOut <= 0n) {
|
|
70737
|
+
throw refuse(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
70738
|
+
}
|
|
70739
|
+
const owner = requireAddress(direction, "owner", params.owner);
|
|
70740
|
+
const psm = requireAddress(direction, "SimplePSMV2", params.addresses.psm);
|
|
70741
|
+
const stablecoin = requireAddress(direction, "stablecoin", params.addresses.stablecoin);
|
|
70742
|
+
const isSwap = direction === "swap";
|
|
70743
|
+
const token = isSwap ? stablecoin : requireAddress(direction, "UCDToken", params.addresses.ucdToken);
|
|
70744
|
+
const spender = isSwap ? psm : requireAddress(direction, "UCDController", params.addresses.ucdController);
|
|
70745
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
70746
|
+
throw refuse(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
70747
|
+
}
|
|
70748
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
70749
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
70750
|
+
const approvals = [];
|
|
70751
|
+
if (allowanceBefore < amountIn) {
|
|
70752
|
+
if (allowanceBefore > 0n) {
|
|
70753
|
+
approvals.push({
|
|
70754
|
+
step: "reset-approve",
|
|
70755
|
+
tx: buildPsmApproveTx({ token, spender, amount: 0n, chainId }),
|
|
70756
|
+
expected: approveExpected(0n)
|
|
70757
|
+
});
|
|
70758
|
+
}
|
|
70759
|
+
approvals.push({
|
|
70760
|
+
step: "approve",
|
|
70761
|
+
tx: buildPsmApproveTx({ token, spender, amount: amountIn, chainId }),
|
|
70762
|
+
expected: approveExpected(amountIn)
|
|
70763
|
+
});
|
|
70764
|
+
}
|
|
70765
|
+
const exec = isSwap ? {
|
|
70766
|
+
step: "swap",
|
|
70767
|
+
tx: buildPsmSwapTx2({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
70768
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
70769
|
+
} : {
|
|
70770
|
+
step: "redeem",
|
|
70771
|
+
tx: buildPsmRedeemTx2({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
70772
|
+
expected: {
|
|
70773
|
+
kind: "psm-redeem",
|
|
70774
|
+
psmAddress: psm,
|
|
70775
|
+
stablecoin,
|
|
70776
|
+
amountUcdWei: amountIn.toString(),
|
|
70777
|
+
minOut: minOut.toString()
|
|
70778
|
+
}
|
|
70779
|
+
};
|
|
70780
|
+
for (const leg of [...approvals, exec]) {
|
|
70781
|
+
validateUnsignedTx2({ ...leg.tx }, leg.expected, vctx);
|
|
70782
|
+
}
|
|
70783
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
70784
|
+
}
|
|
70785
|
+
async function executePsmPlan(plan, signer, vctx) {
|
|
70786
|
+
const approvalHashes = [];
|
|
70787
|
+
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.`;
|
|
70788
|
+
const sendLeg = async (leg) => {
|
|
70789
|
+
const request = { to: leg.tx.to, data: leg.tx.data, value: 0n, chainId: leg.tx.chainId };
|
|
70790
|
+
validateUnsignedTx2({ ...request }, leg.expected, vctx);
|
|
70791
|
+
const sent = await signer.sendTransaction(request);
|
|
70792
|
+
const receipt = await sent.wait();
|
|
70793
|
+
if (!receipt)
|
|
70794
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} returned no receipt`);
|
|
70795
|
+
if (receipt.status !== 1)
|
|
70796
|
+
throw new Error(`PSM ${leg.step} tx ${sent.hash} reverted`);
|
|
70797
|
+
return { hash: sent.hash, blockNumber: receipt.blockNumber };
|
|
70798
|
+
};
|
|
70799
|
+
for (const leg of plan.approvals) {
|
|
70800
|
+
const landed = await sendLeg(leg).catch((e) => {
|
|
70801
|
+
throw new Error(`PSM ${leg.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
70802
|
+
});
|
|
70803
|
+
approvalHashes.push(landed.hash);
|
|
70804
|
+
}
|
|
70805
|
+
const exec = await sendLeg(plan.exec).catch((e) => {
|
|
70806
|
+
throw new Error(`PSM ${plan.exec.step} failed: ${e instanceof Error ? e.message : String(e)}.${residual()}`);
|
|
70807
|
+
});
|
|
70808
|
+
return { ...exec, approvalHashes };
|
|
70809
|
+
}
|
|
70810
|
+
var LIT_ACTION_CHAIN_NAMES = Object.freeze({
|
|
70811
|
+
1: "ethereum",
|
|
70812
|
+
11155111: "sepolia",
|
|
70813
|
+
1337: "hardhat",
|
|
70814
|
+
31337: "hardhat"
|
|
70815
|
+
});
|
|
70816
|
+
function litActionChainNameForChainId(chainId) {
|
|
70817
|
+
const name = LIT_ACTION_CHAIN_NAMES[Number(chainId)];
|
|
70818
|
+
if (!name) {
|
|
70819
|
+
throw new Error(
|
|
70820
|
+
`Unsupported chainId ${String(chainId)} for a Lit Action (supported: ${Object.keys(LIT_ACTION_CHAIN_NAMES).join(", ")})`
|
|
70821
|
+
);
|
|
70822
|
+
}
|
|
70823
|
+
return name;
|
|
70824
|
+
}
|
|
69924
70825
|
var MockTokenManager = class {
|
|
69925
70826
|
config;
|
|
69926
70827
|
constructor(config) {
|
|
@@ -70894,6 +71795,19 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
70894
71795
|
*/
|
|
70895
71796
|
static async create(config) {
|
|
70896
71797
|
const userProvidedServiceEndpoint = config.serviceEndpoint;
|
|
71798
|
+
if (typeof config.chainId === "number" && config.provider) {
|
|
71799
|
+
const mismatch = await describeProviderChainMismatch(config.provider, config.chainId);
|
|
71800
|
+
if (mismatch) {
|
|
71801
|
+
return failure(
|
|
71802
|
+
new SDKError({
|
|
71803
|
+
message: mismatch,
|
|
71804
|
+
category: "CONFIGURATION",
|
|
71805
|
+
severity: "HIGH"
|
|
71806
|
+
/* HIGH */
|
|
71807
|
+
})
|
|
71808
|
+
);
|
|
71809
|
+
}
|
|
71810
|
+
}
|
|
70897
71811
|
const enrichedConfig = await _DiamondHandsSDK.enrichConfigWithNetworkDefaults(config);
|
|
70898
71812
|
if (userProvidedServiceEndpoint) {
|
|
70899
71813
|
enrichedConfig.serviceEndpoint = userProvidedServiceEndpoint;
|
|
@@ -71544,6 +72458,53 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71544
72458
|
if (this.config.debug) {
|
|
71545
72459
|
log.info(` Position PKP ID: ${position2.pkpId}`);
|
|
71546
72460
|
}
|
|
72461
|
+
const termsResult = await this.getTermsWithFees();
|
|
72462
|
+
if (!termsResult.success) {
|
|
72463
|
+
return {
|
|
72464
|
+
success: false,
|
|
72465
|
+
error: `Cannot verify the loan cap before minting: ${termsResult.error.message}`
|
|
72466
|
+
};
|
|
72467
|
+
}
|
|
72468
|
+
const positionTermMonths = Number(position2.selectedTerm);
|
|
72469
|
+
const positionTerm = termsResult.value.terms.find(
|
|
72470
|
+
(term) => term.termMonths === positionTermMonths
|
|
72471
|
+
);
|
|
72472
|
+
if (!positionTerm) {
|
|
72473
|
+
return {
|
|
72474
|
+
success: false,
|
|
72475
|
+
error: `Cannot verify the loan cap before minting: TermManager has no fee entry for the position's ${positionTermMonths}-month term`
|
|
72476
|
+
};
|
|
72477
|
+
}
|
|
72478
|
+
const currentDebtWei = BigInt(position2.ucdDebt);
|
|
72479
|
+
const baseFeeWei = baseMintFeeWei(
|
|
72480
|
+
requestAmountWei,
|
|
72481
|
+
positionTerm.originationFeeBps
|
|
72482
|
+
);
|
|
72483
|
+
if (debtAfterMintExceedsLoanCap({
|
|
72484
|
+
currentDebtWei,
|
|
72485
|
+
mintAmountWei: requestAmountWei,
|
|
72486
|
+
mintFeeWei: baseFeeWei,
|
|
72487
|
+
maxLoanWei: maxLoanValueWei
|
|
72488
|
+
})) {
|
|
72489
|
+
const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
|
|
72490
|
+
const maxPrincipalUcd = Number(
|
|
72491
|
+
maxPrincipalWithinLoanCap({
|
|
72492
|
+
maxLoanWei: maxLoanValueWei,
|
|
72493
|
+
currentDebtWei,
|
|
72494
|
+
originationFeeBps: positionTerm.originationFeeBps
|
|
72495
|
+
}) / BigInt(10 ** 18)
|
|
72496
|
+
);
|
|
72497
|
+
return {
|
|
72498
|
+
success: false,
|
|
72499
|
+
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.`
|
|
72500
|
+
};
|
|
72501
|
+
}
|
|
72502
|
+
if (this.config.debug) {
|
|
72503
|
+
log.info(
|
|
72504
|
+
`\u2705 Fee-inclusive loan cap check passed: ${(0, import_ethers13.formatEther)(currentDebtWei + requestAmountWei + baseFeeWei)} UCD <= ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD`,
|
|
72505
|
+
{}
|
|
72506
|
+
);
|
|
72507
|
+
}
|
|
71547
72508
|
let pkpPublicKey;
|
|
71548
72509
|
let pkpEthAddress;
|
|
71549
72510
|
const pkpCache = this.cacheManager.getCache("pkp-data", {
|
|
@@ -71633,7 +72594,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
|
|
|
71633
72594
|
` UCDController: ${contracts?.UCDController || "MISSING"}`
|
|
71634
72595
|
);
|
|
71635
72596
|
}
|
|
71636
|
-
const chain = this.config.chain || (
|
|
72597
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
71637
72598
|
const devBitcoinProviderUrl = request.customBitcoinRpcUrl || this.config.bitcoinProviders?.[0]?.url;
|
|
71638
72599
|
if (this.config.debug) {
|
|
71639
72600
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -72233,6 +73194,25 @@ Error data: none`
|
|
|
72233
73194
|
}
|
|
72234
73195
|
const selector = simError.selector;
|
|
72235
73196
|
const errorName = simError.errorName ?? (selector ? `Unknown error ${selector}` : "unknown");
|
|
73197
|
+
const MINT_GUARD_CODES = {
|
|
73198
|
+
"1": "MINT_GUARD_LOAN_MAX_EXCEEDED \u2014 the position's total debt after this mint (existing debt + principal + fee) exceeds maximumLoanValueUcd",
|
|
73199
|
+
"2": "MINT_GUARD_CIRCUIT_BREAKER_EXCEEDED \u2014 exceeds CircuitBreaker maxSingleLoanValue",
|
|
73200
|
+
"3": "MINT_GUARD_PSM_DAILY_EXCEEDED \u2014 exceeds the PSM daily mint limit"
|
|
73201
|
+
};
|
|
73202
|
+
let loanCapDiagnostics = "";
|
|
73203
|
+
if (selector === "0xe6dd4d41") {
|
|
73204
|
+
const guardCode = BigInt(
|
|
73205
|
+
"0x" + String(simError.data).slice(10).padStart(64, "0")
|
|
73206
|
+
).toString();
|
|
73207
|
+
const guardMeaning = MINT_GUARD_CODES[guardCode] ?? `unknown MintGuardFailed code ${guardCode}`;
|
|
73208
|
+
loanCapDiagnostics = `
|
|
73209
|
+
|
|
73210
|
+
MintGuardFailed(${guardCode}): ${guardMeaning}
|
|
73211
|
+
Lit mintAmount: ${validationResponse.mintAmount}
|
|
73212
|
+
Lit mintFee: ${validationResponse.mintFee}
|
|
73213
|
+
Lit newDebt: ${validationResponse.newDebt}
|
|
73214
|
+
Protocol maximum: ${(0, import_ethers13.formatEther)(maxLoanValueWei)} UCD (fee-inclusive)`;
|
|
73215
|
+
}
|
|
72236
73216
|
const mintDebtDiagnostics = selector === "0xb9d419a7" || // DebtUpdateVerificationFailed()
|
|
72237
73217
|
selector === "0xc7e20553" || // DebtUpdateVerificationFailedDetailed(...)
|
|
72238
73218
|
selector === "0x0cfd2a97" || // MintVerificationMismatch(uint256,uint256)
|
|
@@ -72278,7 +73258,7 @@ Quantum Timing Analysis:
|
|
|
72278
73258
|
Error selector: ${selector}
|
|
72279
73259
|
Error data: ${simError.data}
|
|
72280
73260
|
Call path: mintUCD -> mintUCDWithAuthorization -> increaseDebtFromMint -> finalizeMintDebtIncrease
|
|
72281
|
-
Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
73261
|
+
Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnostics}`
|
|
72282
73262
|
);
|
|
72283
73263
|
}
|
|
72284
73264
|
const tx2 = await sendEip1559Transaction({
|
|
@@ -74886,7 +75866,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
74886
75866
|
` BTCSpendAuthorizer: ${contracts.BTCSpendAuthorizer || "MISSING"}`
|
|
74887
75867
|
);
|
|
74888
75868
|
}
|
|
74889
|
-
const chain = this.config.chain || (
|
|
75869
|
+
const chain = this.config.chain || litActionChainNameForChainId(network.chainId);
|
|
74890
75870
|
const devBitcoinProviderUrl = this.config.bitcoinProviders?.[0]?.url;
|
|
74891
75871
|
if (this.config.debug) {
|
|
74892
75872
|
log.info(` Network: ${chain} (chainId: ${network.chainId})`);
|
|
@@ -75441,13 +76421,7 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
75441
76421
|
return { success: false, error: "Failed to resolve PKP public key" };
|
|
75442
76422
|
}
|
|
75443
76423
|
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];
|
|
76424
|
+
const chainName = LIT_ACTION_CHAIN_NAMES[chainId];
|
|
75451
76425
|
if (!chainName) {
|
|
75452
76426
|
return {
|
|
75453
76427
|
success: false,
|
|
@@ -76669,6 +77643,18 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76669
77643
|
async getLoansByBorrower(borrower, pagination, orderBy, orderDirection) {
|
|
76670
77644
|
return this.loanQuery.getLoansByBorrower(borrower, pagination, orderBy, orderDirection);
|
|
76671
77645
|
}
|
|
77646
|
+
/**
|
|
77647
|
+
* Combined UCD debt (canonical wei string + display string) and by-status loan
|
|
77648
|
+
* counts for a borrower, from one pass over the subgraph. `source: "subgraph"` —
|
|
77649
|
+
* an INDEXED, informational figure that lags writes; never size a transaction
|
|
77650
|
+
* from it (repayments read the chain via `getPositionDetailsView`).
|
|
77651
|
+
*
|
|
77652
|
+
* Fails loud with a SUBGRAPH-category `SDKError` (cause attached) on any page
|
|
77653
|
+
* failure or past 10,000 positions; never returns a partial total.
|
|
77654
|
+
*/
|
|
77655
|
+
async getBorrowerUcdDebtSummary(borrower) {
|
|
77656
|
+
return this.loanQuery.getBorrowerUcdDebtSummary(borrower);
|
|
77657
|
+
}
|
|
76672
77658
|
/**
|
|
76673
77659
|
* Get all active loans
|
|
76674
77660
|
*
|
|
@@ -76794,11 +77780,12 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76794
77780
|
}
|
|
76795
77781
|
/**
|
|
76796
77782
|
* Execute a PSM stablecoin → UCD swap.
|
|
76797
|
-
*
|
|
77783
|
+
* Approves EXACTLY `amountWei` to the PSM when the current allowance is short (resetting a
|
|
77784
|
+
* partial allowance to zero first); every leg is validated by the sign-guard before it is sent.
|
|
76798
77785
|
*
|
|
76799
77786
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
|
|
76800
77787
|
* @param params.amountWei - Stablecoin amount in native decimals (bigint)
|
|
76801
|
-
* @param params.minUcdOutWei - Minimum UCD to receive;
|
|
77788
|
+
* @param params.minUcdOutWei - Minimum UCD to receive; must be > 0 (reverts on-chain if below)
|
|
76802
77789
|
* @param params.signer - Connected signer for the approval and swap transactions
|
|
76803
77790
|
*/
|
|
76804
77791
|
async psmSwap(params) {
|
|
@@ -76808,32 +77795,23 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76808
77795
|
"SimplePSMV2 address not configured \u2014 provide contractAddresses.simplePsmV2"
|
|
76809
77796
|
);
|
|
76810
77797
|
}
|
|
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 };
|
|
77798
|
+
return this.runPsmExchange({
|
|
77799
|
+
direction: "swap",
|
|
77800
|
+
signer: params.signer,
|
|
77801
|
+
addresses: { psm: psmAddress, stablecoin: params.stablecoinAddress },
|
|
77802
|
+
amountIn: params.amountWei,
|
|
77803
|
+
minOut: params.minUcdOutWei
|
|
77804
|
+
});
|
|
76828
77805
|
}
|
|
76829
77806
|
/**
|
|
76830
77807
|
* Execute a PSM UCD → stablecoin redeem.
|
|
76831
|
-
*
|
|
76832
|
-
* UCDToken.burn(from, amount) calls
|
|
77808
|
+
* Approves EXACTLY `ucdAmountWei` of UCD to the UCDController (not the PSM) to satisfy the
|
|
77809
|
+
* M-4 burn allowance guard: UCDToken.burn(from, amount) calls
|
|
77810
|
+
* _spendAllowance(from, msg.sender=ucdController, amount).
|
|
76833
77811
|
*
|
|
76834
77812
|
* @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
|
|
76835
77813
|
* @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
|
|
76836
|
-
* @param params.minStablecoinOutWei - Minimum stablecoin to receive
|
|
77814
|
+
* @param params.minStablecoinOutWei - Minimum stablecoin to receive; must be > 0
|
|
76837
77815
|
* @param params.signer - Connected signer
|
|
76838
77816
|
*/
|
|
76839
77817
|
async psmRedeem(params) {
|
|
@@ -76846,23 +77824,51 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
76846
77824
|
throw new Error("UCDToken address not configured \u2014 provide contractAddresses.ucdToken");
|
|
76847
77825
|
if (!ucdControllerAddress)
|
|
76848
77826
|
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
|
-
|
|
77827
|
+
return this.runPsmExchange({
|
|
77828
|
+
direction: "redeem",
|
|
77829
|
+
signer: params.signer,
|
|
77830
|
+
addresses: {
|
|
77831
|
+
psm: psmAddress,
|
|
77832
|
+
stablecoin: params.stablecoinAddress,
|
|
77833
|
+
ucdToken: ucdAddress,
|
|
77834
|
+
ucdController: ucdControllerAddress
|
|
77835
|
+
},
|
|
77836
|
+
amountIn: params.ucdAmountWei,
|
|
77837
|
+
minOut: params.minStablecoinOutWei
|
|
77838
|
+
});
|
|
77839
|
+
}
|
|
77840
|
+
/**
|
|
77841
|
+
* Shared PSM path: plan + validate every leg against the chain the SIGNER is on, then send.
|
|
77842
|
+
* The signer's chain must match the SDK's configured chain — the addresses came from it.
|
|
77843
|
+
*/
|
|
77844
|
+
async runPsmExchange(params) {
|
|
77845
|
+
const provider = params.signer.provider;
|
|
77846
|
+
if (!provider) {
|
|
77847
|
+
throw new Error(`PSM ${params.direction} needs a signer connected to a provider`);
|
|
77848
|
+
}
|
|
77849
|
+
const configuredChainId = this.config.chainId ?? this.config.networkOverride?.chainId;
|
|
77850
|
+
if (typeof configuredChainId !== "number") {
|
|
77851
|
+
throw new Error(`PSM ${params.direction} needs the SDK's chainId \u2014 configure chainId`);
|
|
77852
|
+
}
|
|
77853
|
+
const mismatch = await describeProviderChainMismatch(provider, configuredChainId);
|
|
77854
|
+
if (mismatch)
|
|
77855
|
+
throw new Error(mismatch);
|
|
77856
|
+
const vctx = {
|
|
77857
|
+
chainId: configuredChainId,
|
|
77858
|
+
network: String(configuredChainId),
|
|
77859
|
+
contracts: {}
|
|
77860
|
+
};
|
|
77861
|
+
const plan = await planPsmExchange({
|
|
77862
|
+
direction: params.direction,
|
|
77863
|
+
owner: await params.signer.getAddress(),
|
|
77864
|
+
addresses: params.addresses,
|
|
77865
|
+
amountIn: params.amountIn,
|
|
77866
|
+
minOut: params.minOut,
|
|
77867
|
+
vctx,
|
|
77868
|
+
reads: psmExchangeReadsFromProvider(provider, params.addresses.psm)
|
|
77869
|
+
});
|
|
77870
|
+
const { hash, blockNumber } = await executePsmPlan(plan, params.signer, vctx);
|
|
77871
|
+
return { hash, blockNumber };
|
|
76866
77872
|
}
|
|
76867
77873
|
/**
|
|
76868
77874
|
* Wait for the subgraph to index up to (and including) the given block number.
|
|
@@ -77043,18 +78049,31 @@ Message: ${causeMessage}${quantumContext}${mintDebtDiagnostics}`
|
|
|
77043
78049
|
const user = await signer.getAddress();
|
|
77044
78050
|
const registry = AgentDelegationRegistry__factory.connect(addr, signer);
|
|
77045
78051
|
let agentAddress;
|
|
77046
|
-
const
|
|
77047
|
-
|
|
77048
|
-
|
|
78052
|
+
const [isActive, record, latestBlock] = await Promise.all([
|
|
78053
|
+
registry.isAgentActive(user),
|
|
78054
|
+
registry.agentOf(user),
|
|
78055
|
+
this.getProviderOrThrow().getBlock("latest")
|
|
78056
|
+
]);
|
|
78057
|
+
if (!latestBlock) {
|
|
78058
|
+
throw new SDKError({
|
|
78059
|
+
message: "Could not read the latest block to check the agent registration's expiry",
|
|
78060
|
+
category: "NETWORK",
|
|
78061
|
+
severity: "HIGH"
|
|
78062
|
+
/* HIGH */
|
|
78063
|
+
});
|
|
78064
|
+
}
|
|
78065
|
+
const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
|
|
78066
|
+
if (plan.kind === "reuse") {
|
|
78067
|
+
agentAddress = plan.agent;
|
|
77049
78068
|
} else {
|
|
77050
78069
|
agentAddress = await mintAgentPkp({
|
|
77051
78070
|
serviceEndpoint: this.config.serviceEndpoint,
|
|
77052
78071
|
authHeader: this.serverSession ? () => this.serverSession.getAuthHeader() : void 0
|
|
77053
78072
|
});
|
|
77054
78073
|
const validitySeconds = options?.agentValiditySeconds ?? 90 * 24 * 60 * 60;
|
|
77055
|
-
const validUntil =
|
|
77056
|
-
const
|
|
77057
|
-
await
|
|
78074
|
+
const validUntil = latestBlock.timestamp + validitySeconds;
|
|
78075
|
+
const bindTx = plan.kind === "rotate" ? await registry.rotateAgent(user, agentAddress, validUntil) : await registry.registerAgent(user, agentAddress, validUntil);
|
|
78076
|
+
await bindTx.wait();
|
|
77058
78077
|
}
|
|
77059
78078
|
const currentDelegate = await getPositionDelegate(pid, signer, pdrAddr).catch(
|
|
77060
78079
|
() => null
|
|
@@ -78446,7 +79465,552 @@ var SUPPORTED_STABLECOINS = `
|
|
|
78446
79465
|
}`;
|
|
78447
79466
|
|
|
78448
79467
|
// src/boundary/upstream/real/psm-calls.ts
|
|
78449
|
-
var
|
|
79468
|
+
var import_ethers41 = require("ethers");
|
|
79469
|
+
|
|
79470
|
+
// node_modules/@gvnrdao/dh-sdk/dist/sign-guard.mjs
|
|
79471
|
+
var import_ethers35 = require("ethers");
|
|
79472
|
+
var import_ethers36 = require("ethers");
|
|
79473
|
+
var import_ethers37 = require("ethers");
|
|
79474
|
+
var import_ethers38 = require("ethers");
|
|
79475
|
+
var import_ethers39 = require("ethers");
|
|
79476
|
+
var import_ethers40 = require("ethers");
|
|
79477
|
+
var TxValidationError3 = class extends Error {
|
|
79478
|
+
/**
|
|
79479
|
+
* @param subject What is being refused. Defaults to the server-returned transaction the
|
|
79480
|
+
* validator exists for; client-built flows (the PSM exchange) name themselves instead.
|
|
79481
|
+
*/
|
|
79482
|
+
constructor(msg, subject = "server-returned transaction") {
|
|
79483
|
+
super(`Refusing to sign ${subject}: ${msg}`);
|
|
79484
|
+
this.name = "TxValidationError";
|
|
79485
|
+
}
|
|
79486
|
+
};
|
|
79487
|
+
var SIGNABLE_FUNCTIONS3 = [
|
|
79488
|
+
"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)",
|
|
79489
|
+
// `makePayment` is the ONLY repayment entry point. A `repayPosition` entry
|
|
79490
|
+
// used to sit here; it is not a function on any deployed contract — the
|
|
79491
|
+
// compiled PositionManager ABI has no `repay*` function at all, and the name
|
|
79492
|
+
// survives only in `archive/` prototypes. Nothing in lit-ops-server, the
|
|
79493
|
+
// lit-actions, or the SDK ever emitted it, and AgentModule never whitelisted
|
|
79494
|
+
// it. A signable-function whitelist should not carry calldata shapes the
|
|
79495
|
+
// protocol cannot execute.
|
|
79496
|
+
"function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
|
|
79497
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
79498
|
+
"function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
|
|
79499
|
+
// Struct-version: matches the actual on-chain function signature and the
|
|
79500
|
+
// SDK's calldata builder. An earlier 3-arg declaration was stale and would
|
|
79501
|
+
// silently fail to decode real `withdrawBTC` calldata. networkFee is NOT a
|
|
79502
|
+
// contract param — it is an off-chain Phase-2 BTC tx fee, validated elsewhere.
|
|
79503
|
+
"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)",
|
|
79504
|
+
// `cancelStaleSpendByOwner` removed in audit #62210 follow-up — the on-chain
|
|
79505
|
+
// function reverts permanently. The trustless replacement
|
|
79506
|
+
// (`cancelStaleSpendWithProof` on BTCSpendAuthorizer) lands via a separate
|
|
79507
|
+
// entry when its LIT Action ships.
|
|
79508
|
+
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
79509
|
+
"function setPositionDelegate(bytes32 positionId, address newDelegate) external",
|
|
79510
|
+
// Position creation. Signed opaquely by the SDK (like withdrawBTC), so
|
|
79511
|
+
// without an entry here it decoded as "<unparseable>" and the CLI's
|
|
79512
|
+
// WithdrawGuard waved it through — the flow that locks the user's BTC
|
|
79513
|
+
// collateral had no client-side pin at all.
|
|
79514
|
+
"function createPosition(bytes32 pkpId, bytes calldata validatorSignature, string mainnetVaultAddress, string regtestVaultAddress, uint256 selectedTermMonths, uint256 validatorVersion, bytes calldata pkpPublicKey) external returns (bytes32 positionId)",
|
|
79515
|
+
// SimplePSMV2 — the PSM exchange pair. Direct EOA calls, never routed through
|
|
79516
|
+
// AgentModule; the parity test documents them as client-only.
|
|
79517
|
+
"function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256)",
|
|
79518
|
+
"function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256)",
|
|
79519
|
+
// BitcoinWithdrawalAddressRegistry — `msg.sender` must be the borrower, so
|
|
79520
|
+
// this too is client-only and never module-whitelisted.
|
|
79521
|
+
"function addAddress(string btcAddress) external"
|
|
79522
|
+
];
|
|
79523
|
+
var IFACE3 = new import_ethers35.ethers.Interface(SIGNABLE_FUNCTIONS3);
|
|
79524
|
+
function encodeSignable3(fn, args) {
|
|
79525
|
+
return IFACE3.encodeFunctionData(fn, args);
|
|
79526
|
+
}
|
|
79527
|
+
function decodeSignable3(data) {
|
|
79528
|
+
try {
|
|
79529
|
+
const parsed = IFACE3.parseTransaction({ data });
|
|
79530
|
+
if (!parsed) {
|
|
79531
|
+
throw new TxValidationError3(
|
|
79532
|
+
`unsignedTx.data does not decode against the signable-function whitelist`
|
|
79533
|
+
);
|
|
79534
|
+
}
|
|
79535
|
+
return { name: parsed.name, args: parsed.args };
|
|
79536
|
+
} catch (e) {
|
|
79537
|
+
if (e instanceof TxValidationError3)
|
|
79538
|
+
throw e;
|
|
79539
|
+
throw new TxValidationError3(
|
|
79540
|
+
`unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
|
|
79541
|
+
);
|
|
79542
|
+
}
|
|
79543
|
+
}
|
|
79544
|
+
var MAX_GAS_LIMIT2 = 5000000n;
|
|
79545
|
+
var MAX_FEE_PER_GAS_WEI2 = 2000000000000n;
|
|
79546
|
+
var DEFAULT_MAX_TX_FEE_WEI2 = 250000000000000000n;
|
|
79547
|
+
var DEFAULT_FEE_CEILING2 = {
|
|
79548
|
+
maxGasLimit: MAX_GAS_LIMIT2,
|
|
79549
|
+
maxFeePerGasWei: MAX_FEE_PER_GAS_WEI2,
|
|
79550
|
+
maxTxFeeWei: DEFAULT_MAX_TX_FEE_WEI2
|
|
79551
|
+
};
|
|
79552
|
+
function fmtEth2(wei) {
|
|
79553
|
+
return `${import_ethers36.ethers.formatEther(wei)} ETH`;
|
|
79554
|
+
}
|
|
79555
|
+
function fmtGwei2(wei) {
|
|
79556
|
+
return `${import_ethers36.ethers.formatUnits(wei, "gwei")} gwei`;
|
|
79557
|
+
}
|
|
79558
|
+
function worstCaseFeeWei2(gasLimit, maxFeePerGas) {
|
|
79559
|
+
if (gasLimit == null || maxFeePerGas == null)
|
|
79560
|
+
return null;
|
|
79561
|
+
return gasLimit * maxFeePerGas;
|
|
79562
|
+
}
|
|
79563
|
+
function assertFeeCeiling2(gasLimit, maxFeePerGas, raise, ceiling = DEFAULT_FEE_CEILING2) {
|
|
79564
|
+
if (gasLimit != null && gasLimit > ceiling.maxGasLimit) {
|
|
79565
|
+
raise(`gasLimit ${gasLimit} exceeds the signing ceiling of ${ceiling.maxGasLimit}`);
|
|
79566
|
+
}
|
|
79567
|
+
if (maxFeePerGas != null && maxFeePerGas > ceiling.maxFeePerGasWei) {
|
|
79568
|
+
raise(
|
|
79569
|
+
`maxFeePerGas ${fmtGwei2(maxFeePerGas)} exceeds the signing ceiling of ${fmtGwei2(ceiling.maxFeePerGasWei)}`
|
|
79570
|
+
);
|
|
79571
|
+
}
|
|
79572
|
+
const worst = worstCaseFeeWei2(gasLimit, maxFeePerGas);
|
|
79573
|
+
if (worst != null && worst > ceiling.maxTxFeeWei) {
|
|
79574
|
+
raise(
|
|
79575
|
+
`worst-case transaction fee ${fmtEth2(worst)} (gasLimit ${gasLimit} \xD7 ${fmtGwei2(maxFeePerGas)}) exceeds the signing ceiling of ${fmtEth2(ceiling.maxTxFeeWei)}.${ceiling.raiseHint ? ` ${ceiling.raiseHint}` : ""}`
|
|
79576
|
+
);
|
|
79577
|
+
}
|
|
79578
|
+
}
|
|
79579
|
+
function eqAddr3(a, b) {
|
|
79580
|
+
if (!a || !b)
|
|
79581
|
+
return false;
|
|
79582
|
+
try {
|
|
79583
|
+
return import_ethers37.ethers.getAddress(a) === import_ethers37.ethers.getAddress(b);
|
|
79584
|
+
} catch {
|
|
79585
|
+
return false;
|
|
79586
|
+
}
|
|
79587
|
+
}
|
|
79588
|
+
function readToAddress3(tx2) {
|
|
79589
|
+
const to = tx2["to"];
|
|
79590
|
+
if (typeof to !== "string") {
|
|
79591
|
+
throw new TxValidationError3(`unsignedTx.to is missing or not a string`);
|
|
79592
|
+
}
|
|
79593
|
+
return to;
|
|
79594
|
+
}
|
|
79595
|
+
function readData3(tx2) {
|
|
79596
|
+
const data = tx2["data"];
|
|
79597
|
+
if (typeof data !== "string" || !data.startsWith("0x")) {
|
|
79598
|
+
throw new TxValidationError3(`unsignedTx.data missing or malformed`);
|
|
79599
|
+
}
|
|
79600
|
+
return data;
|
|
79601
|
+
}
|
|
79602
|
+
function readChainId3(tx2) {
|
|
79603
|
+
const c = tx2["chainId"];
|
|
79604
|
+
if (c == null)
|
|
79605
|
+
return null;
|
|
79606
|
+
if (typeof c === "number")
|
|
79607
|
+
return c;
|
|
79608
|
+
if (typeof c === "string")
|
|
79609
|
+
return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
|
|
79610
|
+
if (typeof c === "bigint")
|
|
79611
|
+
return Number(c);
|
|
79612
|
+
return null;
|
|
79613
|
+
}
|
|
79614
|
+
function readOptionalBigInt2(tx2, key) {
|
|
79615
|
+
const v = tx2[key];
|
|
79616
|
+
if (v == null)
|
|
79617
|
+
return null;
|
|
79618
|
+
try {
|
|
79619
|
+
if (typeof v === "bigint")
|
|
79620
|
+
return v;
|
|
79621
|
+
if (typeof v === "number")
|
|
79622
|
+
return BigInt(v);
|
|
79623
|
+
if (typeof v === "string")
|
|
79624
|
+
return BigInt(v);
|
|
79625
|
+
return BigInt(v.toString());
|
|
79626
|
+
} catch {
|
|
79627
|
+
throw new TxValidationError3(`unsignedTx.${key} is present but not a valid integer`);
|
|
79628
|
+
}
|
|
79629
|
+
}
|
|
79630
|
+
function readValue3(tx2) {
|
|
79631
|
+
const v = tx2["value"];
|
|
79632
|
+
if (v == null)
|
|
79633
|
+
return 0n;
|
|
79634
|
+
if (typeof v === "string")
|
|
79635
|
+
return BigInt(v);
|
|
79636
|
+
if (typeof v === "number")
|
|
79637
|
+
return BigInt(v);
|
|
79638
|
+
if (typeof v === "bigint")
|
|
79639
|
+
return v;
|
|
79640
|
+
const maybe = v;
|
|
79641
|
+
if (typeof maybe.toBigInt === "function")
|
|
79642
|
+
return maybe.toBigInt();
|
|
79643
|
+
if (typeof maybe.toString === "function")
|
|
79644
|
+
return BigInt(maybe.toString());
|
|
79645
|
+
throw new TxValidationError3(`unsignedTx.value has unrecognized type`);
|
|
79646
|
+
}
|
|
79647
|
+
function normalizePositionId3(id) {
|
|
79648
|
+
const hex = id.startsWith("0x") ? id : `0x${id}`;
|
|
79649
|
+
return import_ethers37.ethers.zeroPadValue(hex, 32).toLowerCase();
|
|
79650
|
+
}
|
|
79651
|
+
function requirePositionId2(actual, expected) {
|
|
79652
|
+
const txPositionId = String(actual).toLowerCase();
|
|
79653
|
+
if (txPositionId !== normalizePositionId3(expected)) {
|
|
79654
|
+
throw new TxValidationError3(
|
|
79655
|
+
`positionId mismatch \u2014 tx ${txPositionId}, expected ${normalizePositionId3(expected)}`
|
|
79656
|
+
);
|
|
79657
|
+
}
|
|
79658
|
+
}
|
|
79659
|
+
function validateUnsignedTx3(unsignedTx, expected, vctx) {
|
|
79660
|
+
const txChainId = readChainId3(unsignedTx);
|
|
79661
|
+
if (txChainId == null) {
|
|
79662
|
+
throw new TxValidationError3(
|
|
79663
|
+
`unsignedTx.chainId is missing \u2014 refusing to sign a transaction with no chain binding (client is on ${vctx.chainId})`
|
|
79664
|
+
);
|
|
79665
|
+
}
|
|
79666
|
+
if (txChainId !== vctx.chainId) {
|
|
79667
|
+
throw new TxValidationError3(
|
|
79668
|
+
`chainId mismatch \u2014 tx says ${txChainId}, client is on ${vctx.chainId}`
|
|
79669
|
+
);
|
|
79670
|
+
}
|
|
79671
|
+
const value = readValue3(unsignedTx);
|
|
79672
|
+
if (value !== 0n) {
|
|
79673
|
+
throw new TxValidationError3(
|
|
79674
|
+
`unsignedTx.value is non-zero (${value}); none of the protocol functions accept ETH`
|
|
79675
|
+
);
|
|
79676
|
+
}
|
|
79677
|
+
assertFeeCeiling2(
|
|
79678
|
+
readOptionalBigInt2(unsignedTx, "gasLimit"),
|
|
79679
|
+
readOptionalBigInt2(unsignedTx, "maxFeePerGas") ?? readOptionalBigInt2(unsignedTx, "gasPrice"),
|
|
79680
|
+
(msg) => {
|
|
79681
|
+
throw new TxValidationError3(msg);
|
|
79682
|
+
},
|
|
79683
|
+
vctx.feeCeiling
|
|
79684
|
+
);
|
|
79685
|
+
const to = readToAddress3(unsignedTx);
|
|
79686
|
+
const data = readData3(unsignedTx);
|
|
79687
|
+
const { name, args } = decodeSignable3(data);
|
|
79688
|
+
const pm = vctx.contracts.PositionManager;
|
|
79689
|
+
switch (expected.kind) {
|
|
79690
|
+
case "mint": {
|
|
79691
|
+
if (name !== "mintUCD") {
|
|
79692
|
+
throw new TxValidationError3(`expected mintUCD, server returned ${name}`);
|
|
79693
|
+
}
|
|
79694
|
+
if (!eqAddr3(to, pm)) {
|
|
79695
|
+
throw new TxValidationError3(`mintUCD must target PositionManager (${pm}), got ${to}`);
|
|
79696
|
+
}
|
|
79697
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79698
|
+
const txMintAmount = BigInt(String(args[1]));
|
|
79699
|
+
if (txMintAmount.toString() !== expected.amountWei) {
|
|
79700
|
+
throw new TxValidationError3(`mintAmount mismatch \u2014 tx ${txMintAmount}, expected ${expected.amountWei}`);
|
|
79701
|
+
}
|
|
79702
|
+
const txMintFee = BigInt(String(args[2]));
|
|
79703
|
+
if (txMintFee.toString() !== expected.mintFeeWei) {
|
|
79704
|
+
throw new TxValidationError3(`mintFee mismatch \u2014 tx ${txMintFee}, expected ${expected.mintFeeWei}`);
|
|
79705
|
+
}
|
|
79706
|
+
break;
|
|
79707
|
+
}
|
|
79708
|
+
case "repay": {
|
|
79709
|
+
if (name !== "makePayment") {
|
|
79710
|
+
throw new TxValidationError3(`expected makePayment, server returned ${name}`);
|
|
79711
|
+
}
|
|
79712
|
+
if (!eqAddr3(to, pm)) {
|
|
79713
|
+
throw new TxValidationError3(`${name} must target PositionManager (${pm}), got ${to}`);
|
|
79714
|
+
}
|
|
79715
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79716
|
+
const txAmount = BigInt(String(args[1]));
|
|
79717
|
+
if (txAmount.toString() !== expected.amountWei) {
|
|
79718
|
+
throw new TxValidationError3(`paymentAmount mismatch \u2014 tx ${txAmount}, expected ${expected.amountWei}`);
|
|
79719
|
+
}
|
|
79720
|
+
break;
|
|
79721
|
+
}
|
|
79722
|
+
case "extend": {
|
|
79723
|
+
if (name !== "extendPosition") {
|
|
79724
|
+
throw new TxValidationError3(`expected extendPosition, server returned ${name}`);
|
|
79725
|
+
}
|
|
79726
|
+
if (!eqAddr3(to, pm)) {
|
|
79727
|
+
throw new TxValidationError3(`extendPosition must target PositionManager (${pm}), got ${to}`);
|
|
79728
|
+
}
|
|
79729
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79730
|
+
const txTerm = Number(args[1]);
|
|
79731
|
+
if (txTerm !== expected.selectedTerm) {
|
|
79732
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
79733
|
+
}
|
|
79734
|
+
if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
|
|
79735
|
+
const txFee = BigInt(String(args[5]));
|
|
79736
|
+
const upper = BigInt(expected.upperBoundProRataFeeWei);
|
|
79737
|
+
if (txFee > upper) {
|
|
79738
|
+
throw new TxValidationError3(
|
|
79739
|
+
`proRataRenewalFee=${txFee} exceeds upper bound=${upper}. A compromised validator could otherwise inflate the fee to drain UCD.`
|
|
79740
|
+
);
|
|
79741
|
+
}
|
|
79742
|
+
}
|
|
79743
|
+
break;
|
|
79744
|
+
}
|
|
79745
|
+
case "withdraw-btc": {
|
|
79746
|
+
if (name !== "withdrawBTC") {
|
|
79747
|
+
throw new TxValidationError3(`expected withdrawBTC, server returned ${name}`);
|
|
79748
|
+
}
|
|
79749
|
+
if (!eqAddr3(to, pm)) {
|
|
79750
|
+
throw new TxValidationError3(`withdrawBTC must target PositionManager (${pm}), got ${to}`);
|
|
79751
|
+
}
|
|
79752
|
+
const paramsTuple = args[0];
|
|
79753
|
+
requirePositionId2(paramsTuple[0], expected.positionId);
|
|
79754
|
+
const txWithdrawalAddress = String(paramsTuple[5]);
|
|
79755
|
+
if (txWithdrawalAddress !== expected.btcAddress) {
|
|
79756
|
+
throw new TxValidationError3(`btcAddress mismatch \u2014 tx '${txWithdrawalAddress}', expected '${expected.btcAddress}'`);
|
|
79757
|
+
}
|
|
79758
|
+
if (expected.upperBoundTotalDeduction != null) {
|
|
79759
|
+
const txDeduction = BigInt(String(paramsTuple[6]));
|
|
79760
|
+
const upper = BigInt(expected.upperBoundTotalDeduction);
|
|
79761
|
+
if (txDeduction > upper) {
|
|
79762
|
+
throw new TxValidationError3(
|
|
79763
|
+
`totalDeduction=${txDeduction} exceeds approved upper bound=${upper}. A compromised validator could otherwise drain collateral beyond the approved amount.`
|
|
79764
|
+
);
|
|
79765
|
+
}
|
|
79766
|
+
}
|
|
79767
|
+
break;
|
|
79768
|
+
}
|
|
79769
|
+
case "ucd-approve": {
|
|
79770
|
+
if (name !== "approve") {
|
|
79771
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79772
|
+
}
|
|
79773
|
+
const ucd = vctx.contracts.UCDToken;
|
|
79774
|
+
if (!eqAddr3(to, ucd)) {
|
|
79775
|
+
throw new TxValidationError3(`approve must target UCDToken (${ucd}), got ${to}`);
|
|
79776
|
+
}
|
|
79777
|
+
const spender = String(args[0]);
|
|
79778
|
+
const ok = expected.spenderCandidates.some((s) => eqAddr3(spender, s));
|
|
79779
|
+
if (!ok) {
|
|
79780
|
+
throw new TxValidationError3(
|
|
79781
|
+
`approve spender ${spender} not in expected set ${expected.spenderCandidates.join(", ")}`
|
|
79782
|
+
);
|
|
79783
|
+
}
|
|
79784
|
+
const amt = BigInt(String(args[1]));
|
|
79785
|
+
const min = BigInt(expected.minAmountWei);
|
|
79786
|
+
if (amt < min) {
|
|
79787
|
+
throw new TxValidationError3(`approve amount ${amt} is less than required ${min}`);
|
|
79788
|
+
}
|
|
79789
|
+
const SANITY_MAX = min * 1000n;
|
|
79790
|
+
if (amt > SANITY_MAX) {
|
|
79791
|
+
throw new TxValidationError3(`approve amount ${amt} exceeds sanity cap ${SANITY_MAX} (1000x requested)`);
|
|
79792
|
+
}
|
|
79793
|
+
break;
|
|
79794
|
+
}
|
|
79795
|
+
case "create-position": {
|
|
79796
|
+
if (name !== "createPosition") {
|
|
79797
|
+
throw new TxValidationError3(`expected createPosition, server returned ${name}`);
|
|
79798
|
+
}
|
|
79799
|
+
if (!eqAddr3(to, pm)) {
|
|
79800
|
+
throw new TxValidationError3(`createPosition must target PositionManager (${pm}), got ${to}`);
|
|
79801
|
+
}
|
|
79802
|
+
const txTerm = BigInt(String(args[4]));
|
|
79803
|
+
if (txTerm !== BigInt(expected.selectedTerm)) {
|
|
79804
|
+
throw new TxValidationError3(`selectedTerm mismatch \u2014 tx ${txTerm}, expected ${expected.selectedTerm}`);
|
|
79805
|
+
}
|
|
79806
|
+
break;
|
|
79807
|
+
}
|
|
79808
|
+
case "set-position-delegate": {
|
|
79809
|
+
if (name !== "setPositionDelegate") {
|
|
79810
|
+
throw new TxValidationError3(`expected setPositionDelegate, server returned ${name}`);
|
|
79811
|
+
}
|
|
79812
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
79813
|
+
throw new TxValidationError3(
|
|
79814
|
+
`setPositionDelegate must target PositionDelegateRegistry (${expected.registryAddress}), got ${to}`
|
|
79815
|
+
);
|
|
79816
|
+
}
|
|
79817
|
+
requirePositionId2(args[0], expected.positionId);
|
|
79818
|
+
const txDelegate = String(args[1]);
|
|
79819
|
+
if (!eqAddr3(txDelegate, expected.delegate)) {
|
|
79820
|
+
throw new TxValidationError3(`delegate mismatch \u2014 tx ${txDelegate}, expected ${expected.delegate}`);
|
|
79821
|
+
}
|
|
79822
|
+
break;
|
|
79823
|
+
}
|
|
79824
|
+
case "bwar-add-address": {
|
|
79825
|
+
if (name !== "addAddress") {
|
|
79826
|
+
throw new TxValidationError3(`expected addAddress, decoded ${name}`);
|
|
79827
|
+
}
|
|
79828
|
+
if (!eqAddr3(to, expected.registryAddress)) {
|
|
79829
|
+
throw new TxValidationError3(
|
|
79830
|
+
`addAddress must target the BitcoinWithdrawalAddressRegistry (${expected.registryAddress}), got ${to}`
|
|
79831
|
+
);
|
|
79832
|
+
}
|
|
79833
|
+
if (String(args[0]) !== expected.btcAddress) {
|
|
79834
|
+
throw new TxValidationError3(
|
|
79835
|
+
`btcAddress mismatch \u2014 tx says '${String(args[0])}', user asked for '${expected.btcAddress}'`
|
|
79836
|
+
);
|
|
79837
|
+
}
|
|
79838
|
+
break;
|
|
79839
|
+
}
|
|
79840
|
+
case "stablecoin-approve": {
|
|
79841
|
+
if (name !== "approve") {
|
|
79842
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79843
|
+
}
|
|
79844
|
+
if (!eqAddr3(to, expected.tokenAddress)) {
|
|
79845
|
+
throw new TxValidationError3(`approve must target the stablecoin token (${expected.tokenAddress}), got ${to}`);
|
|
79846
|
+
}
|
|
79847
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
79848
|
+
throw new TxValidationError3(`approve spender must be the PSM (${expected.spender}), got ${String(args[0])}`);
|
|
79849
|
+
}
|
|
79850
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUnits) {
|
|
79851
|
+
throw new TxValidationError3(
|
|
79852
|
+
`approve amount must be EXACTLY ${expected.amountUnits} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
79853
|
+
);
|
|
79854
|
+
}
|
|
79855
|
+
break;
|
|
79856
|
+
}
|
|
79857
|
+
case "ucd-approve-controller": {
|
|
79858
|
+
if (name !== "approve") {
|
|
79859
|
+
throw new TxValidationError3(`expected ERC-20 approve, server returned ${name}`);
|
|
79860
|
+
}
|
|
79861
|
+
if (!eqAddr3(to, expected.ucdTokenAddress)) {
|
|
79862
|
+
throw new TxValidationError3(`approve must target UCDToken (${expected.ucdTokenAddress}), got ${to}`);
|
|
79863
|
+
}
|
|
79864
|
+
if (!eqAddr3(String(args[0]), expected.spender)) {
|
|
79865
|
+
throw new TxValidationError3(`approve spender must be the UCDController (${expected.spender}), got ${String(args[0])}`);
|
|
79866
|
+
}
|
|
79867
|
+
if (BigInt(String(args[1])).toString() !== expected.amountWei) {
|
|
79868
|
+
throw new TxValidationError3(
|
|
79869
|
+
`approve amount must be EXACTLY ${expected.amountWei} (exact-amount rule), got ${BigInt(String(args[1]))}`
|
|
79870
|
+
);
|
|
79871
|
+
}
|
|
79872
|
+
break;
|
|
79873
|
+
}
|
|
79874
|
+
case "psm-swap": {
|
|
79875
|
+
if (name !== "swap")
|
|
79876
|
+
throw new TxValidationError3(`expected swap, server returned ${name}`);
|
|
79877
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
79878
|
+
throw new TxValidationError3(`swap must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
79879
|
+
}
|
|
79880
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
79881
|
+
throw new TxValidationError3(`swap stablecoin mismatch`);
|
|
79882
|
+
if (BigInt(String(args[1])).toString() !== expected.amountIn)
|
|
79883
|
+
throw new TxValidationError3(`swap amountIn mismatch`);
|
|
79884
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
79885
|
+
throw new TxValidationError3(`swap minUcdOut mismatch`);
|
|
79886
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
79887
|
+
throw new TxValidationError3(`swap minUcdOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
79888
|
+
}
|
|
79889
|
+
break;
|
|
79890
|
+
}
|
|
79891
|
+
case "psm-redeem": {
|
|
79892
|
+
if (name !== "redeem")
|
|
79893
|
+
throw new TxValidationError3(`expected redeem, server returned ${name}`);
|
|
79894
|
+
if (!eqAddr3(to, expected.psmAddress)) {
|
|
79895
|
+
throw new TxValidationError3(`redeem must target the PSM (${expected.psmAddress}), got ${to}`);
|
|
79896
|
+
}
|
|
79897
|
+
if (!eqAddr3(String(args[0]), expected.stablecoin))
|
|
79898
|
+
throw new TxValidationError3(`redeem stablecoin mismatch`);
|
|
79899
|
+
if (BigInt(String(args[1])).toString() !== expected.amountUcdWei)
|
|
79900
|
+
throw new TxValidationError3(`redeem ucdAmount mismatch`);
|
|
79901
|
+
if (BigInt(String(args[2])).toString() !== expected.minOut)
|
|
79902
|
+
throw new TxValidationError3(`redeem minStablecoinOut mismatch`);
|
|
79903
|
+
if (BigInt(expected.minOut) === 0n) {
|
|
79904
|
+
throw new TxValidationError3(`redeem minStablecoinOut is 0 \u2014 a slippage floor is mandatory (SlippageProtectionRequired)`);
|
|
79905
|
+
}
|
|
79906
|
+
break;
|
|
79907
|
+
}
|
|
79908
|
+
default: {
|
|
79909
|
+
const _exhaustive = expected;
|
|
79910
|
+
throw new TxValidationError3(`unhandled expected action kind: ${JSON.stringify(_exhaustive)}`);
|
|
79911
|
+
}
|
|
79912
|
+
}
|
|
79913
|
+
}
|
|
79914
|
+
var SLOT_SECONDS2 = 12;
|
|
79915
|
+
var INCLUSION_SLOT_TOLERANCE2 = 3;
|
|
79916
|
+
var INCLUSION_LATENCY_BUDGET2 = SLOT_SECONDS2 * INCLUSION_SLOT_TOLERANCE2;
|
|
79917
|
+
function buildPsmApproveTx2(p) {
|
|
79918
|
+
return {
|
|
79919
|
+
to: p.token,
|
|
79920
|
+
data: encodeSignable3("approve", [p.spender, p.amount]),
|
|
79921
|
+
value: "0x0",
|
|
79922
|
+
chainId: p.chainId
|
|
79923
|
+
};
|
|
79924
|
+
}
|
|
79925
|
+
function buildPsmSwapTx3(p) {
|
|
79926
|
+
return {
|
|
79927
|
+
to: p.psm,
|
|
79928
|
+
data: encodeSignable3("swap", [p.stablecoin, p.amountIn, p.minOut]),
|
|
79929
|
+
value: "0x0",
|
|
79930
|
+
chainId: p.chainId
|
|
79931
|
+
};
|
|
79932
|
+
}
|
|
79933
|
+
function buildPsmRedeemTx3(p) {
|
|
79934
|
+
return {
|
|
79935
|
+
to: p.psm,
|
|
79936
|
+
data: encodeSignable3("redeem", [p.stablecoin, p.ucdAmount, p.minOut]),
|
|
79937
|
+
value: "0x0",
|
|
79938
|
+
chainId: p.chainId
|
|
79939
|
+
};
|
|
79940
|
+
}
|
|
79941
|
+
var PSM_READS_ABI2 = ["function supportedStablecoins(address) view returns (bool)"];
|
|
79942
|
+
var ERC20_READS_ABI2 = ["function allowance(address owner, address spender) view returns (uint256)"];
|
|
79943
|
+
function psmExchangeReadsFromProvider2(provider, psmAddress) {
|
|
79944
|
+
const psm = new import_ethers40.ethers.Contract(psmAddress, PSM_READS_ABI2, provider);
|
|
79945
|
+
return {
|
|
79946
|
+
isStablecoinSupported: async (stablecoin) => await psm.getFunction("supportedStablecoins")(stablecoin),
|
|
79947
|
+
allowance: async (token, owner, spender) => await new import_ethers40.ethers.Contract(token, ERC20_READS_ABI2, provider).getFunction("allowance")(owner, spender)
|
|
79948
|
+
};
|
|
79949
|
+
}
|
|
79950
|
+
var refuse2 = (direction, msg) => new TxValidationError3(msg, `PSM ${direction}`);
|
|
79951
|
+
function requireAddress2(direction, label, value) {
|
|
79952
|
+
if (!value || !import_ethers40.ethers.isAddress(value)) {
|
|
79953
|
+
throw refuse2(direction, `${label} address is missing or invalid (${String(value)})`);
|
|
79954
|
+
}
|
|
79955
|
+
return import_ethers40.ethers.getAddress(value);
|
|
79956
|
+
}
|
|
79957
|
+
async function planPsmExchange2(params) {
|
|
79958
|
+
const { direction, amountIn, minOut, vctx, reads } = params;
|
|
79959
|
+
const chainId = vctx.chainId;
|
|
79960
|
+
if (amountIn <= 0n) {
|
|
79961
|
+
throw refuse2(direction, `amount must be greater than zero (got ${amountIn})`);
|
|
79962
|
+
}
|
|
79963
|
+
if (minOut <= 0n) {
|
|
79964
|
+
throw refuse2(direction, `minimum-out floor must be greater than zero (got ${minOut}) \u2014 a zero floor is refused on-chain`);
|
|
79965
|
+
}
|
|
79966
|
+
const owner = requireAddress2(direction, "owner", params.owner);
|
|
79967
|
+
const psm = requireAddress2(direction, "SimplePSMV2", params.addresses.psm);
|
|
79968
|
+
const stablecoin = requireAddress2(direction, "stablecoin", params.addresses.stablecoin);
|
|
79969
|
+
const isSwap = direction === "swap";
|
|
79970
|
+
const token = isSwap ? stablecoin : requireAddress2(direction, "UCDToken", params.addresses.ucdToken);
|
|
79971
|
+
const spender = isSwap ? psm : requireAddress2(direction, "UCDController", params.addresses.ucdController);
|
|
79972
|
+
if (!await reads.isStablecoinSupported(stablecoin)) {
|
|
79973
|
+
throw refuse2(direction, `stablecoin ${stablecoin} is not supported by the PSM at ${psm}`);
|
|
79974
|
+
}
|
|
79975
|
+
const approveExpected = (amount) => isSwap ? { kind: "stablecoin-approve", tokenAddress: token, spender, amountUnits: amount.toString() } : { kind: "ucd-approve-controller", ucdTokenAddress: token, spender, amountWei: amount.toString() };
|
|
79976
|
+
const allowanceBefore = await reads.allowance(token, owner, spender);
|
|
79977
|
+
const approvals = [];
|
|
79978
|
+
if (allowanceBefore < amountIn) {
|
|
79979
|
+
if (allowanceBefore > 0n) {
|
|
79980
|
+
approvals.push({
|
|
79981
|
+
step: "reset-approve",
|
|
79982
|
+
tx: buildPsmApproveTx2({ token, spender, amount: 0n, chainId }),
|
|
79983
|
+
expected: approveExpected(0n)
|
|
79984
|
+
});
|
|
79985
|
+
}
|
|
79986
|
+
approvals.push({
|
|
79987
|
+
step: "approve",
|
|
79988
|
+
tx: buildPsmApproveTx2({ token, spender, amount: amountIn, chainId }),
|
|
79989
|
+
expected: approveExpected(amountIn)
|
|
79990
|
+
});
|
|
79991
|
+
}
|
|
79992
|
+
const exec = isSwap ? {
|
|
79993
|
+
step: "swap",
|
|
79994
|
+
tx: buildPsmSwapTx3({ psm, stablecoin, amountIn, minOut, chainId }),
|
|
79995
|
+
expected: { kind: "psm-swap", psmAddress: psm, stablecoin, amountIn: amountIn.toString(), minOut: minOut.toString() }
|
|
79996
|
+
} : {
|
|
79997
|
+
step: "redeem",
|
|
79998
|
+
tx: buildPsmRedeemTx3({ psm, stablecoin, ucdAmount: amountIn, minOut, chainId }),
|
|
79999
|
+
expected: {
|
|
80000
|
+
kind: "psm-redeem",
|
|
80001
|
+
psmAddress: psm,
|
|
80002
|
+
stablecoin,
|
|
80003
|
+
amountUcdWei: amountIn.toString(),
|
|
80004
|
+
minOut: minOut.toString()
|
|
80005
|
+
}
|
|
80006
|
+
};
|
|
80007
|
+
for (const leg of [...approvals, exec]) {
|
|
80008
|
+
validateUnsignedTx3({ ...leg.tx }, leg.expected, vctx);
|
|
80009
|
+
}
|
|
80010
|
+
return { direction, owner, token, spender, amountIn, minOut, allowanceBefore, approvals, exec };
|
|
80011
|
+
}
|
|
80012
|
+
|
|
80013
|
+
// src/boundary/upstream/real/psm-calls.ts
|
|
78450
80014
|
var PSM_VIEW_FRAGMENTS = [
|
|
78451
80015
|
"function VERSION() view returns (string)",
|
|
78452
80016
|
"function supportedStablecoins(address) view returns (bool)",
|
|
@@ -78466,15 +80030,7 @@ var PSM_VIEW_FRAGMENTS = [
|
|
|
78466
80030
|
"function getSwapQuote(address stablecoin, uint256 amountIn) view returns (uint256 ucdOut, uint256 fee)",
|
|
78467
80031
|
"function getRedemptionQuote(address stablecoin, uint256 ucdAmount) view returns (uint256 stablecoinOut, uint256 exitFee)"
|
|
78468
80032
|
];
|
|
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);
|
|
80033
|
+
var ERC20_FRAGMENTS = ["function balanceOf(address holder) view returns (uint256)"];
|
|
78478
80034
|
var PSM_ERROR_FRAGMENTS = [
|
|
78479
80035
|
"error StablecoinNotSupported(address stablecoin)",
|
|
78480
80036
|
"error InvalidAmount()",
|
|
@@ -78522,9 +80078,9 @@ var RENDERERS = {
|
|
|
78522
80078
|
var PsmCalls = class {
|
|
78523
80079
|
constructor(deps) {
|
|
78524
80080
|
this.deps = deps;
|
|
78525
|
-
const abi = [...PSM_VIEW_FRAGMENTS, ...
|
|
78526
|
-
this.iface = new
|
|
78527
|
-
this.psm = new
|
|
80081
|
+
const abi = [...PSM_VIEW_FRAGMENTS, ...PSM_ERROR_FRAGMENTS];
|
|
80082
|
+
this.iface = new import_ethers41.ethers.Interface(abi);
|
|
80083
|
+
this.psm = new import_ethers41.ethers.Contract(deps.psmAddress, abi, deps.provider);
|
|
78528
80084
|
}
|
|
78529
80085
|
psm;
|
|
78530
80086
|
iface;
|
|
@@ -78537,34 +80093,10 @@ var PsmCalls = class {
|
|
|
78537
80093
|
...this.deps.ucdControllerAddress ? { ucdController: this.deps.ucdControllerAddress } : {}
|
|
78538
80094
|
};
|
|
78539
80095
|
}
|
|
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
|
-
};
|
|
80096
|
+
/** The two live reads the SDK's exchange planner depends on (supported set + allowance),
|
|
80097
|
+
* over this wrapper's provider and PSM. */
|
|
80098
|
+
exchangeReads() {
|
|
80099
|
+
return psmExchangeReadsFromProvider2(this.deps.provider, this.deps.psmAddress);
|
|
78568
80100
|
}
|
|
78569
80101
|
/** Post-pair wallet balances (UCD wei + stablecoin smallest units) — live reads. */
|
|
78570
80102
|
async balances(holder) {
|
|
@@ -78577,8 +80109,8 @@ var PsmCalls = class {
|
|
|
78577
80109
|
});
|
|
78578
80110
|
}
|
|
78579
80111
|
return this.call(async () => {
|
|
78580
|
-
const ucd = new
|
|
78581
|
-
const stable = new
|
|
80112
|
+
const ucd = new import_ethers41.ethers.Contract(ucdToken, ERC20_FRAGMENTS, this.deps.provider);
|
|
80113
|
+
const stable = new import_ethers41.ethers.Contract(this.deps.stablecoinAddress, ERC20_FRAGMENTS, this.deps.provider);
|
|
78582
80114
|
const [ucdWei, stablecoinUnits] = await Promise.all([ucd["balanceOf"](holder), stable["balanceOf"](holder)]);
|
|
78583
80115
|
return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
|
|
78584
80116
|
});
|
|
@@ -78696,7 +80228,7 @@ var PsmCalls = class {
|
|
|
78696
80228
|
};
|
|
78697
80229
|
|
|
78698
80230
|
// src/boundary/upstream/real/session.ts
|
|
78699
|
-
var
|
|
80231
|
+
var import_ethers42 = require("ethers");
|
|
78700
80232
|
var REFRESH_LEEWAY_SEC = 30;
|
|
78701
80233
|
var LOGIN_TYPES_WITH_AUDIENCE3 = {
|
|
78702
80234
|
DiamondHands: [
|
|
@@ -78744,7 +80276,7 @@ var LitOpsSession = class {
|
|
|
78744
80276
|
const message = {
|
|
78745
80277
|
address: this.wallet.address,
|
|
78746
80278
|
issuedAt: Math.floor(Date.now() / 1e3),
|
|
78747
|
-
nonce: "0x" + Buffer.from(
|
|
80279
|
+
nonce: "0x" + Buffer.from(import_ethers42.ethers.randomBytes(32)).toString("hex"),
|
|
78748
80280
|
audience: this.serviceEndpoint
|
|
78749
80281
|
};
|
|
78750
80282
|
const signature = await this.wallet.signTypedData(
|
|
@@ -78786,7 +80318,7 @@ function decodeJwtExp(token) {
|
|
|
78786
80318
|
}
|
|
78787
80319
|
|
|
78788
80320
|
// src/boundary/upstream/real/write-ops.ts
|
|
78789
|
-
var
|
|
80321
|
+
var import_ethers44 = require("ethers");
|
|
78790
80322
|
|
|
78791
80323
|
// src/signer/types.ts
|
|
78792
80324
|
var OperationDeclined = class extends Error {
|
|
@@ -78796,7 +80328,7 @@ var OperationDeclined = class extends Error {
|
|
|
78796
80328
|
init_tx_validator();
|
|
78797
80329
|
|
|
78798
80330
|
// src/boundary/upstream/shared/external-bridge/page-crypto.ts
|
|
78799
|
-
var
|
|
80331
|
+
var import_ethers43 = require("ethers");
|
|
78800
80332
|
var PERSONAL_SIGN_LAYOUTS = {
|
|
78801
80333
|
"dh-op-envelope-v1": {
|
|
78802
80334
|
types: ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
|
|
@@ -78817,9 +80349,9 @@ function hashForLayout(layout, fields) {
|
|
|
78817
80349
|
const values = def.fieldOrder.map((name) => {
|
|
78818
80350
|
const raw = fields[name];
|
|
78819
80351
|
if (raw === void 0) throw new Error(`page-crypto: layout "${layout}" missing field "${name}"`);
|
|
78820
|
-
return hashUtf8.has(name) ?
|
|
80352
|
+
return hashUtf8.has(name) ? import_ethers43.ethers.keccak256(import_ethers43.ethers.toUtf8Bytes(raw)) : raw;
|
|
78821
80353
|
});
|
|
78822
|
-
return
|
|
80354
|
+
return import_ethers43.ethers.solidityPackedKeccak256(def.types, values);
|
|
78823
80355
|
}
|
|
78824
80356
|
var PAGE_CRYPTO_JS = `"use strict";
|
|
78825
80357
|
(function () {
|
|
@@ -79048,9 +80580,21 @@ function buildValidationContext(network, chainId) {
|
|
|
79048
80580
|
|
|
79049
80581
|
// src/boundary/upstream/real/write-ops.ts
|
|
79050
80582
|
var SOURCE5 = "real-ops";
|
|
80583
|
+
function mcpExpected(leg) {
|
|
80584
|
+
const e = leg.expected;
|
|
80585
|
+
switch (e.kind) {
|
|
80586
|
+
case "stablecoin-approve":
|
|
80587
|
+
case "ucd-approve-controller":
|
|
80588
|
+
case "psm-swap":
|
|
80589
|
+
case "psm-redeem":
|
|
80590
|
+
return e;
|
|
80591
|
+
default:
|
|
80592
|
+
throw new Error(`the PSM plan produced a non-PSM expectation '${e.kind}' for its ${leg.step} leg`);
|
|
80593
|
+
}
|
|
80594
|
+
}
|
|
79051
80595
|
var OP_LAYOUT = "dh-op-envelope-v1";
|
|
79052
80596
|
function randomNonceHex() {
|
|
79053
|
-
return "0x" + Buffer.from(
|
|
80597
|
+
return "0x" + Buffer.from(import_ethers44.ethers.randomBytes(16)).toString("hex");
|
|
79054
80598
|
}
|
|
79055
80599
|
async function postJson(url2, body, headers) {
|
|
79056
80600
|
const res = await fetch(url2, {
|
|
@@ -79111,7 +80655,7 @@ function buildWriteOps(deps) {
|
|
|
79111
80655
|
return {
|
|
79112
80656
|
to: String(tx2["to"] ?? ""),
|
|
79113
80657
|
data: String(tx2["data"] ?? "0x"),
|
|
79114
|
-
value: tx2["value"] != null ?
|
|
80658
|
+
value: tx2["value"] != null ? import_ethers44.ethers.toBeHex(BigInt(String(tx2["value"]))) : "0x0",
|
|
79115
80659
|
chainId: tx2["chainId"] != null ? Number(tx2["chainId"]) : chainId
|
|
79116
80660
|
};
|
|
79117
80661
|
}
|
|
@@ -79196,8 +80740,9 @@ function buildWriteOps(deps) {
|
|
|
79196
80740
|
}
|
|
79197
80741
|
return {
|
|
79198
80742
|
createPosition: async (p) => {
|
|
79199
|
-
const
|
|
79200
|
-
if (!
|
|
80743
|
+
const built = await deps.getWriteSdk();
|
|
80744
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
80745
|
+
const sdk = built.sdk;
|
|
79201
80746
|
try {
|
|
79202
80747
|
await deps.assertValidatorConfigured();
|
|
79203
80748
|
} catch (e) {
|
|
@@ -79276,7 +80821,7 @@ function buildWriteOps(deps) {
|
|
|
79276
80821
|
mintedUcdWei: minted,
|
|
79277
80822
|
feeUcdWei: mintFee,
|
|
79278
80823
|
echoedAmountUcdWei: minted,
|
|
79279
|
-
authorization: auth(action, `mint ${
|
|
80824
|
+
authorization: auth(action, `mint ${import_ethers44.ethers.formatEther(amountWei)} UCD against ${p.positionId}`, r.value.digest)
|
|
79280
80825
|
},
|
|
79281
80826
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79282
80827
|
);
|
|
@@ -79317,7 +80862,7 @@ function buildWriteOps(deps) {
|
|
|
79317
80862
|
txRef: { kind: "eth-tx", id: r.value.txHash },
|
|
79318
80863
|
paidUcdWei: paid,
|
|
79319
80864
|
echoedAmountUcdWei: paid,
|
|
79320
|
-
authorization: auth(action, `repay ${
|
|
80865
|
+
authorization: auth(action, `repay ${import_ethers44.ethers.formatEther(amountWei)} UCD on ${p.positionId}`, r.value.digest)
|
|
79321
80866
|
},
|
|
79322
80867
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79323
80868
|
);
|
|
@@ -79357,8 +80902,9 @@ function buildWriteOps(deps) {
|
|
|
79357
80902
|
);
|
|
79358
80903
|
},
|
|
79359
80904
|
withdraw: async (p) => {
|
|
79360
|
-
const
|
|
79361
|
-
if (!
|
|
80905
|
+
const built = await deps.getWriteSdk();
|
|
80906
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
80907
|
+
const sdk = built.sdk;
|
|
79362
80908
|
const amountSats = Number(p.amountSats);
|
|
79363
80909
|
const feeSats = Number(p.networkFeeSats);
|
|
79364
80910
|
let result;
|
|
@@ -79387,12 +80933,13 @@ function buildWriteOps(deps) {
|
|
|
79387
80933
|
{ id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
79388
80934
|
);
|
|
79389
80935
|
},
|
|
79390
|
-
/** PSM exchange
|
|
79391
|
-
* orchestration.
|
|
79392
|
-
*
|
|
79393
|
-
*
|
|
79394
|
-
*
|
|
79395
|
-
*
|
|
80936
|
+
/** PSM exchange (plan 08 W1; seam 1.4): pure on-chain calls — no LIT action, no server
|
|
80937
|
+
* orchestration. The legs come from the SDK sign-guard's `planPsmExchange` — the ONE
|
|
80938
|
+
* builder every client shares (it replaced this file's own builders and the SDK's old
|
|
80939
|
+
* MaxUint256 helpers): it verifies the stablecoin on-chain, reads the standing
|
|
80940
|
+
* allowance, plans 0/1/2 exact-amount approve legs, and validates every leg. Each leg is
|
|
80941
|
+
* validated again here by the MCP's own whitelist (the one the approval card decodes
|
|
80942
|
+
* with), then signed through the session signer and broadcast — one at a time. */
|
|
79396
80943
|
psmSwap: async (p) => {
|
|
79397
80944
|
const pr = await deps.psm(p.stablecoin);
|
|
79398
80945
|
if (!pr.ok) return upFail(pr.failure);
|
|
@@ -79406,11 +80953,7 @@ function buildWriteOps(deps) {
|
|
|
79406
80953
|
message: "the bundled deployment table lacks a UCDToken/UCDController address \u2014 the redeem approve leg refuses rather than guess a spender."
|
|
79407
80954
|
});
|
|
79408
80955
|
}
|
|
79409
|
-
const amountIn = BigInt(p.amountIn);
|
|
79410
|
-
const minOut = BigInt(p.minOut);
|
|
79411
80956
|
const vctx = buildValidationContext(config.network, chainId);
|
|
79412
|
-
const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
|
|
79413
|
-
const spenderAddress = isSwap ? addr.psm : addr.ucdController;
|
|
79414
80957
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
79415
80958
|
const tokenSymbol = isSwap ? calls.symbol() : "UCD";
|
|
79416
80959
|
const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
|
|
@@ -79427,49 +80970,66 @@ function buildWriteOps(deps) {
|
|
|
79427
80970
|
return submitFailure(leg, e);
|
|
79428
80971
|
}
|
|
79429
80972
|
};
|
|
79430
|
-
|
|
80973
|
+
let plan;
|
|
79431
80974
|
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
|
-
);
|
|
80975
|
+
plan = await planPsmExchange2({
|
|
80976
|
+
direction: p.direction,
|
|
80977
|
+
owner: p.borrower,
|
|
80978
|
+
addresses: addr,
|
|
80979
|
+
amountIn: BigInt(p.amountIn),
|
|
80980
|
+
minOut: BigInt(p.minOut),
|
|
80981
|
+
vctx,
|
|
80982
|
+
reads: calls.exchangeReads()
|
|
80983
|
+
});
|
|
79452
80984
|
} catch (e) {
|
|
79453
|
-
return upFail({ kind: "rejected", source: SOURCE5, message:
|
|
80985
|
+
return e instanceof TxValidationError3 ? upFail({ kind: "rejected", source: SOURCE5, message: `${e.message} \u2014 nothing was signed` }) : upFail({
|
|
80986
|
+
kind: "unavailable",
|
|
80987
|
+
source: SOURCE5,
|
|
80988
|
+
message: `the PSM ${p.direction} could not be planned (allowance / supported-stablecoin read): ${e.message} \u2014 nothing was signed`,
|
|
80989
|
+
raw: String(e)
|
|
80990
|
+
});
|
|
79454
80991
|
}
|
|
79455
|
-
const
|
|
79456
|
-
const
|
|
79457
|
-
|
|
79458
|
-
|
|
79459
|
-
|
|
80992
|
+
const { token: tokenAddress, spender: spenderAddress, allowanceBefore } = plan;
|
|
80993
|
+
const unit = `${tokenSymbol} smallest units`;
|
|
80994
|
+
const landed = [];
|
|
80995
|
+
const residualNote = () => {
|
|
80996
|
+
const last = landed[landed.length - 1];
|
|
80997
|
+
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`;
|
|
80998
|
+
return `${standing}. No retry was attempted \u2014 re-run psm_swap to use or replace it`;
|
|
80999
|
+
};
|
|
81000
|
+
const runLeg = async (leg) => {
|
|
81001
|
+
const withResidual = (message) => landed.length > 0 || leg === plan.exec ? `${message} \u2014 ${residualNote()}` : message;
|
|
81002
|
+
try {
|
|
81003
|
+
validateUnsignedTx({ ...leg.tx }, mcpExpected(leg), vctx);
|
|
81004
|
+
} catch (e) {
|
|
81005
|
+
return upFail({ kind: "rejected", source: SOURCE5, message: withResidual(`PSM ${leg.step} tx failed the whitelist: ${e.message}`) });
|
|
81006
|
+
}
|
|
81007
|
+
const action = leg.step === "swap" ? "psm-swap" : leg.step === "redeem" ? "psm-redeem" : "psm-approve";
|
|
81008
|
+
const r = await broadcast(`psmSwap (${leg.step})`, action, leg.tx);
|
|
81009
|
+
return r.ok ? r : upFail({ ...r.failure, message: withResidual(r.failure.message) });
|
|
81010
|
+
};
|
|
81011
|
+
const approvals = [];
|
|
81012
|
+
for (const leg of plan.approvals) {
|
|
81013
|
+
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})`;
|
|
81014
|
+
const step = leg.step === "reset-approve" ? "reset-approve" : "approve";
|
|
81015
|
+
const r = await runLeg(leg);
|
|
81016
|
+
if (!r.ok) return r;
|
|
81017
|
+
landed.push({ step, hash: r.value });
|
|
81018
|
+
approvals.push({
|
|
81019
|
+
step,
|
|
81020
|
+
txRef: { kind: "eth-tx", id: r.value },
|
|
81021
|
+
amount: leg.step === "reset-approve" ? "0" : p.amountIn,
|
|
81022
|
+
authorization: auth("psm-approve", card, r.value)
|
|
81023
|
+
});
|
|
79460
81024
|
}
|
|
81025
|
+
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}`;
|
|
81026
|
+
const execHashR = await runLeg(plan.exec);
|
|
81027
|
+
if (!execHashR.ok) return execHashR;
|
|
79461
81028
|
const execHash = execHashR.value;
|
|
79462
81029
|
const balancesR = await calls.balances(p.borrower);
|
|
79463
81030
|
const row = {
|
|
79464
|
-
|
|
79465
|
-
|
|
79466
|
-
tokenSymbol,
|
|
79467
|
-
tokenAddress,
|
|
79468
|
-
spenderAddress,
|
|
79469
|
-
spenderContract,
|
|
79470
|
-
amount: p.amountIn,
|
|
79471
|
-
authorization: auth("psm-approve", approveCard, approveHash)
|
|
79472
|
-
},
|
|
81031
|
+
allowance: { tokenSymbol, tokenAddress, spenderAddress, spenderContract, before: allowanceBefore.toString() },
|
|
81032
|
+
approvals,
|
|
79473
81033
|
execute: {
|
|
79474
81034
|
txRef: { kind: "eth-tx", id: execHash },
|
|
79475
81035
|
amountIn: p.amountIn,
|
|
@@ -79486,8 +81046,9 @@ function buildWriteOps(deps) {
|
|
|
79486
81046
|
// registry's msg.sender). Safe borrowers stay ceremony-class: the Safe itself must be
|
|
79487
81047
|
// msg.sender, so their path is a SafeTx — never this keystore leg.
|
|
79488
81048
|
allowlistWithdrawalAddress: async (p) => {
|
|
79489
|
-
const
|
|
79490
|
-
if (!
|
|
81049
|
+
const built = await deps.getWriteSdk();
|
|
81050
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81051
|
+
const sdk = built.sdk;
|
|
79491
81052
|
let result;
|
|
79492
81053
|
try {
|
|
79493
81054
|
result = await sdk.addApprovedWithdrawalAddress(p.btcAddress);
|
|
@@ -79534,8 +81095,9 @@ function buildWriteOps(deps) {
|
|
|
79534
81095
|
message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
|
|
79535
81096
|
}),
|
|
79536
81097
|
retryWithdrawExecute: async (p) => {
|
|
79537
|
-
const
|
|
79538
|
-
if (!
|
|
81098
|
+
const built = await deps.getWriteSdk();
|
|
81099
|
+
if (!built.ok) return upFail({ kind: "unavailable", source: SOURCE5, message: `write SDK could not be built: ${built.reason}` });
|
|
81100
|
+
const sdk = built.sdk;
|
|
79539
81101
|
let rows;
|
|
79540
81102
|
try {
|
|
79541
81103
|
rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
|
|
@@ -79563,7 +81125,7 @@ function buildWriteOps(deps) {
|
|
|
79563
81125
|
}
|
|
79564
81126
|
|
|
79565
81127
|
// src/signer/eoa-dh.ts
|
|
79566
|
-
var
|
|
81128
|
+
var import_ethers45 = require("ethers");
|
|
79567
81129
|
var EoaDHSigner = class {
|
|
79568
81130
|
constructor(wallet, broadcast, clock = Date.now) {
|
|
79569
81131
|
this.wallet = wallet;
|
|
@@ -79580,7 +81142,7 @@ var EoaDHSigner = class {
|
|
|
79580
81142
|
async signAuthorization(spec) {
|
|
79581
81143
|
const quantumTs = nextQuantumTimestamp(this.clock());
|
|
79582
81144
|
const { fields, hashHex } = spec.stamp(quantumTs);
|
|
79583
|
-
const signature = await this.wallet.signMessage(
|
|
81145
|
+
const signature = await this.wallet.signMessage(import_ethers45.ethers.getBytes(hashHex));
|
|
79584
81146
|
return { signature, quantumTs, fields };
|
|
79585
81147
|
}
|
|
79586
81148
|
async wrapInnerTx(innerTx) {
|
|
@@ -79598,10 +81160,10 @@ var EoaDHSigner = class {
|
|
|
79598
81160
|
|
|
79599
81161
|
// src/signer/external-eoa.ts
|
|
79600
81162
|
var import_node_crypto5 = require("crypto");
|
|
79601
|
-
var
|
|
81163
|
+
var import_ethers47 = require("ethers");
|
|
79602
81164
|
|
|
79603
81165
|
// src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
|
|
79604
|
-
var
|
|
81166
|
+
var import_ethers46 = require("ethers");
|
|
79605
81167
|
function eq2(a, b) {
|
|
79606
81168
|
return a.toLowerCase() === b.toLowerCase();
|
|
79607
81169
|
}
|
|
@@ -79624,7 +81186,7 @@ function compareLandedTx(landed, approved, borrower) {
|
|
|
79624
81186
|
return { status: "verified", from: landed.from, hash: landed.hash };
|
|
79625
81187
|
}
|
|
79626
81188
|
function verifyRawSignedTx(rawSignedTx, approved, borrower) {
|
|
79627
|
-
const parsed =
|
|
81189
|
+
const parsed = import_ethers46.ethers.Transaction.from(rawSignedTx);
|
|
79628
81190
|
if (!parsed.from || !parsed.to || !parsed.hash) {
|
|
79629
81191
|
return { status: "mismatch", hash: parsed.hash ?? "0x", reason: "the returned raw transaction is unsigned or malformed" };
|
|
79630
81192
|
}
|
|
@@ -79662,7 +81224,7 @@ async function gasHintAcrossBlocks(provider, from, tx2, action) {
|
|
|
79662
81224
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
79663
81225
|
try {
|
|
79664
81226
|
const est = await provider.estimateGas({ from, to: tx2.to, data: tx2.data, value: BigInt(tx2.value) });
|
|
79665
|
-
return
|
|
81227
|
+
return import_ethers47.ethers.toBeHex(est * 15n / 10n);
|
|
79666
81228
|
} catch (e) {
|
|
79667
81229
|
lastErr = e;
|
|
79668
81230
|
await new Promise((r) => setTimeout(r, 13e3));
|
|
@@ -79712,7 +81274,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79712
81274
|
throw new OperationDeclined(`the ${spec.action} authorization was not signed: ${describeOutcome(outcome)}`);
|
|
79713
81275
|
}
|
|
79714
81276
|
const finalHash = spec.stamp(used.quantumTs).hashHex;
|
|
79715
|
-
const recovered =
|
|
81277
|
+
const recovered = import_ethers47.ethers.verifyMessage(import_ethers47.ethers.getBytes(finalHash), outcome.signature);
|
|
79716
81278
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
79717
81279
|
throw new Error(`the ${spec.action} authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
79718
81280
|
}
|
|
@@ -79723,7 +81285,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79723
81285
|
}
|
|
79724
81286
|
async submitValidatedTx(outerTx, ctx) {
|
|
79725
81287
|
const approved = toApprovedTx(outerTx, this.deps.chainId);
|
|
79726
|
-
const gas = outerTx.gasLimit != null ?
|
|
81288
|
+
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
81289
|
const outcome = await this.deps.bridge.requestSignature({
|
|
79728
81290
|
id: (0, import_node_crypto5.randomUUID)(),
|
|
79729
81291
|
kind: "transaction",
|
|
@@ -79757,7 +81319,7 @@ var ExternalEoaDHSigner = class {
|
|
|
79757
81319
|
return new BridgeEthersSigner(this.deps);
|
|
79758
81320
|
}
|
|
79759
81321
|
};
|
|
79760
|
-
var BridgeEthersSigner = class _BridgeEthersSigner extends
|
|
81322
|
+
var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers47.ethers.AbstractSigner {
|
|
79761
81323
|
constructor(deps) {
|
|
79762
81324
|
super(deps.provider);
|
|
79763
81325
|
this.deps = deps;
|
|
@@ -79768,13 +81330,13 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79768
81330
|
return this.deps.borrower;
|
|
79769
81331
|
}
|
|
79770
81332
|
async signMessage(message) {
|
|
79771
|
-
const bytes = typeof message === "string" ?
|
|
81333
|
+
const bytes = typeof message === "string" ? import_ethers47.ethers.toUtf8Bytes(message) : message;
|
|
79772
81334
|
if (bytes.length !== 32) {
|
|
79773
81335
|
throw new Error(
|
|
79774
81336
|
`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
81337
|
);
|
|
79776
81338
|
}
|
|
79777
|
-
const hashHex =
|
|
81339
|
+
const hashHex = import_ethers47.ethers.hexlify(bytes).toLowerCase();
|
|
79778
81340
|
const nowMs = (this.deps.clock ?? Date.now)();
|
|
79779
81341
|
const expiresAtSec = nextQuantumTimestamp(nowMs);
|
|
79780
81342
|
const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
|
|
@@ -79804,7 +81366,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79804
81366
|
if (outcome.status !== "approved" || !outcome.signature) {
|
|
79805
81367
|
throw new OperationDeclined(`the btc-withdrawal authorization was not signed: ${describeOutcome(outcome)}`);
|
|
79806
81368
|
}
|
|
79807
|
-
const recovered =
|
|
81369
|
+
const recovered = import_ethers47.ethers.verifyMessage(bytes, outcome.signature);
|
|
79808
81370
|
if (recovered.toLowerCase() !== this.deps.borrower.toLowerCase()) {
|
|
79809
81371
|
throw new Error(`the btc-withdrawal authorization was signed by ${recovered}, not the borrower ${this.deps.borrower}`);
|
|
79810
81372
|
}
|
|
@@ -79838,11 +81400,11 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
|
|
|
79838
81400
|
const approved = {
|
|
79839
81401
|
to: tx2.to,
|
|
79840
81402
|
data: tx2.data,
|
|
79841
|
-
value: tx2.value != null ?
|
|
81403
|
+
value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
79842
81404
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : this.deps.chainId
|
|
79843
81405
|
};
|
|
79844
81406
|
const card = cardForTx(approved);
|
|
79845
|
-
const gas = tx2.gasLimit != null ?
|
|
81407
|
+
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
81408
|
const outcome = await this.deps.bridge.requestSignature({
|
|
79847
81409
|
id: (0, import_node_crypto5.randomUUID)(),
|
|
79848
81410
|
kind: "transaction",
|
|
@@ -79884,14 +81446,14 @@ function toApprovedTx(tx2, fallbackChainId) {
|
|
|
79884
81446
|
return {
|
|
79885
81447
|
to: tx2.to,
|
|
79886
81448
|
data: tx2.data,
|
|
79887
|
-
value: tx2.value != null ?
|
|
81449
|
+
value: tx2.value != null ? import_ethers47.ethers.toBeHex(BigInt(String(tx2.value))) : "0x0",
|
|
79888
81450
|
chainId: tx2.chainId != null ? Number(tx2.chainId) : fallbackChainId
|
|
79889
81451
|
};
|
|
79890
81452
|
}
|
|
79891
81453
|
function describeFn(data) {
|
|
79892
81454
|
try {
|
|
79893
|
-
const { decodeSignable:
|
|
79894
|
-
return
|
|
81455
|
+
const { decodeSignable: decodeSignable4 } = (init_tx_validator(), __toCommonJS(tx_validator_exports));
|
|
81456
|
+
return decodeSignable4(data).name;
|
|
79895
81457
|
} catch {
|
|
79896
81458
|
return "operation";
|
|
79897
81459
|
}
|
|
@@ -79928,7 +81490,7 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
|
|
|
79928
81490
|
var RealUpstreamPlugin = class {
|
|
79929
81491
|
constructor(config, wallet, runtime) {
|
|
79930
81492
|
this.config = config;
|
|
79931
|
-
this.provider = new
|
|
81493
|
+
this.provider = new import_ethers48.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
|
|
79932
81494
|
this.wallet = wallet ?? null;
|
|
79933
81495
|
this.runtime = runtime ?? null;
|
|
79934
81496
|
this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
|
|
@@ -80059,7 +81621,7 @@ var RealUpstreamPlugin = class {
|
|
|
80059
81621
|
})
|
|
80060
81622
|
)
|
|
80061
81623
|
};
|
|
80062
|
-
const writeRefusalReason = !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014
|
|
81624
|
+
const writeRefusalReason = !this.wallet ? `no signer is configured (SIGNER_UNAVAILABLE) \u2014 EVERY write refuses for this same reason until one is, so trying a different write tool will not get past it (reads are unaffected). Writes need the keystore env pair (DH_KEYSTORE_PATH + DH_KEYSTORE_PASSWORD), or run signer_setup.` : `the lit-ops login session is unavailable \u2014 the keystore is configured but EIP-712 login did not complete; check the broker endpoint and retry.`;
|
|
80063
81625
|
const readOnly = (op) => Promise.resolve(
|
|
80064
81626
|
upFail({
|
|
80065
81627
|
kind: "unavailable",
|
|
@@ -80121,18 +81683,24 @@ var RealUpstreamPlugin = class {
|
|
|
80121
81683
|
* the lit-ops graph proxy over the authenticated session, `/v1/init` is never fetched,
|
|
80122
81684
|
* and the service-mode SDK routes its own subgraph reads through the same proxy — so
|
|
80123
81685
|
* writes survive a world where `/v1/init` stops advertising a graphEndpoint (A2.7).
|
|
80124
|
-
* Safe to call repeatedly
|
|
80125
|
-
*
|
|
81686
|
+
* Safe to call repeatedly. A failed pre-warm is NOT sticky: nothing is cached, and the
|
|
81687
|
+
* first write builds again (see ensureSdk). */
|
|
80126
81688
|
async initWriteSdk() {
|
|
80127
81689
|
if (this.runtime && this.runtime.manager.mode() !== "keystore") return;
|
|
80128
81690
|
const wallet = this.wallet ?? this.runtime?.keystore?.signer() ?? null;
|
|
80129
81691
|
if (!wallet) return;
|
|
80130
81692
|
await this.ensureSdk(`keystore:${wallet.address.toLowerCase()}`, wallet.connect(this.provider));
|
|
80131
81693
|
}
|
|
80132
|
-
/**
|
|
80133
|
-
*
|
|
81694
|
+
/** The signer-bearing WRITE SDK for an identity key: built on first use, cached once built.
|
|
81695
|
+
*
|
|
81696
|
+
* A FAILED build is never cached, and its cause is returned. It used to cache `null` for the
|
|
81697
|
+
* life of the process and drop the error, which was survivable only while `create` never
|
|
81698
|
+
* touched the network — from dh-sdk 0.0.340 it asks the provider which chain it is on, so an
|
|
81699
|
+
* RPC blip at boot would have disabled every later write with no reason given. Now each write
|
|
81700
|
+
* retries, and a persistent failure says what it is. Concurrent callers share one build. */
|
|
80134
81701
|
async ensureSdk(key, signer) {
|
|
80135
|
-
|
|
81702
|
+
const cached = this.sdkCache.get(key);
|
|
81703
|
+
if (cached) return { ok: true, sdk: cached };
|
|
80136
81704
|
const inFlight = this.sdkInFlight.get(key);
|
|
80137
81705
|
if (inFlight) return inFlight;
|
|
80138
81706
|
const build = (async () => {
|
|
@@ -80152,17 +81720,23 @@ var RealUpstreamPlugin = class {
|
|
|
80152
81720
|
// nesting writes under indexer discovery (the M8B-4 coupling this removes).
|
|
80153
81721
|
...v !== void 0 ? { validators: { loanCreation: v, minting: v, payment: v, extension: v } } : {}
|
|
80154
81722
|
});
|
|
80155
|
-
|
|
80156
|
-
|
|
80157
|
-
|
|
81723
|
+
if (isSuccess(builtWrite)) return { ok: true, sdk: builtWrite.value };
|
|
81724
|
+
return { ok: false, reason: builtWrite.error.message };
|
|
81725
|
+
} catch (e) {
|
|
81726
|
+
return { ok: false, reason: e instanceof Error ? e.message : String(e) };
|
|
80158
81727
|
}
|
|
80159
81728
|
})();
|
|
80160
81729
|
this.sdkInFlight.set(key, build);
|
|
80161
81730
|
const built = await build;
|
|
80162
81731
|
this.sdkInFlight.delete(key);
|
|
80163
|
-
this.sdkCache.set(key, built);
|
|
81732
|
+
if (built.ok) this.sdkCache.set(key, built.sdk);
|
|
80164
81733
|
return built;
|
|
80165
81734
|
}
|
|
81735
|
+
/** The write gateway's view of `ensureSdk`, typed to the surface write-ops calls. */
|
|
81736
|
+
async writeSdkFor(key, signer) {
|
|
81737
|
+
const built = await this.ensureSdk(key, signer);
|
|
81738
|
+
return built.ok ? { ok: true, sdk: built.sdk } : built;
|
|
81739
|
+
}
|
|
80166
81740
|
wallet;
|
|
80167
81741
|
// ---- per-call signer resolution (plan 10 A3) ----
|
|
80168
81742
|
/** M10-4 injected transport: the signer layer stays free of lit-ops HTTP — this closure
|
|
@@ -80202,7 +81776,7 @@ var RealUpstreamPlugin = class {
|
|
|
80202
81776
|
chainId: this.config.chainId,
|
|
80203
81777
|
dhSigner: new EoaDHSigner(wallet, this.litOpsBroadcast(session)),
|
|
80204
81778
|
session,
|
|
80205
|
-
getWriteSdk: () => this.
|
|
81779
|
+
getWriteSdk: () => this.writeSdkFor(key, wallet),
|
|
80206
81780
|
readDetails: (id) => this.readPositionDetails(id),
|
|
80207
81781
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
80208
81782
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
@@ -80218,14 +81792,14 @@ var RealUpstreamPlugin = class {
|
|
|
80218
81792
|
if (!pkpValidation) {
|
|
80219
81793
|
throw new Error(`the SDK's ${this.config.network} deployment table has no PKPValidation address \u2014 cannot verify validator version ${version2}.`);
|
|
80220
81794
|
}
|
|
80221
|
-
const registry = new
|
|
81795
|
+
const registry = new import_ethers48.ethers.Contract(pkpValidation, ["function validatorForVersion(uint256) view returns (address)"], this.provider);
|
|
80222
81796
|
let validator;
|
|
80223
81797
|
try {
|
|
80224
81798
|
validator = await registry.validatorForVersion(version2);
|
|
80225
81799
|
} catch (e) {
|
|
80226
81800
|
throw new Error(`could not verify validator version ${version2} on-chain (PKPValidation ${pkpValidation}): ${e.message}`);
|
|
80227
81801
|
}
|
|
80228
|
-
if (validator ===
|
|
81802
|
+
if (validator === import_ethers48.ethers.ZeroAddress) {
|
|
80229
81803
|
throw new Error(
|
|
80230
81804
|
`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
81805
|
);
|
|
@@ -80275,7 +81849,7 @@ var RealUpstreamPlugin = class {
|
|
|
80275
81849
|
failure: {
|
|
80276
81850
|
kind: "signer-missing",
|
|
80277
81851
|
source: "real-ops",
|
|
80278
|
-
message: "no authorization mode is chosen (SIGNER_UNAVAILABLE) \u2014
|
|
81852
|
+
message: "no authorization mode is chosen (SIGNER_UNAVAILABLE) \u2014 EVERY fund-moving tool refuses with this same message until one is, so trying a different write tool will not get past it. Reads are unaffected. Pick a mode via signer_setup ('external' = approve in your own wallet, 'keystore' = automatic signing), or set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD in the server environment."
|
|
80279
81853
|
}
|
|
80280
81854
|
};
|
|
80281
81855
|
}
|
|
@@ -80299,7 +81873,6 @@ var RealUpstreamPlugin = class {
|
|
|
80299
81873
|
gateway = this.keystoreGateway(connected, this.sessionFor(key, connected));
|
|
80300
81874
|
this.opsGatewayCache.set(key, gateway);
|
|
80301
81875
|
}
|
|
80302
|
-
await this.ensureSdk(key, wallet.connect(this.provider));
|
|
80303
81876
|
return { ok: true, gateway };
|
|
80304
81877
|
}
|
|
80305
81878
|
if (mode === "external") {
|
|
@@ -80336,14 +81909,13 @@ var RealUpstreamPlugin = class {
|
|
|
80336
81909
|
chainId: this.config.chainId,
|
|
80337
81910
|
dhSigner: new ExternalEoaDHSigner(deps),
|
|
80338
81911
|
session,
|
|
80339
|
-
getWriteSdk: () => this.
|
|
81912
|
+
getWriteSdk: () => this.writeSdkFor(key, bridgeSigner),
|
|
80340
81913
|
readDetails: (id) => this.readPositionDetails(id),
|
|
80341
81914
|
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
80342
81915
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
80343
81916
|
});
|
|
80344
81917
|
this.opsGatewayCache.set(key, gateway);
|
|
80345
81918
|
}
|
|
80346
|
-
await this.ensureSdk(key, this.externalSigners.get(key));
|
|
80347
81919
|
return { ok: true, gateway };
|
|
80348
81920
|
}
|
|
80349
81921
|
return {
|
|
@@ -80503,7 +82075,7 @@ var RealUpstreamPlugin = class {
|
|
|
80503
82075
|
);
|
|
80504
82076
|
if (!r.ok) return r;
|
|
80505
82077
|
const raw = r.value.data.supportedStablecoins ?? [];
|
|
80506
|
-
const bad = raw.find((x) => !
|
|
82078
|
+
const bad = raw.find((x) => !import_ethers48.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
|
|
80507
82079
|
if (bad) {
|
|
80508
82080
|
return {
|
|
80509
82081
|
ok: false,
|
|
@@ -80586,7 +82158,7 @@ var RealUpstreamPlugin = class {
|
|
|
80586
82158
|
};
|
|
80587
82159
|
}
|
|
80588
82160
|
const symbol = raw.toLowerCase();
|
|
80589
|
-
if (
|
|
82161
|
+
if (import_ethers48.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
|
|
80590
82162
|
const verified = await this.verifiedStablecoins();
|
|
80591
82163
|
if (!verified.ok) return { ok: false, failure: verified.failure };
|
|
80592
82164
|
const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
|
|
@@ -80624,7 +82196,7 @@ var RealUpstreamPlugin = class {
|
|
|
80624
82196
|
* chain, then sign.
|
|
80625
82197
|
*/
|
|
80626
82198
|
async psmCallsFor(stablecoinAddress) {
|
|
80627
|
-
if (!
|
|
82199
|
+
if (!import_ethers48.ethers.isAddress(stablecoinAddress)) {
|
|
80628
82200
|
throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
|
|
80629
82201
|
}
|
|
80630
82202
|
const key = stablecoinAddress.toLowerCase();
|
|
@@ -80644,9 +82216,9 @@ var RealUpstreamPlugin = class {
|
|
|
80644
82216
|
let supported;
|
|
80645
82217
|
let symbol;
|
|
80646
82218
|
try {
|
|
80647
|
-
const psm = new
|
|
82219
|
+
const psm = new import_ethers48.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
|
|
80648
82220
|
supported = await psm["supportedStablecoins"](key);
|
|
80649
|
-
const erc20 = new
|
|
82221
|
+
const erc20 = new import_ethers48.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
|
|
80650
82222
|
symbol = await erc20["symbol"]();
|
|
80651
82223
|
} catch (e) {
|
|
80652
82224
|
return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
|
|
@@ -80859,7 +82431,7 @@ var RealUpstreamPlugin = class {
|
|
|
80859
82431
|
const pm = this.contracts["PositionManager"];
|
|
80860
82432
|
if (!pm) return false;
|
|
80861
82433
|
try {
|
|
80862
|
-
const c = new
|
|
82434
|
+
const c = new import_ethers48.ethers.Contract(pm, PAUSABLE_ABI, this.provider);
|
|
80863
82435
|
return Boolean(await c["paused"]());
|
|
80864
82436
|
} catch {
|
|
80865
82437
|
return false;
|
|
@@ -80868,16 +82440,16 @@ var RealUpstreamPlugin = class {
|
|
|
80868
82440
|
async readPositionDetails(id) {
|
|
80869
82441
|
const core = this.contracts["PositionManagerCoreModule"] ?? this.contracts["PositionManager"];
|
|
80870
82442
|
if (!core) throw new Error(`no PositionManager address for network ${this.config.network}`);
|
|
80871
|
-
const c = new
|
|
82443
|
+
const c = new import_ethers48.ethers.Contract(core, POSITION_DETAILS_ABI, this.provider);
|
|
80872
82444
|
let d;
|
|
80873
82445
|
try {
|
|
80874
|
-
d = await c["getPositionDetails"](
|
|
82446
|
+
d = await c["getPositionDetails"](import_ethers48.ethers.zeroPadValue(id, 32));
|
|
80875
82447
|
} catch (e) {
|
|
80876
82448
|
if (e.code === "CALL_EXCEPTION") return null;
|
|
80877
82449
|
throw e;
|
|
80878
82450
|
}
|
|
80879
82451
|
const borrower = String(d["borrower"]);
|
|
80880
|
-
if (borrower ===
|
|
82452
|
+
if (borrower === import_ethers48.ethers.ZeroAddress) return null;
|
|
80881
82453
|
return {
|
|
80882
82454
|
positionId: String(d["positionId"]),
|
|
80883
82455
|
pkpId: String(d["pkpId"]),
|
|
@@ -82244,16 +83816,18 @@ function resolveWcProjectId(raw, problems) {
|
|
|
82244
83816
|
}
|
|
82245
83817
|
return raw;
|
|
82246
83818
|
}
|
|
83819
|
+
var RPC_PROXY_ORIGIN = "https://api.gvnr.xyz";
|
|
83820
|
+
var rpcProxy = (chainId) => `${RPC_PROXY_ORIGIN}/v1/proxy/rpc/${chainId}`;
|
|
82247
83821
|
var NETWORK_DEFAULTS = {
|
|
82248
83822
|
sepolia: {
|
|
82249
|
-
rpcUrl:
|
|
83823
|
+
rpcUrl: rpcProxy(11155111),
|
|
82250
83824
|
serviceEndpoint: "https://ops-test.gvnr.xyz",
|
|
82251
83825
|
litNetwork: "chipotle",
|
|
82252
83826
|
validatorVersion: 3
|
|
82253
83827
|
// on-chain validator generation, sepolia (2026-07-30)
|
|
82254
83828
|
},
|
|
82255
83829
|
mainnet: {
|
|
82256
|
-
rpcUrl:
|
|
83830
|
+
rpcUrl: rpcProxy(1),
|
|
82257
83831
|
// Cutover 2026-09-08 — see sdk/src/constants/chunks/network-configs.ts for the full
|
|
82258
83832
|
// reasoning. Widening, not a rename: ops.gvnr.xyz serves the same broker and cannot be
|
|
82259
83833
|
// retired while installed copies call it. The sepolia entry above deliberately stays on
|
|
@@ -82371,11 +83945,11 @@ function resolveRealConfig(env) {
|
|
|
82371
83945
|
problems.push(`DH_SIGNER='${signer}' is not supported for the real adapter. Allowed: external | keystore (or unset).`);
|
|
82372
83946
|
}
|
|
82373
83947
|
}
|
|
82374
|
-
const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "
|
|
83948
|
+
const network = env["DH_NETWORK"] === void 0 || env["DH_NETWORK"] === "" ? "mainnet" : env["DH_NETWORK"];
|
|
82375
83949
|
if (NETWORKS[network] === void 0) {
|
|
82376
83950
|
problems.push(`DH_NETWORK='${network}' is not supported. Allowed: ${Object.keys(NETWORKS).join(" | ")}.`);
|
|
82377
83951
|
}
|
|
82378
|
-
const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.
|
|
83952
|
+
const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.mainnet;
|
|
82379
83953
|
const rpcUrl = env["ETH_RPC_URL"] || defaults2.rpcUrl;
|
|
82380
83954
|
const serviceEndpoint = env["DH_SERVICE_ENDPOINT"] || defaults2.serviceEndpoint;
|
|
82381
83955
|
if (!/^https:\/\//.test(serviceEndpoint) && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(serviceEndpoint)) {
|