@gvnrdao/dh-mcp 0.5.14 → 0.5.16
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 +8 -4
- package/dist/boundary.js +520 -99
- package/dist/connector-embed.js +686 -184
- package/dist/connector.js +686 -184
- package/dist/index.js +671 -178
- package/package.json +1 -1
package/dist/connector.js
CHANGED
|
@@ -37,6 +37,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
37
37
|
// src/boundary/upstream/shared/external-bridge/wc-transport.ts
|
|
38
38
|
var wc_transport_exports = {};
|
|
39
39
|
__export(wc_transport_exports, {
|
|
40
|
+
WC_DAPP_METADATA: () => WC_DAPP_METADATA,
|
|
40
41
|
WC_SESSION_METHODS: () => WC_SESSION_METHODS,
|
|
41
42
|
WcTransport: () => WcTransport,
|
|
42
43
|
newIsolatedCore: () => newIsolatedCore,
|
|
@@ -72,7 +73,7 @@ function newIsolatedCore(cfg, label) {
|
|
|
72
73
|
});
|
|
73
74
|
return { core, scratch };
|
|
74
75
|
}
|
|
75
|
-
var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, EVENTS, WcTransport;
|
|
76
|
+
var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
|
|
76
77
|
var init_wc_transport = __esm({
|
|
77
78
|
"src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
|
|
78
79
|
"use strict";
|
|
@@ -82,6 +83,12 @@ var init_wc_transport = __esm({
|
|
|
82
83
|
path = __toESM(require("path"));
|
|
83
84
|
import_node_fs = require("fs");
|
|
84
85
|
WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
|
|
86
|
+
WC_DAPP_METADATA = {
|
|
87
|
+
name: "Diamond Hands MCP",
|
|
88
|
+
description: "Approve Diamond Hands loan operations \u2014 real funds move on your confirmation",
|
|
89
|
+
url: "https://app.diamondhands.credit",
|
|
90
|
+
icons: []
|
|
91
|
+
};
|
|
85
92
|
EVENTS = ["accountsChanged", "chainChanged"];
|
|
86
93
|
WcTransport = class _WcTransport {
|
|
87
94
|
constructor(client, cfg, scratch) {
|
|
@@ -100,12 +107,7 @@ var init_wc_transport = __esm({
|
|
|
100
107
|
const client = await import_sign_client.default.init({
|
|
101
108
|
core,
|
|
102
109
|
projectId: cfg.projectId,
|
|
103
|
-
metadata:
|
|
104
|
-
name: "Diamond Hands MCP",
|
|
105
|
-
description: "Human approval for Diamond Hands operations",
|
|
106
|
-
url: "https://gvnr.xyz",
|
|
107
|
-
icons: []
|
|
108
|
-
}
|
|
110
|
+
metadata: WC_DAPP_METADATA
|
|
109
111
|
});
|
|
110
112
|
return new _WcTransport(client, cfg, scratch);
|
|
111
113
|
}
|
|
@@ -15559,9 +15561,9 @@ ${errorReport}`);
|
|
|
15559
15561
|
var MAX_BTC_AMOUNT = 25e6 * 1e8;
|
|
15560
15562
|
var UTXO_QUERY_MAX_RETRIES = 3;
|
|
15561
15563
|
var UTXO_QUERY_RETRY_DELAY_MS = 500;
|
|
15562
|
-
var
|
|
15564
|
+
var QUANTUM_WINDOW_SECONDS4 = 60;
|
|
15563
15565
|
var DEAD_ZONE_SECONDS2 = 16;
|
|
15564
|
-
var SAFE_EXECUTION_WINDOW_SECONDS =
|
|
15566
|
+
var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS4 - DEAD_ZONE_SECONDS2;
|
|
15565
15567
|
var SECONDS_PER_DAY = 86400;
|
|
15566
15568
|
var DAYS_PER_MONTH = 30;
|
|
15567
15569
|
var LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8e3;
|
|
@@ -41030,7 +41032,7 @@ function htmlPageSecurityHeaders(extra) {
|
|
|
41030
41032
|
}
|
|
41031
41033
|
|
|
41032
41034
|
// src/version.ts
|
|
41033
|
-
var SERVER_VERSION = "0.5.
|
|
41035
|
+
var SERVER_VERSION = "0.5.16";
|
|
41034
41036
|
|
|
41035
41037
|
// src/connector/siwe-oauth.ts
|
|
41036
41038
|
var import_node_crypto2 = require("crypto");
|
|
@@ -41537,6 +41539,21 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
|
|
|
41537
41539
|
var ADAPTERS = ["mock", "real"];
|
|
41538
41540
|
var LATENCIES = ["zero", "realistic"];
|
|
41539
41541
|
var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
41542
|
+
var WC_DISABLED = "off";
|
|
41543
|
+
function wcEnabled(env) {
|
|
41544
|
+
return resolvedWcProjectId(env) !== void 0;
|
|
41545
|
+
}
|
|
41546
|
+
function resolvedWcProjectId(env) {
|
|
41547
|
+
return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
|
|
41548
|
+
}
|
|
41549
|
+
function resolveWcProjectId(raw, problems) {
|
|
41550
|
+
if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
|
|
41551
|
+
if (!/^[0-9a-f]{32}$/.test(raw)) {
|
|
41552
|
+
problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
|
|
41553
|
+
return void 0;
|
|
41554
|
+
}
|
|
41555
|
+
return raw;
|
|
41556
|
+
}
|
|
41540
41557
|
var NETWORK_DEFAULTS = {
|
|
41541
41558
|
sepolia: {
|
|
41542
41559
|
rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
|
|
@@ -41611,10 +41628,7 @@ function resolveBoundaryConfig(env) {
|
|
|
41611
41628
|
}
|
|
41612
41629
|
const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
|
|
41613
41630
|
const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
|
|
41614
|
-
const wcProjectId = env["DH_WC_PROJECT_ID"];
|
|
41615
|
-
if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
|
|
41616
|
-
problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
|
|
41617
|
-
}
|
|
41631
|
+
const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
|
|
41618
41632
|
let bridgeOpenBrowser;
|
|
41619
41633
|
if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
|
|
41620
41634
|
if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
|
|
@@ -41686,10 +41700,7 @@ function resolveRealConfig(env) {
|
|
|
41686
41700
|
const stateDir = env["DH_STATE_DIR"];
|
|
41687
41701
|
const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
|
|
41688
41702
|
const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
|
|
41689
|
-
const wcProjectId = env["DH_WC_PROJECT_ID"];
|
|
41690
|
-
if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
|
|
41691
|
-
problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
|
|
41692
|
-
}
|
|
41703
|
+
const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
|
|
41693
41704
|
let bridgeOpenBrowser;
|
|
41694
41705
|
if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
|
|
41695
41706
|
if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
|
|
@@ -42129,8 +42140,15 @@ var BoundaryCore = class {
|
|
|
42129
42140
|
return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
|
|
42130
42141
|
}
|
|
42131
42142
|
// ---- PSM reads (plan 08 Part B Phase R) ----
|
|
42132
|
-
|
|
42133
|
-
|
|
42143
|
+
/** Which stablecoins this PSM supports. There is deliberately NO default: the caller
|
|
42144
|
+
* names the coin, and this is how they learn what they may name. */
|
|
42145
|
+
async listPsmStablecoins() {
|
|
42146
|
+
const r = await this.deps.plugin.chain.listPsmStablecoins();
|
|
42147
|
+
if (!r.ok) return errEnvelope(failureToError(r.failure));
|
|
42148
|
+
return okEnvelope(r.value, r.source);
|
|
42149
|
+
}
|
|
42150
|
+
async getPsmStatus(p) {
|
|
42151
|
+
const r = await this.deps.plugin.chain.getPsmStatus(p);
|
|
42134
42152
|
if (!r.ok) return errEnvelope(failureToError(r.failure));
|
|
42135
42153
|
return okEnvelope(this.psmStatusData(r.value), r.source);
|
|
42136
42154
|
}
|
|
@@ -42141,7 +42159,7 @@ var BoundaryCore = class {
|
|
|
42141
42159
|
* refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
|
|
42142
42160
|
* whenever `env.ok`. */
|
|
42143
42161
|
async psmQuoteWithStatus(p) {
|
|
42144
|
-
const statusR = await this.deps.plugin.chain.getPsmStatus();
|
|
42162
|
+
const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
|
|
42145
42163
|
if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
|
|
42146
42164
|
const s = statusR.value;
|
|
42147
42165
|
const toUcd = p.direction === "to-ucd";
|
|
@@ -42197,6 +42215,7 @@ var BoundaryCore = class {
|
|
|
42197
42215
|
);
|
|
42198
42216
|
}
|
|
42199
42217
|
const quoteR = await this.deps.plugin.chain.getPsmQuote({
|
|
42218
|
+
stablecoin: p.stablecoin,
|
|
42200
42219
|
direction: toUcd ? "swap" : "redeem",
|
|
42201
42220
|
amountIn: amountIn.toString()
|
|
42202
42221
|
});
|
|
@@ -42263,6 +42282,7 @@ var BoundaryCore = class {
|
|
|
42263
42282
|
let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
|
|
42264
42283
|
if (floor === 0n) floor = 1n;
|
|
42265
42284
|
const r = await this.deps.plugin.ops.psmSwap({
|
|
42285
|
+
stablecoin: p.stablecoin,
|
|
42266
42286
|
direction: q.contractCall,
|
|
42267
42287
|
amountIn: q.amountIn,
|
|
42268
42288
|
minOut: floor.toString(),
|
|
@@ -42362,7 +42382,7 @@ var BoundaryCore = class {
|
|
|
42362
42382
|
feeToken: "UCD",
|
|
42363
42383
|
perBlockCap: s.maxSwapVolumePerBlock
|
|
42364
42384
|
}),
|
|
42365
|
-
|
|
42385
|
+
fromUcd: direction({
|
|
42366
42386
|
minAmount: s.minRedeemAmount,
|
|
42367
42387
|
maxAmount: s.maxRedeemAmount,
|
|
42368
42388
|
amountUnit: ucdUnit,
|
|
@@ -44187,7 +44207,7 @@ var SINK_CONTRACTS = {
|
|
|
44187
44207
|
PositionManager: sinkAddress("PositionManager"),
|
|
44188
44208
|
UCDToken: sinkAddress("UCDToken"),
|
|
44189
44209
|
// PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
|
|
44190
|
-
// to-ucd approves UsdcToken → SimplePSMV2;
|
|
44210
|
+
// to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
|
|
44191
44211
|
SimplePSMV2: sinkAddress("SimplePSMV2"),
|
|
44192
44212
|
UsdcToken: sinkAddress("UsdcToken"),
|
|
44193
44213
|
UCDController: sinkAddress("UCDController")
|
|
@@ -44492,7 +44512,18 @@ var MockUpstreamPlugin = class {
|
|
|
44492
44512
|
getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
|
|
44493
44513
|
// PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
|
|
44494
44514
|
// mock's addresses are honest labels — the mock never fabricates chain-looking values.
|
|
44495
|
-
|
|
44515
|
+
// The practice world models ONE stablecoin, and says so rather than implying a
|
|
44516
|
+
// choice it cannot honour: the caller must still NAME a coin (no default anywhere),
|
|
44517
|
+
// and naming anything but this one is refused the same way the real adapter refuses
|
|
44518
|
+
// an unsupported address — a mock that accepted any name would teach a habit the
|
|
44519
|
+
// real protocol punishes.
|
|
44520
|
+
listPsmStablecoins: () => this.read(
|
|
44521
|
+
"mock-chain",
|
|
44522
|
+
() => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
|
|
44523
|
+
),
|
|
44524
|
+
getPsmStatus: (p) => this.read("mock-chain", () => {
|
|
44525
|
+
const known = this.mockStablecoinRefusal(p.stablecoin);
|
|
44526
|
+
if (known) return known;
|
|
44496
44527
|
const psm = this.world.psmSeed();
|
|
44497
44528
|
return upOk(
|
|
44498
44529
|
{
|
|
@@ -44517,6 +44548,8 @@ var MockUpstreamPlugin = class {
|
|
|
44517
44548
|
);
|
|
44518
44549
|
}),
|
|
44519
44550
|
getPsmQuote: (p) => this.read("mock-chain", () => {
|
|
44551
|
+
const known = this.mockStablecoinRefusal(p.stablecoin);
|
|
44552
|
+
if (known) return known;
|
|
44520
44553
|
const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
|
|
44521
44554
|
return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
|
|
44522
44555
|
})
|
|
@@ -44641,6 +44674,19 @@ var MockUpstreamPlugin = class {
|
|
|
44641
44674
|
return apply();
|
|
44642
44675
|
}
|
|
44643
44676
|
/** Mode `none`: every write answers with the conversational setup invitation. */
|
|
44677
|
+
/** The practice world supports exactly one PSM stablecoin. A name that is not it is
|
|
44678
|
+
* refused with the same shape the real adapter uses for an address the chain does not
|
|
44679
|
+
* list — so practising the choose-a-coin habit here fails the same way it would there,
|
|
44680
|
+
* instead of silently succeeding and teaching that any name works. */
|
|
44681
|
+
mockStablecoinRefusal(stablecoin) {
|
|
44682
|
+
const chosen = stablecoin.trim().toLowerCase();
|
|
44683
|
+
if (chosen === "mock-usdc" || chosen === "usdc") return null;
|
|
44684
|
+
return upFail({
|
|
44685
|
+
kind: "rejected",
|
|
44686
|
+
source: "mock-chain",
|
|
44687
|
+
message: `'${stablecoin}' is not a PSM-supported stablecoin in this practice world \u2014 it supports 'USDC' only. Read protocol://psm for the coins a deployment actually supports; there is no default coin on any tier.`
|
|
44688
|
+
});
|
|
44689
|
+
}
|
|
44644
44690
|
noneRefusal() {
|
|
44645
44691
|
if (this.signer && this.signer.manager.mode() === "none") {
|
|
44646
44692
|
return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
|
|
@@ -79524,6 +79570,13 @@ function listPositionsQuery(f) {
|
|
|
79524
79570
|
}
|
|
79525
79571
|
return { document: LIST_POSITIONS, variables: { first, skip } };
|
|
79526
79572
|
}
|
|
79573
|
+
var SUPPORTED_STABLECOINS = `
|
|
79574
|
+
query GetSupportedStablecoins {
|
|
79575
|
+
supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
|
|
79576
|
+
id address isSupported exchangeRate entryFee exitFee reserves decimals
|
|
79577
|
+
totalSwapVolume totalRedeemVolume swapCount redeemCount addedAt lastUpdated
|
|
79578
|
+
}
|
|
79579
|
+
}`;
|
|
79527
79580
|
|
|
79528
79581
|
// src/boundary/upstream/real/psm-calls.ts
|
|
79529
79582
|
var import_ethers32 = require("ethers");
|
|
@@ -79663,6 +79716,11 @@ var PsmCalls = class {
|
|
|
79663
79716
|
return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
|
|
79664
79717
|
});
|
|
79665
79718
|
}
|
|
79719
|
+
/** The token's own symbol, read at construction. The caller names the coin by this word,
|
|
79720
|
+
* so it must come from the token rather than from a per-network assumption. */
|
|
79721
|
+
symbol() {
|
|
79722
|
+
return this.deps.stablecoinSymbol;
|
|
79723
|
+
}
|
|
79666
79724
|
async status() {
|
|
79667
79725
|
return this.call(async () => {
|
|
79668
79726
|
const s = this.deps.stablecoinAddress;
|
|
@@ -80122,13 +80180,6 @@ function buildValidationContext(network, chainId) {
|
|
|
80122
80180
|
}
|
|
80123
80181
|
|
|
80124
80182
|
// src/boundary/upstream/real/write-ops.ts
|
|
80125
|
-
function psmMainnetWriteRefusal(network, chainId) {
|
|
80126
|
-
return {
|
|
80127
|
-
kind: "rejected",
|
|
80128
|
-
source: SOURCE5,
|
|
80129
|
-
message: `psmSwap is refused (MAINNET_WRITES_DISABLED): PSM writes are enabled on sepolia ONLY, and this process is configured for network '${network}' (chainId ${chainId}) \u2014 the PSM-specific sepolia-only anchor; mainnet PSM operations await their dedicated security review. No ceremony was started and no signer was touched. PSM reads (psm_quote, protocol://psm) remain available. Loan operations are NOT affected by this gate.`
|
|
80130
|
-
};
|
|
80131
|
-
}
|
|
80132
80183
|
var SOURCE5 = "real-ops";
|
|
80133
80184
|
var OP_LAYOUT = "dh-op-envelope-v1";
|
|
80134
80185
|
function randomNonceHex() {
|
|
@@ -80476,8 +80527,7 @@ function buildWriteOps(deps) {
|
|
|
80476
80527
|
* keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
|
|
80477
80528
|
* write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
|
|
80478
80529
|
psmSwap: async (p) => {
|
|
80479
|
-
|
|
80480
|
-
const pr = deps.psm();
|
|
80530
|
+
const pr = await deps.psm(p.stablecoin);
|
|
80481
80531
|
if (!pr.ok) return upFail(pr.failure);
|
|
80482
80532
|
const calls = pr.calls;
|
|
80483
80533
|
const addr = calls.addresses();
|
|
@@ -80495,7 +80545,7 @@ function buildWriteOps(deps) {
|
|
|
80495
80545
|
const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
|
|
80496
80546
|
const spenderAddress = isSwap ? addr.psm : addr.ucdController;
|
|
80497
80547
|
const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
|
|
80498
|
-
const tokenSymbol = isSwap ?
|
|
80548
|
+
const tokenSymbol = isSwap ? calls.symbol() : "UCD";
|
|
80499
80549
|
const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
|
|
80500
80550
|
if (!quoteR.ok) return upFail(quoteR.failure);
|
|
80501
80551
|
const broadcast = async (leg, action, tx2) => {
|
|
@@ -80535,7 +80585,7 @@ function buildWriteOps(deps) {
|
|
|
80535
80585
|
} catch (e) {
|
|
80536
80586
|
return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
|
|
80537
80587
|
}
|
|
80538
|
-
const execCard = `${p.direction} ${p.amountIn} ${isSwap ?
|
|
80588
|
+
const execCard = `${p.direction} ${p.amountIn} ${isSwap ? `${tokenSymbol} smallest units` : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
|
|
80539
80589
|
const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
|
|
80540
80590
|
if (!execHashR.ok) {
|
|
80541
80591
|
const f = execHashR.failure;
|
|
@@ -80858,6 +80908,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80858
80908
|
);
|
|
80859
80909
|
}
|
|
80860
80910
|
const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
|
|
80911
|
+
const nowMs = (this.deps.clock ?? Date.now)();
|
|
80912
|
+
const expiresAtSec = nextQuantumTimestamp(nowMs);
|
|
80913
|
+
const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
|
|
80861
80914
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80862
80915
|
id: (0, import_node_crypto7.randomUUID)(),
|
|
80863
80916
|
kind: "personal-sign",
|
|
@@ -80869,15 +80922,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80869
80922
|
"(identical to how diamondhands.credit signs withdrawals).",
|
|
80870
80923
|
"Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
|
|
80871
80924
|
"",
|
|
80872
|
-
"SIGN NOW \u2014 this one is on a clock
|
|
80873
|
-
`
|
|
80874
|
-
"
|
|
80875
|
-
"
|
|
80876
|
-
"
|
|
80877
|
-
"start again rather than signing something you have not finished reading."
|
|
80925
|
+
"SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
|
|
80926
|
+
` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
|
|
80927
|
+
"The approval page allows far longer than this; the PAYLOAD does not. If it expires",
|
|
80928
|
+
"the signature is refused, the withdrawal does not complete, and the reserved coins",
|
|
80929
|
+
"stay reserved until that is cleared. If the number above is already small, decline",
|
|
80930
|
+
"and start again rather than signing something you have not finished reading."
|
|
80878
80931
|
],
|
|
80879
80932
|
expectedSigner: this.deps.borrower,
|
|
80880
80933
|
chainId: this.deps.chainId,
|
|
80934
|
+
expiresAtSec,
|
|
80881
80935
|
personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
|
|
80882
80936
|
});
|
|
80883
80937
|
if (outcome.status !== "approved" || !outcome.signature) {
|
|
@@ -81081,13 +81135,18 @@ var RealUpstreamPlugin = class {
|
|
|
81081
81135
|
getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
|
|
81082
81136
|
// PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
|
|
81083
81137
|
// wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
|
|
81084
|
-
|
|
81085
|
-
const
|
|
81086
|
-
|
|
81087
|
-
|
|
81088
|
-
|
|
81089
|
-
|
|
81090
|
-
|
|
81138
|
+
listPsmStablecoins: async () => {
|
|
81139
|
+
const verified = await this.verifiedStablecoins();
|
|
81140
|
+
if (!verified.ok) return upFail(verified.failure);
|
|
81141
|
+
return upOk(verified.rows, this.src("subgraph"));
|
|
81142
|
+
},
|
|
81143
|
+
getPsmStatus: async (p) => {
|
|
81144
|
+
const r = await this.psmCallsForChoice(p.stablecoin);
|
|
81145
|
+
return r.ok ? r.calls.status() : upFail(r.failure);
|
|
81146
|
+
},
|
|
81147
|
+
getPsmQuote: async (p) => {
|
|
81148
|
+
const r = await this.psmCallsForChoice(p.stablecoin);
|
|
81149
|
+
if (!r.ok) return upFail(r.failure);
|
|
81091
81150
|
return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
|
|
81092
81151
|
}
|
|
81093
81152
|
};
|
|
@@ -81155,12 +81214,13 @@ var RealUpstreamPlugin = class {
|
|
|
81155
81214
|
allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
|
|
81156
81215
|
delegationSetup: () => readOnly("delegationSetup"),
|
|
81157
81216
|
delegationGrant: () => readOnly("delegationGrant"),
|
|
81158
|
-
//
|
|
81159
|
-
//
|
|
81160
|
-
//
|
|
81161
|
-
//
|
|
81217
|
+
// The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
|
|
81218
|
+
// removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
|
|
81219
|
+
// signerless boot the honest refusal was always the missing signer; the network
|
|
81220
|
+
// gate sat in front of it and answered first. Now there is one reason left, and it
|
|
81221
|
+
// is the true one on this path.
|
|
81162
81222
|
psmSwap: () => Promise.resolve(
|
|
81163
|
-
|
|
81223
|
+
upFail({
|
|
81164
81224
|
kind: "signer-missing",
|
|
81165
81225
|
source: "real-ops",
|
|
81166
81226
|
message: "no signer configured \u2014 psmSwap signs two on-chain transactions (exact-amount approve, then swap/redeem) with the keystore signer. Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
|
|
@@ -81277,7 +81337,7 @@ var RealUpstreamPlugin = class {
|
|
|
81277
81337
|
session,
|
|
81278
81338
|
getWriteSdk: () => this.sdkCache.get(key) ?? null,
|
|
81279
81339
|
readDetails: (id) => this.readPositionDetails(id),
|
|
81280
|
-
psm: () => this.
|
|
81340
|
+
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
81281
81341
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
81282
81342
|
});
|
|
81283
81343
|
}
|
|
@@ -81411,7 +81471,7 @@ var RealUpstreamPlugin = class {
|
|
|
81411
81471
|
session,
|
|
81412
81472
|
getWriteSdk: () => this.sdkCache.get(key) ?? null,
|
|
81413
81473
|
readDetails: (id) => this.readPositionDetails(id),
|
|
81414
|
-
psm: () => this.
|
|
81474
|
+
psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
|
|
81415
81475
|
assertValidatorConfigured: () => this.assertValidatorConfigured()
|
|
81416
81476
|
});
|
|
81417
81477
|
this.opsGatewayCache.set(key, gateway);
|
|
@@ -81557,35 +81617,200 @@ var RealUpstreamPlugin = class {
|
|
|
81557
81617
|
* (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
|
|
81558
81618
|
* SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
|
|
81559
81619
|
* guess the Circle USDC address (reads-verify only, and only once the table names it). */
|
|
81560
|
-
|
|
81561
|
-
|
|
81562
|
-
|
|
81620
|
+
/** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
|
|
81621
|
+
* fees and reserves, so a single cached wrapper would answer for the wrong coin. */
|
|
81622
|
+
psmWrappers = /* @__PURE__ */ new Map();
|
|
81623
|
+
/**
|
|
81624
|
+
* The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
|
|
81625
|
+
*
|
|
81626
|
+
* This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
|
|
81627
|
+
* mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
|
|
81628
|
+
* refused before it ever reached the write gate. Which coins the PSM supports is on-chain
|
|
81629
|
+
* STATE that governance changes, not a constant a package can ship: the SDK's own
|
|
81630
|
+
* `getPSMStablecoins` reads the index for the same reason.
|
|
81631
|
+
*/
|
|
81632
|
+
async listSupportedStablecoins() {
|
|
81633
|
+
const r = await this.graphProxy(
|
|
81634
|
+
SUPPORTED_STABLECOINS,
|
|
81635
|
+
{}
|
|
81636
|
+
);
|
|
81637
|
+
if (!r.ok) return r;
|
|
81638
|
+
const raw = r.value.data.supportedStablecoins ?? [];
|
|
81639
|
+
const bad = raw.find((x) => !import_ethers39.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
|
|
81640
|
+
if (bad) {
|
|
81641
|
+
return {
|
|
81642
|
+
ok: false,
|
|
81643
|
+
failure: {
|
|
81644
|
+
kind: "malformed",
|
|
81645
|
+
source: "subgraph",
|
|
81646
|
+
message: `the indexer returned a PSM stablecoin row this build cannot read (address '${String(bad.address)}', decimals '${String(bad.decimals)}')`
|
|
81647
|
+
}
|
|
81648
|
+
};
|
|
81649
|
+
}
|
|
81650
|
+
const rows = raw.map((x) => ({
|
|
81651
|
+
address: String(x.address).toLowerCase(),
|
|
81652
|
+
decimals: Number(x.decimals)
|
|
81653
|
+
}));
|
|
81654
|
+
if (rows.length === 0) {
|
|
81655
|
+
return {
|
|
81656
|
+
ok: false,
|
|
81657
|
+
failure: {
|
|
81658
|
+
kind: "unavailable",
|
|
81659
|
+
source: "subgraph",
|
|
81660
|
+
message: `the indexer lists NO supported stablecoins for the PSM on ${this.config.network}. Either the subgraph has not indexed the StablecoinAdded events yet (check its start block against the block the coins were added at), or governance has removed every coin. PSM exchange is unavailable here until one of those is resolved \u2014 this is NOT "the PSM supports nothing".`
|
|
81661
|
+
}
|
|
81662
|
+
};
|
|
81663
|
+
}
|
|
81664
|
+
return { ok: true, rows };
|
|
81665
|
+
}
|
|
81666
|
+
/**
|
|
81667
|
+
* The supported set, verified — index rows each re-checked on-chain, carrying the symbol
|
|
81668
|
+
* read from the token itself. This is what `protocol://psm` lists and what a caller's
|
|
81669
|
+
* SYMBOL is resolved against.
|
|
81670
|
+
*
|
|
81671
|
+
* Rows are dropped ONLY for the one reason a drop is honest: the index still lists a coin
|
|
81672
|
+
* the chain no longer supports (index lag behind a governance removal). Any OTHER failure
|
|
81673
|
+
* — an RPC outage mid-loop — propagates, because a list that silently shrinks when the
|
|
81674
|
+
* chain is unreachable is the same silent-failure shape as the empty list above. If
|
|
81675
|
+
* nothing survives verification, that is a refusal too, and it says which side disagreed.
|
|
81676
|
+
*/
|
|
81677
|
+
async verifiedStablecoins() {
|
|
81678
|
+
const listed = await this.listSupportedStablecoins();
|
|
81679
|
+
if (!listed.ok) return listed;
|
|
81680
|
+
const checked = await Promise.all(
|
|
81681
|
+
listed.rows.map(async (row) => ({ row, built: await this.psmCallsFor(row.address) }))
|
|
81682
|
+
);
|
|
81683
|
+
const transport = checked.find((c) => !c.built.ok && c.built.failure.kind !== "rejected");
|
|
81684
|
+
if (transport && !transport.built.ok) return { ok: false, failure: transport.built.failure };
|
|
81685
|
+
const rows = checked.flatMap(
|
|
81686
|
+
({ row, built }) => built.ok ? [{ address: row.address, symbol: built.calls.symbol(), decimals: row.decimals }] : []
|
|
81687
|
+
);
|
|
81688
|
+
if (rows.length === 0) {
|
|
81689
|
+
return {
|
|
81690
|
+
ok: false,
|
|
81691
|
+
failure: {
|
|
81692
|
+
kind: "unavailable",
|
|
81693
|
+
source: "chain-rpc",
|
|
81694
|
+
message: `the indexer lists ${listed.rows.length} PSM stablecoin(s) on ${this.config.network}, and the PSM contract confirms none of them. The index is behind a governance removal, or it is indexing a different PSM than the one in this build's deployment table \u2014 verify before exchanging anything.`
|
|
81695
|
+
}
|
|
81696
|
+
};
|
|
81697
|
+
}
|
|
81698
|
+
return { ok: true, rows };
|
|
81699
|
+
}
|
|
81700
|
+
/**
|
|
81701
|
+
* Resolve what the CALLER named — a symbol or a 0x address — to a verified address.
|
|
81702
|
+
*
|
|
81703
|
+
* The tool schemas have always said "by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address",
|
|
81704
|
+
* and the mock world accepts exactly that. The real adapter accepted only the address:
|
|
81705
|
+
* a symbol went straight into an address-typed `ethers.Contract`, which threw, and the
|
|
81706
|
+
* throw was caught as `kind: "unavailable"` → `UPSTREAM_UNAVAILABLE` — a code the guide
|
|
81707
|
+
* tells the model is "usually transient; retry once". So the documented input produced a
|
|
81708
|
+
* retry loop on the one deployment that moves real money, and a developer practising
|
|
81709
|
+
* against the mock never met it. Both halves are fixed here: the symbol resolves, and a
|
|
81710
|
+
* name that cannot resolve is `rejected` (the caller's input) rather than `unavailable`
|
|
81711
|
+
* (our upstream).
|
|
81712
|
+
*/
|
|
81713
|
+
async psmCallsForChoice(chosen) {
|
|
81714
|
+
const raw = chosen.trim();
|
|
81715
|
+
if (raw.length === 0) {
|
|
81716
|
+
return {
|
|
81717
|
+
ok: false,
|
|
81718
|
+
failure: { kind: "rejected", source: "chain-rpc", message: "no stablecoin named \u2014 name one by symbol (e.g. 'USDC') or by 0x address; there is no default coin." }
|
|
81719
|
+
};
|
|
81720
|
+
}
|
|
81721
|
+
const symbol = raw.toLowerCase();
|
|
81722
|
+
if (import_ethers39.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
|
|
81723
|
+
const verified = await this.verifiedStablecoins();
|
|
81724
|
+
if (!verified.ok) return { ok: false, failure: verified.failure };
|
|
81725
|
+
const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
|
|
81726
|
+
if (hits.length > 1) {
|
|
81727
|
+
return {
|
|
81728
|
+
ok: false,
|
|
81729
|
+
failure: {
|
|
81730
|
+
kind: "rejected",
|
|
81731
|
+
source: "chain-rpc",
|
|
81732
|
+
message: `'${raw}' names ${hits.length} different coins this PSM supports \u2014 ${hits.map((r) => r.address).join(", ")}. Symbols are self-declared and not unique, so this one cannot be resolved for you: name the 0x address of the one you mean.`
|
|
81733
|
+
}
|
|
81734
|
+
};
|
|
81735
|
+
}
|
|
81736
|
+
const hit = hits[0];
|
|
81737
|
+
if (!hit) {
|
|
81738
|
+
const names = verified.rows.map((r) => `${r.symbol} (${r.address})`).join(", ");
|
|
81739
|
+
return {
|
|
81740
|
+
ok: false,
|
|
81741
|
+
failure: {
|
|
81742
|
+
kind: "rejected",
|
|
81743
|
+
source: "chain-rpc",
|
|
81744
|
+
message: `'${raw}' is not a coin this PSM supports on ${this.config.network} \u2014 it supports ${names}. Name one of those by symbol or address. \`protocol://psm\` carries each one's fees, limits and reserves.`
|
|
81745
|
+
}
|
|
81746
|
+
};
|
|
81747
|
+
}
|
|
81748
|
+
return this.psmCallsFor(hit.address);
|
|
81749
|
+
}
|
|
81750
|
+
/**
|
|
81751
|
+
* Build the PSM wrapper for ONE caller-chosen stablecoin.
|
|
81752
|
+
*
|
|
81753
|
+
* The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
|
|
81754
|
+
* indexer is how the list is discovered and is not authority over it: it can lag a
|
|
81755
|
+
* governance removal, and acting on a stale list would build a swap the contract reverts
|
|
81756
|
+
* — after the user has approved it in their wallet. List from the index, verify on the
|
|
81757
|
+
* chain, then sign.
|
|
81758
|
+
*/
|
|
81759
|
+
async psmCallsFor(stablecoinAddress) {
|
|
81760
|
+
if (!import_ethers39.ethers.isAddress(stablecoinAddress)) {
|
|
81761
|
+
throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
|
|
81762
|
+
}
|
|
81763
|
+
const key = stablecoinAddress.toLowerCase();
|
|
81764
|
+
const cached = this.psmWrappers.get(key);
|
|
81765
|
+
if (cached) return { ok: true, calls: cached };
|
|
81563
81766
|
const psmAddress = this.contracts["SimplePSMV2"];
|
|
81564
|
-
|
|
81565
|
-
if (!psmAddress || !stablecoinAddress) {
|
|
81566
|
-
const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
|
|
81767
|
+
if (!psmAddress) {
|
|
81567
81768
|
return {
|
|
81568
81769
|
ok: false,
|
|
81569
81770
|
failure: {
|
|
81570
81771
|
kind: "unavailable",
|
|
81571
81772
|
source: "chain-rpc",
|
|
81572
|
-
message: `the bundled deployment table has no address
|
|
81773
|
+
message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
|
|
81573
81774
|
}
|
|
81574
81775
|
};
|
|
81575
81776
|
}
|
|
81777
|
+
let supported;
|
|
81778
|
+
let symbol;
|
|
81779
|
+
try {
|
|
81780
|
+
const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
|
|
81781
|
+
supported = await psm["supportedStablecoins"](key);
|
|
81782
|
+
const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
|
|
81783
|
+
symbol = await erc20["symbol"]();
|
|
81784
|
+
} catch (e) {
|
|
81785
|
+
return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
|
|
81786
|
+
}
|
|
81787
|
+
if (!supported) {
|
|
81788
|
+
return {
|
|
81789
|
+
ok: false,
|
|
81790
|
+
failure: {
|
|
81791
|
+
kind: "rejected",
|
|
81792
|
+
source: "chain-rpc",
|
|
81793
|
+
message: `${key} is not a PSM-supported stablecoin on ${this.config.network} (checked on-chain against SimplePSMV2.supportedStablecoins). Read protocol://psm for the coins this deployment actually supports.`
|
|
81794
|
+
}
|
|
81795
|
+
};
|
|
81796
|
+
}
|
|
81797
|
+
const stablecoinAddress2 = key;
|
|
81576
81798
|
const ucdTokenAddress = this.contracts["UCDToken"];
|
|
81577
81799
|
const ucdControllerAddress = this.contracts["UCDController"];
|
|
81578
|
-
|
|
81800
|
+
const built = new PsmCalls({
|
|
81579
81801
|
provider: this.provider,
|
|
81580
81802
|
psmAddress,
|
|
81581
|
-
stablecoinAddress,
|
|
81582
|
-
|
|
81803
|
+
stablecoinAddress: stablecoinAddress2,
|
|
81804
|
+
// Read from the token, never assumed. The old value was the literal "USDC", which
|
|
81805
|
+
// stops being true the moment a second coin is supported.
|
|
81806
|
+
stablecoinSymbol: symbol,
|
|
81583
81807
|
// Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
|
|
81584
81808
|
// (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
|
|
81585
81809
|
...ucdTokenAddress ? { ucdTokenAddress } : {},
|
|
81586
81810
|
...ucdControllerAddress ? { ucdControllerAddress } : {}
|
|
81587
81811
|
});
|
|
81588
|
-
|
|
81812
|
+
this.psmWrappers.set(key, built);
|
|
81813
|
+
return { ok: true, calls: built };
|
|
81589
81814
|
}
|
|
81590
81815
|
src(id) {
|
|
81591
81816
|
const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
|
|
@@ -81848,6 +82073,7 @@ function renderApprovalPage(sessionId, nonce) {
|
|
|
81848
82073
|
<div id="request" class="hidden">
|
|
81849
82074
|
<div id="action" class="action"></div>
|
|
81850
82075
|
<div id="card" class="card"></div>
|
|
82076
|
+
<div id="deadline" class="status hidden"></div>
|
|
81851
82077
|
<button id="approve">Approve in wallet</button>
|
|
81852
82078
|
<button id="reject">Reject</button>
|
|
81853
82079
|
</div>
|
|
@@ -81880,10 +82106,19 @@ const statusEl = document.getElementById("status");
|
|
|
81880
82106
|
const requestEl = document.getElementById("request");
|
|
81881
82107
|
const actionEl = document.getElementById("action");
|
|
81882
82108
|
const cardEl = document.getElementById("card");
|
|
82109
|
+
const approveEl = document.getElementById("approve");
|
|
82110
|
+
const rejectEl = document.getElementById("reject");
|
|
82111
|
+
const deadlineEl = document.getElementById("deadline");
|
|
82112
|
+
let deadlineTimer = null;
|
|
81883
82113
|
const walletEl = document.getElementById("wallet");
|
|
81884
82114
|
let account = null;
|
|
81885
82115
|
let chainId = null;
|
|
81886
82116
|
let current = null;
|
|
82117
|
+
// EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
|
|
82118
|
+
// nothing, so a k-of-n collection and a WalletConnect request can be live at once and
|
|
82119
|
+
// "events" replays both on attach; with a single slot the loser was gone for good, and a
|
|
82120
|
+
// card the page never renders is one the human can neither read nor reject.
|
|
82121
|
+
const pending = new Map();
|
|
81887
82122
|
|
|
81888
82123
|
function post(path, body) {
|
|
81889
82124
|
return fetch(path, {
|
|
@@ -81946,43 +82181,135 @@ async function onAccountsChanged(accounts) {
|
|
|
81946
82181
|
account = (accounts && accounts[0]) || null;
|
|
81947
82182
|
await post(BASE + "wallet-event", { account: account, chainId: chainId });
|
|
81948
82183
|
showWallet();
|
|
81949
|
-
|
|
82184
|
+
invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
|
|
81950
82185
|
}
|
|
81951
82186
|
|
|
81952
82187
|
async function onChainChanged(cid) {
|
|
81953
82188
|
chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
|
|
81954
82189
|
await post(BASE + "wallet-event", { account: account, chainId: chainId });
|
|
81955
82190
|
showWallet();
|
|
81956
|
-
|
|
82191
|
+
invalidatePageRequests("Network changed \u2014 pending request invalidated.");
|
|
81957
82192
|
}
|
|
81958
82193
|
|
|
81959
82194
|
function listen() {
|
|
81960
82195
|
const es = new EventSource(BASE + "events?s=" + SESSION);
|
|
81961
|
-
es.onmessage = (ev) => {
|
|
82196
|
+
es.onmessage = (ev) => {
|
|
82197
|
+
const next = JSON.parse(ev.data);
|
|
82198
|
+
// A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
|
|
82199
|
+
// payload in place and re-pushes it, so the older frame carries a dead hash.
|
|
82200
|
+
pending.set(next.id, next);
|
|
82201
|
+
showPending();
|
|
82202
|
+
};
|
|
81962
82203
|
es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
|
|
81963
82204
|
}
|
|
81964
82205
|
|
|
82206
|
+
// A read-only mirror must never displace a card this page can actually decide \u2014 but it
|
|
82207
|
+
// must not be thrown away either, so it waits its turn instead. Among equals the card
|
|
82208
|
+
// already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
|
|
82209
|
+
// gets approved.
|
|
82210
|
+
function pickPending() {
|
|
82211
|
+
const held = current ? pending.get(current.id) : undefined;
|
|
82212
|
+
if (held && held.mirror !== true) return held;
|
|
82213
|
+
let best = held || null;
|
|
82214
|
+
pending.forEach((frame) => {
|
|
82215
|
+
if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
|
|
82216
|
+
});
|
|
82217
|
+
return best;
|
|
82218
|
+
}
|
|
82219
|
+
|
|
82220
|
+
// "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
|
|
82221
|
+
function showPending(emptyText) {
|
|
82222
|
+
const next = pickPending();
|
|
82223
|
+
if (!next) {
|
|
82224
|
+
// The queue drained, so no card owns the clock \u2014 leaving it running would tick down
|
|
82225
|
+
// an expiry for a ceremony that is already decided.
|
|
82226
|
+
stopDeadline();
|
|
82227
|
+
current = null;
|
|
82228
|
+
requestEl.classList.add("hidden");
|
|
82229
|
+
if (emptyText) showStatus(emptyText);
|
|
82230
|
+
return;
|
|
82231
|
+
}
|
|
82232
|
+
current = next;
|
|
82233
|
+
renderRequest();
|
|
82234
|
+
}
|
|
82235
|
+
|
|
81965
82236
|
function renderRequest() {
|
|
81966
82237
|
actionEl.textContent = current.action;
|
|
81967
82238
|
cardEl.textContent = current.card.join("\\n");
|
|
82239
|
+
// Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
|
|
82240
|
+
// still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
|
|
82241
|
+
// server-side, which is the actual boundary.
|
|
82242
|
+
const mirrored = current.mirror === true;
|
|
82243
|
+
approveEl.classList.toggle("hidden", mirrored);
|
|
82244
|
+
rejectEl.classList.remove("hidden");
|
|
81968
82245
|
requestEl.classList.remove("hidden");
|
|
81969
|
-
showStatus(
|
|
82246
|
+
showStatus(mirrored
|
|
82247
|
+
? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
|
|
82248
|
+
: "Review the operation below. Nothing signs without your approval.");
|
|
82249
|
+
// The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
|
|
82250
|
+
// card promoted after another settles gets its own clock, not the previous one's.
|
|
82251
|
+
startDeadline();
|
|
81970
82252
|
}
|
|
81971
82253
|
|
|
82254
|
+
// C-46: the card's deadline is computed when the card is RAISED, so by the time a human
|
|
82255
|
+
// has read it the number is already wrong. On the BTC-withdraw execute leg the whole
|
|
82256
|
+
// window is under a minute, which makes a stale figure worse than none \u2014 it implies time
|
|
82257
|
+
// the payload does not have. Counting down from the server-supplied instant keeps the page
|
|
82258
|
+
// honest without it needing to know anything about quantum windows.
|
|
82259
|
+
function stopDeadline() {
|
|
82260
|
+
if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
|
|
82261
|
+
deadlineEl.classList.add("hidden");
|
|
82262
|
+
}
|
|
82263
|
+
|
|
82264
|
+
function startDeadline() {
|
|
82265
|
+
stopDeadline();
|
|
82266
|
+
if (!current || typeof current.expiresAtSec !== "number") return;
|
|
82267
|
+
const tick = () => {
|
|
82268
|
+
const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
|
|
82269
|
+
if (left > 0) {
|
|
82270
|
+
deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
|
|
82271
|
+
" \u2014 after that the signature is refused and the withdrawal does not complete.";
|
|
82272
|
+
} else {
|
|
82273
|
+
// Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
|
|
82274
|
+
// the protocol, and the honest thing is to tell them before the wallet opens, not
|
|
82275
|
+
// after. The button is deliberately left enabled \u2014 declining is still the right
|
|
82276
|
+
// action and the page must not trap them.
|
|
82277
|
+
deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
|
|
82278
|
+
if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
|
|
82279
|
+
}
|
|
82280
|
+
deadlineEl.classList.remove("hidden");
|
|
82281
|
+
};
|
|
82282
|
+
tick();
|
|
82283
|
+
deadlineTimer = setInterval(tick, 1000);
|
|
82284
|
+
}
|
|
82285
|
+
|
|
82286
|
+
// Only the ceremony this page just decided leaves the queue. The bridge never announces a
|
|
82287
|
+
// settlement, so anything else it pushed is still live as far as the page can know \u2014 and
|
|
82288
|
+
// blanking the panel over it stranded a phone ceremony with no card and no Reject.
|
|
81972
82289
|
function clearRequest(text) {
|
|
81973
|
-
current
|
|
81974
|
-
|
|
81975
|
-
|
|
82290
|
+
if (current) pending.delete(current.id);
|
|
82291
|
+
showPending(text);
|
|
82292
|
+
}
|
|
82293
|
+
|
|
82294
|
+
// A wallet or network change settles every ceremony THIS page could decide, and the bridge
|
|
82295
|
+
// deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
|
|
82296
|
+
// stays readable and rejectable.
|
|
82297
|
+
function invalidatePageRequests(text) {
|
|
82298
|
+
pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
|
|
82299
|
+
showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
|
|
81976
82300
|
}
|
|
81977
82301
|
|
|
81978
|
-
|
|
82302
|
+
rejectEl.onclick = async () => {
|
|
81979
82303
|
if (!current) return;
|
|
81980
82304
|
await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
|
|
81981
82305
|
clearRequest("Rejected. Waiting for the next request\u2026");
|
|
81982
82306
|
};
|
|
81983
82307
|
|
|
81984
|
-
|
|
82308
|
+
approveEl.onclick = async () => {
|
|
81985
82309
|
if (!current) return;
|
|
82310
|
+
// Re-checked at the click, not just at render: hiding a button is CSS, and a stale
|
|
82311
|
+
// request or a DOM poke must not open a wallet for a ceremony the phone owns.
|
|
82312
|
+
if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
|
|
81986
82313
|
const req = current;
|
|
81987
82314
|
try {
|
|
81988
82315
|
if (req.kind === "transaction") {
|
|
@@ -81999,7 +82326,10 @@ document.getElementById("approve").onclick = async () => {
|
|
|
81999
82326
|
const fbody = await fr.json();
|
|
82000
82327
|
if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
|
|
82001
82328
|
const fresh = fbody.request;
|
|
82002
|
-
// \u2026re-render what will actually sign
|
|
82329
|
+
// \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
|
|
82330
|
+
// another card arriving while the wallet popup is open re-picks from there, and the
|
|
82331
|
+
// pre-finalize frame would put the OLD hash's card back under an open wallet.
|
|
82332
|
+
pending.set(fresh.id, fresh);
|
|
82003
82333
|
current = fresh; renderRequest();
|
|
82004
82334
|
// \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
|
|
82005
82335
|
const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
|
|
@@ -82154,9 +82484,6 @@ var SignatureBridge = class {
|
|
|
82154
82484
|
/** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
|
|
82155
82485
|
maxPending;
|
|
82156
82486
|
attachGraceMs;
|
|
82157
|
-
/** Last sweep tick that saw a live attachment — the unattended grace measures from
|
|
82158
|
-
* max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
|
|
82159
|
-
lastAttachedMs = 0;
|
|
82160
82487
|
server = null;
|
|
82161
82488
|
port = 0;
|
|
82162
82489
|
/** Started state independent of the transport binding (mounted bridges own no server). */
|
|
@@ -82307,13 +82634,16 @@ var SignatureBridge = class {
|
|
|
82307
82634
|
enqueuedMs: now,
|
|
82308
82635
|
resolve,
|
|
82309
82636
|
settled: false,
|
|
82310
|
-
...handlers?.finalize ? { finalize: handlers.finalize } : {}
|
|
82637
|
+
...handlers?.finalize ? { finalize: handlers.finalize } : {},
|
|
82638
|
+
owner: this.wcActive ? "wc" : "page",
|
|
82639
|
+
dispatched: false,
|
|
82640
|
+
lastAttachedMs: now
|
|
82311
82641
|
};
|
|
82312
82642
|
this.pending.set(request.id, entry);
|
|
82313
|
-
if (
|
|
82643
|
+
if (entry.owner === "wc") {
|
|
82314
82644
|
void this.driveWc(entry);
|
|
82315
82645
|
} else {
|
|
82316
|
-
this.
|
|
82646
|
+
this.pushEntry(entry);
|
|
82317
82647
|
}
|
|
82318
82648
|
});
|
|
82319
82649
|
}
|
|
@@ -82334,10 +82664,16 @@ var SignatureBridge = class {
|
|
|
82334
82664
|
enqueuedMs: now,
|
|
82335
82665
|
resolve,
|
|
82336
82666
|
settled: false,
|
|
82337
|
-
collect
|
|
82667
|
+
collect,
|
|
82668
|
+
// A collection asks the page AND (below) WalletConnect at once, so it is owned by
|
|
82669
|
+
// BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
|
|
82670
|
+
// ceremony could not reach quorum through the very pages it is broadcast to.
|
|
82671
|
+
owner: "both",
|
|
82672
|
+
dispatched: false,
|
|
82673
|
+
lastAttachedMs: now
|
|
82338
82674
|
};
|
|
82339
82675
|
this.pending.set(request.id, entry);
|
|
82340
|
-
this.
|
|
82676
|
+
this.pushEntry(entry);
|
|
82341
82677
|
if (this.wcActive) void this.driveWcCollection(entry);
|
|
82342
82678
|
});
|
|
82343
82679
|
}
|
|
@@ -82376,7 +82712,9 @@ var SignatureBridge = class {
|
|
|
82376
82712
|
}
|
|
82377
82713
|
try {
|
|
82378
82714
|
if (req.kind === "transaction") {
|
|
82715
|
+
this.pushEntry(entry);
|
|
82379
82716
|
const tx2 = req.tx;
|
|
82717
|
+
entry.dispatched = true;
|
|
82380
82718
|
const txHash = await transport.request("eth_sendTransaction", [
|
|
82381
82719
|
{ from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
|
|
82382
82720
|
]);
|
|
@@ -82388,11 +82726,22 @@ var SignatureBridge = class {
|
|
|
82388
82726
|
req.card = fresh.card;
|
|
82389
82727
|
}
|
|
82390
82728
|
const ps = req.personalSign;
|
|
82729
|
+
if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
|
|
82730
|
+
this.settle(entry, {
|
|
82731
|
+
status: "invalidated",
|
|
82732
|
+
reason: `this step signs a 32-byte hash your wallet cannot decode, and no approval page is open to show you what it authorizes \u2014 open ${this.url()} and re-run the withdrawal with loan_withdraw_retry (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`
|
|
82733
|
+
});
|
|
82734
|
+
return;
|
|
82735
|
+
}
|
|
82736
|
+
this.pushEntry(entry);
|
|
82737
|
+
entry.dispatched = true;
|
|
82391
82738
|
const signature = await transport.request("personal_sign", [ps.hashHex, account]);
|
|
82392
82739
|
if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
|
|
82393
82740
|
} else {
|
|
82741
|
+
this.pushEntry(entry);
|
|
82394
82742
|
const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
|
|
82395
82743
|
const payload = withEip712DomainType2(req.typedData);
|
|
82744
|
+
entry.dispatched = true;
|
|
82396
82745
|
const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
|
|
82397
82746
|
if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
|
|
82398
82747
|
}
|
|
@@ -82412,30 +82761,55 @@ var SignatureBridge = class {
|
|
|
82412
82761
|
* with a live attachment is in use and must never be evicted. */
|
|
82413
82762
|
attachedNow() {
|
|
82414
82763
|
if (this.wcActive) return true;
|
|
82415
|
-
|
|
82764
|
+
return this.pageAttached();
|
|
82765
|
+
}
|
|
82766
|
+
/** A live approval PAGE specifically — the only surface that can render a card. Excludes
|
|
82767
|
+
* quarantined sessions, which `push` already refuses to write to (C-47): a page that
|
|
82768
|
+
* receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
|
|
82769
|
+
* WalletConnect and must stay global for the connector's eviction predicate. */
|
|
82770
|
+
pageAttached() {
|
|
82771
|
+
for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
|
|
82416
82772
|
return false;
|
|
82417
82773
|
}
|
|
82774
|
+
/** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
|
|
82775
|
+
* predicate said "a WC session is attached", which is true but irrelevant to a
|
|
82776
|
+
* page-owned request, and vice versa: an entry whose own wallet has gone silently sat
|
|
82777
|
+
* out the full expiry instead of failing fast at the grace. */
|
|
82778
|
+
attachedFor(entry) {
|
|
82779
|
+
if (entry.owner === "wc") return this.wcActive;
|
|
82780
|
+
if (entry.owner === "both") return this.wcActive || this.pageAttached();
|
|
82781
|
+
return this.pageAttached();
|
|
82782
|
+
}
|
|
82418
82783
|
/** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
|
|
82419
82784
|
* interval; tests call it directly with the injected clock advanced. Order matters:
|
|
82420
82785
|
* the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
|
|
82421
82786
|
sweep() {
|
|
82422
82787
|
const now = this.clock();
|
|
82423
|
-
const attached = this.attachedNow();
|
|
82424
|
-
if (attached) this.lastAttachedMs = now;
|
|
82425
82788
|
for (const entry of this.pending.values()) {
|
|
82426
82789
|
if (entry.settled) continue;
|
|
82427
82790
|
if (now >= entry.deadlineMs) {
|
|
82428
82791
|
this.settle(entry, { status: "expired" });
|
|
82429
82792
|
continue;
|
|
82430
82793
|
}
|
|
82431
|
-
if (
|
|
82432
|
-
|
|
82433
|
-
|
|
82434
|
-
reason: `no wallet approval page is attached to this bridge (it may have been closed) \u2014 open ${this.url()} in the browser, connect the wallet, and retry the operation`
|
|
82435
|
-
});
|
|
82794
|
+
if (this.attachedFor(entry)) {
|
|
82795
|
+
entry.lastAttachedMs = now;
|
|
82796
|
+
continue;
|
|
82436
82797
|
}
|
|
82798
|
+
if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
|
|
82799
|
+
this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
|
|
82437
82800
|
}
|
|
82438
82801
|
}
|
|
82802
|
+
/** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
|
|
82803
|
+
* a phone, the warning that giving up here is not the same as nothing having happened. */
|
|
82804
|
+
unattendedReason(entry) {
|
|
82805
|
+
if (entry.dispatched && entry.request.kind === "transaction") {
|
|
82806
|
+
return "the mobile wallet holding this transaction went away before answering, but it was already asked to send it \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice.";
|
|
82807
|
+
}
|
|
82808
|
+
if (entry.owner === "wc") {
|
|
82809
|
+
return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
|
|
82810
|
+
}
|
|
82811
|
+
return `no wallet approval page is attached to this bridge (it may have been closed) \u2014 open ${this.url()} in the browser, connect the wallet, and retry the operation`;
|
|
82812
|
+
}
|
|
82439
82813
|
/** A live WalletConnect session exists right now (disconnect reports it truthfully). */
|
|
82440
82814
|
walletConnectActive() {
|
|
82441
82815
|
return this.wcActive;
|
|
@@ -82559,6 +82933,7 @@ var SignatureBridge = class {
|
|
|
82559
82933
|
if (info && refusal) {
|
|
82560
82934
|
this.wcActive = false;
|
|
82561
82935
|
this.rebuildSharedWallet();
|
|
82936
|
+
this.demoteWcEntries();
|
|
82562
82937
|
process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
|
|
82563
82938
|
`);
|
|
82564
82939
|
return;
|
|
@@ -82568,7 +82943,10 @@ var SignatureBridge = class {
|
|
|
82568
82943
|
if (info === null) {
|
|
82569
82944
|
for (const entry of this.pending.values()) {
|
|
82570
82945
|
if (!entry.settled && !entry.collect) {
|
|
82571
|
-
this.settle(entry, {
|
|
82946
|
+
this.settle(entry, {
|
|
82947
|
+
status: "invalidated",
|
|
82948
|
+
reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
|
|
82949
|
+
});
|
|
82572
82950
|
}
|
|
82573
82951
|
}
|
|
82574
82952
|
}
|
|
@@ -82640,9 +83018,7 @@ var SignatureBridge = class {
|
|
|
82640
83018
|
session.sse?.end();
|
|
82641
83019
|
session.sse = res;
|
|
82642
83020
|
for (const entry of this.pending.values()) {
|
|
82643
|
-
if (!entry.settled) res.write(
|
|
82644
|
-
|
|
82645
|
-
`);
|
|
83021
|
+
if (!entry.settled) res.write(this.wireFor(entry));
|
|
82646
83022
|
}
|
|
82647
83023
|
const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
|
|
82648
83024
|
keepAlive.unref();
|
|
@@ -82718,10 +83094,36 @@ var SignatureBridge = class {
|
|
|
82718
83094
|
}
|
|
82719
83095
|
const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
|
|
82720
83096
|
for (const entry of this.pending.values()) {
|
|
82721
|
-
if (
|
|
83097
|
+
if (entry.settled || entry.collect) continue;
|
|
83098
|
+
if (this.ownedByWc(entry)) continue;
|
|
83099
|
+
this.settle(entry, { status: "invalidated", reason });
|
|
82722
83100
|
}
|
|
82723
83101
|
this.ok(res);
|
|
82724
83102
|
}
|
|
83103
|
+
/** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
|
|
83104
|
+
* session hands the request back to the page rather than stranding it. */
|
|
83105
|
+
ownedByWc(entry) {
|
|
83106
|
+
if (entry.owner !== "wc") return false;
|
|
83107
|
+
return this.wcActive || entry.dispatched;
|
|
83108
|
+
}
|
|
83109
|
+
/** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
|
|
83110
|
+
* them so the card stops rendering read-only. Collections are already `both`.
|
|
83111
|
+
*
|
|
83112
|
+
* DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
|
|
83113
|
+
* phone is still holding does not replace one wallet with another, it adds a second: the
|
|
83114
|
+
* outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
|
|
83115
|
+
* keeps the transport alive on purpose), so an actionable page card alongside it means
|
|
83116
|
+
* both can approve — and for a transaction that is two broadcasts of the same operation.
|
|
83117
|
+
* Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
|
|
83118
|
+
* false for them, and `unattendedReason` says plainly that the phone may already have
|
|
83119
|
+
* acted. */
|
|
83120
|
+
demoteWcEntries() {
|
|
83121
|
+
for (const entry of this.pending.values()) {
|
|
83122
|
+
if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
|
|
83123
|
+
entry.owner = "page";
|
|
83124
|
+
this.pushEntry(entry);
|
|
83125
|
+
}
|
|
83126
|
+
}
|
|
82725
83127
|
/** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
|
|
82726
83128
|
* request. Idempotent for requests without a finalize handler (payload as enqueued). */
|
|
82727
83129
|
async onFinalize(body, res) {
|
|
@@ -82735,6 +83137,10 @@ var SignatureBridge = class {
|
|
|
82735
83137
|
this.deny(res, 400, "finalize applies only to personal-sign requests");
|
|
82736
83138
|
return;
|
|
82737
83139
|
}
|
|
83140
|
+
if (this.ownedByWc(entry)) {
|
|
83141
|
+
this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
|
|
83142
|
+
return;
|
|
83143
|
+
}
|
|
82738
83144
|
if (entry.finalize) {
|
|
82739
83145
|
let fresh;
|
|
82740
83146
|
try {
|
|
@@ -82761,10 +83167,22 @@ var SignatureBridge = class {
|
|
|
82761
83167
|
return;
|
|
82762
83168
|
}
|
|
82763
83169
|
if (body["approved"] !== true) {
|
|
83170
|
+
if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
|
|
83171
|
+
this.settle(entry, {
|
|
83172
|
+
status: "invalidated",
|
|
83173
|
+
reason: "cancelled on the approval page, but a mobile wallet was already asked to send this transaction \u2014 it may have broadcast already. Check the chain (or your wallet's activity) before retrying, or you may pay twice."
|
|
83174
|
+
});
|
|
83175
|
+
this.ok(res);
|
|
83176
|
+
return;
|
|
83177
|
+
}
|
|
82764
83178
|
this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
|
|
82765
83179
|
this.ok(res);
|
|
82766
83180
|
return;
|
|
82767
83181
|
}
|
|
83182
|
+
if (this.ownedByWc(entry)) {
|
|
83183
|
+
this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
|
|
83184
|
+
return;
|
|
83185
|
+
}
|
|
82768
83186
|
const account = String(body["account"] ?? "");
|
|
82769
83187
|
if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
|
|
82770
83188
|
this.deny(res, 400, "approved result requires the signing account");
|
|
@@ -82801,11 +83219,20 @@ var SignatureBridge = class {
|
|
|
82801
83219
|
this.pending.delete(entry.request.id);
|
|
82802
83220
|
entry.resolve(outcome);
|
|
82803
83221
|
}
|
|
82804
|
-
/**
|
|
82805
|
-
|
|
82806
|
-
|
|
83222
|
+
/** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
|
|
83223
|
+
* written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
|
|
83224
|
+
* `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
|
|
83225
|
+
* same object in place — a stored flag would leak into all three and go sticky, leaving
|
|
83226
|
+
* a permanently read-only card that nobody is allowed to decide. */
|
|
83227
|
+
wireFor(entry) {
|
|
83228
|
+
const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
|
|
83229
|
+
return `data: ${JSON.stringify(payload)}
|
|
82807
83230
|
|
|
82808
83231
|
`;
|
|
83232
|
+
}
|
|
83233
|
+
/** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
|
|
83234
|
+
pushEntry(entry) {
|
|
83235
|
+
const data = this.wireFor(entry);
|
|
82809
83236
|
for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
|
|
82810
83237
|
}
|
|
82811
83238
|
/** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
|
|
@@ -83288,7 +83715,7 @@ var FIELD_GLOSSARY = {
|
|
|
83288
83715
|
originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
|
|
83289
83716
|
extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
|
|
83290
83717
|
// ---- psm quote ----
|
|
83291
|
-
direction: "'to-ucd' = pay stablecoin, receive UCD; '
|
|
83718
|
+
direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
|
|
83292
83719
|
contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
|
|
83293
83720
|
amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
|
|
83294
83721
|
amountInToken: "the token you pay with",
|
|
@@ -83355,6 +83782,17 @@ function signerModeSourceClause(d) {
|
|
|
83355
83782
|
function phoneWalletOffer(d) {
|
|
83356
83783
|
return d.walletConnect ? "or scan the WalletConnect QR (or paste the pairing code) to approve on a phone wallet" : "This deployment does NOT offer the WalletConnect phone-wallet leg \u2014 there is no QR to scan and `/wc-pairing` answers 404; a browser-extension wallet is the only path here";
|
|
83357
83784
|
}
|
|
83785
|
+
function worldAxes(d) {
|
|
83786
|
+
const axes = [];
|
|
83787
|
+
axes.push(
|
|
83788
|
+
offers(d, "mock-simulated") ? "practice (mock) or real adapter" : "the REAL adapter \u2014 there is no practice (mock) world on this deployment"
|
|
83789
|
+
);
|
|
83790
|
+
axes.push(
|
|
83791
|
+
d.networks.length > 1 ? "sepolia (practice money) or mainnet (real money)" : d.networks.includes("mainnet") ? "MAINNET only, so every fund movement here is real money" : "sepolia only, so the ceremonies are real and the money is practice"
|
|
83792
|
+
);
|
|
83793
|
+
axes.push("that writes are enabled, and what actually gates one is whether a signing identity is connected");
|
|
83794
|
+
return axes.join("; ");
|
|
83795
|
+
}
|
|
83358
83796
|
function moneyTruth(d) {
|
|
83359
83797
|
const practice = offers(d, "mock-simulated");
|
|
83360
83798
|
const sepolia = d.networks.includes("sepolia");
|
|
@@ -83386,11 +83824,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
|
|
|
83386
83824
|
// speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
|
|
83387
83825
|
// on the real adapter these modes refuse") carry the narrower adapter axis.
|
|
83388
83826
|
signerModes: GUIDE_SIGNER_MODES,
|
|
83389
|
-
// FALSE,
|
|
83390
|
-
//
|
|
83391
|
-
//
|
|
83392
|
-
//
|
|
83393
|
-
//
|
|
83827
|
+
// FALSE as the FALLBACK, which is no longer the same statement as "a default install has
|
|
83828
|
+
// no WalletConnect". Since 2026-09-10 a local install ships a default project id
|
|
83829
|
+
// (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
|
|
83830
|
+
// usually `true` — and a live boot derives exactly that, from the same resolution the
|
|
83831
|
+
// bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
|
|
83832
|
+
// nobody supplied a deployment at all, and understating a capability there is the safe
|
|
83833
|
+
// direction: the first draft said `true` "to keep the walkthrough complete", which is the
|
|
83834
|
+
// overclaim C-44 is about — promising a QR the build cannot show.
|
|
83394
83835
|
walletConnect: false
|
|
83395
83836
|
};
|
|
83396
83837
|
function servedNetworks(d) {
|
|
@@ -83401,7 +83842,7 @@ function servedNetworks(d) {
|
|
|
83401
83842
|
return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
|
|
83402
83843
|
}
|
|
83403
83844
|
if (mainnet) {
|
|
83404
|
-
return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing
|
|
83845
|
+
return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing; PSM swaps are NOT an exception \u2014 they execute here and move real funds), and there is no practice network on this deployment to fall back to";
|
|
83405
83846
|
}
|
|
83406
83847
|
return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
|
|
83407
83848
|
}
|
|
@@ -83480,13 +83921,14 @@ function switchNetworkRules(d) {
|
|
|
83480
83921
|
the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
|
|
83481
83922
|
- NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
|
|
83482
83923
|
A sepolia position does not exist on mainnet and vice versa.
|
|
83483
|
-
- Fund-moving
|
|
83484
|
-
and every one still requires the user's explicit
|
|
83485
|
-
ceremony.
|
|
83924
|
+
- Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
|
|
83925
|
+
mainnet they move REAL money, and every one still requires the user's explicit
|
|
83926
|
+
confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
|
|
83927
|
+
stablecoin; that name is checked against the PSM's on-chain set before anything is
|
|
83928
|
+
signed.`;
|
|
83486
83929
|
}
|
|
83487
83930
|
const only = d.networks[0];
|
|
83488
83931
|
const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
|
|
83489
|
-
const psm = d.networks.includes("mainnet") ? "The exception is PSM swaps \u2014 the write port refuses them here." : "PSM swaps run here, and are refused on every other network.";
|
|
83490
83932
|
return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
|
|
83491
83933
|
network this deployment is rolled out to \u2014 every other target is REFUSED with that
|
|
83492
83934
|
rollout truth. There is nothing to switch TO here; never offer the user another world.
|
|
@@ -83495,7 +83937,9 @@ function switchNetworkRules(d) {
|
|
|
83495
83937
|
belong to ${only} and would not exist anywhere else.
|
|
83496
83938
|
- Fund-moving loan operations run on ${only}, each still requiring the user's explicit
|
|
83497
83939
|
confirmation plus the signer ceremony.
|
|
83498
|
-
- ${
|
|
83940
|
+
- PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
|
|
83941
|
+
the caller must NAME the stablecoin, checked against the PSM's on-chain set before
|
|
83942
|
+
anything is signed.`;
|
|
83499
83943
|
}
|
|
83500
83944
|
function wrongNetworkTroubleshootingRow(d) {
|
|
83501
83945
|
if (d.networks.length > 1) {
|
|
@@ -83515,20 +83959,23 @@ function switchNetworkIndexLine(d) {
|
|
|
83515
83959
|
const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
|
|
83516
83960
|
return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
|
|
83517
83961
|
}
|
|
83518
|
-
function
|
|
83519
|
-
if (d.networks.includes("sepolia"))
|
|
83520
|
-
|
|
83521
|
-
|
|
83522
|
-
\`
|
|
83523
|
-
the
|
|
83524
|
-
|
|
83525
|
-
|
|
83962
|
+
function psmStablecoinRealityNote(d) {
|
|
83963
|
+
if (d.networks.includes("sepolia")) {
|
|
83964
|
+
return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
|
|
83965
|
+
\`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
|
|
83966
|
+
the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
|
|
83967
|
+
the money is real. On mainnet the stablecoin is real Circle USDC.`;
|
|
83968
|
+
}
|
|
83969
|
+
return `**Real money, and no practice path from here.** This deployment is not rolled out to
|
|
83970
|
+
sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
|
|
83971
|
+
every swap executed on this deployment moves real Circle USDC and real UCD.
|
|
83972
|
+
\`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
|
|
83973
|
+
have to guess whether the money is real.`;
|
|
83526
83974
|
}
|
|
83527
83975
|
function authorizationModeBullets(d) {
|
|
83528
83976
|
const bullets = [];
|
|
83529
83977
|
if (offers(d, "external")) {
|
|
83530
|
-
bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
|
|
83531
|
-
mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
|
|
83978
|
+
bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup${d.walletConnect ? ", or WalletConnect\n mobile via QR/paste-code" : " \u2014 this build has no WalletConnect\n mobile leg"}). Real adapter and mock. For TRANSACTIONS the approval card
|
|
83532
83979
|
is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
|
|
83533
83980
|
The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
|
|
83534
83981
|
approval page states plainly it CANNOT decode. Never extend the card promise over
|
|
@@ -83591,8 +84038,7 @@ install matrix. ${connectorInstallNote(d)}
|
|
|
83591
84038
|
Nothing needs a config file. Three steps:
|
|
83592
84039
|
|
|
83593
84040
|
**1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
|
|
83594
|
-
\`protocol_status\`, then tell the user
|
|
83595
|
-
(practice money) or mainnet (real money); whether writes are enabled here and which
|
|
84041
|
+
\`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
|
|
83596
84042
|
signer modes exist; current terms (\`protocol_terms\`).
|
|
83597
84043
|
|
|
83598
84044
|
**2. Choose HOW to authorize operations** (the user's choice, made by talking):
|
|
@@ -83636,7 +84082,7 @@ on the real adapter and the mock.
|
|
|
83636
84082
|
**The walkthrough:**
|
|
83637
84083
|
1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
|
|
83638
84084
|
desktop browser; ${approvalPageLocation(d)}
|
|
83639
|
-
2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code." : ". " + phoneWalletOffer(d) + "."}
|
|
84085
|
+
2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code. KEEP THE APPROVAL PAGE OPEN: while a\n phone wallet is connected the page becomes the READ-ONLY reader for every ceremony \u2014\n it shows the full card, the phone shows only what a wallet can render, and you approve\n or decline in the phone. (Cancel still works from the page.)" : ". " + phoneWalletOffer(d) + "."}
|
|
83640
84086
|
3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
|
|
83641
84087
|
login ceremony explicitly (one typed-data signature in the wallet).
|
|
83642
84088
|
4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
|
|
@@ -83675,7 +84121,14 @@ on the real adapter and the mock.
|
|
|
83675
84121
|
hash the SDK builds internally, which the approval page shows bare and says plainly it
|
|
83676
84122
|
cannot decode (the production web app signs the same way). Tell the user before that
|
|
83677
84123
|
ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
|
|
83678
|
-
expect an unreadable card and click through the readable one.
|
|
84124
|
+
expect an unreadable card and click through the readable one.${d.walletConnect ? `
|
|
84125
|
+
- **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
|
|
84126
|
+
it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
|
|
84127
|
+
\u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
|
|
84128
|
+
on the card, and the page is the only surface that shows it. With no page attached the
|
|
84129
|
+
step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
|
|
84130
|
+
coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
|
|
84131
|
+
mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
|
|
83679
84132
|
- **The READABLE phase can be asked for up to THREE times.** Its authorization is only
|
|
83680
84133
|
valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
|
|
83681
84134
|
attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
|
|
@@ -83694,8 +84147,7 @@ on the real adapter and the mock.
|
|
|
83694
84147
|
10 UCD.
|
|
83695
84148
|
|
|
83696
84149
|
**Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
|
|
83697
|
-
\`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
|
|
83698
|
-
WalletConnect session (pending approvals are cancelled loudly), discards the login
|
|
84150
|
+
\`disconnect\`):** the FULL wallet flush. It ends every approval-page session${d.walletConnect ? " and any\nWalletConnect session" : ""} (pending approvals are cancelled loudly), discards the login
|
|
83699
84151
|
token from server memory AND revokes it at the service, and unbinds the borrower
|
|
83700
84152
|
identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
|
|
83701
84153
|
a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
|
|
@@ -83756,9 +84208,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
|
|
|
83756
84208
|
|
|
83757
84209
|
Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
|
|
83758
84210
|
signed, amounts included. Read it back when the user asks what happened.`,
|
|
83759
|
-
psm: (d) => `# PSM \u2014 exchanging UCD \u2194
|
|
84211
|
+
psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
|
|
83760
84212
|
|
|
83761
|
-
|
|
84213
|
+
The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
|
|
83762
84214
|
directions, in user words:
|
|
83763
84215
|
|
|
83764
84216
|
- **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
|
|
@@ -83766,20 +84218,27 @@ directions, in user words:
|
|
|
83766
84218
|
The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
|
|
83767
84219
|
UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
|
|
83768
84220
|
and you receive 99 UCD.
|
|
83769
|
-
- **"Get
|
|
83770
|
-
and the PSM pays you
|
|
83771
|
-
|
|
83772
|
-
only possible while reserves cover the payout \u2014 the quote shows live
|
|
83773
|
-
shortfall refuses with both figures (available vs required).
|
|
84221
|
+
- **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
|
|
84222
|
+
burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
|
|
84223
|
+
is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
|
|
84224
|
+
10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
|
|
84225
|
+
reserves, and a shortfall refuses with both figures (available vs required).
|
|
84226
|
+
|
|
84227
|
+
**Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
|
|
84228
|
+
default and that is deliberate: the PSM can carry several coins, each with its own
|
|
84229
|
+
reserves, fees and limits, so picking one silently would move someone's money through a
|
|
84230
|
+
token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
|
|
84231
|
+
there rather than guessing one.
|
|
83774
84232
|
|
|
83775
84233
|
The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
|
|
83776
84234
|
is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
|
|
83777
84235
|
1e18 = 1:1) and can be changed by protocol governance.
|
|
83778
84236
|
|
|
83779
84237
|
**Limits and switches** (all visible in \`protocol://psm\`):
|
|
83780
|
-
- Each direction has a min and max PER OPERATION
|
|
83781
|
-
units,
|
|
83782
|
-
|
|
84238
|
+
- Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
|
|
84239
|
+
are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
|
|
84240
|
+
direction is DISABLED.
|
|
84241
|
+
- \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
|
|
83783
84242
|
direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
|
|
83784
84243
|
- Per-block volume caps may exist per direction ("uncapped" when none is set).
|
|
83785
84244
|
|
|
@@ -83788,23 +84247,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
|
|
|
83788
84247
|
change between your quote and execution; the floor makes a drifted execution REFUSE
|
|
83789
84248
|
rather than silently deliver less than quoted.
|
|
83790
84249
|
|
|
83791
|
-
|
|
83792
|
-
\`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
|
|
83793
|
-
the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
|
|
83794
|
-
the money is real. On mainnet the stablecoin is real Circle USDC.
|
|
84250
|
+
${psmStablecoinRealityNote(d)}
|
|
83795
84251
|
|
|
83796
84252
|
**Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
|
|
83797
84253
|
result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
|
|
83798
84254
|
differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
|
|
83799
|
-
|
|
83800
|
-
UCD to the **UCDController** (the PSM burns your UCD through the
|
|
83801
|
-
swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
|
|
84255
|
+
the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
|
|
84256
|
+
you approve UCD to the **UCDController** (the PSM burns your UCD through the
|
|
84257
|
+
controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
|
|
83802
84258
|
tolerance; if fees or the rate drifted beyond that between quote and execution, the
|
|
83803
84259
|
contract refuses \u2014 you never silently receive less. Output always lands at the signer's
|
|
83804
84260
|
own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
|
|
83805
84261
|
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
|
|
83806
|
-
|
|
83807
|
-
|
|
84262
|
+
PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
|
|
84263
|
+
REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
|
|
84264
|
+
wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
|
|
84265
|
+
PSM's supported set on-chain before anything is signed), the explicit confirmation plus
|
|
84266
|
+
signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
|
|
84267
|
+
per-operation and per-block limits,
|
|
84268
|
+
\`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
|
|
84269
|
+
mainnet swap, not after.`,
|
|
83808
84270
|
authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
|
|
83809
84271
|
|
|
83810
84272
|
Every fund-moving operation needs TWO things, always in this order:
|
|
@@ -84063,9 +84525,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
|
|
|
84063
84525
|
- **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
|
|
84064
84526
|
the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
|
|
84065
84527
|
the same way \u2014 reconnect on the user's word.`}
|
|
84066
|
-
|
|
84067
|
-
|
|
84068
|
-
|
|
84528
|
+
- **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
|
|
84529
|
+
this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
|
|
84530
|
+
support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
|
|
84531
|
+
per-operation or per-block limit, reserves too thin for the redemption, or no signer.
|
|
84532
|
+
Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
|
|
84069
84533
|
${wrongNetworkTroubleshootingRow(d)}
|
|
84070
84534
|
- **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
|
|
84071
84535
|
SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
|
|
@@ -84141,7 +84605,7 @@ function renderGuideIndex(deployment) {
|
|
|
84141
84605
|
|
|
84142
84606
|
- getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
|
|
84143
84607
|
- first-setup \u2014 zero to ready by conversation (authorization choice included)
|
|
84144
|
-
- connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
|
|
84608
|
+
- connect-wallet \u2014 external-wallet walkthrough: approval page, ${deployment.walletConnect ? "extension or WalletConnect QR" : "browser extension (no WalletConnect leg here)"}, popup cadence, login honesty, disconnect/log-out
|
|
84145
84609
|
- lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
|
|
84146
84610
|
- fees \u2014 the two fee models, plainly
|
|
84147
84611
|
- psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
|
|
@@ -84223,12 +84687,13 @@ function guideDeployment(overrides, env) {
|
|
|
84223
84687
|
tier: overrides?.bridgeMount ? "hosted" : "local",
|
|
84224
84688
|
networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
|
|
84225
84689
|
signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
|
|
84226
|
-
// C-44 F8, the fourth derivation.
|
|
84227
|
-
//
|
|
84228
|
-
//
|
|
84229
|
-
//
|
|
84230
|
-
//
|
|
84231
|
-
|
|
84690
|
+
// C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
|
|
84691
|
+
// config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
|
|
84692
|
+
// QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
|
|
84693
|
+
// until the leg gained a shipped default and an `off` sentinel — after which absence no
|
|
84694
|
+
// longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
|
|
84695
|
+
// default is what keeps the guide and `/auth.md` agreeing about the same server.
|
|
84696
|
+
walletConnect: wcEnabled(env)
|
|
84232
84697
|
};
|
|
84233
84698
|
}
|
|
84234
84699
|
function assembleWorld(opts) {
|
|
@@ -84868,39 +85333,45 @@ function registerPsmTools(server, getB) {
|
|
|
84868
85333
|
server,
|
|
84869
85334
|
"psm_quote",
|
|
84870
85335
|
{
|
|
84871
|
-
title: "Quote a UCD \u2194
|
|
84872
|
-
description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay
|
|
85336
|
+
title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
|
|
85337
|
+
description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay the stablecoin, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'from-ucd' = pay UCD, receive the stablecoin back from the PSM's reserves; the EXIT fee is charged IN that stablecoin and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). The result names both amounts, the fee WITH its token, and (from-ucd) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
|
|
84873
85338
|
inputSchema: {
|
|
84874
|
-
|
|
84875
|
-
|
|
85339
|
+
stablecoin: import_zod4.z.string().min(1).describe(
|
|
85340
|
+
"The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
|
|
85341
|
+
),
|
|
85342
|
+
direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
|
|
85343
|
+
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals.")
|
|
84876
85344
|
},
|
|
84877
85345
|
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
|
|
84878
85346
|
},
|
|
84879
|
-
async ({ direction, amount }) => guarded(async () => {
|
|
84880
|
-
const label = direction === "to-ucd" ?
|
|
85347
|
+
async ({ stablecoin, direction, amount }) => guarded(async () => {
|
|
85348
|
+
const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
|
|
84881
85349
|
const problem = checkUcdAmount(amount, label);
|
|
84882
85350
|
if (problem) return validationFailed(problem);
|
|
84883
85351
|
const b = getB();
|
|
84884
85352
|
if (!b.ok) return renderError(b.error);
|
|
84885
|
-
return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
|
|
85353
|
+
return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
|
|
84886
85354
|
})
|
|
84887
85355
|
);
|
|
84888
85356
|
registerBoundaryTool(
|
|
84889
85357
|
server,
|
|
84890
85358
|
"psm_swap",
|
|
84891
85359
|
{
|
|
84892
|
-
title: "Exchange UCD \u2194
|
|
84893
|
-
description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay
|
|
85360
|
+
title: "Exchange UCD \u2194 a stablecoin through the PSM",
|
|
85361
|
+
description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
|
|
84894
85362
|
inputSchema: {
|
|
84895
|
-
|
|
84896
|
-
|
|
85363
|
+
stablecoin: import_zod4.z.string().min(1).describe(
|
|
85364
|
+
"The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
|
|
85365
|
+
),
|
|
85366
|
+
direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
|
|
85367
|
+
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals."),
|
|
84897
85368
|
confirmed: confirmedSchema2
|
|
84898
85369
|
},
|
|
84899
85370
|
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
|
|
84900
85371
|
},
|
|
84901
|
-
async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
|
|
84902
|
-
const inputToken = direction === "to-ucd" ?
|
|
84903
|
-
const outputToken = direction === "to-ucd" ? "UCD" :
|
|
85372
|
+
async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
|
|
85373
|
+
const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
|
|
85374
|
+
const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
|
|
84904
85375
|
const gate = requireConfirmation(
|
|
84905
85376
|
confirmed,
|
|
84906
85377
|
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
|
|
@@ -84910,7 +85381,7 @@ function registerPsmTools(server, getB) {
|
|
|
84910
85381
|
if (problem) return validationFailed(problem);
|
|
84911
85382
|
const b = getB();
|
|
84912
85383
|
if (!b.ok) return renderError(b.error);
|
|
84913
|
-
return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
|
|
85384
|
+
return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
|
|
84914
85385
|
})
|
|
84915
85386
|
);
|
|
84916
85387
|
}
|
|
@@ -85356,7 +85827,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
|
|
|
85356
85827
|
"network_switch",
|
|
85357
85828
|
{
|
|
85358
85829
|
title: "Show or switch the active network",
|
|
85359
|
-
description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks (on mainnet they move REAL money
|
|
85830
|
+
description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks \u2014 loan operations and PSM swaps alike (on mainnet they move REAL money). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
|
|
85360
85831
|
inputSchema: {
|
|
85361
85832
|
action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
|
|
85362
85833
|
network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
|
|
@@ -85374,7 +85845,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
|
|
|
85374
85845
|
lines.push(
|
|
85375
85846
|
`Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
|
|
85376
85847
|
"A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
|
|
85377
|
-
"Fund-moving operations work on both networks \u2014 on mainnet they move REAL money
|
|
85848
|
+
"Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
|
|
85378
85849
|
"Session-scoped: the configured default network returns when the server restarts."
|
|
85379
85850
|
);
|
|
85380
85851
|
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
@@ -85480,13 +85951,26 @@ function registerProtocolResources(server, getB) {
|
|
|
85480
85951
|
"protocol://psm",
|
|
85481
85952
|
{
|
|
85482
85953
|
title: "PSM status (UCD \u2194 USDC exchange)",
|
|
85483
|
-
description: "Live SimplePSMV2 state as {data, warnings, source}
|
|
85954
|
+
description: "Live SimplePSMV2 state as {data, warnings, source}. `data` carries network + chainId + psmAddress (the money surface names its chain) and `stablecoins`: EVERY coin this PSM supports, each with its own stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in the stablecoin's smallest units, from-ucd caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0). This is where a caller learns the coin names that `psm_quote` and `psm_swap` require.",
|
|
85484
85955
|
mimeType: "application/json"
|
|
85485
85956
|
},
|
|
85486
85957
|
async (uri) => {
|
|
85487
85958
|
const b = getB();
|
|
85488
85959
|
if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
|
|
85489
|
-
const
|
|
85960
|
+
const listed = await b.boundary.listPsmStablecoins();
|
|
85961
|
+
if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
|
|
85962
|
+
const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
|
|
85963
|
+
const failed = perCoin.find((s) => !s.ok);
|
|
85964
|
+
if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
|
|
85965
|
+
const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
|
|
85966
|
+
const head = coins[0];
|
|
85967
|
+
const env = {
|
|
85968
|
+
...listed,
|
|
85969
|
+
data: {
|
|
85970
|
+
...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
|
|
85971
|
+
stablecoins: coins
|
|
85972
|
+
}
|
|
85973
|
+
};
|
|
85490
85974
|
return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
|
|
85491
85975
|
}
|
|
85492
85976
|
);
|
|
@@ -85699,12 +86183,15 @@ function composeConnector(opts, rawPublicOrigin) {
|
|
|
85699
86183
|
for (const session of sessions.values()) held.add(session.tenant);
|
|
85700
86184
|
return held;
|
|
85701
86185
|
}
|
|
85702
|
-
function
|
|
85703
|
-
if (held.has(tenantKey)) return false;
|
|
86186
|
+
function isEvictable(world) {
|
|
85704
86187
|
const bridge = world.deps.signer?.bridge;
|
|
85705
86188
|
if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
|
|
85706
86189
|
return true;
|
|
85707
86190
|
}
|
|
86191
|
+
function isReclaimable(tenantKey, world, held) {
|
|
86192
|
+
if (held.has(tenantKey)) return false;
|
|
86193
|
+
return isEvictable(world);
|
|
86194
|
+
}
|
|
85708
86195
|
function sweepService() {
|
|
85709
86196
|
const now = clock();
|
|
85710
86197
|
for (const [sid, session] of [...sessions]) {
|
|
@@ -85720,13 +86207,12 @@ function composeConnector(opts, rawPublicOrigin) {
|
|
|
85720
86207
|
dropWorld(tenantKey, world, "idle eviction");
|
|
85721
86208
|
}
|
|
85722
86209
|
}
|
|
85723
|
-
function
|
|
85724
|
-
const held = tenantsWithSessions();
|
|
86210
|
+
function leastRecentlyActive(eligible) {
|
|
85725
86211
|
let victimKey = null;
|
|
85726
86212
|
let victim = null;
|
|
85727
86213
|
let oldest = Number.POSITIVE_INFINITY;
|
|
85728
86214
|
for (const [tenantKey, world] of readyWorlds) {
|
|
85729
|
-
if (!
|
|
86215
|
+
if (!eligible(tenantKey, world)) continue;
|
|
85730
86216
|
const activeAt = lastActivity.get(tenantKey) ?? 0;
|
|
85731
86217
|
if (activeAt < oldest) {
|
|
85732
86218
|
oldest = activeAt;
|
|
@@ -85734,8 +86220,23 @@ function composeConnector(opts, rawPublicOrigin) {
|
|
|
85734
86220
|
victim = world;
|
|
85735
86221
|
}
|
|
85736
86222
|
}
|
|
85737
|
-
|
|
85738
|
-
|
|
86223
|
+
return victimKey !== null && victim !== null ? [victimKey, victim] : null;
|
|
86224
|
+
}
|
|
86225
|
+
function reclaimIdleWorld() {
|
|
86226
|
+
const held = tenantsWithSessions();
|
|
86227
|
+
const tier1 = leastRecentlyActive((k, w) => isReclaimable(k, w, held));
|
|
86228
|
+
if (tier1) {
|
|
86229
|
+
dropWorld(tier1[0], tier1[1], "capacity reclamation (least recently active idle world)");
|
|
86230
|
+
return true;
|
|
86231
|
+
}
|
|
86232
|
+
const tier2 = leastRecentlyActive((_k, w) => isEvictable(w));
|
|
86233
|
+
if (!tier2) return false;
|
|
86234
|
+
for (const [sid, session] of [...sessions]) {
|
|
86235
|
+
if (session.tenant !== tier2[0]) continue;
|
|
86236
|
+
sessions.delete(sid);
|
|
86237
|
+
void session.transport.close().catch(() => void 0);
|
|
86238
|
+
}
|
|
86239
|
+
dropWorld(tier2[0], tier2[1], "capacity eviction (least recently active world; its sessions were closed)");
|
|
85739
86240
|
return true;
|
|
85740
86241
|
}
|
|
85741
86242
|
class TenantCapacityError extends Error {
|
|
@@ -85953,7 +86454,8 @@ function composeConnector(opts, rawPublicOrigin) {
|
|
|
85953
86454
|
if (opts.auth) {
|
|
85954
86455
|
authImpl = opts.auth;
|
|
85955
86456
|
} else {
|
|
85956
|
-
const
|
|
86457
|
+
const envWcProjectId = resolvedWcProjectId(opts.env);
|
|
86458
|
+
const wcLeg = opts.siweWc ?? (envWcProjectId !== void 0 ? { projectId: envWcProjectId } : void 0);
|
|
85957
86459
|
const siwe = new SiweOAuthProvider({
|
|
85958
86460
|
origin: () => publicOrigin,
|
|
85959
86461
|
chainId: launchNetwork === "mainnet" ? 1 : 11155111,
|