@gvnrdao/dh-mcp 0.5.9 → 0.5.11
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 +5 -3
- package/connector-embed.d.ts +23 -0
- package/dist/boundary.js +67 -35
- package/dist/connector-embed.js +2156 -1399
- package/dist/connector.js +2166 -1392
- package/dist/index.js +1369 -1050
- package/package.json +6 -5
package/dist/connector.js
CHANGED
|
@@ -617,7 +617,7 @@ var require_utils = __commonJS({
|
|
|
617
617
|
exports2.createHasher = createHasher2;
|
|
618
618
|
exports2.createOptHasher = createOptHasher;
|
|
619
619
|
exports2.createXOFer = createXOFer;
|
|
620
|
-
exports2.randomBytes =
|
|
620
|
+
exports2.randomBytes = randomBytes5;
|
|
621
621
|
var crypto_1 = require_cryptoNode();
|
|
622
622
|
function isBytes2(a) {
|
|
623
623
|
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
@@ -815,7 +815,7 @@ var require_utils = __commonJS({
|
|
|
815
815
|
exports2.wrapConstructor = createHasher2;
|
|
816
816
|
exports2.wrapConstructorWithOpts = createOptHasher;
|
|
817
817
|
exports2.wrapXOFConstructorWithOpts = createXOFer;
|
|
818
|
-
function
|
|
818
|
+
function randomBytes5(bytesLength = 32) {
|
|
819
819
|
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
|
|
820
820
|
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
|
|
821
821
|
}
|
|
@@ -40619,19 +40619,208 @@ var net = __toESM(require("net"));
|
|
|
40619
40619
|
|
|
40620
40620
|
// src/connector/service.ts
|
|
40621
40621
|
var import_node_http = require("http");
|
|
40622
|
-
var
|
|
40622
|
+
var import_node_crypto10 = require("crypto");
|
|
40623
40623
|
var import_express = __toESM(require("express"));
|
|
40624
40624
|
var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
40625
40625
|
var import_router = require("@modelcontextprotocol/sdk/server/auth/router.js");
|
|
40626
40626
|
var import_types4 = require("@modelcontextprotocol/sdk/types.js");
|
|
40627
40627
|
|
|
40628
|
+
// src/connector/auth-md.ts
|
|
40629
|
+
var CHAIN_IDS = { mainnet: 1, sepolia: 11155111 };
|
|
40630
|
+
function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled }) {
|
|
40631
|
+
const origin2 = publicOrigin.replace(/\/+$/, "");
|
|
40632
|
+
const launchNetwork = networks2[0];
|
|
40633
|
+
if (launchNetwork === void 0) {
|
|
40634
|
+
throw new Error("renderAuthMd: networks must name at least one network");
|
|
40635
|
+
}
|
|
40636
|
+
const chainId = CHAIN_IDS[launchNetwork];
|
|
40637
|
+
if (chainId === void 0) {
|
|
40638
|
+
throw new Error(
|
|
40639
|
+
`renderAuthMd: no chain id known for network '${launchNetwork}' \u2014 allowed: ${Object.keys(CHAIN_IDS).join(", ")}`
|
|
40640
|
+
);
|
|
40641
|
+
}
|
|
40642
|
+
const isMainnet = launchNetwork === "mainnet";
|
|
40643
|
+
const wcLine = walletConnectEnabled ? "" : " **Mobile WalletConnect sign-in is not enabled on this deployment** \u2014 browser extension or own-key only.";
|
|
40644
|
+
const agentAuth = {
|
|
40645
|
+
agent_auth: {
|
|
40646
|
+
skill: "operate-position",
|
|
40647
|
+
register_uri: `${origin2}/register`,
|
|
40648
|
+
authorization_servers: [`${origin2}/`],
|
|
40649
|
+
resource: `${origin2}/mcp`,
|
|
40650
|
+
methods: [
|
|
40651
|
+
{
|
|
40652
|
+
type: "oauth2",
|
|
40653
|
+
registration: "rfc7591-dynamic-client-registration",
|
|
40654
|
+
register_uri: `${origin2}/register`,
|
|
40655
|
+
authorization_uri: `${origin2}/authorize`,
|
|
40656
|
+
token_uri: `${origin2}/token`,
|
|
40657
|
+
revocation_uri: `${origin2}/revoke`,
|
|
40658
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
40659
|
+
response_types_supported: ["code"],
|
|
40660
|
+
code_challenge_methods_supported: ["S256"],
|
|
40661
|
+
token_endpoint_auth_methods_supported: ["client_secret_post", "none"],
|
|
40662
|
+
bearer_methods_supported: ["header"],
|
|
40663
|
+
identity_types_supported: ["wallet_signature"],
|
|
40664
|
+
wallet_signature: {
|
|
40665
|
+
standard: "EIP-4361",
|
|
40666
|
+
chain_id: chainId,
|
|
40667
|
+
credential_types_supported: ["access_token", "refresh_token"]
|
|
40668
|
+
}
|
|
40669
|
+
}
|
|
40670
|
+
]
|
|
40671
|
+
}
|
|
40672
|
+
};
|
|
40673
|
+
return `# auth.md
|
|
40674
|
+
|
|
40675
|
+
> Agent authentication and registration for Diamond Hands \u2014 a self-custodial Bitcoin
|
|
40676
|
+
> line of credit. Lock native BTC in an isolated L1 vault, mint UCD against it, keep
|
|
40677
|
+
> the Bitcoin.
|
|
40678
|
+
|
|
40679
|
+
This document is for **autonomous agents** that operate a Bitcoin-collateralized UCD
|
|
40680
|
+
position on behalf of the person who owns the wallet. It is generated from this
|
|
40681
|
+
deployment's live configuration, so the endpoints and the chain id below are the ones
|
|
40682
|
+
actually being served.
|
|
40683
|
+
|
|
40684
|
+
## Agent service
|
|
40685
|
+
|
|
40686
|
+
| | |
|
|
40687
|
+
|---|---|
|
|
40688
|
+
| Protocol | Model Context Protocol (MCP), streamable HTTP |
|
|
40689
|
+
| Endpoint | \`${origin2}/mcp\` |
|
|
40690
|
+
| Network | ${isMainnet ? "Ethereum mainnet (chain id 1) \u2014 real BTC, real UCD" : `${launchNetwork} (chain id ${chainId}) \u2014 test network, test funds`} |
|
|
40691
|
+
| Protected resource metadata | ${origin2}/.well-known/oauth-protected-resource |
|
|
40692
|
+
| Authorization server metadata | ${origin2}/.well-known/oauth-authorization-server |
|
|
40693
|
+
|
|
40694
|
+
\`\`\`json
|
|
40695
|
+
{
|
|
40696
|
+
"mcpServers": {
|
|
40697
|
+
"diamond-hands": {
|
|
40698
|
+
"type": "http",
|
|
40699
|
+
"url": "${origin2}/mcp"
|
|
40700
|
+
}
|
|
40701
|
+
}
|
|
40702
|
+
}
|
|
40703
|
+
\`\`\`
|
|
40704
|
+
|
|
40705
|
+
## agent_auth
|
|
40706
|
+
|
|
40707
|
+
\`\`\`json
|
|
40708
|
+
${JSON.stringify(agentAuth, null, 2)}
|
|
40709
|
+
\`\`\`
|
|
40710
|
+
|
|
40711
|
+
### The registration flow, end to end
|
|
40712
|
+
|
|
40713
|
+
1. **Register.** \`POST ${origin2}/register\` \u2014 RFC 7591 dynamic client registration,
|
|
40714
|
+
open, no pre-shared credential. You receive a \`client_id\`.
|
|
40715
|
+
2. **Authorize.** Send the user to \`${origin2}/authorize\` with \`response_type=code\`,
|
|
40716
|
+
your \`client_id\`, \`redirect_uri\`, and a PKCE \`code_challenge\` (\`S256\` \u2014
|
|
40717
|
+
required).
|
|
40718
|
+
3. **Sign in.** One Sign-In-with-Ethereum signature (EIP-4361) over a message this
|
|
40719
|
+
server minted for that flow. Nothing you supply is parsed back \u2014 the server verifies
|
|
40720
|
+
against its own canonical text, and pins the chain id itself. A person signs this in
|
|
40721
|
+
a browser wallet extension; an agent holding its own key signs the same message
|
|
40722
|
+
through the flow's JSON endpoints.${wcLine}
|
|
40723
|
+
4. **Exchange.** \`POST ${origin2}/token\` with the code and your \`code_verifier\`. You
|
|
40724
|
+
get an access token and a refresh token.
|
|
40725
|
+
5. **Call.** Send the access token to \`${origin2}/mcp\` as
|
|
40726
|
+
\`Authorization: Bearer <token>\`. Unauthenticated calls answer \`401\` with a
|
|
40727
|
+
JSON-RPC error, not a redirect.
|
|
40728
|
+
|
|
40729
|
+
### What the credential is, and is not
|
|
40730
|
+
|
|
40731
|
+
The **wallet address is the account.** There are no passwords, no email addresses, and
|
|
40732
|
+
no user database. Registration creates an OAuth client, not a Diamond Hands account \u2014
|
|
40733
|
+
there is nothing to delete, and no personal data is collected.
|
|
40734
|
+
|
|
40735
|
+
The access token proves **session identity only**. It can read what that address could
|
|
40736
|
+
already read, and it can *stage* a fund-moving operation \u2014 arm a mint, a repayment, a
|
|
40737
|
+
withdrawal \u2014 but it can never complete one: each of those terminates in a wallet
|
|
40738
|
+
signature over that specific operation, which the token cannot produce. So it is not a
|
|
40739
|
+
read-only credential, and it is not a spending one either. A stolen token cannot spend.
|
|
40740
|
+
|
|
40741
|
+
- Access token: ~1 hour. Refresh token: rotating, expires after inactivity.
|
|
40742
|
+
- All authorization state is held **in memory**. A service restart ends every session
|
|
40743
|
+
and the user signs in again. Nothing is persisted at rest.
|
|
40744
|
+
- \`scopes_supported\` is empty and tokens are minted with no scopes \u2014 this
|
|
40745
|
+
authorization server does not implement scoped access. Do not request a scope; you
|
|
40746
|
+
will not receive one.
|
|
40747
|
+
|
|
40748
|
+
### Who holds the wallet \u2014 read this before you rely on the approval step
|
|
40749
|
+
|
|
40750
|
+
This protocol authenticates **addresses, not people**. It cannot tell whether a
|
|
40751
|
+
signature came from a person clicking a wallet extension or from software holding a key,
|
|
40752
|
+
and it does not try to. Two arrangements are supported, and they have **materially
|
|
40753
|
+
different guarantees**. Be clear which one you are.
|
|
40754
|
+
|
|
40755
|
+
**1. You act for a person, on their wallet.** The human owns the position and signs each
|
|
40756
|
+
operation themselves. This is the arrangement the approval page is designed for: every
|
|
40757
|
+
fund-moving step raises a card the person reads and approves, and you cannot proceed
|
|
40758
|
+
without them. Your token gives you reads and the ability to *stage* a ceremony \u2014 never
|
|
40759
|
+
to complete one.
|
|
40760
|
+
|
|
40761
|
+
**2. You hold your own key and own your own position.** Nothing here treats you
|
|
40762
|
+
differently: you sign in with your key, you create and fund your own vault, you borrow
|
|
40763
|
+
against your own BTC. But then **you are the approver.** The approval card's "Approve
|
|
40764
|
+
ONLY if you initiated this exact BTC withdrawal" is addressed to a human reader, and
|
|
40765
|
+
there is no human in this arrangement. Do not present that step to your operator as
|
|
40766
|
+
independent oversight \u2014 it is not; you are satisfying it yourself.
|
|
40767
|
+
|
|
40768
|
+
What actually bounds arrangement 2 is **on-chain, not in this service**: a BTC
|
|
40769
|
+
withdrawal can only go to an address already on the position's on-chain allowlist, and
|
|
40770
|
+
adding one takes a separate, fully decodable transaction plus the registry's delay \u2014
|
|
40771
|
+
read live from the contract at execution${isMainnet ? " (24 hours on mainnet today)" : ""}.
|
|
40772
|
+
Treat that allowlist as your real safety boundary, and put an address on it
|
|
40773
|
+
deliberately.
|
|
40774
|
+
|
|
40775
|
+
**3. Acting on someone else's position with your own key** \u2014 a delegated agent key \u2014 is
|
|
40776
|
+
**not offered on this endpoint yet.** If you need it, do not attempt to approximate it
|
|
40777
|
+
by holding a person's key; contact us.
|
|
40778
|
+
|
|
40779
|
+
If your operator has asked you to run unattended, you are in arrangement 2. Say so
|
|
40780
|
+
plainly to them, and do not describe the approval step as human review.
|
|
40781
|
+
|
|
40782
|
+
### Flows this service does not offer
|
|
40783
|
+
|
|
40784
|
+
Stated plainly so a scanner does not infer otherwise: there is **no** ID-JAG
|
|
40785
|
+
(\`urn:ietf:params:oauth:token-type:id-jag\`) identity-assertion flow, **no**
|
|
40786
|
+
verified-email flow, and **no** anonymous flow. The only identity type is a wallet
|
|
40787
|
+
signature.
|
|
40788
|
+
|
|
40789
|
+
## Public data needs no credential
|
|
40790
|
+
|
|
40791
|
+
Protocol data \u2014 live loans, terms, the peg stability module \u2014 is public. Start at
|
|
40792
|
+
<https://app.diamondhands.credit/llms.txt>, or request any app page with
|
|
40793
|
+
\`Accept: text/markdown\`.
|
|
40794
|
+
|
|
40795
|
+
## Local alternative
|
|
40796
|
+
|
|
40797
|
+
An agent on the user's own machine can skip this service and talk to the protocol
|
|
40798
|
+
directly through the published MCP server, which carries the same tools:
|
|
40799
|
+
|
|
40800
|
+
- \`npx -y @gvnrdao/dh-mcp\` (requires Node \u2265 18)
|
|
40801
|
+
- \`curl -fsSL https://assets.gvnr.xyz/dh-mcp/install.sh | sh\` (self-contained binary)
|
|
40802
|
+
- Claude Desktop bundle and checksums: <https://assets.gvnr.xyz/dh-mcp/>
|
|
40803
|
+
|
|
40804
|
+
## Contact
|
|
40805
|
+
|
|
40806
|
+
Security contact and disclosure policy:
|
|
40807
|
+
<https://app.diamondhands.credit/.well-known/security.txt>
|
|
40808
|
+
|
|
40809
|
+
Do not probe \`POST /register\` or \`/authorize\` during passive scans. This document,
|
|
40810
|
+
the protected-resource metadata, and the authorization-server metadata are the safe
|
|
40811
|
+
source of truth.
|
|
40812
|
+
`;
|
|
40813
|
+
}
|
|
40814
|
+
|
|
40628
40815
|
// src/connector/siwe-oauth.ts
|
|
40629
|
-
var
|
|
40816
|
+
var import_node_crypto2 = require("crypto");
|
|
40630
40817
|
var import_ethers = require("ethers");
|
|
40631
40818
|
var import_errors = require("@modelcontextprotocol/sdk/server/auth/errors.js");
|
|
40632
40819
|
|
|
40633
40820
|
// src/connector/siwe-page.ts
|
|
40634
|
-
function renderSiwePage(
|
|
40821
|
+
function renderSiwePage(opts) {
|
|
40822
|
+
const { flowId, redirectHost, nonce } = opts;
|
|
40823
|
+
const clientName = clampClientName(opts.clientName);
|
|
40635
40824
|
return `<!DOCTYPE html>
|
|
40636
40825
|
<html>
|
|
40637
40826
|
<head>
|
|
@@ -40645,6 +40834,26 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
|
|
|
40645
40834
|
#status { margin-top: 1rem; color: #444; min-height: 1.5rem; }
|
|
40646
40835
|
.err { color: #b00020; }
|
|
40647
40836
|
.note { font-size: 0.85rem; color: #666; margin-top: 2rem; }
|
|
40837
|
+
/* "position: relative" is load-bearing, not cosmetic: it puts the consent box in its
|
|
40838
|
+
own stacking context so it paints ABOVE the inline content of the paragraph before
|
|
40839
|
+
it. Without it, a client name built from stacked combining marks overflows its line
|
|
40840
|
+
box downward and paints over this text \u2014 the CSS painting order draws every block
|
|
40841
|
+
background first, then all inline content in tree order. */
|
|
40842
|
+
.dest { background: #fff8e1; border-left: 3px solid #c77700; padding: 0.7rem 0.9rem; font-size: 0.9rem; position: relative; }
|
|
40843
|
+
/* The destination must stay legible under a host the attacker chose the length of:
|
|
40844
|
+
"overflow-wrap: anywhere" lets it wrap mid-label (a dot is not a break opportunity),
|
|
40845
|
+
and the isolate keeps any bidi control inside from reordering the sentence around
|
|
40846
|
+
it. splitRedirectHost has already bounded the length; this bounds the geometry. */
|
|
40847
|
+
.dest code { font-family: ui-monospace, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
|
|
40848
|
+
.dest .host-head { color: #5a5a5a; }
|
|
40849
|
+
.dest .host-tail { font-weight: 700; color: #000; }
|
|
40850
|
+
/* The elision is NOT decoration \u2014 it is the page admitting it withheld characters, so
|
|
40851
|
+
it must be as visible as the text it replaced. */
|
|
40852
|
+
.dest .host-cut { color: #c77700; font-weight: 700; font-style: normal; }
|
|
40853
|
+
/* The attacker-chosen name is clipped to a fixed box: bounded characters alone do not
|
|
40854
|
+
bound HEIGHT (combining marks stack vertically), and an isolate stops an unpaired
|
|
40855
|
+
RTL override inside the name from reversing the rest of the sentence. */
|
|
40856
|
+
.cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 700; }
|
|
40648
40857
|
#qr { max-width: 16rem; margin-top: 1rem; }
|
|
40649
40858
|
#qr svg { width: 100%; height: auto; }
|
|
40650
40859
|
#wc-uri { font-size: 0.7rem; word-break: break-all; color: #888; }
|
|
@@ -40652,14 +40861,15 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
|
|
|
40652
40861
|
</head>
|
|
40653
40862
|
<body>
|
|
40654
40863
|
<h1>Sign in to Diamond Hands</h1>
|
|
40655
|
-
<p><
|
|
40864
|
+
<p><span class="cname" dir="ltr">${escapeHtml(clientName)}</span> is asking to connect. Signing in proves you own a wallet address \u2014 it authorizes nothing on-chain and can never move funds.</p>
|
|
40865
|
+
<p class="dest">When you sign, this connection is handed to <code dir="ltr">${renderRedirectHost(redirectHost)}</code>. Anyone can register a client under any name, so read the host, not the name \u2014 and read it from the <b>bold end</b>, which is the part that decides who actually owns it. If you do not recognize it, close this page; nothing has happened yet.</p>
|
|
40656
40866
|
<button id="connect">Browser wallet</button>
|
|
40657
40867
|
<button id="wc">Mobile wallet (QR)</button>
|
|
40658
40868
|
<div id="status"></div>
|
|
40659
40869
|
<div id="qr"></div>
|
|
40660
40870
|
<p id="wc-uri"></p>
|
|
40661
40871
|
<p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect).</p>
|
|
40662
|
-
<script>
|
|
40872
|
+
<script nonce="${nonce}">
|
|
40663
40873
|
const FLOW = ${JSON.stringify(flowId)};
|
|
40664
40874
|
const statusEl = document.getElementById("status");
|
|
40665
40875
|
function show(text, isErr) { statusEl.textContent = text; statusEl.className = isErr ? "err" : ""; }
|
|
@@ -40730,6 +40940,46 @@ document.getElementById("wc").addEventListener("click", async () => {
|
|
|
40730
40940
|
function escapeHtml(s) {
|
|
40731
40941
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
40732
40942
|
}
|
|
40943
|
+
var MAX_CLIENT_NAME_CHARS = 64;
|
|
40944
|
+
var HOST_TAIL_CHARS = 48;
|
|
40945
|
+
var HOST_HEAD_CHARS = 12;
|
|
40946
|
+
var HOST_TAIL_LABELS = 3;
|
|
40947
|
+
var HOST_ELISION_FLOOR = 12;
|
|
40948
|
+
var MAX_HOST_DISPLAY_CHARS = HOST_HEAD_CHARS + HOST_TAIL_CHARS + 24;
|
|
40949
|
+
function splitRedirectHost(host) {
|
|
40950
|
+
const labels = host.split(".");
|
|
40951
|
+
const labelTail = labels.slice(-HOST_TAIL_LABELS).join(".");
|
|
40952
|
+
const tailStart = Math.max(host.length - labelTail.length, host.length - HOST_TAIL_CHARS, 0);
|
|
40953
|
+
const tail = host.slice(tailStart);
|
|
40954
|
+
const fullHead = host.slice(0, tailStart);
|
|
40955
|
+
if (fullHead.length <= HOST_HEAD_CHARS + HOST_ELISION_FLOOR) return { head: fullHead, elided: 0, tail };
|
|
40956
|
+
return { head: fullHead.slice(0, HOST_HEAD_CHARS), elided: fullHead.length - HOST_HEAD_CHARS, tail };
|
|
40957
|
+
}
|
|
40958
|
+
function renderRedirectHost(host) {
|
|
40959
|
+
const { head, elided, tail } = splitRedirectHost(host);
|
|
40960
|
+
const cut = elided === 0 ? "" : `<span class="host-cut">\u2026+${elided} chars\u2026</span>`;
|
|
40961
|
+
return `<span class="host-head">${escapeHtml(head)}</span>${cut}<span class="host-tail">${escapeHtml(tail)}</span>`;
|
|
40962
|
+
}
|
|
40963
|
+
function clampClientName(name) {
|
|
40964
|
+
const points = [...name];
|
|
40965
|
+
if (points.length <= MAX_CLIENT_NAME_CHARS) return name;
|
|
40966
|
+
return `${points.slice(0, MAX_CLIENT_NAME_CHARS - 1).join("")}\u2026`;
|
|
40967
|
+
}
|
|
40968
|
+
|
|
40969
|
+
// src/util/page-headers.ts
|
|
40970
|
+
var import_node_crypto = require("crypto");
|
|
40971
|
+
function htmlPageSecurityHeaders() {
|
|
40972
|
+
const nonce = (0, import_node_crypto.randomBytes)(16).toString("base64");
|
|
40973
|
+
return {
|
|
40974
|
+
nonce,
|
|
40975
|
+
headers: {
|
|
40976
|
+
"Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
|
|
40977
|
+
"X-Frame-Options": "DENY",
|
|
40978
|
+
"Referrer-Policy": "no-referrer",
|
|
40979
|
+
"X-Content-Type-Options": "nosniff"
|
|
40980
|
+
}
|
|
40981
|
+
};
|
|
40982
|
+
}
|
|
40733
40983
|
|
|
40734
40984
|
// src/connector/siwe-oauth.ts
|
|
40735
40985
|
var FLOW_TTL_MS = 10 * 60 * 1e3;
|
|
@@ -40758,6 +41008,12 @@ var SiweOAuthProvider = class {
|
|
|
40758
41008
|
return {
|
|
40759
41009
|
getClient: (clientId) => clients.get(clientId),
|
|
40760
41010
|
registerClient: (client) => {
|
|
41011
|
+
const name = client.client_name;
|
|
41012
|
+
if (name !== void 0 && [...name].length > MAX_CLIENT_NAME_CHARS) {
|
|
41013
|
+
throw new import_errors.InvalidClientMetadataError(
|
|
41014
|
+
`client_name is ${[...name].length} characters \u2014 this authorization server displays it on a consent screen and accepts at most ${MAX_CLIENT_NAME_CHARS}`
|
|
41015
|
+
);
|
|
41016
|
+
}
|
|
40761
41017
|
while (clients.size >= maxClients) {
|
|
40762
41018
|
const oldest = clients.keys().next().value;
|
|
40763
41019
|
if (oldest === void 0) break;
|
|
@@ -40768,12 +41024,28 @@ var SiweOAuthProvider = class {
|
|
|
40768
41024
|
}
|
|
40769
41025
|
};
|
|
40770
41026
|
}
|
|
40771
|
-
/** SDK authorize handler → we render the SIWE sign-in page for this flow.
|
|
41027
|
+
/** SDK authorize handler → we render the SIWE sign-in page for this flow.
|
|
41028
|
+
*
|
|
41029
|
+
* C-45: the page is a PUBLIC sign-in surface served ahead of any host helmet, so this
|
|
41030
|
+
* response carries its own security headers, and the page names the redirect HOST —
|
|
41031
|
+
* the consent fact that open registration makes `client_name` unable to carry. */
|
|
40772
41032
|
async authorize(client, params, res) {
|
|
40773
41033
|
this.sweep();
|
|
40774
|
-
const flowId = (0,
|
|
41034
|
+
const flowId = (0, import_node_crypto2.randomBytes)(16).toString("hex");
|
|
40775
41035
|
this.flows.set(flowId, { clientId: client.client_id, params, createdAt: this.clock() });
|
|
40776
|
-
|
|
41036
|
+
const page = htmlPageSecurityHeaders();
|
|
41037
|
+
for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
|
|
41038
|
+
res.status(200).type("html").send(
|
|
41039
|
+
renderSiwePage({
|
|
41040
|
+
flowId,
|
|
41041
|
+
clientName: client.client_name ?? client.client_id,
|
|
41042
|
+
// Parseable by the time authorize() runs: the SDK validates every registered
|
|
41043
|
+
// redirect_uri (SafeUrlSchema) and, for a request-supplied one, URL.canParse
|
|
41044
|
+
// plus a registered-URI match — so this constructor cannot throw here.
|
|
41045
|
+
redirectHost: new URL(params.redirectUri).host,
|
|
41046
|
+
nonce: page.nonce
|
|
41047
|
+
})
|
|
41048
|
+
);
|
|
40777
41049
|
}
|
|
40778
41050
|
/** Page step 1: the wallet reported its address — mint the CANONICAL SIWE message.
|
|
40779
41051
|
* Re-calling rebinds (the user switched wallet accounts before signing). The chain id
|
|
@@ -40790,7 +41062,7 @@ var SiweOAuthProvider = class {
|
|
|
40790
41062
|
mintSiweMessage(checksummedAddress) {
|
|
40791
41063
|
const origin2 = this.opts.origin();
|
|
40792
41064
|
const domain = new URL(origin2).host;
|
|
40793
|
-
const nonce = (0,
|
|
41065
|
+
const nonce = (0, import_node_crypto2.randomBytes)(8).toString("hex");
|
|
40794
41066
|
return `${domain} wants you to sign in with your Ethereum account:
|
|
40795
41067
|
${checksummedAddress}
|
|
40796
41068
|
|
|
@@ -40889,7 +41161,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
|
|
|
40889
41161
|
void transport.close().catch(() => void 0);
|
|
40890
41162
|
return;
|
|
40891
41163
|
}
|
|
40892
|
-
const code = (0,
|
|
41164
|
+
const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
|
|
40893
41165
|
this.codes.set(code, {
|
|
40894
41166
|
clientId: flow.clientId,
|
|
40895
41167
|
address: checksummed,
|
|
@@ -40956,7 +41228,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
|
|
|
40956
41228
|
return { ok: false, status: 401, reason: "the signature does not match the connected wallet address" };
|
|
40957
41229
|
}
|
|
40958
41230
|
this.deleteFlow(flowId, flow);
|
|
40959
|
-
const code = (0,
|
|
41231
|
+
const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
|
|
40960
41232
|
this.codes.set(code, {
|
|
40961
41233
|
clientId: flow.clientId,
|
|
40962
41234
|
address: flow.siwe.address,
|
|
@@ -41014,8 +41286,8 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
|
|
|
41014
41286
|
if (r && r.clientId === client.client_id) this.refresh.delete(request.token);
|
|
41015
41287
|
}
|
|
41016
41288
|
mintTokens(address, clientId) {
|
|
41017
|
-
const accessToken = (0,
|
|
41018
|
-
const refreshToken = (0,
|
|
41289
|
+
const accessToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
|
|
41290
|
+
const refreshToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
|
|
41019
41291
|
this.access.set(accessToken, { address, clientId, expiresAt: Math.floor(this.clock() / 1e3) + ACCESS_TTL_S });
|
|
41020
41292
|
this.refresh.set(refreshToken, { address, clientId, lastUsed: this.clock() });
|
|
41021
41293
|
return { access_token: accessToken, token_type: "bearer", expires_in: ACCESS_TTL_S, refresh_token: refreshToken };
|
|
@@ -41261,7 +41533,7 @@ var fs6 = __toESM(require("fs"));
|
|
|
41261
41533
|
var import_ethers40 = require("ethers");
|
|
41262
41534
|
|
|
41263
41535
|
// src/boundary/index.ts
|
|
41264
|
-
var
|
|
41536
|
+
var import_node_crypto9 = require("crypto");
|
|
41265
41537
|
var fs5 = __toESM(require("fs"));
|
|
41266
41538
|
var os2 = __toESM(require("os"));
|
|
41267
41539
|
var path4 = __toESM(require("path"));
|
|
@@ -42285,7 +42557,7 @@ var DEFAULT_SEED = {
|
|
|
42285
42557
|
};
|
|
42286
42558
|
|
|
42287
42559
|
// src/boundary/upstream/mock/world.ts
|
|
42288
|
-
var
|
|
42560
|
+
var import_node_crypto3 = require("crypto");
|
|
42289
42561
|
var import_ethers3 = require("ethers");
|
|
42290
42562
|
|
|
42291
42563
|
// src/signer/safe.ts
|
|
@@ -42489,7 +42761,7 @@ var World = class {
|
|
|
42489
42761
|
nextId(prefix) {
|
|
42490
42762
|
this.state.counter += 1;
|
|
42491
42763
|
const n = this.state.counter;
|
|
42492
|
-
const hash = (0,
|
|
42764
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
|
|
42493
42765
|
return { n, hash };
|
|
42494
42766
|
}
|
|
42495
42767
|
nextTxRef() {
|
|
@@ -42769,11 +43041,10 @@ var World = class {
|
|
|
42769
43041
|
const spend = BigInt(p.amountSats);
|
|
42770
43042
|
const fee = BigInt(p.networkFeeSats);
|
|
42771
43043
|
const available = this.availableSats(p.positionId);
|
|
42772
|
-
if (spend
|
|
42773
|
-
const maxSpend = available > fee ? available - fee : 0n;
|
|
43044
|
+
if (spend > available) {
|
|
42774
43045
|
return {
|
|
42775
43046
|
ok: false,
|
|
42776
|
-
reason: `withdrawal of ${spend.toString()} sats
|
|
43047
|
+
reason: `withdrawal of ${spend.toString()} sats exceeds the ${available.toString()} sats available (TargetExceedsInputValue) \u2014 max amountSats now is ${available.toString()} (destination then receives ${(available > fee ? available - fee : 0n).toString()} after the fee)`
|
|
42777
43048
|
};
|
|
42778
43049
|
}
|
|
42779
43050
|
const debt = BigInt(pos.debtUcdWei);
|
|
@@ -43369,7 +43640,7 @@ var WorldStore = class {
|
|
|
43369
43640
|
};
|
|
43370
43641
|
|
|
43371
43642
|
// src/boundary/upstream/mock/signer.ts
|
|
43372
|
-
var
|
|
43643
|
+
var import_node_crypto4 = require("crypto");
|
|
43373
43644
|
function mockSign(op, borrower, stance) {
|
|
43374
43645
|
if (stance === "decline") {
|
|
43375
43646
|
return {
|
|
@@ -43384,7 +43655,7 @@ function mockSign(op, borrower, stance) {
|
|
|
43384
43655
|
signer: borrower,
|
|
43385
43656
|
action: op.action,
|
|
43386
43657
|
card: op.card,
|
|
43387
|
-
digest: (0,
|
|
43658
|
+
digest: (0, import_node_crypto4.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
|
|
43388
43659
|
}
|
|
43389
43660
|
};
|
|
43390
43661
|
}
|
|
@@ -44656,7 +44927,7 @@ var MockUpstreamPlugin = class {
|
|
|
44656
44927
|
};
|
|
44657
44928
|
|
|
44658
44929
|
// src/boundary/upstream/mock/external-ceremony.ts
|
|
44659
|
-
var
|
|
44930
|
+
var import_node_crypto5 = require("crypto");
|
|
44660
44931
|
var import_node_child_process = require("child_process");
|
|
44661
44932
|
var import_ethers10 = require("ethers");
|
|
44662
44933
|
|
|
@@ -44849,7 +45120,7 @@ var ExternalCeremony = class {
|
|
|
44849
45120
|
validateUnsignedTx({ ...p.tx }, p.expected, this.deps.vctx);
|
|
44850
45121
|
const card = cardForTx(p.tx);
|
|
44851
45122
|
const outcome = await this.request({
|
|
44852
|
-
id: (0,
|
|
45123
|
+
id: (0, import_node_crypto5.randomUUID)(),
|
|
44853
45124
|
kind: "transaction",
|
|
44854
45125
|
action: p.action,
|
|
44855
45126
|
card,
|
|
@@ -44894,7 +45165,7 @@ var ExternalCeremony = class {
|
|
|
44894
45165
|
message
|
|
44895
45166
|
};
|
|
44896
45167
|
const outcome = await this.request({
|
|
44897
|
-
id: (0,
|
|
45168
|
+
id: (0, import_node_crypto5.randomUUID)(),
|
|
44898
45169
|
kind: "typed-data",
|
|
44899
45170
|
action: "login",
|
|
44900
45171
|
card: cardForTypedData("login", typedData),
|
|
@@ -44922,7 +45193,7 @@ var ExternalCeremony = class {
|
|
|
44922
45193
|
});
|
|
44923
45194
|
const card = cardForTypedData(p.action, typedData);
|
|
44924
45195
|
const outcome = await this.request({
|
|
44925
|
-
id: (0,
|
|
45196
|
+
id: (0, import_node_crypto5.randomUUID)(),
|
|
44926
45197
|
kind: "typed-data",
|
|
44927
45198
|
action: p.action,
|
|
44928
45199
|
card,
|
|
@@ -45097,7 +45368,7 @@ var KeystoreCeremony = class {
|
|
|
45097
45368
|
};
|
|
45098
45369
|
|
|
45099
45370
|
// src/boundary/upstream/mock/safe-ceremony.ts
|
|
45100
|
-
var
|
|
45371
|
+
var import_node_crypto6 = require("crypto");
|
|
45101
45372
|
var import_ethers12 = require("ethers");
|
|
45102
45373
|
init_tx_validator();
|
|
45103
45374
|
|
|
@@ -45398,7 +45669,7 @@ var SafeCeremony = class {
|
|
|
45398
45669
|
const primaryType = Object.keys(build.payload.types)[0];
|
|
45399
45670
|
const outcome = await bridge.requestSignatureCollection(
|
|
45400
45671
|
{
|
|
45401
|
-
id: (0,
|
|
45672
|
+
id: (0, import_node_crypto6.randomUUID)(),
|
|
45402
45673
|
kind: "typed-data",
|
|
45403
45674
|
action,
|
|
45404
45675
|
card: build.card,
|
|
@@ -51954,9 +52225,9 @@ var init_deployment_addresses = __esm2({
|
|
|
51954
52225
|
reason: "Shared upgrade script: LiquidationManagerModule implementation update"
|
|
51955
52226
|
},
|
|
51956
52227
|
BTCSpendAuthorizer: {
|
|
51957
|
-
previousImplementation: "
|
|
51958
|
-
newImplementation: "
|
|
51959
|
-
upgradedAt: "2026-
|
|
52228
|
+
previousImplementation: "0xdd3DFaEc50d6214d57eA64e8b76ff318b501607b",
|
|
52229
|
+
newImplementation: "0xf3282B5A1AE6428ee1b08cfaAF4EB4e198877484",
|
|
52230
|
+
upgradedAt: "2026-09-06T15:03:13.627Z",
|
|
51960
52231
|
upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
|
|
51961
52232
|
reason: "Shared upgrade script: BTCSpendAuthorizer implementation update"
|
|
51962
52233
|
},
|
|
@@ -52022,6 +52293,13 @@ var init_deployment_addresses = __esm2({
|
|
|
52022
52293
|
upgradedAt: "2026-07-07T16:56:49.844Z",
|
|
52023
52294
|
upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
|
|
52024
52295
|
reason: "Shared upgrade script: BitcoinWithdrawalAddressRegistry implementation update"
|
|
52296
|
+
},
|
|
52297
|
+
AgentDelegationRegistry: {
|
|
52298
|
+
previousImplementation: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
|
|
52299
|
+
newImplementation: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
|
|
52300
|
+
upgradedAt: "2026-09-06T15:06:02.814Z",
|
|
52301
|
+
upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
|
|
52302
|
+
reason: "Reconciled implementation from chain"
|
|
52025
52303
|
}
|
|
52026
52304
|
},
|
|
52027
52305
|
history: {
|
|
@@ -52107,7 +52385,7 @@ var init_deployment_addresses = __esm2({
|
|
|
52107
52385
|
LIQUIDATION_MANAGER_MODULE: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76",
|
|
52108
52386
|
LIQUIDATION_MANAGER_MODULE_IMPL: "0xCe7587C47094BBb3dCa13D7a2299Ec9beA6cd759",
|
|
52109
52387
|
BTC_SPEND_AUTHORIZER: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
|
|
52110
|
-
BTC_SPEND_AUTHORIZER_IMPL: "
|
|
52388
|
+
BTC_SPEND_AUTHORIZER_IMPL: "0xf3282B5A1AE6428ee1b08cfaAF4EB4e198877484",
|
|
52111
52389
|
UPGRADE_VALIDATOR: "0x592e650edD9bA26ecc407989fdd6F9cdcDeC27A6",
|
|
52112
52390
|
UPGRADE_VALIDATOR_IMPL: "0x9E70e1D07AB11ac9dD37B67AA091Efe97d7Ed84b",
|
|
52113
52391
|
BITCOIN_PROVIDER_REGISTRY: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
|
|
@@ -59225,12 +59503,12 @@ async function reconcileAuthorizedSpend(spend, esploraBaseUrl, httpGetJson = def
|
|
|
59225
59503
|
{ txid: spend.txid, vout: spend.vout }
|
|
59226
59504
|
);
|
|
59227
59505
|
}
|
|
59228
|
-
if (spend.targetAmount
|
|
59506
|
+
if (spend.targetAmount > spend.satoshis) {
|
|
59229
59507
|
return {
|
|
59230
59508
|
spend,
|
|
59231
59509
|
status: "CORRUPT",
|
|
59232
59510
|
onChainOutputValue,
|
|
59233
|
-
reason: `Authorized targetAmount ${spend.targetAmount} sats
|
|
59511
|
+
reason: `Authorized targetAmount ${spend.targetAmount} sats exceeds the ${spend.satoshis}-sat aggregate input value \u2014 the contract could never have authorized this`
|
|
59234
59512
|
};
|
|
59235
59513
|
}
|
|
59236
59514
|
const outspendRes = await httpGetJson(
|
|
@@ -79994,7 +80272,7 @@ var EoaDHSigner = class {
|
|
|
79994
80272
|
};
|
|
79995
80273
|
|
|
79996
80274
|
// src/signer/external-eoa.ts
|
|
79997
|
-
var
|
|
80275
|
+
var import_node_crypto7 = require("crypto");
|
|
79998
80276
|
var import_ethers38 = require("ethers");
|
|
79999
80277
|
|
|
80000
80278
|
// src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
|
|
@@ -80088,7 +80366,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80088
80366
|
let used = { quantumTs: initialTs, fields: initial.fields };
|
|
80089
80367
|
const outcome = await this.deps.bridge.requestSignature(
|
|
80090
80368
|
{
|
|
80091
|
-
id: (0,
|
|
80369
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80092
80370
|
kind: "personal-sign",
|
|
80093
80371
|
action: spec.action,
|
|
80094
80372
|
card: initial.card,
|
|
@@ -80122,7 +80400,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80122
80400
|
const approved = toApprovedTx(outerTx, this.deps.chainId);
|
|
80123
80401
|
const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
|
|
80124
80402
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80125
|
-
id: (0,
|
|
80403
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80126
80404
|
kind: "transaction",
|
|
80127
80405
|
action: ctx.action,
|
|
80128
80406
|
card: ctx.card,
|
|
@@ -80173,15 +80451,22 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80173
80451
|
}
|
|
80174
80452
|
const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
|
|
80175
80453
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80176
|
-
id: (0,
|
|
80454
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80177
80455
|
kind: "personal-sign",
|
|
80178
|
-
action: "btc-withdrawal
|
|
80456
|
+
action: "btc-withdrawal EXECUTE step (blind hash)",
|
|
80179
80457
|
card: [
|
|
80180
|
-
"BLIND SIGNATURE \u2014 BTC withdrawal
|
|
80458
|
+
"BLIND SIGNATURE \u2014 BTC withdrawal, EXECUTE step",
|
|
80181
80459
|
`hash: ${hashHex}`,
|
|
80182
80460
|
"This hash is built inside the SDK and its contents CANNOT be decoded or verified by this page",
|
|
80183
80461
|
"(identical to how diamondhands.credit signs withdrawals).",
|
|
80184
|
-
"Approve ONLY if you initiated this exact BTC withdrawal in the conversation."
|
|
80462
|
+
"Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
|
|
80463
|
+
"",
|
|
80464
|
+
"SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
|
|
80465
|
+
`raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
|
|
80466
|
+
"under a minute and often nearer twenty seconds \u2014 far less than the approval page",
|
|
80467
|
+
"itself allows. If it expires the signature is refused, the withdrawal does not",
|
|
80468
|
+
"complete, and the reserved coins stay reserved until that is cleared. Decline and",
|
|
80469
|
+
"start again rather than signing something you have not finished reading."
|
|
80185
80470
|
],
|
|
80186
80471
|
expectedSigner: this.deps.borrower,
|
|
80187
80472
|
chainId: this.deps.chainId,
|
|
@@ -80204,7 +80489,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80204
80489
|
message: value
|
|
80205
80490
|
};
|
|
80206
80491
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80207
|
-
id: (0,
|
|
80492
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80208
80493
|
kind: "typed-data",
|
|
80209
80494
|
action: "login",
|
|
80210
80495
|
card: cardForTypedData("login", typedData),
|
|
@@ -80230,7 +80515,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80230
80515
|
const card = cardForTx(approved);
|
|
80231
80516
|
const gas = tx2.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
|
|
80232
80517
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80233
|
-
id: (0,
|
|
80518
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80234
80519
|
kind: "transaction",
|
|
80235
80520
|
action: describeFn(approved.data),
|
|
80236
80521
|
card,
|
|
@@ -81114,10 +81399,10 @@ var RealUpstreamPlugin = class {
|
|
|
81114
81399
|
// src/boundary/upstream/shared/external-bridge/bridge.ts
|
|
81115
81400
|
var fs4 = __toESM(require("fs"));
|
|
81116
81401
|
var http3 = __toESM(require("http"));
|
|
81117
|
-
var
|
|
81402
|
+
var import_node_crypto8 = require("crypto");
|
|
81118
81403
|
|
|
81119
81404
|
// src/boundary/upstream/shared/external-bridge/approval-page.ts
|
|
81120
|
-
function renderApprovalPage(sessionId) {
|
|
81405
|
+
function renderApprovalPage(sessionId, nonce) {
|
|
81121
81406
|
return `<!doctype html>
|
|
81122
81407
|
<html lang="en">
|
|
81123
81408
|
<head>
|
|
@@ -81167,15 +81452,17 @@ function renderApprovalPage(sessionId) {
|
|
|
81167
81452
|
</div>
|
|
81168
81453
|
</div>
|
|
81169
81454
|
</main>
|
|
81170
|
-
<script>
|
|
81455
|
+
<script nonce="${nonce}">
|
|
81171
81456
|
${PAGE_CRYPTO_JS}
|
|
81172
81457
|
</script>
|
|
81173
|
-
<script>
|
|
81458
|
+
<script nonce="${nonce}">
|
|
81174
81459
|
"use strict";
|
|
81175
81460
|
const SESSION = ${JSON.stringify(sessionId)};
|
|
81176
81461
|
// One-time token leaves the address bar (and history) immediately.
|
|
81177
81462
|
// Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
|
|
81178
81463
|
// at loopback root ("/") and under a hosted tenant mount ("/approval/<id>/").
|
|
81464
|
+
// EVERY endpoint reference goes through BASE \u2014 an origin-absolute "/x" resolves to the
|
|
81465
|
+
// ORIGIN root, which on a mount is the host, not the bridge, and 404s silently.
|
|
81179
81466
|
const BASE = location.pathname.replace(/[^/]*$/, "");
|
|
81180
81467
|
history.replaceState(null, "", location.pathname);
|
|
81181
81468
|
|
|
@@ -81247,14 +81534,14 @@ async function connect() {
|
|
|
81247
81534
|
// wallet's own state transition and can report the stale value.
|
|
81248
81535
|
async function onAccountsChanged(accounts) {
|
|
81249
81536
|
account = (accounts && accounts[0]) || null;
|
|
81250
|
-
await post("
|
|
81537
|
+
await post(BASE + "wallet-event", { account: account, chainId: chainId });
|
|
81251
81538
|
showWallet();
|
|
81252
81539
|
clearRequest("Wallet changed \u2014 pending request invalidated.");
|
|
81253
81540
|
}
|
|
81254
81541
|
|
|
81255
81542
|
async function onChainChanged(cid) {
|
|
81256
81543
|
chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
|
|
81257
|
-
await post("
|
|
81544
|
+
await post(BASE + "wallet-event", { account: account, chainId: chainId });
|
|
81258
81545
|
showWallet();
|
|
81259
81546
|
clearRequest("Network changed \u2014 pending request invalidated.");
|
|
81260
81547
|
}
|
|
@@ -81362,7 +81649,7 @@ connect();
|
|
|
81362
81649
|
</body>
|
|
81363
81650
|
</html>`;
|
|
81364
81651
|
}
|
|
81365
|
-
function renderUnlockPage(sessionId) {
|
|
81652
|
+
function renderUnlockPage(sessionId, nonce) {
|
|
81366
81653
|
return `<!doctype html>
|
|
81367
81654
|
<html lang="en">
|
|
81368
81655
|
<head>
|
|
@@ -81404,7 +81691,7 @@ function renderUnlockPage(sessionId) {
|
|
|
81404
81691
|
<div id="status" class="status"></div>
|
|
81405
81692
|
</div>
|
|
81406
81693
|
</main>
|
|
81407
|
-
<script>
|
|
81694
|
+
<script nonce="${nonce}">
|
|
81408
81695
|
"use strict";
|
|
81409
81696
|
const SESSION = ${JSON.stringify(sessionId)};
|
|
81410
81697
|
// Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
|
|
@@ -81462,7 +81749,7 @@ var SignatureBridge = class {
|
|
|
81462
81749
|
/** Started state independent of the transport binding (mounted bridges own no server). */
|
|
81463
81750
|
started = false;
|
|
81464
81751
|
mount;
|
|
81465
|
-
token = (0,
|
|
81752
|
+
token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81466
81753
|
/** Hosted mounts: when the current page token was minted (rotation basis). */
|
|
81467
81754
|
tokenMintedAt = 0;
|
|
81468
81755
|
/** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
|
|
@@ -81499,7 +81786,7 @@ var SignatureBridge = class {
|
|
|
81499
81786
|
unlockUrl() {
|
|
81500
81787
|
if (!this.started) throw new Error("bridge is not started");
|
|
81501
81788
|
if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
|
|
81502
|
-
this.unlockToken = (0,
|
|
81789
|
+
this.unlockToken = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81503
81790
|
return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
|
|
81504
81791
|
}
|
|
81505
81792
|
/** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
|
|
@@ -81540,7 +81827,7 @@ var SignatureBridge = class {
|
|
|
81540
81827
|
if (this.mount) {
|
|
81541
81828
|
const now = this.clock();
|
|
81542
81829
|
if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
|
|
81543
|
-
this.token = (0,
|
|
81830
|
+
this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81544
81831
|
this.tokenMintedAt = now;
|
|
81545
81832
|
}
|
|
81546
81833
|
return `${this.mount.baseUrl}/?t=${this.token}`;
|
|
@@ -81756,7 +82043,7 @@ var SignatureBridge = class {
|
|
|
81756
82043
|
this.server = null;
|
|
81757
82044
|
this.started = false;
|
|
81758
82045
|
this.wallet = null;
|
|
81759
|
-
this.token = (0,
|
|
82046
|
+
this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81760
82047
|
this.tokenMintedAt = 0;
|
|
81761
82048
|
if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
|
|
81762
82049
|
void this.wcTransport?.close().catch(() => void 0);
|
|
@@ -81826,10 +82113,11 @@ var SignatureBridge = class {
|
|
|
81826
82113
|
this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
|
|
81827
82114
|
return;
|
|
81828
82115
|
}
|
|
81829
|
-
const sessionId = (0,
|
|
82116
|
+
const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81830
82117
|
this.sessions.set(sessionId, { wallet: null, sse: null });
|
|
81831
|
-
|
|
81832
|
-
res.
|
|
82118
|
+
const page = htmlPageSecurityHeaders();
|
|
82119
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
|
|
82120
|
+
res.end(renderApprovalPage(sessionId, page.nonce));
|
|
81833
82121
|
}
|
|
81834
82122
|
/** Target-network hints for the page's chain self-heal (session-gated). */
|
|
81835
82123
|
serveConfig(url2, res) {
|
|
@@ -81889,9 +82177,10 @@ var SignatureBridge = class {
|
|
|
81889
82177
|
return;
|
|
81890
82178
|
}
|
|
81891
82179
|
this.unlockToken = null;
|
|
81892
|
-
this.unlockSession = (0,
|
|
81893
|
-
|
|
81894
|
-
res.
|
|
82180
|
+
this.unlockSession = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
82181
|
+
const page = htmlPageSecurityHeaders();
|
|
82182
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
|
|
82183
|
+
res.end(renderUnlockPage(this.unlockSession, page.nonce));
|
|
81895
82184
|
}
|
|
81896
82185
|
async onUnlockSubmit(body, res) {
|
|
81897
82186
|
if (!this.keystoreUnlock) {
|
|
@@ -82137,7 +82426,7 @@ function createBoundary(config, opts) {
|
|
|
82137
82426
|
"createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
|
|
82138
82427
|
);
|
|
82139
82428
|
}
|
|
82140
|
-
const configFingerprint = (0,
|
|
82429
|
+
const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
|
|
82141
82430
|
if (opts?.ceremony) {
|
|
82142
82431
|
const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
|
|
82143
82432
|
const boundary2 = new BoundaryCore({
|
|
@@ -82306,7 +82595,7 @@ async function createRealBoundary(config, wallet, overrides) {
|
|
|
82306
82595
|
}
|
|
82307
82596
|
const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
|
|
82308
82597
|
await plugin.initWriteSdk();
|
|
82309
|
-
const configFingerprint = (0,
|
|
82598
|
+
const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
|
|
82310
82599
|
const capabilities = () => ({
|
|
82311
82600
|
reads: {
|
|
82312
82601
|
public: true,
|
|
@@ -82406,1239 +82695,406 @@ async function buildBoundary(configResult, overrides) {
|
|
|
82406
82695
|
return { boundaryResult: { ok: true, boundary }, signer, dispose };
|
|
82407
82696
|
}
|
|
82408
82697
|
|
|
82409
|
-
// src/
|
|
82410
|
-
var
|
|
82411
|
-
|
|
82412
|
-
|
|
82413
|
-
|
|
82414
|
-
|
|
82415
|
-
|
|
82416
|
-
|
|
82417
|
-
|
|
82418
|
-
|
|
82419
|
-
|
|
82420
|
-
|
|
82421
|
-
|
|
82422
|
-
|
|
82423
|
-
|
|
82424
|
-
|
|
82425
|
-
|
|
82426
|
-
|
|
82427
|
-
|
|
82428
|
-
|
|
82429
|
-
|
|
82430
|
-
|
|
82431
|
-
|
|
82432
|
-
|
|
82433
|
-
|
|
82434
|
-
|
|
82435
|
-
|
|
82436
|
-
|
|
82437
|
-
|
|
82438
|
-
|
|
82439
|
-
|
|
82440
|
-
|
|
82441
|
-
|
|
82442
|
-
|
|
82443
|
-
|
|
82444
|
-
|
|
82445
|
-
|
|
82446
|
-
|
|
82447
|
-
|
|
82448
|
-
|
|
82449
|
-
|
|
82450
|
-
|
|
82451
|
-
|
|
82452
|
-
|
|
82453
|
-
|
|
82454
|
-
|
|
82455
|
-
|
|
82456
|
-
|
|
82457
|
-
|
|
82458
|
-
|
|
82459
|
-
|
|
82460
|
-
|
|
82461
|
-
|
|
82462
|
-
|
|
82463
|
-
|
|
82464
|
-
|
|
82465
|
-
|
|
82466
|
-
|
|
82467
|
-
|
|
82468
|
-
|
|
82469
|
-
|
|
82698
|
+
// src/boundary/field-glossary.ts
|
|
82699
|
+
var FIELD_GLOSSARY = {
|
|
82700
|
+
// ---- identity / envelope structure ----
|
|
82701
|
+
positionId: "the position's 32-byte id (0x\u202664 hex) \u2014 the input every position_* tool takes",
|
|
82702
|
+
borrower: "the Ethereum address that owns the position (the borrowing identity)",
|
|
82703
|
+
vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
|
|
82704
|
+
pkpId: "internal id of the programmable key pair holding BTC custody for this position",
|
|
82705
|
+
id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
|
|
82706
|
+
kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
|
|
82707
|
+
fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
|
|
82708
|
+
// ---- position facts (chain) ----
|
|
82709
|
+
state: "lifecycle state. On position_status it is read from the CHAIN (authoritative); on position_list rows it is an INDEXER snapshot that can lag the chain. PENDING_DEPOSIT/PENDING_MINT mean 'not yet minted' \u2014 activation happens on the FIRST mint, never on deposit confirmation alone",
|
|
82710
|
+
termMonths: "the current term length in months",
|
|
82711
|
+
totalTermMonths: "cumulative months across the original term plus every extension",
|
|
82712
|
+
createdAt: "ISO timestamp the position was created",
|
|
82713
|
+
expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
|
|
82714
|
+
previousExpiryAt: "the expiry before the latest extension (null when never extended)",
|
|
82715
|
+
lastUpdatedAt: "ISO timestamp of the last state change",
|
|
82716
|
+
debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
|
|
82717
|
+
// ---- indexed health (indexer snapshot) ----
|
|
82718
|
+
indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
|
|
82719
|
+
collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
|
|
82720
|
+
healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
|
|
82721
|
+
asOf: "ISO timestamp the indexer snapshot was computed",
|
|
82722
|
+
basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
|
|
82723
|
+
// ---- collateral (live BTC view) ----
|
|
82724
|
+
collateral: "the live Bitcoin-side view of the position's vault",
|
|
82725
|
+
availableSats: "CONFIRMED collateral in satoshis, minus authorized (reserved) spends \u2014 deposits count only once their confirmations reach minConfirmations. null ONLY alongside a SOURCE_DEGRADED warning, never a fabricated zero",
|
|
82726
|
+
availableSource: "which source served availableSats (null when degraded)",
|
|
82727
|
+
pendingDeposits: "the LIVE per-transaction list of unconfirmed deposits \u2014 each entry carries its own confirmations count. EMPTY ARRAY = nothing unconfirmed in flight (not an error). null ONLY with a SOURCE_DEGRADED warning",
|
|
82728
|
+
txid: "Bitcoin transaction id",
|
|
82729
|
+
sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
|
|
82730
|
+
confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
|
|
82731
|
+
minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
|
|
82732
|
+
pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
|
|
82733
|
+
maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
|
|
82734
|
+
// ---- valuation ----
|
|
82735
|
+
valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
|
|
82736
|
+
btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82737
|
+
priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82738
|
+
priceSource: "which oracle served the price",
|
|
82739
|
+
collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
|
|
82740
|
+
currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
|
|
82741
|
+
maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
|
|
82742
|
+
liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
|
|
82743
|
+
maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
|
|
82744
|
+
maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
|
|
82745
|
+
liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
|
|
82746
|
+
reading: "conditional reading notes emitted by the server ONLY while a known misreading trap is live \u2014 treat them as authoritative instructions for interpreting this exact payload",
|
|
82747
|
+
// ---- list envelope ----
|
|
82748
|
+
items: "the rows of this page",
|
|
82749
|
+
page: "1-based page number of this response",
|
|
82750
|
+
pageSize: "requested rows per page",
|
|
82751
|
+
total: "total rows matching the filter across all pages",
|
|
82752
|
+
// ---- events ----
|
|
82753
|
+
positionCreated: "creation events (seq, time, selected term)",
|
|
82754
|
+
seq: "the event's sequence number within the position's history (ordering key)",
|
|
82755
|
+
at: "ISO timestamp of the event",
|
|
82756
|
+
selectedTerm: "term length chosen, in months",
|
|
82757
|
+
mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
|
|
82758
|
+
amountUcdWei: "the event's UCD amount in wei",
|
|
82759
|
+
feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
|
|
82760
|
+
payments: "repayment events: when and how much UCD was paid back",
|
|
82761
|
+
type: "the payment's kind label as indexed (e.g. partial/full)",
|
|
82762
|
+
renewals: "extension events: added term, extension fee, and the new expiry",
|
|
82763
|
+
extensionTerm: "months added by this extension",
|
|
82764
|
+
extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
|
|
82765
|
+
newExpiryAt: "the expiry after this extension (ISO)",
|
|
82766
|
+
withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
|
|
82767
|
+
amountSats: "the withdrawal amount in satoshis",
|
|
82768
|
+
networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
|
|
82769
|
+
targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
|
|
82770
|
+
liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
|
|
82771
|
+
other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
|
|
82772
|
+
totalEvents: "total events across all groups",
|
|
82773
|
+
// ---- pending withdrawals ----
|
|
82774
|
+
vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
|
|
82775
|
+
satoshis: "the reserved amount in satoshis",
|
|
82776
|
+
// ---- protocol status / terms ----
|
|
82777
|
+
paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
|
|
82778
|
+
ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
|
|
82779
|
+
btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
|
|
82780
|
+
terms: "the offered term tiers with their fee rates",
|
|
82781
|
+
months: "the tier's term length in months",
|
|
82782
|
+
originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
|
|
82783
|
+
extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
|
|
82784
|
+
// ---- psm quote ----
|
|
82785
|
+
direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
|
|
82786
|
+
contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
|
|
82787
|
+
amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
|
|
82788
|
+
amountInToken: "the token you pay with",
|
|
82789
|
+
amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
|
|
82790
|
+
amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
|
|
82791
|
+
amountOutToken: "the token you receive",
|
|
82792
|
+
amountOutUnit: "the smallest-unit name of amountOut",
|
|
82793
|
+
fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
|
|
82794
|
+
amount: "the amount of the item it sits on, in that item's stated unit/token",
|
|
82795
|
+
token: "the token the amount is denominated in",
|
|
82796
|
+
bps: "the rate in basis points (100 bps = 1%)",
|
|
82797
|
+
reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
|
|
82798
|
+
available: "how much of the reserve is available, in its stated unit",
|
|
82799
|
+
unit: "the smallest-unit name for the amount it sits on",
|
|
82800
|
+
human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
|
|
82801
|
+
executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
|
|
82802
|
+
};
|
|
82803
|
+
function fieldGuide(...fields) {
|
|
82804
|
+
const lines = fields.map((f) => {
|
|
82805
|
+
const meaning = FIELD_GLOSSARY[f];
|
|
82806
|
+
if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
|
|
82807
|
+
return `${f} = ${meaning}`;
|
|
82808
|
+
});
|
|
82809
|
+
return ` Field guide: ${lines.join("; ")}.`;
|
|
82470
82810
|
}
|
|
82811
|
+
function renderFieldGlossaryTopic() {
|
|
82812
|
+
const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
|
|
82813
|
+
return `# Reading the data \u2014 every field, its exact meaning
|
|
82471
82814
|
|
|
82472
|
-
|
|
82473
|
-
|
|
82474
|
-
|
|
82475
|
-
|
|
82476
|
-
var import_zod = require("zod");
|
|
82477
|
-
var import_ethers41 = require("ethers");
|
|
82815
|
+
The payload's fields and notes are AUTHORITATIVE. State what they say; never speculate
|
|
82816
|
+
past them; when the data does not carry something, say "the data does not carry X".
|
|
82817
|
+
Conditional \`reading\` notes in a payload are instructions for interpreting that exact
|
|
82818
|
+
response \u2014 follow them over any prior assumption.
|
|
82478
82819
|
|
|
82479
|
-
|
|
82480
|
-
function bigintReplacer(_key, value) {
|
|
82481
|
-
if (typeof value === "bigint") return value.toString();
|
|
82482
|
-
return value;
|
|
82483
|
-
}
|
|
82484
|
-
function serialize(data) {
|
|
82485
|
-
return JSON.stringify(data, bigintReplacer, 2);
|
|
82820
|
+
${lines.join("\n")}`;
|
|
82486
82821
|
}
|
|
82487
82822
|
|
|
82488
|
-
// src/
|
|
82489
|
-
|
|
82490
|
-
|
|
82823
|
+
// src/guide/content.ts
|
|
82824
|
+
var GUIDE_TOPICS = [
|
|
82825
|
+
"getting-started",
|
|
82826
|
+
"first-setup",
|
|
82827
|
+
"connect-wallet",
|
|
82828
|
+
"lifecycle",
|
|
82829
|
+
"fees",
|
|
82830
|
+
"psm",
|
|
82831
|
+
"authorization",
|
|
82832
|
+
"safe",
|
|
82833
|
+
"delegation",
|
|
82834
|
+
"safety",
|
|
82835
|
+
"switch-network",
|
|
82836
|
+
"connector",
|
|
82837
|
+
"troubleshooting",
|
|
82838
|
+
"glossary",
|
|
82839
|
+
"reading-data"
|
|
82840
|
+
];
|
|
82841
|
+
var GUIDE_SIGNER_MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
82842
|
+
var EXTERNAL_ONLY_SIGNER_MODES = ["external"];
|
|
82843
|
+
function offers(d, mode) {
|
|
82844
|
+
return d.signerModes.includes(mode);
|
|
82491
82845
|
}
|
|
82492
|
-
function
|
|
82493
|
-
|
|
82494
|
-
if (error.source) lines.push(`source: ${error.source}`);
|
|
82495
|
-
return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
|
|
82846
|
+
function signerModeSourceClause(d) {
|
|
82847
|
+
return offers(d, "keystore") ? "the set `signer_setup` offers. `boundary://info` reports the NARROWER set the active adapter actually constructs under `capabilities.writes.signerModes` (the real adapter builds `external` + `keystore`; the practice ceremonies are mock-adapter only) \u2014 when the two differ, `boundary://info` is authoritative" : "the same set `signer_setup` offers and `boundary://info` reports under `capabilities.writes.signerModes`";
|
|
82496
82848
|
}
|
|
82497
|
-
|
|
82498
|
-
|
|
82499
|
-
|
|
82500
|
-
|
|
82501
|
-
|
|
82502
|
-
|
|
82503
|
-
|
|
82849
|
+
var LOCAL_GUIDE_DEPLOYMENT = {
|
|
82850
|
+
tier: "local",
|
|
82851
|
+
networks: ["sepolia", "mainnet"],
|
|
82852
|
+
// A local install constructs the whole signer runtime: the real adapter offers
|
|
82853
|
+
// external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
|
|
82854
|
+
// speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
|
|
82855
|
+
// on the real adapter these modes refuse") carry the narrower adapter axis.
|
|
82856
|
+
signerModes: GUIDE_SIGNER_MODES
|
|
82857
|
+
};
|
|
82858
|
+
function servedNetworks(d) {
|
|
82859
|
+
if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
|
|
82860
|
+
const mainnet = d.networks.includes("mainnet");
|
|
82861
|
+
const sepolia = d.networks.includes("sepolia");
|
|
82862
|
+
if (mainnet && sepolia) {
|
|
82863
|
+
return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
|
|
82504
82864
|
}
|
|
82505
|
-
|
|
82506
|
-
|
|
82865
|
+
if (mainnet) {
|
|
82866
|
+
return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing, and PSM swaps are refused on mainnet), and there is no practice network on this deployment to fall back to";
|
|
82867
|
+
}
|
|
82868
|
+
return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
|
|
82507
82869
|
}
|
|
82508
|
-
function
|
|
82509
|
-
|
|
82870
|
+
function connectorStatusTruth(d) {
|
|
82871
|
+
if (d.tier === "hosted") {
|
|
82872
|
+
return `**STATUS TRUTH (say this first when asked):** this session IS the hosted
|
|
82873
|
+
connector \u2014 the user is already on it, so there is nothing to install and no URL to hand
|
|
82874
|
+
out. It serves ${servedNetworks(d)}. State that money reality unprompted, and never
|
|
82875
|
+
promise a network, a tier or a timing this deployment does not already serve.`;
|
|
82876
|
+
}
|
|
82877
|
+
return `**STATUS TRUTH (say this first when asked):** this session is a LOCAL install,
|
|
82878
|
+
not the hosted connector. Whether a public connector URL is being served today is the
|
|
82879
|
+
operator's rollout decision and this build cannot see it \u2014 so never assert that one is
|
|
82880
|
+
available, and never assert that one is not. If the user already has a URL, everything
|
|
82881
|
+
below describes what they get; otherwise the local install paths (\`first-setup\`) are the
|
|
82882
|
+
way in. Never promise availability or timing.`;
|
|
82510
82883
|
}
|
|
82511
|
-
function
|
|
82512
|
-
if (
|
|
82513
|
-
|
|
82884
|
+
function connectorNetworkTruth(d) {
|
|
82885
|
+
if (d.tier === "hosted") {
|
|
82886
|
+
return `And it serves only the networks its deployment is rolled out to \u2014 this one
|
|
82887
|
+
serves ${servedNetworks(d)}. Which networks a deployment is rolled out to is the
|
|
82888
|
+
operator's deploy decision, never a hidden knob \u2014 and it is not a field of
|
|
82889
|
+
\`boundary://info\`, whose capabilities block reports the world THIS session is on right
|
|
82890
|
+
now (network, chainId, practiceWorld) plus the read/write/signer planes. \`network_switch\`
|
|
82891
|
+
is what states the rollout: asked for a network this deployment is not rolled out to, it
|
|
82892
|
+
refuses and names the ones it is.`;
|
|
82893
|
+
}
|
|
82894
|
+
return `And any connector deployment serves only the networks it is rolled out to \u2014
|
|
82895
|
+
which ones is the operator's deploy decision, never a hidden knob. Do not go looking for
|
|
82896
|
+
that list in \`boundary://info\`: its capabilities block reports the world THIS session is
|
|
82897
|
+
on (network, chainId, practiceWorld) plus the read/write/signer planes, never another
|
|
82898
|
+
deployment's rollout. \`network_switch\` is what states it \u2014 asked for a network a
|
|
82899
|
+
deployment is not rolled out to, it refuses and names the ones it is. This local build
|
|
82900
|
+
cannot see another deployment's rollout at all: ask that server, never assume.`;
|
|
82514
82901
|
}
|
|
82515
|
-
function
|
|
82516
|
-
|
|
82902
|
+
function connectorInstallNote(d) {
|
|
82903
|
+
if (d.tier === "hosted") {
|
|
82904
|
+
return `(The user is ALREADY on the fourth, zero-install path \u2014 the claude.ai
|
|
82905
|
+
connector \u2014 so none of the above is needed HERE; those paths are for other machines.
|
|
82906
|
+
Truth and trust model: \`guide connector\`.)`;
|
|
82907
|
+
}
|
|
82908
|
+
return `(A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented in this
|
|
82909
|
+
build. Whether it is publicly served today is the operator's rollout decision and this
|
|
82910
|
+
session cannot see it: do not assert either way. Truth and trust model:
|
|
82911
|
+
\`guide connector\`.)`;
|
|
82517
82912
|
}
|
|
82518
|
-
function
|
|
82519
|
-
if (
|
|
82520
|
-
|
|
82521
|
-
|
|
82522
|
-
|
|
82523
|
-
|
|
82524
|
-
|
|
82525
|
-
|
|
82526
|
-
|
|
82527
|
-
|
|
82528
|
-
],
|
|
82529
|
-
isError: true
|
|
82530
|
-
};
|
|
82913
|
+
function connectorTroubleshootingRow(d) {
|
|
82914
|
+
if (d.tier === "hosted") {
|
|
82915
|
+
return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 that is THIS
|
|
82916
|
+
session. Nothing to install, no URL to look up; it serves ${servedNetworks(d)}. Full
|
|
82917
|
+
truth: \`guide connector\`.`;
|
|
82918
|
+
}
|
|
82919
|
+
return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 this session is
|
|
82920
|
+
a local install, not that tier. Whether a public URL is being served today is the
|
|
82921
|
+
operator's rollout decision and this build cannot see it: do not assert either way. The
|
|
82922
|
+
local install paths work regardless. Full truth: \`guide connector\`.`;
|
|
82531
82923
|
}
|
|
82532
|
-
function
|
|
82533
|
-
if (
|
|
82534
|
-
|
|
82535
|
-
|
|
82536
|
-
|
|
82924
|
+
function approvalPageLocation(d) {
|
|
82925
|
+
if (d.tier === "hosted") {
|
|
82926
|
+
return `its URL is ALSO in the tool result. On this hosted tier the page is served by
|
|
82927
|
+
the connector itself over HTTPS on its own public origin, so ANY browser reaches it,
|
|
82928
|
+
including a phone's. The link carries a one-time session token \u2014 treat it as a secret,
|
|
82929
|
+
never forward it, and check the address bar shows that same origin before connecting a
|
|
82930
|
+
wallet.`;
|
|
82931
|
+
}
|
|
82932
|
+
return `its URL is ALSO in the tool result. On this local install the page is served by
|
|
82933
|
+
the server's own loopback listener (127.0.0.1): it exists only on the machine the
|
|
82934
|
+
server runs on, so open it there \u2014 no other device can reach it.`;
|
|
82537
82935
|
}
|
|
82538
|
-
|
|
82539
|
-
|
|
82540
|
-
const stamp = envStamp(getB());
|
|
82541
|
-
const content = result.content.map(
|
|
82542
|
-
(c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
|
|
82543
|
-
|
|
82544
|
-
${stamp}` } : c
|
|
82545
|
-
);
|
|
82546
|
-
return { ...result, content };
|
|
82936
|
+
function switchNetworkHeadline(d) {
|
|
82937
|
+
return d.networks.length > 1 ? "sepolia \u2194 mainnet by conversation (real adapter)" : `${d.networks[0]} ONLY on this deployment (real adapter)`;
|
|
82547
82938
|
}
|
|
82548
|
-
|
|
82549
|
-
|
|
82550
|
-
return
|
|
82551
|
-
|
|
82552
|
-
|
|
82553
|
-
|
|
82554
|
-
|
|
82555
|
-
|
|
82556
|
-
|
|
82557
|
-
}
|
|
82939
|
+
function switchNetworkRules(d) {
|
|
82940
|
+
if (d.networks.length > 1) {
|
|
82941
|
+
return `- \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
|
|
82942
|
+
the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
|
|
82943
|
+
- NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
|
|
82944
|
+
A sepolia position does not exist on mainnet and vice versa.
|
|
82945
|
+
- Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
|
|
82946
|
+
and every one still requires the user's explicit confirmation plus the signer
|
|
82947
|
+
ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
|
|
82948
|
+
}
|
|
82949
|
+
const only = d.networks[0];
|
|
82950
|
+
const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
|
|
82951
|
+
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.";
|
|
82952
|
+
return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
|
|
82953
|
+
network this deployment is rolled out to \u2014 every other target is REFUSED with that
|
|
82954
|
+
rollout truth. There is nothing to switch TO here; never offer the user another world.
|
|
82955
|
+
Money reality: ${money}.
|
|
82956
|
+
- State is per-network by construction: positions, vaults, signer bindings and logins
|
|
82957
|
+
belong to ${only} and would not exist anywhere else.
|
|
82958
|
+
- Fund-moving loan operations run on ${only}, each still requiring the user's explicit
|
|
82959
|
+
confirmation plus the signer ceremony.
|
|
82960
|
+
- ${psm}`;
|
|
82558
82961
|
}
|
|
82559
|
-
|
|
82560
|
-
|
|
82561
|
-
|
|
82562
|
-
|
|
82563
|
-
|
|
82564
|
-
function checkPositionIdHex(id, label = "Position ID") {
|
|
82565
|
-
if (!POSITION_ID_RE.test(id)) {
|
|
82566
|
-
return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
|
|
82962
|
+
function wrongNetworkTroubleshootingRow(d) {
|
|
82963
|
+
if (d.networks.length > 1) {
|
|
82964
|
+
return `- **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
|
|
82965
|
+
(human-confirmed card; nothing carries across networks). Mock: the world is pinned by
|
|
82966
|
+
config \u2014 no switch exists there.`;
|
|
82567
82967
|
}
|
|
82568
|
-
return
|
|
82968
|
+
return `- **Wrong network / asks for another one** \u2014 this deployment is rolled out to
|
|
82969
|
+
${d.networks[0]} alone, so \`network_switch\` refuses every other target with that
|
|
82970
|
+
rollout truth. Relay the refusal; do not suggest a world this service does not serve.`;
|
|
82569
82971
|
}
|
|
82570
|
-
function
|
|
82571
|
-
if (
|
|
82572
|
-
return
|
|
82573
|
-
}
|
|
82574
|
-
if (amount > UCD_SANITY_CAP) {
|
|
82575
|
-
return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
|
|
82576
|
-
}
|
|
82577
|
-
if (amount > 0 && amount < 1e-6) {
|
|
82578
|
-
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
82579
|
-
}
|
|
82580
|
-
const decimals = amount.toString().split(".")[1];
|
|
82581
|
-
if (decimals && decimals.length > 6) {
|
|
82582
|
-
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
82972
|
+
function switchNetworkIndexLine(d) {
|
|
82973
|
+
if (d.networks.length > 1) {
|
|
82974
|
+
return "- switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated";
|
|
82583
82975
|
}
|
|
82584
|
-
|
|
82976
|
+
const only = d.networks[0];
|
|
82977
|
+
const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
|
|
82978
|
+
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`;
|
|
82585
82979
|
}
|
|
82586
|
-
function
|
|
82587
|
-
if (
|
|
82588
|
-
|
|
82589
|
-
|
|
82590
|
-
|
|
82591
|
-
|
|
82592
|
-
|
|
82593
|
-
|
|
82980
|
+
function psmAvailabilityNote(d) {
|
|
82981
|
+
if (d.networks.includes("sepolia")) return "";
|
|
82982
|
+
return `**Not executable on this deployment.** The PSM write port refuses on every network
|
|
82983
|
+
but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
|
|
82984
|
+
\`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
|
|
82985
|
+
the mechanism, not an offer: say so before a user plans around it.
|
|
82986
|
+
|
|
82987
|
+
`;
|
|
82594
82988
|
}
|
|
82595
|
-
function
|
|
82596
|
-
|
|
82597
|
-
|
|
82598
|
-
|
|
82599
|
-
|
|
82600
|
-
|
|
82601
|
-
|
|
82602
|
-
|
|
82989
|
+
function authorizationModeBullets(d) {
|
|
82990
|
+
const bullets = [];
|
|
82991
|
+
if (offers(d, "external")) {
|
|
82992
|
+
bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
|
|
82993
|
+
mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
|
|
82994
|
+
is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
|
|
82995
|
+
The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
|
|
82996
|
+
approval page states plainly it CANNOT decode. Never extend the card promise over
|
|
82997
|
+
that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
|
|
82998
|
+
}
|
|
82999
|
+
if (offers(d, "keystore")) {
|
|
83000
|
+
bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
|
|
83001
|
+
Real adapter and mock.`);
|
|
83002
|
+
}
|
|
83003
|
+
if (offers(d, "safe") || offers(d, "safe-module")) {
|
|
83004
|
+
bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
|
|
83005
|
+
refuse with that true reason (their planes ship in their own deliveries).`);
|
|
83006
|
+
}
|
|
83007
|
+
if (offers(d, "mock-simulated")) {
|
|
83008
|
+
bullets.push(` - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).`);
|
|
83009
|
+
}
|
|
83010
|
+
return bullets.join("\n");
|
|
83011
|
+
}
|
|
83012
|
+
function keystoreAbsenceParagraph(d) {
|
|
83013
|
+
if (offers(d, "keystore")) return "";
|
|
83014
|
+
return `
|
|
83015
|
+
**There is no keystore mode on this build.** It is ABSENT, not disabled: the provider
|
|
83016
|
+
is never constructed, so no key material can exist server-side and there is nothing to
|
|
83017
|
+
unlock. "Sign automatically, without popups" is impossible here \u2014 say that true reason
|
|
83018
|
+
instead of describing a keystore, and never ask for a password.
|
|
83019
|
+
`;
|
|
83020
|
+
}
|
|
83021
|
+
function keystoreAbsenceBullet() {
|
|
83022
|
+
return `- **"Sign automatically / no popups" cannot happen here** \u2014 there is no keystore mode
|
|
83023
|
+
on this build. It is ABSENT, not disabled: the provider is never constructed, so no key
|
|
83024
|
+
material can exist server-side and nothing can be unlocked. Give that true reason, and
|
|
83025
|
+
never ask for a password.`;
|
|
82603
83026
|
}
|
|
83027
|
+
var GUIDE_TOPIC_SOURCES = {
|
|
83028
|
+
"getting-started": `# Diamond Hands \u2014 what this is
|
|
82604
83029
|
|
|
82605
|
-
|
|
82606
|
-
|
|
82607
|
-
|
|
82608
|
-
real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
|
|
82609
|
-
};
|
|
82610
|
-
var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
|
|
82611
|
-
var confirmedSchema = import_zod.z.boolean().optional().describe(
|
|
82612
|
-
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
82613
|
-
);
|
|
82614
|
-
var DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
82615
|
-
readOnlyHint: false,
|
|
82616
|
-
destructiveHint: true,
|
|
82617
|
-
idempotentHint: false,
|
|
82618
|
-
openWorldHint: true
|
|
82619
|
-
};
|
|
82620
|
-
function registerLoanTools(server, getB, adapter2 = "real") {
|
|
82621
|
-
const LATENCY_NOTE = LATENCY_NOTES[adapter2];
|
|
82622
|
-
registerBoundaryTool(
|
|
82623
|
-
server,
|
|
82624
|
-
"loan_create",
|
|
82625
|
-
{
|
|
82626
|
-
title: "Create a new lending position",
|
|
82627
|
-
description: `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
82628
|
-
inputSchema: {
|
|
82629
|
-
selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
|
|
82630
|
-
confirmed: confirmedSchema
|
|
82631
|
-
},
|
|
82632
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82633
|
-
},
|
|
82634
|
-
async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
82635
|
-
const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
|
|
82636
|
-
if (gate) return gate;
|
|
82637
|
-
const problem = checkSelectedTerm(selectedTerm);
|
|
82638
|
-
if (problem) return validationFailed(problem);
|
|
82639
|
-
const b = getB();
|
|
82640
|
-
if (!b.ok) return renderError(b.error);
|
|
82641
|
-
return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
|
|
82642
|
-
})
|
|
82643
|
-
);
|
|
82644
|
-
registerBoundaryTool(
|
|
82645
|
-
server,
|
|
82646
|
-
"loan_mint",
|
|
82647
|
-
{
|
|
82648
|
-
title: "Mint UCD against a position",
|
|
82649
|
-
description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
82650
|
-
inputSchema: {
|
|
82651
|
-
positionId: positionIdSchema,
|
|
82652
|
-
amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
|
|
82653
|
-
confirmed: confirmedSchema
|
|
82654
|
-
},
|
|
82655
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82656
|
-
},
|
|
82657
|
-
async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
|
|
82658
|
-
const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
|
|
82659
|
-
if (gate) return gate;
|
|
82660
|
-
const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
|
|
82661
|
-
if (problem) return validationFailed(problem);
|
|
82662
|
-
const b = getB();
|
|
82663
|
-
if (!b.ok) return renderError(b.error);
|
|
82664
|
-
return renderEnvelope(
|
|
82665
|
-
await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
|
|
82666
|
-
);
|
|
82667
|
-
})
|
|
82668
|
-
);
|
|
82669
|
-
registerBoundaryTool(
|
|
82670
|
-
server,
|
|
82671
|
-
"loan_pay",
|
|
82672
|
-
{
|
|
82673
|
-
title: "Make a UCD payment toward a position's debt",
|
|
82674
|
-
description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
82675
|
-
inputSchema: {
|
|
82676
|
-
positionId: positionIdSchema,
|
|
82677
|
-
amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
|
|
82678
|
-
repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
|
|
82679
|
-
confirmed: confirmedSchema
|
|
82680
|
-
},
|
|
82681
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82682
|
-
},
|
|
82683
|
-
async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
|
|
82684
|
-
if (repayAll === true === (amountUcd !== void 0)) {
|
|
82685
|
-
return validationFailed("provide exactly one of amountUcd or repayAll: true");
|
|
82686
|
-
}
|
|
82687
|
-
const gate = requireConfirmation(
|
|
82688
|
-
confirmed,
|
|
82689
|
-
repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
|
|
82690
|
-
);
|
|
82691
|
-
if (gate) return gate;
|
|
82692
|
-
const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
|
|
82693
|
-
if (problem) return validationFailed(problem);
|
|
82694
|
-
const b = getB();
|
|
82695
|
-
if (!b.ok) return renderError(b.error);
|
|
82696
|
-
let amountUcdWei;
|
|
82697
|
-
if (repayAll) {
|
|
82698
|
-
const detail = await b.boundary.getPosition(positionId);
|
|
82699
|
-
if (!detail.ok) return renderError(detail.error);
|
|
82700
|
-
if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
|
|
82701
|
-
amountUcdWei = detail.data.debtUcdWei;
|
|
82702
|
-
} else {
|
|
82703
|
-
amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
|
|
82704
|
-
}
|
|
82705
|
-
return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
|
|
82706
|
-
})
|
|
82707
|
-
);
|
|
82708
|
-
registerBoundaryTool(
|
|
82709
|
-
server,
|
|
82710
|
-
"loan_extend",
|
|
82711
|
-
{
|
|
82712
|
-
title: "Extend / renew a position's term",
|
|
82713
|
-
description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
82714
|
-
inputSchema: {
|
|
82715
|
-
positionId: positionIdSchema,
|
|
82716
|
-
selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
|
|
82717
|
-
confirmed: confirmedSchema
|
|
82718
|
-
},
|
|
82719
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82720
|
-
},
|
|
82721
|
-
async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
82722
|
-
const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
|
|
82723
|
-
if (gate) return gate;
|
|
82724
|
-
const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
|
|
82725
|
-
if (problem) return validationFailed(problem);
|
|
82726
|
-
const b = getB();
|
|
82727
|
-
if (!b.ok) return renderError(b.error);
|
|
82728
|
-
return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
|
|
82729
|
-
})
|
|
82730
|
-
);
|
|
82731
|
-
registerBoundaryTool(
|
|
82732
|
-
server,
|
|
82733
|
-
"loan_withdraw",
|
|
82734
|
-
{
|
|
82735
|
-
title: "Withdraw BTC from a position vault",
|
|
82736
|
-
description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
82737
|
-
inputSchema: {
|
|
82738
|
-
positionId: positionIdSchema,
|
|
82739
|
-
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
|
|
82740
|
-
amountSats: import_zod.z.number().int().positive().describe(
|
|
82741
|
-
"GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. You cannot spend the whole balance \u2014 the vault must keep room for the fee (TargetMustLeaveFeeRoom), so max amountSats = available \u2212 fee and a withdrawal always leaves fee-sized dust behind."
|
|
82742
|
-
),
|
|
82743
|
-
networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
|
|
82744
|
-
confirmed: confirmedSchema
|
|
82745
|
-
},
|
|
82746
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82747
|
-
},
|
|
82748
|
-
async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
|
|
82749
|
-
const gate = requireConfirmation(
|
|
82750
|
-
confirmed,
|
|
82751
|
-
`withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
|
|
82752
|
-
);
|
|
82753
|
-
if (gate) return gate;
|
|
82754
|
-
const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
|
|
82755
|
-
if (problem) return validationFailed(problem);
|
|
82756
|
-
const b = getB();
|
|
82757
|
-
if (!b.ok) return renderError(b.error);
|
|
82758
|
-
return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
|
|
82759
|
-
})
|
|
82760
|
-
);
|
|
82761
|
-
registerBoundaryTool(
|
|
82762
|
-
server,
|
|
82763
|
-
"loan_allowlist_destination",
|
|
82764
|
-
{
|
|
82765
|
-
title: "Allowlist a BTC withdrawal destination",
|
|
82766
|
-
description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
|
|
82767
|
-
inputSchema: {
|
|
82768
|
-
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
|
|
82769
|
-
confirmed: confirmedSchema
|
|
82770
|
-
},
|
|
82771
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82772
|
-
},
|
|
82773
|
-
async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
|
|
82774
|
-
const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
|
|
82775
|
-
if (gate) return gate;
|
|
82776
|
-
const b = getB();
|
|
82777
|
-
if (!b.ok) return renderError(b.error);
|
|
82778
|
-
return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
|
|
82779
|
-
})
|
|
82780
|
-
);
|
|
82781
|
-
registerBoundaryTool(
|
|
82782
|
-
server,
|
|
82783
|
-
"loan_delegation_setup",
|
|
82784
|
-
{
|
|
82785
|
-
title: "Install delegation on the Safe (one owner ceremony)",
|
|
82786
|
-
description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
|
|
82787
|
-
inputSchema: {
|
|
82788
|
-
btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
|
|
82789
|
-
confirmed: confirmedSchema
|
|
82790
|
-
},
|
|
82791
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82792
|
-
},
|
|
82793
|
-
async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
|
|
82794
|
-
const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
|
|
82795
|
-
if (gate) return gate;
|
|
82796
|
-
const b = getB();
|
|
82797
|
-
if (!b.ok) return renderError(b.error);
|
|
82798
|
-
return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
|
|
82799
|
-
})
|
|
82800
|
-
);
|
|
82801
|
-
registerBoundaryTool(
|
|
82802
|
-
server,
|
|
82803
|
-
"loan_delegation_grant",
|
|
82804
|
-
{
|
|
82805
|
-
title: "Grant the agent per-position scopes (owners sign)",
|
|
82806
|
-
description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
|
|
82807
|
-
inputSchema: {
|
|
82808
|
-
positionId: positionIdSchema,
|
|
82809
|
-
renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
|
|
82810
|
-
repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
|
|
82811
|
-
mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
|
|
82812
|
-
confirmed: confirmedSchema
|
|
82813
|
-
},
|
|
82814
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82815
|
-
},
|
|
82816
|
-
async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
|
|
82817
|
-
const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
|
|
82818
|
-
if (gate) return gate;
|
|
82819
|
-
const b = getB();
|
|
82820
|
-
if (!b.ok) return renderError(b.error);
|
|
82821
|
-
return renderEnvelope(
|
|
82822
|
-
await b.boundary.delegationGrant({
|
|
82823
|
-
positionId,
|
|
82824
|
-
renew: renew ?? false,
|
|
82825
|
-
repay: repay ?? false,
|
|
82826
|
-
mintFloorBps: mintFloorBps ?? null
|
|
82827
|
-
})
|
|
82828
|
-
);
|
|
82829
|
-
})
|
|
82830
|
-
);
|
|
82831
|
-
registerBoundaryTool(
|
|
82832
|
-
server,
|
|
82833
|
-
"loan_recover_stale_spend",
|
|
82834
|
-
{
|
|
82835
|
-
title: "Recover a stale BTC reservation via LIT-attested proof",
|
|
82836
|
-
description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
|
|
82837
|
-
inputSchema: {
|
|
82838
|
-
positionId: positionIdSchema,
|
|
82839
|
-
utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
|
|
82840
|
-
utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
|
|
82841
|
-
invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
|
|
82842
|
-
minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
|
|
82843
|
-
},
|
|
82844
|
-
annotations: {
|
|
82845
|
-
readOnlyHint: false,
|
|
82846
|
-
destructiveHint: false,
|
|
82847
|
-
idempotentHint: true,
|
|
82848
|
-
openWorldHint: true
|
|
82849
|
-
}
|
|
82850
|
-
},
|
|
82851
|
-
async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
|
|
82852
|
-
const problem = checkPositionIdHex(positionId);
|
|
82853
|
-
if (problem) return validationFailed(problem);
|
|
82854
|
-
const b = getB();
|
|
82855
|
-
if (!b.ok) return renderError(b.error);
|
|
82856
|
-
return renderEnvelope(
|
|
82857
|
-
await b.boundary.recoverStaleSpend({
|
|
82858
|
-
positionId,
|
|
82859
|
-
utxoTxid,
|
|
82860
|
-
utxoVout,
|
|
82861
|
-
invalidatorTxid,
|
|
82862
|
-
...minConfirmations !== void 0 ? { minConfirmations } : {}
|
|
82863
|
-
})
|
|
82864
|
-
);
|
|
82865
|
-
})
|
|
82866
|
-
);
|
|
82867
|
-
}
|
|
83030
|
+
Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
|
|
83031
|
+
without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
|
|
83032
|
+
against it, pay it back whenever you like, and take your BTC out again.
|
|
82868
83033
|
|
|
82869
|
-
|
|
82870
|
-
|
|
83034
|
+
**Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
|
|
83035
|
+
topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
|
|
83036
|
+
\`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
|
|
83037
|
+
are enabled (and the true reason when not), and which signer modes this build offers;
|
|
83038
|
+
never promise a capability it does not list. The money truth has THREE cases:
|
|
83039
|
+
- Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
|
|
83040
|
+
- Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
|
|
83041
|
+
the test network: real ceremonies and signatures, PRACTICE money (test funds).
|
|
83042
|
+
- Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
|
|
83043
|
+
explicitly arms them; the capabilities block states which applies.
|
|
83044
|
+
SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
|
|
82871
83045
|
|
|
82872
|
-
|
|
82873
|
-
|
|
82874
|
-
|
|
82875
|
-
|
|
82876
|
-
|
|
82877
|
-
vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
|
|
82878
|
-
pkpId: "internal id of the programmable key pair holding BTC custody for this position",
|
|
82879
|
-
id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
|
|
82880
|
-
kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
|
|
82881
|
-
fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
|
|
82882
|
-
// ---- position facts (chain) ----
|
|
82883
|
-
state: "lifecycle state. On position_status it is read from the CHAIN (authoritative); on position_list rows it is an INDEXER snapshot that can lag the chain. PENDING_DEPOSIT/PENDING_MINT mean 'not yet minted' \u2014 activation happens on the FIRST mint, never on deposit confirmation alone",
|
|
82884
|
-
termMonths: "the current term length in months",
|
|
82885
|
-
totalTermMonths: "cumulative months across the original term plus every extension",
|
|
82886
|
-
createdAt: "ISO timestamp the position was created",
|
|
82887
|
-
expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
|
|
82888
|
-
previousExpiryAt: "the expiry before the latest extension (null when never extended)",
|
|
82889
|
-
lastUpdatedAt: "ISO timestamp of the last state change",
|
|
82890
|
-
debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
|
|
82891
|
-
// ---- indexed health (indexer snapshot) ----
|
|
82892
|
-
indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
|
|
82893
|
-
collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
|
|
82894
|
-
healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
|
|
82895
|
-
asOf: "ISO timestamp the indexer snapshot was computed",
|
|
82896
|
-
basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
|
|
82897
|
-
// ---- collateral (live BTC view) ----
|
|
82898
|
-
collateral: "the live Bitcoin-side view of the position's vault",
|
|
82899
|
-
availableSats: "CONFIRMED collateral in satoshis, minus authorized (reserved) spends \u2014 deposits count only once their confirmations reach minConfirmations. null ONLY alongside a SOURCE_DEGRADED warning, never a fabricated zero",
|
|
82900
|
-
availableSource: "which source served availableSats (null when degraded)",
|
|
82901
|
-
pendingDeposits: "the LIVE per-transaction list of unconfirmed deposits \u2014 each entry carries its own confirmations count. EMPTY ARRAY = nothing unconfirmed in flight (not an error). null ONLY with a SOURCE_DEGRADED warning",
|
|
82902
|
-
txid: "Bitcoin transaction id",
|
|
82903
|
-
sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
|
|
82904
|
-
confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
|
|
82905
|
-
minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
|
|
82906
|
-
pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
|
|
82907
|
-
maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
|
|
82908
|
-
// ---- valuation ----
|
|
82909
|
-
valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
|
|
82910
|
-
btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82911
|
-
priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82912
|
-
priceSource: "which oracle served the price",
|
|
82913
|
-
collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
|
|
82914
|
-
currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
|
|
82915
|
-
maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
|
|
82916
|
-
liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
|
|
82917
|
-
maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
|
|
82918
|
-
maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
|
|
82919
|
-
liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
|
|
82920
|
-
reading: "conditional reading notes emitted by the server ONLY while a known misreading trap is live \u2014 treat them as authoritative instructions for interpreting this exact payload",
|
|
82921
|
-
// ---- list envelope ----
|
|
82922
|
-
items: "the rows of this page",
|
|
82923
|
-
page: "1-based page number of this response",
|
|
82924
|
-
pageSize: "requested rows per page",
|
|
82925
|
-
total: "total rows matching the filter across all pages",
|
|
82926
|
-
// ---- events ----
|
|
82927
|
-
positionCreated: "creation events (seq, time, selected term)",
|
|
82928
|
-
seq: "the event's sequence number within the position's history (ordering key)",
|
|
82929
|
-
at: "ISO timestamp of the event",
|
|
82930
|
-
selectedTerm: "term length chosen, in months",
|
|
82931
|
-
mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
|
|
82932
|
-
amountUcdWei: "the event's UCD amount in wei",
|
|
82933
|
-
feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
|
|
82934
|
-
payments: "repayment events: when and how much UCD was paid back",
|
|
82935
|
-
type: "the payment's kind label as indexed (e.g. partial/full)",
|
|
82936
|
-
renewals: "extension events: added term, extension fee, and the new expiry",
|
|
82937
|
-
extensionTerm: "months added by this extension",
|
|
82938
|
-
extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
|
|
82939
|
-
newExpiryAt: "the expiry after this extension (ISO)",
|
|
82940
|
-
withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
|
|
82941
|
-
amountSats: "the withdrawal amount in satoshis",
|
|
82942
|
-
networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
|
|
82943
|
-
targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
|
|
82944
|
-
liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
|
|
82945
|
-
other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
|
|
82946
|
-
totalEvents: "total events across all groups",
|
|
82947
|
-
// ---- pending withdrawals ----
|
|
82948
|
-
vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
|
|
82949
|
-
satoshis: "the reserved amount in satoshis",
|
|
82950
|
-
// ---- protocol status / terms ----
|
|
82951
|
-
paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
|
|
82952
|
-
ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
|
|
82953
|
-
btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
|
|
82954
|
-
terms: "the offered term tiers with their fee rates",
|
|
82955
|
-
months: "the tier's term length in months",
|
|
82956
|
-
originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
|
|
82957
|
-
extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
|
|
82958
|
-
// ---- psm quote ----
|
|
82959
|
-
direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
|
|
82960
|
-
contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
|
|
82961
|
-
amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
|
|
82962
|
-
amountInToken: "the token you pay with",
|
|
82963
|
-
amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
|
|
82964
|
-
amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
|
|
82965
|
-
amountOutToken: "the token you receive",
|
|
82966
|
-
amountOutUnit: "the smallest-unit name of amountOut",
|
|
82967
|
-
fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
|
|
82968
|
-
amount: "the amount of the item it sits on, in that item's stated unit/token",
|
|
82969
|
-
token: "the token the amount is denominated in",
|
|
82970
|
-
bps: "the rate in basis points (100 bps = 1%)",
|
|
82971
|
-
reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
|
|
82972
|
-
available: "how much of the reserve is available, in its stated unit",
|
|
82973
|
-
unit: "the smallest-unit name for the amount it sits on",
|
|
82974
|
-
human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
|
|
82975
|
-
executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
|
|
82976
|
-
};
|
|
82977
|
-
function fieldGuide(...fields) {
|
|
82978
|
-
const lines = fields.map((f) => {
|
|
82979
|
-
const meaning = FIELD_GLOSSARY[f];
|
|
82980
|
-
if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
|
|
82981
|
-
return `${f} = ${meaning}`;
|
|
82982
|
-
});
|
|
82983
|
-
return ` Field guide: ${lines.join("; ")}.`;
|
|
82984
|
-
}
|
|
82985
|
-
function renderFieldGlossaryTopic() {
|
|
82986
|
-
const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
|
|
82987
|
-
return `# Reading the data \u2014 every field, its exact meaning
|
|
83046
|
+
A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
|
|
83047
|
+
authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
|
|
83048
|
+
calls. Every operation that moves funds requires the user's explicit confirmation
|
|
83049
|
+
(\`confirmed: true\`) \u2014 nothing is ever silent.`,
|
|
83050
|
+
"first-setup": (d) => `# First setup \u2014 from zero to ready, by conversation only
|
|
82988
83051
|
|
|
82989
|
-
|
|
82990
|
-
|
|
82991
|
-
|
|
82992
|
-
|
|
83052
|
+
Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
|
|
83053
|
+
\u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
|
|
83054
|
+
host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
|
|
83055
|
+
developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
|
|
83056
|
+
install matrix. ${connectorInstallNote(d)}
|
|
82993
83057
|
|
|
82994
|
-
|
|
82995
|
-
}
|
|
83058
|
+
Nothing needs a config file. Three steps:
|
|
82996
83059
|
|
|
82997
|
-
|
|
82998
|
-
|
|
82999
|
-
|
|
83000
|
-
|
|
83001
|
-
"PENDING_MINT",
|
|
83002
|
-
"ACTIVE",
|
|
83003
|
-
"EXPIRED",
|
|
83004
|
-
"LIQUIDATABLE",
|
|
83005
|
-
"LIQUIDATED",
|
|
83006
|
-
"REPAID",
|
|
83007
|
-
"CLOSED"
|
|
83008
|
-
];
|
|
83009
|
-
function registerPositionTools(server, getB) {
|
|
83010
|
-
registerBoundaryTool(
|
|
83011
|
-
server,
|
|
83012
|
-
"position_status",
|
|
83013
|
-
{
|
|
83014
|
-
title: "Get a position's full status",
|
|
83015
|
-
description: "Return detailed status for a single position: chain facts (debt, term, expiry, state), live collateral (confirmed sats + per-transaction pending deposits, plus maxWithdrawableSats \u2014 directly usable as a withdrawal amountSats), and a basis-carrying valuation (maxMintableUcd is directly usable as amountUcd). If a withdrawal reservation was already spent on Bitcoin but availableSats still shows it deducted, run loan_recover_stale_spend to release the redundant hold. Any `reading` notes in the result are authoritative interpretation instructions for that exact payload \u2014 follow them." + fieldGuide("state", "availableSats", "minConfirmations", "pendingDeposits", "maxWithdrawableSats", "maxMintableUcd", "debtUcdWei"),
|
|
83016
|
-
inputSchema: {
|
|
83017
|
-
id: positionIdSchema2
|
|
83018
|
-
}
|
|
83019
|
-
},
|
|
83020
|
-
async ({ id }) => guarded(async () => {
|
|
83021
|
-
const problem = checkPositionIdHex(id);
|
|
83022
|
-
if (problem) return validationFailed(problem);
|
|
83023
|
-
const b = getB();
|
|
83024
|
-
if (!b.ok) return renderError(b.error);
|
|
83025
|
-
return renderEnvelope(await b.boundary.getPosition(id));
|
|
83026
|
-
})
|
|
83027
|
-
);
|
|
83028
|
-
registerBoundaryTool(
|
|
83029
|
-
server,
|
|
83030
|
-
"position_list",
|
|
83031
|
-
{
|
|
83032
|
-
title: "List lending positions",
|
|
83033
|
-
description: "List positions with optional filters. `borrower` and `state` COMBINE (logical AND); with no filter, returns active positions. Rows are the INDEXER's view \u2014 `state` here is an indexer snapshot that can lag the chain; position_status reads the chain and is authoritative for one position." + fieldGuide("state", "debtUcdWei", "indexedHealth"),
|
|
83034
|
-
inputSchema: {
|
|
83035
|
-
borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
|
|
83036
|
-
state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
|
|
83037
|
-
page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
|
|
83038
|
-
pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
|
|
83039
|
-
}
|
|
83040
|
-
},
|
|
83041
|
-
async ({ borrower, state, page, pageSize }) => guarded(async () => {
|
|
83042
|
-
if (state !== void 0 && !POSITION_STATES.includes(state)) {
|
|
83043
|
-
return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
|
|
83044
|
-
}
|
|
83045
|
-
const b = getB();
|
|
83046
|
-
if (!b.ok) return renderError(b.error);
|
|
83047
|
-
const filter2 = {
|
|
83048
|
-
page,
|
|
83049
|
-
pageSize,
|
|
83050
|
-
...borrower !== void 0 ? { borrower } : {},
|
|
83051
|
-
...state !== void 0 ? { state } : {}
|
|
83052
|
-
};
|
|
83053
|
-
if (filter2.borrower === void 0 && filter2.state === void 0) {
|
|
83054
|
-
return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
|
|
83055
|
-
}
|
|
83056
|
-
return renderEnvelope(await b.boundary.listPositions(filter2));
|
|
83057
|
-
})
|
|
83058
|
-
);
|
|
83059
|
-
registerBoundaryTool(
|
|
83060
|
-
server,
|
|
83061
|
-
"position_events",
|
|
83062
|
-
{
|
|
83063
|
-
title: "Get a position's event history",
|
|
83064
|
-
description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
|
|
83065
|
-
inputSchema: {
|
|
83066
|
-
id: positionIdSchema2
|
|
83067
|
-
}
|
|
83068
|
-
},
|
|
83069
|
-
async ({ id }) => guarded(async () => {
|
|
83070
|
-
const problem = checkPositionIdHex(id);
|
|
83071
|
-
if (problem) return validationFailed(problem);
|
|
83072
|
-
const b = getB();
|
|
83073
|
-
if (!b.ok) return renderError(b.error);
|
|
83074
|
-
return renderEnvelope(await b.boundary.getPositionEvents(id));
|
|
83075
|
-
})
|
|
83076
|
-
);
|
|
83077
|
-
registerBoundaryTool(
|
|
83078
|
-
server,
|
|
83079
|
-
"position_pending_withdrawals",
|
|
83080
|
-
{
|
|
83081
|
-
title: "List a position's pending BTC withdrawal reservations",
|
|
83082
|
-
description: "Query the spend authorizer for BTC withdrawal reservations on a position. Each entry has txid/vout, satoshis, and target address (txid/vout feed recovery).",
|
|
83083
|
-
inputSchema: {
|
|
83084
|
-
id: positionIdSchema2
|
|
83085
|
-
}
|
|
83086
|
-
},
|
|
83087
|
-
async ({ id }) => guarded(async () => {
|
|
83088
|
-
const problem = checkPositionIdHex(id);
|
|
83089
|
-
if (problem) return validationFailed(problem);
|
|
83090
|
-
const b = getB();
|
|
83091
|
-
if (!b.ok) return renderError(b.error);
|
|
83092
|
-
return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
|
|
83093
|
-
})
|
|
83094
|
-
);
|
|
83095
|
-
}
|
|
83060
|
+
**1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
|
|
83061
|
+
\`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
|
|
83062
|
+
(practice money) or mainnet (real money); whether writes are enabled here and which
|
|
83063
|
+
signer modes exist; current terms (\`protocol_terms\`).
|
|
83096
83064
|
|
|
83097
|
-
|
|
83098
|
-
|
|
83099
|
-
|
|
83100
|
-
|
|
83101
|
-
|
|
83102
|
-
|
|
83103
|
-
|
|
83104
|
-
|
|
83105
|
-
|
|
83106
|
-
|
|
83107
|
-
|
|
83108
|
-
|
|
83109
|
-
|
|
83110
|
-
|
|
83111
|
-
|
|
83112
|
-
|
|
83113
|
-
|
|
83114
|
-
|
|
83115
|
-
|
|
83116
|
-
|
|
83117
|
-
|
|
83118
|
-
|
|
83119
|
-
|
|
83120
|
-
|
|
83121
|
-
|
|
83122
|
-
inputSchema: {}
|
|
83123
|
-
},
|
|
83124
|
-
async () => guarded(async () => {
|
|
83125
|
-
const b = getB();
|
|
83126
|
-
if (!b.ok) return renderError(b.error);
|
|
83127
|
-
return renderEnvelope(await b.boundary.getBitcoinPrice());
|
|
83128
|
-
})
|
|
83129
|
-
);
|
|
83130
|
-
}
|
|
83065
|
+
**2. Choose HOW to authorize operations** (the user's choice, made by talking):
|
|
83066
|
+
- **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
|
|
83067
|
+
on the real adapter and the mock. The approval page auto-opens in the browser (its URL
|
|
83068
|
+
is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
|
|
83069
|
+
/ pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
|
|
83070
|
+
their own wallet. The first verified signature binds their wallet address as the
|
|
83071
|
+
borrower. Full walkthrough: \`guide connect-wallet\`.
|
|
83072
|
+
${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
|
|
83073
|
+
signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
|
|
83074
|
+
\`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
|
|
83075
|
+
LOCAL PAGE opens where the user types the password or generates a fresh keystore.
|
|
83076
|
+
NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
|
|
83077
|
+
them to use the unlock page instead.` : keystoreAbsenceBullet()}
|
|
83078
|
+
${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
|
|
83079
|
+
real adapter they refuse with that true reason. Try them in a mock world.` : `- **Safe / delegation borrowing is not offered by this build** \u2014 its authorization
|
|
83080
|
+
surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
|
|
83081
|
+
\`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
|
|
83082
|
+
- Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
|
|
83083
|
+
- **No signer is also a valid start:** every public read works without one \u2014
|
|
83084
|
+
\`position_list {borrower}\` with the user's address needs no signer and no login.
|
|
83085
|
+
${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
|
|
83086
|
+
talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
|
|
83087
|
+
the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
|
|
83088
|
+
\`network_switch\` refuses every other target with that rollout truth. See
|
|
83089
|
+
\`guide switch-network\`; never offer a world this service does not serve.`}
|
|
83131
83090
|
|
|
83132
|
-
|
|
83133
|
-
|
|
83134
|
-
|
|
83135
|
-
|
|
83136
|
-
"protocol_status",
|
|
83137
|
-
{
|
|
83138
|
-
title: "Get protocol configuration and status",
|
|
83139
|
-
description: "Return protocol status: pause flag, mint LTV limit (ltvBps), liquidation threshold (liquidationThresholdBps \u2014 a COLLATERAL RATIO in bps, i.e. collateralValue/debt, so 11000 = 110%; note this is the inverse basis of ltvBps which is debt/collateral), deposit confirmation threshold, BTC network.",
|
|
83140
|
-
inputSchema: {}
|
|
83141
|
-
},
|
|
83142
|
-
async () => guarded(async () => {
|
|
83143
|
-
const b = getB();
|
|
83144
|
-
if (!b.ok) return renderError(b.error);
|
|
83145
|
-
return renderEnvelope(await b.boundary.getProtocolStatus());
|
|
83146
|
-
})
|
|
83147
|
-
);
|
|
83148
|
-
registerBoundaryTool(
|
|
83149
|
-
server,
|
|
83150
|
-
"protocol_terms",
|
|
83151
|
-
{
|
|
83152
|
-
title: "List available loan terms with fees",
|
|
83153
|
-
description: "Return all configured loan terms (in months) with their fees. Term length: 12 months = exactly 365 days; any other term = N \xD7 30-day months. originationFeeBps: % of a mint, ADDED to debt. extensionFeeRateBps: the renewal fee CEILING as % of outstanding debt PER RENEWAL (a flat rate, NOT per month); the charged fee is ADDED TO DEBT and reduced by origination fees already paid this term.",
|
|
83154
|
-
inputSchema: {}
|
|
83155
|
-
},
|
|
83156
|
-
async () => guarded(async () => {
|
|
83157
|
-
const b = getB();
|
|
83158
|
-
if (!b.ok) return renderError(b.error);
|
|
83159
|
-
return renderEnvelope(await b.boundary.getTerms());
|
|
83160
|
-
})
|
|
83161
|
-
);
|
|
83162
|
-
}
|
|
83163
|
-
|
|
83164
|
-
// src/tools/psm.ts
|
|
83165
|
-
var import_zod4 = require("zod");
|
|
83166
|
-
var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
|
|
83167
|
-
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
83168
|
-
);
|
|
83169
|
-
var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
|
|
83170
|
-
readOnlyHint: false,
|
|
83171
|
-
destructiveHint: true,
|
|
83172
|
-
idempotentHint: false,
|
|
83173
|
-
openWorldHint: true
|
|
83174
|
-
};
|
|
83175
|
-
function registerPsmTools(server, getB) {
|
|
83176
|
-
registerBoundaryTool(
|
|
83177
|
-
server,
|
|
83178
|
-
"psm_quote",
|
|
83179
|
-
{
|
|
83180
|
-
title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
|
|
83181
|
-
description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) 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.",
|
|
83182
|
-
inputSchema: {
|
|
83183
|
-
direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = get UCD for USDC (contract swap); 'to-usdc' = get USDC back for UCD (contract redeem)"),
|
|
83184
|
-
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
|
|
83185
|
-
},
|
|
83186
|
-
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
|
|
83187
|
-
},
|
|
83188
|
-
async ({ direction, amount }) => guarded(async () => {
|
|
83189
|
-
const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
|
|
83190
|
-
const problem = checkUcdAmount(amount, label);
|
|
83191
|
-
if (problem) return validationFailed(problem);
|
|
83192
|
-
const b = getB();
|
|
83193
|
-
if (!b.ok) return renderError(b.error);
|
|
83194
|
-
return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
|
|
83195
|
-
})
|
|
83196
|
-
);
|
|
83197
|
-
registerBoundaryTool(
|
|
83198
|
-
server,
|
|
83199
|
-
"psm_swap",
|
|
83200
|
-
{
|
|
83201
|
-
title: "Exchange UCD \u2194 USDC through the PSM",
|
|
83202
|
-
description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC 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 USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc 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; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
|
|
83203
|
-
inputSchema: {
|
|
83204
|
-
direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = pay USDC, get UCD (contract swap); 'to-usdc' = pay UCD, get USDC back (contract redeem)"),
|
|
83205
|
-
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
|
|
83206
|
-
confirmed: confirmedSchema2
|
|
83207
|
-
},
|
|
83208
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
|
|
83209
|
-
},
|
|
83210
|
-
async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
|
|
83211
|
-
const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
|
|
83212
|
-
const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
|
|
83213
|
-
const gate = requireConfirmation(
|
|
83214
|
-
confirmed,
|
|
83215
|
-
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
|
|
83216
|
-
);
|
|
83217
|
-
if (gate) return gate;
|
|
83218
|
-
const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
|
|
83219
|
-
if (problem) return validationFailed(problem);
|
|
83220
|
-
const b = getB();
|
|
83221
|
-
if (!b.ok) return renderError(b.error);
|
|
83222
|
-
return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
|
|
83223
|
-
})
|
|
83224
|
-
);
|
|
83225
|
-
}
|
|
83226
|
-
|
|
83227
|
-
// src/tools/mock-control.ts
|
|
83228
|
-
var import_zod5 = require("zod");
|
|
83229
|
-
var ACTIONS = [
|
|
83230
|
-
"submit-deposit",
|
|
83231
|
-
"confirm-deposit",
|
|
83232
|
-
"confirm-spend-consumed",
|
|
83233
|
-
"advance-time",
|
|
83234
|
-
"set-btc-price",
|
|
83235
|
-
"set-paused",
|
|
83236
|
-
"set-wallet",
|
|
83237
|
-
"liquidate",
|
|
83238
|
-
"deploy-safe",
|
|
83239
|
-
"revoke-agent",
|
|
83240
|
-
"inject-fault",
|
|
83241
|
-
"clear-fault",
|
|
83242
|
-
"psm-set-paused",
|
|
83243
|
-
"psm-set-redeem-enabled",
|
|
83244
|
-
"psm-set-reserves",
|
|
83245
|
-
"psm-set-fees",
|
|
83246
|
-
"psm-mint-usdc"
|
|
83247
|
-
];
|
|
83248
|
-
function requireField(value, name, action) {
|
|
83249
|
-
if (value === void 0) {
|
|
83250
|
-
throw new Error(`action '${action}' requires '${name}'`);
|
|
83251
|
-
}
|
|
83252
|
-
return value;
|
|
83253
|
-
}
|
|
83254
|
-
function run(control, a, chainId) {
|
|
83255
|
-
switch (a.action) {
|
|
83256
|
-
case "submit-deposit": {
|
|
83257
|
-
const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
|
|
83258
|
-
return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
|
|
83259
|
-
}
|
|
83260
|
-
case "confirm-deposit": {
|
|
83261
|
-
const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
|
|
83262
|
-
return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
|
|
83263
|
-
}
|
|
83264
|
-
case "confirm-spend-consumed": {
|
|
83265
|
-
control.confirmSpendConsumed(
|
|
83266
|
-
requireField(a.txid, "txid", a.action),
|
|
83267
|
-
requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
|
|
83268
|
-
requireField(a.confirmations, "confirmations", a.action)
|
|
83269
|
-
);
|
|
83270
|
-
return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
|
|
83271
|
-
}
|
|
83272
|
-
case "advance-time": {
|
|
83273
|
-
control.advanceTime(requireField(a.seconds, "seconds", a.action));
|
|
83274
|
-
return { simulated: "virtual clock advanced", seconds: a.seconds };
|
|
83275
|
-
}
|
|
83276
|
-
case "set-btc-price": {
|
|
83277
|
-
control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
|
|
83278
|
-
return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
|
|
83279
|
-
}
|
|
83280
|
-
case "set-paused": {
|
|
83281
|
-
control.setPaused(requireField(a.paused, "paused", a.action));
|
|
83282
|
-
return { simulated: "protocol pause flag set", paused: a.paused };
|
|
83283
|
-
}
|
|
83284
|
-
case "set-wallet": {
|
|
83285
|
-
control.setWalletStance(requireField(a.stance, "stance", a.action));
|
|
83286
|
-
return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
|
|
83287
|
-
}
|
|
83288
|
-
case "liquidate": {
|
|
83289
|
-
control.liquidate(requireField(a.positionId, "positionId", a.action));
|
|
83290
|
-
return { simulated: "liquidation executed", positionId: a.positionId };
|
|
83291
|
-
}
|
|
83292
|
-
case "deploy-safe": {
|
|
83293
|
-
const safe = control.deploySafe({
|
|
83294
|
-
owners: requireField(a.owners, "owners", a.action),
|
|
83295
|
-
threshold: requireField(a.threshold, "threshold", a.action),
|
|
83296
|
-
chainId
|
|
83297
|
-
});
|
|
83298
|
-
return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
|
|
83299
|
-
}
|
|
83300
|
-
case "revoke-agent": {
|
|
83301
|
-
const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
|
|
83302
|
-
return {
|
|
83303
|
-
simulated: "agent revoked and BURNED forever (AR-1 \u2014 plan 09 test lever; on the real protocol the owners or the deny-only registrar revoke)",
|
|
83304
|
-
...r
|
|
83305
|
-
};
|
|
83306
|
-
}
|
|
83307
|
-
case "inject-fault": {
|
|
83308
|
-
control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
|
|
83309
|
-
return { simulated: "fault armed", faultKey: a.faultKey };
|
|
83310
|
-
}
|
|
83311
|
-
case "clear-fault": {
|
|
83312
|
-
control.clearFault(requireField(a.faultKey, "faultKey", a.action));
|
|
83313
|
-
return { simulated: "fault cleared", faultKey: a.faultKey };
|
|
83314
|
-
}
|
|
83315
|
-
case "psm-set-paused": {
|
|
83316
|
-
control.psmSetPaused(requireField(a.paused, "paused", a.action));
|
|
83317
|
-
return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
|
|
83318
|
-
}
|
|
83319
|
-
case "psm-set-redeem-enabled": {
|
|
83320
|
-
control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
|
|
83321
|
-
return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
|
|
83322
|
-
}
|
|
83323
|
-
case "psm-set-reserves": {
|
|
83324
|
-
control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
|
|
83325
|
-
return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
|
|
83326
|
-
}
|
|
83327
|
-
case "psm-mint-usdc": {
|
|
83328
|
-
const r = control.psmMintUsdc(
|
|
83329
|
-
requireField(a.holder, "holder", a.action),
|
|
83330
|
-
requireField(a.usdcUnits, "usdcUnits", a.action)
|
|
83331
|
-
);
|
|
83332
|
-
return {
|
|
83333
|
-
simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
|
|
83334
|
-
holder: a.holder,
|
|
83335
|
-
minted: a.usdcUnits,
|
|
83336
|
-
newBalanceUnits: r.newBalanceUnits
|
|
83337
|
-
};
|
|
83338
|
-
}
|
|
83339
|
-
case "psm-set-fees": {
|
|
83340
|
-
control.psmSetFees({
|
|
83341
|
-
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
83342
|
-
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
83343
|
-
});
|
|
83344
|
-
return {
|
|
83345
|
-
simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
|
|
83346
|
-
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
83347
|
-
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
83348
|
-
};
|
|
83349
|
-
}
|
|
83350
|
-
}
|
|
83351
|
-
}
|
|
83352
|
-
function registerMockControlTool(server, control, chainId = 1337) {
|
|
83353
|
-
registerBoundaryTool(
|
|
83354
|
-
server,
|
|
83355
|
-
"mock_control",
|
|
83356
|
-
{
|
|
83357
|
-
title: "SIMULATOR control (mock world only)",
|
|
83358
|
-
description: "Drive the simulated rest-of-the-world of the MOCK protocol: broadcast/confirm BTC deposits, confirm reserved spends, advance the virtual clock, set the oracle price, pause the protocol, liquidate, arm/clear faults, and drive the simulated PSM (pause, redeemEnabled, reserves, fees, practice-USDC mint). This tool exists ONLY against the mock adapter \u2014 nothing here touches or ever exists on the real protocol.",
|
|
83359
|
-
inputSchema: {
|
|
83360
|
-
action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
|
|
83361
|
-
positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
|
|
83362
|
-
txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
83363
|
-
sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
|
|
83364
|
-
confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
83365
|
-
invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
|
|
83366
|
-
seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
|
|
83367
|
-
priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
|
|
83368
|
-
paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
|
|
83369
|
-
stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
|
|
83370
|
-
owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
|
|
83371
|
-
threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
|
|
83372
|
-
safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
|
|
83373
|
-
faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
|
|
83374
|
-
faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
|
|
83375
|
-
enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
|
|
83376
|
-
reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
|
|
83377
|
-
entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
|
|
83378
|
-
exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
|
|
83379
|
-
holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
|
|
83380
|
-
usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
|
|
83381
|
-
},
|
|
83382
|
-
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
|
|
83383
|
-
},
|
|
83384
|
-
async (args) => guarded(async () => {
|
|
83385
|
-
let result;
|
|
83386
|
-
try {
|
|
83387
|
-
result = run(control, args, chainId);
|
|
83388
|
-
} catch (e) {
|
|
83389
|
-
return validationFailed(e.message);
|
|
83390
|
-
}
|
|
83391
|
-
if (result === void 0) {
|
|
83392
|
-
return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
|
|
83393
|
-
}
|
|
83394
|
-
return { content: [{ type: "text", text: serialize(result) }] };
|
|
83395
|
-
})
|
|
83396
|
-
);
|
|
83397
|
-
}
|
|
83398
|
-
|
|
83399
|
-
// src/tools/signer.ts
|
|
83400
|
-
var import_zod6 = require("zod");
|
|
83401
|
-
var import_ethers42 = require("ethers");
|
|
83402
|
-
var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
83403
|
-
var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
|
|
83404
|
-
var EXTERNAL_ONLY_MODES = ["external"];
|
|
83405
|
-
var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
|
|
83406
|
-
function looksSecretShaped(value) {
|
|
83407
|
-
return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
|
|
83408
|
-
}
|
|
83409
|
-
var SECRET_REFUSAL = "That value looks like a password or key. NEVER paste secrets into the conversation \u2014 they would enter the model context and transcripts. To provide keystore material, say 'unlock my keystore' (a secure local page opens and the password goes directly to the server), or set DH_KEYSTORE_PATH/DH_KEYSTORE_PASSWORD in the server environment.";
|
|
83410
|
-
function registerSignerTool(server, getRuntime, opts) {
|
|
83411
|
-
const externalOnly = opts?.externalOnly === true;
|
|
83412
|
-
const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
|
|
83413
|
-
const description = externalOnly ? "Inspect or manage how operations are authorized. This build is EXTERNAL-WALLET-ONLY: every operation is approved in YOUR OWN wallet (browser wallet, or mobile via WalletConnect); the server can never sign by itself. Actions: 'status' (what is active, what is connected \u2014 start here), 'use' (mode 'external' \u2014 the only mode this build offers), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'connect' (run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out: the FULL wallet flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect." : "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat), 'connect' (external mode, real protocol: run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out of the external wallet: the FULL flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect.";
|
|
83414
|
-
registerBoundaryTool(
|
|
83415
|
-
server,
|
|
83416
|
-
"signer_setup",
|
|
83417
|
-
{
|
|
83418
|
-
title: "Choose how operations are authorized",
|
|
83419
|
-
description,
|
|
83420
|
-
inputSchema: {
|
|
83421
|
-
action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
|
|
83422
|
-
mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
|
|
83423
|
-
...externalOnly ? {} : {
|
|
83424
|
-
safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
|
|
83425
|
-
}
|
|
83426
|
-
},
|
|
83427
|
-
annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
|
|
83428
|
-
},
|
|
83429
|
-
async ({ action, mode, safeAddress }) => guarded(async () => {
|
|
83430
|
-
const runtime = getRuntime();
|
|
83431
|
-
if (!runtime) {
|
|
83432
|
-
return renderError(
|
|
83433
|
-
boundaryError(
|
|
83434
|
-
"SIGNER_UNAVAILABLE",
|
|
83435
|
-
"no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
|
|
83436
|
-
)
|
|
83437
|
-
);
|
|
83438
|
-
}
|
|
83439
|
-
const { manager, bridge } = runtime;
|
|
83440
|
-
if (mode !== void 0 && !offeredModes.includes(mode)) {
|
|
83441
|
-
return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
|
|
83442
|
-
}
|
|
83443
|
-
if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
|
|
83444
|
-
return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
|
|
83445
|
-
}
|
|
83446
|
-
if (action === "status") {
|
|
83447
|
-
await bridge.start();
|
|
83448
|
-
const s = manager.status();
|
|
83449
|
-
return ok({
|
|
83450
|
-
...s,
|
|
83451
|
-
// Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
|
|
83452
|
-
// identity is known. borrower = a persisted binding; candidate = a live
|
|
83453
|
-
// wallet connection in THIS process only.
|
|
83454
|
-
identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
|
|
83455
|
-
approvalPageUrl: bridge.url(),
|
|
83456
|
-
hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
|
|
83457
|
-
});
|
|
83458
|
-
}
|
|
83459
|
-
if (action === "use") {
|
|
83460
|
-
if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
|
|
83461
|
-
const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
|
|
83462
|
-
if (!r.ok) return validationFailed(r.reason);
|
|
83463
|
-
if (mode === "safe-module") {
|
|
83464
|
-
const s = manager.status();
|
|
83465
|
-
return ok({
|
|
83466
|
-
mode,
|
|
83467
|
-
safe: s.safe,
|
|
83468
|
-
agent: s.keystoreAddress,
|
|
83469
|
-
next: "This session operates AS the Safe with DELEGATION: the keystore key is the AGENT. One owner ceremony installs it (loan_delegation_setup \u2014 enables the module, binds the agent, pre-approves BTC destinations); afterwards create/mint/pay/extend run agent-solo (per-position grants via loan_delegation_grant, a quorum signature). The agent can NEVER withdraw alone, add destinations, or manage the module \u2014 withdrawals still gather the owners for a short signing burst. See guide topic 'delegation'."
|
|
83470
|
-
});
|
|
83471
|
-
}
|
|
83472
|
-
if (mode === "safe") {
|
|
83473
|
-
const s = manager.status();
|
|
83474
|
-
return ok({
|
|
83475
|
-
mode,
|
|
83476
|
-
safe: s.safe,
|
|
83477
|
-
next: "This session now operates AS the Safe. Operations are authorized by owner signatures (this phase: the local keystore owner signs; it also submits transactions). BTC withdrawals additionally need the destination allowlisted first \u2014 see loan_allowlist_destination."
|
|
83478
|
-
});
|
|
83479
|
-
}
|
|
83480
|
-
if (mode === "external") {
|
|
83481
|
-
await bridge.start();
|
|
83482
|
-
return ok({
|
|
83483
|
-
mode,
|
|
83484
|
-
approvalPageUrl: bridge.url(),
|
|
83485
|
-
next: "Open the approval page and connect your wallet (browser extension, or 'Use a mobile wallet' for WalletConnect). Each operation will then ask for your approval there."
|
|
83486
|
-
});
|
|
83487
|
-
}
|
|
83488
|
-
return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
|
|
83489
|
-
}
|
|
83490
|
-
if (action === "connect") {
|
|
83491
|
-
if (!runtime.connect) {
|
|
83492
|
-
return validationFailed(
|
|
83493
|
-
"action 'connect' applies to the real protocol's external mode (lit-ops login). This adapter has no separate login step \u2014 pick a mode with 'use' and writes will ceremony as needed."
|
|
83494
|
-
);
|
|
83495
|
-
}
|
|
83496
|
-
const r = await runtime.connect();
|
|
83497
|
-
if (!r.ok) return validationFailed(r.reason);
|
|
83498
|
-
const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
|
|
83499
|
-
return ok({
|
|
83500
|
-
connected: true,
|
|
83501
|
-
address: r.address,
|
|
83502
|
-
login,
|
|
83503
|
-
next: (login === "cached-session" ? "Logged in via a still-valid CACHED session \u2014 no wallet signature was requested. To force a full logout first, use 'disconnect'. " : "Logged in with a FRESH wallet signature. ") + "Authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
|
|
83504
|
-
});
|
|
83505
|
-
}
|
|
83506
|
-
if (action === "disconnect") {
|
|
83507
|
-
if (!runtime.disconnect) {
|
|
83508
|
-
return validationFailed(
|
|
83509
|
-
"this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
|
|
83510
|
-
);
|
|
83511
|
-
}
|
|
83512
|
-
const report = await runtime.disconnect();
|
|
83513
|
-
const f = report.flushed;
|
|
83514
|
-
const tokenLine = !report.hadLogin ? "login token: none existed" : f.upstreamRevoked >= f.loginSessions ? `login token: discarded from memory AND revoked at the service (${f.upstreamRevoked} revoked)` : `login token: discarded from this process's memory; ${f.upstreamRevoked}/${f.loginSessions} could be revoked at the service \u2014 an unrevoked token stays valid upstream until its natural expiry (it was never stored on disk)`;
|
|
83515
|
-
return ok({
|
|
83516
|
-
disconnected: true,
|
|
83517
|
-
mode: manager.mode(),
|
|
83518
|
-
flushed: {
|
|
83519
|
-
...f,
|
|
83520
|
-
note: tokenLine
|
|
83521
|
-
},
|
|
83522
|
-
whatThisServerCannotRevoke: "Your wallet's own site permission for the approval-page origin \u2014 revoke it wallet-side (MetaMask: Settings \u2192 Connections / Connected sites \u2192 remove this site).",
|
|
83523
|
-
// Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
|
|
83524
|
-
// relationship; the OAuth session is a separate thing with its own revocation.
|
|
83525
|
-
// Neither claims to do the other's job.
|
|
83526
|
-
...bridge.isHosted() ? {
|
|
83527
|
-
oauthSession: "This disconnect ends the WALLET relationship only. Your assistant's connection to this MCP server (the OAuth session) stays alive until you revoke it on the claude.ai side (connector settings) \u2014 and revoking THAT does not disconnect your wallet here."
|
|
83528
|
-
} : {},
|
|
83529
|
-
next: `Wallet disconnected \u2014 mode stays '${manager.mode()}'. Reconnecting requires opening the approval page again (signer_setup 'status' shows the link) and a fresh wallet signature ('connect').`
|
|
83530
|
-
});
|
|
83531
|
-
}
|
|
83532
|
-
if (action === "reset-borrower") {
|
|
83533
|
-
manager.resetBorrower();
|
|
83534
|
-
return ok({
|
|
83535
|
-
reset: true,
|
|
83536
|
-
next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower. NOTE: this is an identity swap, NOT a disconnect \u2014 any wallet connection and login session remain alive; use 'disconnect' to log out fully."
|
|
83537
|
-
});
|
|
83538
|
-
}
|
|
83539
|
-
await bridge.start();
|
|
83540
|
-
const unlockUrl = bridge.unlockUrl();
|
|
83541
|
-
return ok({
|
|
83542
|
-
unlockPageUrl: unlockUrl,
|
|
83543
|
-
next: "Open this local page and enter the keystore password THERE (never in chat). Paste an encrypted keystore JSON or generate a fresh one, then say 'use keystore'."
|
|
83544
|
-
});
|
|
83545
|
-
})
|
|
83546
|
-
);
|
|
83547
|
-
}
|
|
83548
|
-
function ok(data) {
|
|
83549
|
-
return { content: [{ type: "text", text: serialize(data) }] };
|
|
83550
|
-
}
|
|
83551
|
-
|
|
83552
|
-
// src/tools/guide.ts
|
|
83553
|
-
var import_zod7 = require("zod");
|
|
83554
|
-
|
|
83555
|
-
// src/guide/content.ts
|
|
83556
|
-
var GUIDE_TOPICS = [
|
|
83557
|
-
"getting-started",
|
|
83558
|
-
"first-setup",
|
|
83559
|
-
"connect-wallet",
|
|
83560
|
-
"lifecycle",
|
|
83561
|
-
"fees",
|
|
83562
|
-
"psm",
|
|
83563
|
-
"authorization",
|
|
83564
|
-
"safe",
|
|
83565
|
-
"delegation",
|
|
83566
|
-
"safety",
|
|
83567
|
-
"switch-network",
|
|
83568
|
-
"connector",
|
|
83569
|
-
"troubleshooting",
|
|
83570
|
-
"glossary",
|
|
83571
|
-
"reading-data"
|
|
83572
|
-
];
|
|
83573
|
-
var GUIDE_CONTENT = {
|
|
83574
|
-
"getting-started": `# Diamond Hands \u2014 what this is
|
|
83575
|
-
|
|
83576
|
-
Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
|
|
83577
|
-
without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
|
|
83578
|
-
against it, pay it back whenever you like, and take your BTC out again.
|
|
83579
|
-
|
|
83580
|
-
**Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
|
|
83581
|
-
topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
|
|
83582
|
-
\`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
|
|
83583
|
-
are enabled (and the true reason when not), and which signer modes this build offers;
|
|
83584
|
-
never promise a capability it does not list. The money truth has THREE cases:
|
|
83585
|
-
- Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
|
|
83586
|
-
- Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
|
|
83587
|
-
the test network: real ceremonies and signatures, PRACTICE money (test funds).
|
|
83588
|
-
- Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
|
|
83589
|
-
explicitly arms them; the capabilities block states which applies.
|
|
83590
|
-
SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
|
|
83591
|
-
|
|
83592
|
-
A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
|
|
83593
|
-
authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
|
|
83594
|
-
calls. Every operation that moves funds requires the user's explicit confirmation
|
|
83595
|
-
(\`confirmed: true\`) \u2014 nothing is ever silent.`,
|
|
83596
|
-
"first-setup": `# First setup \u2014 from zero to ready, by conversation only
|
|
83597
|
-
|
|
83598
|
-
Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
|
|
83599
|
-
\u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
|
|
83600
|
-
host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
|
|
83601
|
-
developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
|
|
83602
|
-
install matrix. (A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented
|
|
83603
|
-
but NOT yet publicly served; its rollout is operator-gated. Truth and trust model:
|
|
83604
|
-
\`guide connector\`.)
|
|
83605
|
-
|
|
83606
|
-
Nothing needs a config file. Three steps:
|
|
83607
|
-
|
|
83608
|
-
**1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
|
|
83609
|
-
\`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
|
|
83610
|
-
(practice money) or mainnet (real money); whether writes are enabled here and which
|
|
83611
|
-
signer modes exist; current terms (\`protocol_terms\`).
|
|
83612
|
-
|
|
83613
|
-
**2. Choose HOW to authorize operations** (the user's choice, made by talking):
|
|
83614
|
-
- **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
|
|
83615
|
-
on the real adapter and the mock. The approval page auto-opens in the browser (its URL
|
|
83616
|
-
is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
|
|
83617
|
-
/ pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
|
|
83618
|
-
their own wallet. The first verified signature binds their wallet address as the
|
|
83619
|
-
borrower. Full walkthrough: \`guide connect-wallet\`.
|
|
83620
|
-
- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
|
|
83621
|
-
signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
|
|
83622
|
-
\`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
|
|
83623
|
-
LOCAL PAGE opens where the user types the password or generates a fresh keystore.
|
|
83624
|
-
NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
|
|
83625
|
-
them to use the unlock page instead.
|
|
83626
|
-
- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
|
|
83627
|
-
real adapter they refuse with that true reason. Try them in a mock world.
|
|
83628
|
-
- Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
|
|
83629
|
-
- **No signer is also a valid start:** every public read works without one \u2014
|
|
83630
|
-
\`position_list {borrower}\` with the user's address needs no signer and no login.
|
|
83631
|
-
- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
|
|
83632
|
-
talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
|
|
83633
|
-
the money reality after any switch.
|
|
83634
|
-
|
|
83635
|
-
**3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
|
|
83636
|
-
\`confirmed: true\` from the user). Then deposit BTC to the vault address
|
|
83637
|
-
(practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
|
|
83638
|
-
and mint with \`loan_mint\`.
|
|
83091
|
+
**3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
|
|
83092
|
+
\`confirmed: true\` from the user). Then deposit BTC to the vault address
|
|
83093
|
+
(practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
|
|
83094
|
+
and mint with \`loan_mint\`.
|
|
83639
83095
|
|
|
83640
83096
|
The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
|
|
83641
|
-
"connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
|
|
83097
|
+
"connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
|
|
83642
83098
|
|
|
83643
83099
|
External mode means the user approves every operation in their OWN wallet \u2014 a browser
|
|
83644
83100
|
extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
|
|
@@ -83646,17 +83102,19 @@ the mock.
|
|
|
83646
83102
|
|
|
83647
83103
|
**The walkthrough:**
|
|
83648
83104
|
1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
|
|
83649
|
-
desktop browser;
|
|
83650
|
-
same machine the server runs on).
|
|
83105
|
+
desktop browser; ${approvalPageLocation(d)}
|
|
83651
83106
|
2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
|
|
83652
83107
|
WalletConnect QR code or paste the pairing code.
|
|
83653
83108
|
3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
|
|
83654
83109
|
login ceremony explicitly (one typed-data signature in the wallet).
|
|
83655
83110
|
4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
|
|
83656
83111
|
across sessions (\`signer_setup reset-borrower\` unbinds it).
|
|
83657
|
-
5. From then on, every fund-moving operation shows an approval card in the wallet
|
|
83658
|
-
decoded from the exact
|
|
83659
|
-
|
|
83112
|
+
5. From then on, every fund-moving operation shows an approval card in the wallet. For
|
|
83113
|
+
TRANSACTIONS that card is decoded from the exact bytes being signed \u2014 what you read
|
|
83114
|
+
IS what executes. The ONE exception is the BTC withdrawal, which signs an opaque
|
|
83115
|
+
32-byte hash the page states plainly it CANNOT decode (honesty note below); say so
|
|
83116
|
+
before those popups, never "what you read is what executes". Declining always safely
|
|
83117
|
+
cancels.
|
|
83660
83118
|
|
|
83661
83119
|
**Popup cadence \u2014 exactly this many wallet interactions per operation:**
|
|
83662
83120
|
|
|
@@ -83668,7 +83126,7 @@ the mock.
|
|
|
83668
83126
|
| repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
|
|
83669
83127
|
| extend | 1 personal-sign + 1 tx |
|
|
83670
83128
|
| allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
|
|
83671
|
-
| withdraw BTC |
|
|
83129
|
+
| withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
|
|
83672
83130
|
| PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
|
|
83673
83131
|
|
|
83674
83132
|
**Honesty notes (say these plainly):**
|
|
@@ -83679,10 +83137,19 @@ the mock.
|
|
|
83679
83137
|
authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
|
|
83680
83138
|
surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
|
|
83681
83139
|
login means "wait and retry", not a wallet failure.
|
|
83682
|
-
- **Withdraw-BTC under external mode
|
|
83683
|
-
|
|
83684
|
-
|
|
83685
|
-
|
|
83140
|
+
- **Withdraw-BTC under external mode has ONE blind signature, not two.** The
|
|
83141
|
+
authorization phase is EIP-712 typed data \u2014 the wallet renders position, amount and
|
|
83142
|
+
destination and the user can read it. Only the EXECUTE phase signs an opaque 32-byte
|
|
83143
|
+
hash the SDK builds internally, which the approval page shows bare and says plainly it
|
|
83144
|
+
cannot decode (the production web app signs the same way). Tell the user before that
|
|
83145
|
+
ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
|
|
83146
|
+
expect an unreadable card and click through the readable one.
|
|
83147
|
+
- **The READABLE phase can be asked for up to THREE times.** Its authorization is only
|
|
83148
|
+
valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
|
|
83149
|
+
attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
|
|
83150
|
+
back. Warn the user: a second or third identical card is the retry, NOT a duplicate
|
|
83151
|
+
charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
|
|
83152
|
+
signature. The blind execute popup happens once.
|
|
83686
83153
|
- **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
|
|
83687
83154
|
(\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
|
|
83688
83155
|
hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
|
|
@@ -83717,7 +83184,7 @@ Connections / Connected sites).`,
|
|
|
83717
83184
|
reduced by unused origination-fee credit from the current term.
|
|
83718
83185
|
6. **Withdraw BTC** \u2014 \`loan_withdraw {positionId, btcAddress, amountSats, confirmed:true}\`.
|
|
83719
83186
|
BTC sends are IRREVERSIBLE \u2014 read the address back to the user before confirming.
|
|
83720
|
-
|
|
83187
|
+
amountSats is gross (fee comes out of it) and may be the whole available balance.
|
|
83721
83188
|
7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
|
|
83722
83189
|
\`position_events\` (history), \`btc_price\`, \`protocol_status\`.
|
|
83723
83190
|
|
|
@@ -83738,9 +83205,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
|
|
|
83738
83205
|
|
|
83739
83206
|
Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
|
|
83740
83207
|
signed, amounts included. Read it back when the user asks what happened.`,
|
|
83741
|
-
psm: `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
|
|
83208
|
+
psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
|
|
83742
83209
|
|
|
83743
|
-
The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
|
|
83210
|
+
${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
|
|
83744
83211
|
directions, in user words:
|
|
83745
83212
|
|
|
83746
83213
|
- **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
|
|
@@ -83787,24 +83254,18 @@ own address. If you approve step 1 but decline step 2, the exact-amount allowanc
|
|
|
83787
83254
|
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
|
|
83788
83255
|
On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
|
|
83789
83256
|
(the PSM-specific sepolia-only anchor; loan operations are not affected).`,
|
|
83790
|
-
authorization: `# Authorization \u2014 who signs, and what a signature means
|
|
83257
|
+
authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
|
|
83791
83258
|
|
|
83792
83259
|
Every fund-moving operation needs TWO things, always in this order:
|
|
83793
83260
|
1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
|
|
83794
83261
|
must ask, never assume.
|
|
83795
|
-
2. **A cryptographic authorization** by the chosen signer mode
|
|
83796
|
-
|
|
83797
|
-
|
|
83798
|
-
|
|
83799
|
-
|
|
83800
|
-
- \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
|
|
83801
|
-
Real adapter and mock.
|
|
83802
|
-
- \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
|
|
83803
|
-
refuse with that true reason (their planes ship in their own deliveries).
|
|
83804
|
-
- \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
|
|
83805
|
-
|
|
83262
|
+
2. **A cryptographic authorization** by the chosen signer mode. This build offers
|
|
83263
|
+
exactly ${d.signerModes.map((m) => `\`${m}\``).join(", ")} \u2014 ${signerModeSourceClause(d)}. Never
|
|
83264
|
+
describe a mode outside it:
|
|
83265
|
+
${authorizationModeBullets(d)}
|
|
83266
|
+
${keystoreAbsenceParagraph(d)}
|
|
83806
83267
|
**Reads never summon the wallet.** Public reads need no signer at all. Authenticated
|
|
83807
|
-
reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
|
|
83268
|
+
reads need a login \u2014 ${offers(d, "keystore") ? "the keystore env pair, or " : ""}an explicit "connect my wallet"
|
|
83808
83269
|
(\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
|
|
83809
83270
|
only ever caused by a write ceremony or that explicit connect. The login (one typed-data
|
|
83810
83271
|
signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
|
|
@@ -83820,9 +83281,28 @@ BOUND by the first verified signature (it persists across sessions). Connected \
|
|
|
83820
83281
|
picking external mode is a preference \u2014 a wallet still has to connect on the approval
|
|
83821
83282
|
page, and the page link comes from \`signer_setup status\`.
|
|
83822
83283
|
|
|
83823
|
-
Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat
|
|
83824
|
-
|
|
83825
|
-
|
|
83284
|
+
Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat${offers(d, "keystore") ? ";\nkeystore passwords go only into the secure unlock page." : " \u2014\nand this build has no password to ask for in the first place."}`,
|
|
83285
|
+
// Rendered on the capability axis: a build that constructs no Safe-shaped mode must not
|
|
83286
|
+
// hand a user a setup walkthrough its `signer_setup` cannot accept (the F1/F2 class,
|
|
83287
|
+
// one topic over). The concepts a Safe owner still needs stay; the instructions go.
|
|
83288
|
+
safe: (d) => !offers(d, "safe") ? `# Safe accounts \u2014 not offered by this build
|
|
83289
|
+
|
|
83290
|
+
A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
|
|
83291
|
+
signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Diamond Hands can
|
|
83292
|
+
treat a Safe AS THE BORROWER \u2014 but not from here. This build's authorization surface is
|
|
83293
|
+
the wallet ceremony alone; \`signer_setup\` lists no Safe-shaped option, so there is
|
|
83294
|
+
nothing to set up. Say that plainly instead of walking a user through a ceremony this
|
|
83295
|
+
service cannot run.
|
|
83296
|
+
|
|
83297
|
+
**What still holds for a Safe's position anywhere:** its BTC withdrawal destination must
|
|
83298
|
+
be ALLOWLISTED first, and the allowlist delay is READ LIVE from the chain \u2014 24 hours on
|
|
83299
|
+
mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS. Owner authorizations
|
|
83300
|
+
for mint/pay/renew expire in minutes and withdrawal authorizations within the minute, so
|
|
83301
|
+
a multi-owner signing session happens TOGETHER, live.
|
|
83302
|
+
|
|
83303
|
+
**Where it does exist:** the local install's practice worlds run the Safe borrower plane
|
|
83304
|
+
end to end, and the web app (diamondhands.credit) speaks to the same chain state. A user
|
|
83305
|
+
who needs it is not blocked \u2014 they are on the wrong surface for it.` : `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
|
|
83826
83306
|
|
|
83827
83307
|
A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
|
|
83828
83308
|
signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companies and
|
|
@@ -83858,7 +83338,24 @@ expire after ~3 minutes, and withdrawal authorizations within the minute \u2014
|
|
|
83858
83338
|
owner signing session happens TOGETHER, live ("gather first, sign in one burst").
|
|
83859
83339
|
Creating a position and allowlisting a destination have NO expiry \u2014 owners can sign
|
|
83860
83340
|
those at their own pace. The ceremony guides this; never widen a window.`,
|
|
83861
|
-
delegation: `# Delegation \u2014
|
|
83341
|
+
delegation: (d) => !offers(d, "safe-module") ? `# Delegation \u2014 not offered by this build
|
|
83342
|
+
|
|
83343
|
+
Delegation is the protocol's answer to multi-owner Safes: the owners sign ONCE to install
|
|
83344
|
+
a tightly-caged AGENT key, and day-to-day work then runs without disturbing them. It is a
|
|
83345
|
+
Safe-shaped authorization plane, and this build constructs none \u2014 \`signer_setup\` lists
|
|
83346
|
+
no such option and \`loan_delegation_setup\` has no plane to install into here. Say that
|
|
83347
|
+
plainly rather than describing a ceremony this service cannot run.
|
|
83348
|
+
|
|
83349
|
+
**The cage, for a user who asks what it would mean:** an agent may create a position and
|
|
83350
|
+
\u2014 only after the owners grant it, per position \u2014 repay, renew, and mint while the
|
|
83351
|
+
post-mint collateral ratio stays at or above the floor the owners set. It can NEVER
|
|
83352
|
+
withdraw Bitcoin alone, never add or change withdrawal destinations, never touch the
|
|
83353
|
+
module or the registry, never move ETH. A stolen agent key can shuffle money WITHIN a
|
|
83354
|
+
position \u2014 never out. Revoking an agent BURNS its address forever, which is why
|
|
83355
|
+
revocation is always safe.
|
|
83356
|
+
|
|
83357
|
+
**Where it does exist:** the local install's practice worlds, pending the plane's own
|
|
83358
|
+
delivery on the real adapter. The web app and the SDK reach the same chain state.` : `# Delegation \u2014 one owner ceremony, then day-to-day solo
|
|
83862
83359
|
|
|
83863
83360
|
Multi-owner Safes cannot practically sign every operation inside the protocol's short
|
|
83864
83361
|
signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
|
|
@@ -83902,8 +83399,11 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
|
|
|
83902
83399
|
|
|
83903
83400
|
- **Nothing moves without you.** Every write needs \`confirmed: true\` AND the signer
|
|
83904
83401
|
ceremony. A decline anywhere cleanly cancels \u2014 declining is always safe.
|
|
83905
|
-
- **The card is the truth.** In external mode the wallet card
|
|
83906
|
-
|
|
83402
|
+
- **The card is the truth \u2014 with one named exception.** In external mode the wallet card
|
|
83403
|
+
is decoded from the exact TRANSACTION bytes being signed: what you read IS what
|
|
83404
|
+
executes. The exception is the BTC-withdraw blind signature \u2014 an opaque 32-byte hash
|
|
83405
|
+
the approval page says plainly it cannot decode (\`guide connect-wallet\`). Never
|
|
83406
|
+
extend the "what you read is what executes" promise over that one.
|
|
83907
83407
|
- **Liquidation:** if collateral value falls so the collateral ratio drops under the
|
|
83908
83408
|
liquidation threshold (\`protocol_status.liquidationThresholdBps\`, e.g. 110%), the
|
|
83909
83409
|
position can be liquidated. Watch \`position_status.valuation\` \u2014 \`currentLtvBps\` vs the
|
|
@@ -83916,23 +83416,21 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
|
|
|
83916
83416
|
withdrawing to a wrong address. Repaid-in-full positions release all collateral.
|
|
83917
83417
|
- **Practice vs real:** mock worlds are stated as such (\`boundary://info\`). Never let a
|
|
83918
83418
|
user believe practice gains/losses are real, or vice versa.`,
|
|
83919
|
-
"switch-network": `# Switch network \u2014
|
|
83419
|
+
"switch-network": (d) => `# Switch network \u2014 ${switchNetworkHeadline(d)}
|
|
83920
83420
|
|
|
83921
83421
|
The \`network_switch\` tool moves THIS SESSION between worlds. Check
|
|
83922
83422
|
\`boundary://info\` capabilities first: \`networkSwitch: true\` means it is available
|
|
83923
83423
|
(real adapter); in a practice sandbox (mock) the world is pinned by config \u2014 there is
|
|
83924
83424
|
no switch, and that is by design.
|
|
83925
83425
|
|
|
83426
|
+
**Served here:** ${servedNetworks(d)}. A network this deployment does not serve is
|
|
83427
|
+
refused with that reason \u2014 the tool existing is not a promise that both worlds are
|
|
83428
|
+
reachable, so never offer the user a network this deployment does not serve.
|
|
83429
|
+
|
|
83926
83430
|
**The rules, plainly:**
|
|
83927
83431
|
- \`network_switch status\` \u2014 which network is active and whether money is real. Say
|
|
83928
83432
|
this to the user BEFORE and AFTER any switch, always.
|
|
83929
|
-
|
|
83930
|
-
the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
|
|
83931
|
-
- NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
|
|
83932
|
-
A sepolia position does not exist on mainnet and vice versa.
|
|
83933
|
-
- Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
|
|
83934
|
-
and every one still requires the user's explicit confirmation plus the signer
|
|
83935
|
-
ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.
|
|
83433
|
+
${switchNetworkRules(d)}
|
|
83936
83434
|
- A pending signing ceremony blocks the switch (finish or decline it first).
|
|
83937
83435
|
- The switch is session-scoped: when the server restarts, the configured default
|
|
83938
83436
|
network returns.
|
|
@@ -83942,12 +83440,9 @@ reality in your next message. The user must never have to ask which world they a
|
|
|
83942
83440
|
// Plan 17 B1 — the hosted tier's truth, in user language. The trust ledger below is
|
|
83943
83441
|
// the plan-12 Part 0 ledger (BINDING, archive/12-remote-connector.md) — all six
|
|
83944
83442
|
// entries, verbatim-equivalent; G-CONN pins anchor phrases from every entry.
|
|
83945
|
-
connector: `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
|
|
83443
|
+
connector: (d) => `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
|
|
83946
83444
|
|
|
83947
|
-
|
|
83948
|
-
publicly served \u2014 the operator's rollout gates (a security audit, then a URL) come
|
|
83949
|
-
first. Until then there is no URL to give out, and the local install paths
|
|
83950
|
-
(\`first-setup\`) are the way in. Never promise availability or timing.
|
|
83445
|
+
${connectorStatusTruth(d)}
|
|
83951
83446
|
|
|
83952
83447
|
**What it is:** instead of installing anything, the user adds Diamond Hands to
|
|
83953
83448
|
claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
|
|
@@ -83974,9 +83469,17 @@ honestly when asked "is this safe"):
|
|
|
83974
83469
|
is never written to disk. A breach here is privacy-class, never money-class.
|
|
83975
83470
|
3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
|
|
83976
83471
|
a security concern is filed and audited for exactly this channel.
|
|
83977
|
-
4. **Tenant separation
|
|
83978
|
-
|
|
83979
|
-
|
|
83472
|
+
4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
|
|
83473
|
+
gets its own world: its own boundary, its own signer state, its own approval-page
|
|
83474
|
+
mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
|
|
83475
|
+
world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
|
|
83476
|
+
plus an earlier connection would make a different wallet this session's signer. That
|
|
83477
|
+
is signing-class, not merely privacy-class; do not tell a user it cannot be. What
|
|
83478
|
+
contains it: the mount id is freshly random per world and travels only in the user's
|
|
83479
|
+
own tool result (treat the link as a secret), and EVERY fund movement verifies the
|
|
83480
|
+
signature against that bound borrower \u2014 no key material exists server-side, so
|
|
83481
|
+
whoever reaches the page still cannot sign for anyone else. The gap is filed and
|
|
83482
|
+
audited; state it this way rather than claiming a binding that isn't there.
|
|
83980
83483
|
5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
|
|
83981
83484
|
version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
|
|
83982
83485
|
reports the exact server version.
|
|
@@ -83988,30 +83491,37 @@ honestly when asked "is this safe"):
|
|
|
83988
83491
|
|
|
83989
83492
|
**What it structurally CANNOT do:** hold keys or custody \u2014 keystore mode is ABSENT
|
|
83990
83493
|
from the connector build (not disabled: never constructed), so every fund-moving
|
|
83991
|
-
action needs a fresh signature from the user's own wallet.
|
|
83992
|
-
networks its deployment is rolled out to \u2014 this deployment serves sepolia during
|
|
83993
|
-
rollout; mainnet enablement is the operator's deploy decision, stated in capabilities
|
|
83994
|
-
by reason, never a hidden knob.
|
|
83494
|
+
action needs a fresh signature from the user's own wallet. ${connectorNetworkTruth(d)}
|
|
83995
83495
|
|
|
83996
83496
|
**Independent exits:** the web app (diamondhands.credit) and the SDK speak to the SAME
|
|
83997
83497
|
chain state. The connector going down strands nothing and gates nothing.`,
|
|
83998
|
-
troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
|
|
83498
|
+
troubleshooting: (d) => `# Troubleshooting \u2014 what error codes mean, in plain words
|
|
83999
83499
|
|
|
84000
|
-
|
|
83500
|
+
${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
|
|
84001
83501
|
keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
|
|
84002
83502
|
"connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
|
|
84003
83503
|
status\` explains what is active; \`first-setup\` step 2 has the full choice.
|
|
84004
83504
|
- **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
|
|
84005
83505
|
the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
|
|
84006
|
-
EXPIRED login refuses the same way \u2014 reconnect on the user's word.
|
|
84007
|
-
|
|
84008
|
-
|
|
84009
|
-
|
|
84010
|
-
|
|
84011
|
-
|
|
83506
|
+
EXPIRED login refuses the same way \u2014 reconnect on the user's word.` : `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. This build has exactly
|
|
83507
|
+
ONE remedy: the user says "connect my wallet" \u2192 \`signer_setup\` action \`connect\`
|
|
83508
|
+
(external mode). There is no keystore here to configure and no password to supply \u2014
|
|
83509
|
+
saying otherwise sends the user hunting for a setting that does not exist.
|
|
83510
|
+
\`signer_setup status\` explains what is active; \`first-setup\` step 2 has the choice.
|
|
83511
|
+
- **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
|
|
83512
|
+
the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
|
|
83513
|
+
the same way \u2014 reconnect on the user's word.`}
|
|
83514
|
+
${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
|
|
83515
|
+
not a bug); loan operations work on mainnet. Reads keep working everywhere.` : `- **PSM write refused** \u2014 the PSM write port answers on sepolia alone (a deliberate
|
|
83516
|
+
anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
|
|
83517
|
+
${wrongNetworkTroubleshootingRow(d)}
|
|
84012
83518
|
- **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
|
|
84013
|
-
SDK builds the
|
|
84014
|
-
|
|
83519
|
+
SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
|
|
83520
|
+
signature per withdrawal, not two: the authorization phase is EIP-712 typed data
|
|
83521
|
+
(\`WithdrawRequest\` \u2014 the wallet renders position, amount and destination), and only
|
|
83522
|
+
the execute phase is opaque. Warn the user before that one popup, and do not describe
|
|
83523
|
+
the typed one as blind \u2014 overstating it teaches them to expect an unreadable card and
|
|
83524
|
+
click through the readable one.
|
|
84015
83525
|
- **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
|
|
84016
83526
|
That is the broker throttle, not a wallet failure.
|
|
84017
83527
|
- **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
|
|
@@ -84026,9 +83536,7 @@ chain state. The connector going down strands nothing and gates nothing.`,
|
|
|
84026
83536
|
which source and when from. Prefer chain-sourced values; re-read before acting.
|
|
84027
83537
|
- Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
|
|
84028
83538
|
Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
|
|
84029
|
-
|
|
84030
|
-
publicly served (the operator's audit + rollout gates come first). There is no URL to
|
|
84031
|
-
give out; the local install paths work today. Full truth: \`guide connector\`.
|
|
83539
|
+
${connectorTroubleshootingRow(d)}
|
|
84032
83540
|
- **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
|
|
84033
83541
|
the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
|
|
84034
83542
|
Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
|
|
@@ -84048,7 +83556,8 @@ Synonym sets (treat these as the SAME intent):
|
|
|
84048
83556
|
- **UCD** = the dollar-pegged token you borrow ("the dollars")
|
|
84049
83557
|
- **sats** = satoshis, 1 BTC = 100,000,000 sats
|
|
84050
83558
|
- **connector** = remote = hosted tier = "claude.ai integration" = "use it without
|
|
84051
|
-
installing" \u2192 \`guide connector\` (
|
|
83559
|
+
installing" \u2192 \`guide connector\` (it states which tier THIS session is, and the
|
|
83560
|
+
trust model that comes with it)
|
|
84052
83561
|
|
|
84053
83562
|
Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
|
|
84054
83563
|
- **vault** \u2014 the position's BTC custody address. Its balance is your COLLATERAL, not
|
|
@@ -84059,39 +83568,1099 @@ Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
|
|
|
84059
83568
|
- **interest** \u2014 Diamond Hands charges FEES (origination/extension), not running
|
|
84060
83569
|
interest; see \`fees\`.
|
|
84061
83570
|
|
|
84062
|
-
Language: answer in the user's language, whatever it is. These mappings apply to meaning,
|
|
84063
|
-
not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
|
|
84064
|
-
"emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
|
|
84065
|
-
// Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
|
|
84066
|
-
// the same entries the anchor test pins against the actually-serialized fields.
|
|
84067
|
-
"reading-data": renderFieldGlossaryTopic()
|
|
83571
|
+
Language: answer in the user's language, whatever it is. These mappings apply to meaning,
|
|
83572
|
+
not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
|
|
83573
|
+
"emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
|
|
83574
|
+
// Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
|
|
83575
|
+
// the same entries the anchor test pins against the actually-serialized fields.
|
|
83576
|
+
"reading-data": renderFieldGlossaryTopic()
|
|
83577
|
+
};
|
|
83578
|
+
function renderGuideContent(deployment) {
|
|
83579
|
+
const content = {};
|
|
83580
|
+
for (const topic of GUIDE_TOPICS) {
|
|
83581
|
+
const source = GUIDE_TOPIC_SOURCES[topic];
|
|
83582
|
+
content[topic] = typeof source === "string" ? source : source(deployment);
|
|
83583
|
+
}
|
|
83584
|
+
return content;
|
|
83585
|
+
}
|
|
83586
|
+
function renderGuideIndex(deployment) {
|
|
83587
|
+
const connectorLine = deployment.tier === "hosted" ? `- connector \u2014 the hosted claude.ai tier THIS session is running on (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. Serves ${servedNetworks(deployment)}` : "- connector \u2014 the hosted claude.ai tier (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. THIS session is a local install, not that tier";
|
|
83588
|
+
return `# Diamond Hands guide \u2014 topics
|
|
83589
|
+
|
|
83590
|
+
- getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
|
|
83591
|
+
- first-setup \u2014 zero to ready by conversation (authorization choice included)
|
|
83592
|
+
- connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
|
|
83593
|
+
- lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
|
|
83594
|
+
- fees \u2014 the two fee models, plainly
|
|
83595
|
+
- psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
|
|
83596
|
+
- authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
|
|
83597
|
+
${offers(deployment, "safe") ? "- safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today" : "- safe \u2014 borrowing as a Safe smart-account: NOT offered by this build (no Safe-shaped mode exists here), and what still holds wherever it is"}
|
|
83598
|
+
${offers(deployment, "safe-module") ? "- delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today" : "- delegation \u2014 the caged agent key for multi-owner Safes: NOT offered by this build, and what the cage would mean where it is"}
|
|
83599
|
+
- safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
|
|
83600
|
+
${switchNetworkIndexLine(deployment)}
|
|
83601
|
+
${connectorLine}
|
|
83602
|
+
- troubleshooting \u2014 error codes in plain words, with the real remedies
|
|
83603
|
+
- glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
|
|
83604
|
+
- reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
|
|
83605
|
+
|
|
83606
|
+
Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
|
|
83607
|
+
selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
|
|
83608
|
+
signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
|
|
83609
|
+
and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
|
|
83610
|
+
only mainnet is real money.`;
|
|
83611
|
+
}
|
|
83612
|
+
var deploymentKey = (d) => `${d.tier}|${d.networks.join(",")}|${d.signerModes.join(",")}`;
|
|
83613
|
+
var RENDERED = /* @__PURE__ */ new Map();
|
|
83614
|
+
function renderedGuide(deployment) {
|
|
83615
|
+
const key = deploymentKey(deployment);
|
|
83616
|
+
let rendered = RENDERED.get(key);
|
|
83617
|
+
if (!rendered) {
|
|
83618
|
+
rendered = Object.freeze({
|
|
83619
|
+
content: Object.freeze(renderGuideContent(deployment)),
|
|
83620
|
+
index: renderGuideIndex(deployment)
|
|
83621
|
+
});
|
|
83622
|
+
RENDERED.set(key, rendered);
|
|
83623
|
+
}
|
|
83624
|
+
return rendered;
|
|
83625
|
+
}
|
|
83626
|
+
function buildGuideContent(deployment) {
|
|
83627
|
+
return renderedGuide(deployment).content;
|
|
83628
|
+
}
|
|
83629
|
+
function buildGuideIndex(deployment) {
|
|
83630
|
+
return renderedGuide(deployment).index;
|
|
83631
|
+
}
|
|
83632
|
+
var GUIDE_CONTENT = buildGuideContent(LOCAL_GUIDE_DEPLOYMENT);
|
|
83633
|
+
var GUIDE_INDEX = buildGuideIndex(LOCAL_GUIDE_DEPLOYMENT);
|
|
83634
|
+
|
|
83635
|
+
// src/network-switch.ts
|
|
83636
|
+
var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
|
|
83637
|
+
function createNetworkSwitchRuntime(opts) {
|
|
83638
|
+
return {
|
|
83639
|
+
current() {
|
|
83640
|
+
const b = opts.getBoot().boundaryResult;
|
|
83641
|
+
if (!b.ok) return null;
|
|
83642
|
+
const w = b.boundary.world();
|
|
83643
|
+
return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
|
|
83644
|
+
},
|
|
83645
|
+
async switchTo(network) {
|
|
83646
|
+
const allowed = opts.overrides?.allowedNetworks;
|
|
83647
|
+
if (allowed && !allowed.includes(network)) {
|
|
83648
|
+
return {
|
|
83649
|
+
ok: false,
|
|
83650
|
+
error: boundaryError(
|
|
83651
|
+
"VALIDATION_FAILED",
|
|
83652
|
+
`this deployment serves ${allowed.join(", ")} \u2014 '${network}' is not enabled on this service. Mainnet service enablement is a rollout step of the deployment, not a session setting.`
|
|
83653
|
+
)
|
|
83654
|
+
};
|
|
83655
|
+
}
|
|
83656
|
+
const targetEnv = { ...opts.env, DH_NETWORK: network };
|
|
83657
|
+
const configResult = resolveBoundaryConfig(targetEnv);
|
|
83658
|
+
if (!configResult.ok) return { ok: false, error: configResult.error };
|
|
83659
|
+
const next = await buildBoundary(configResult, opts.overrides);
|
|
83660
|
+
if (!next.boundaryResult.ok) {
|
|
83661
|
+
next.dispose();
|
|
83662
|
+
return { ok: false, error: next.boundaryResult.error };
|
|
83663
|
+
}
|
|
83664
|
+
opts.swap(next);
|
|
83665
|
+
return { ok: true };
|
|
83666
|
+
}
|
|
83667
|
+
};
|
|
83668
|
+
}
|
|
83669
|
+
function guideDeployment(overrides) {
|
|
83670
|
+
return {
|
|
83671
|
+
tier: overrides?.bridgeMount ? "hosted" : "local",
|
|
83672
|
+
networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
|
|
83673
|
+
signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
|
|
83674
|
+
};
|
|
83675
|
+
}
|
|
83676
|
+
function assembleWorld(opts) {
|
|
83677
|
+
let boot = opts.boot;
|
|
83678
|
+
const deps = {
|
|
83679
|
+
boundaryResult: boot.boundaryResult,
|
|
83680
|
+
...boot.mockControl ? { mockControl: boot.mockControl } : {},
|
|
83681
|
+
...boot.signer ? { signer: boot.signer } : {},
|
|
83682
|
+
...opts.overrides?.externalOnly ? { externalOnly: true } : {},
|
|
83683
|
+
deployment: guideDeployment(opts.overrides),
|
|
83684
|
+
...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
|
|
83685
|
+
};
|
|
83686
|
+
if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
|
|
83687
|
+
deps.networkSwitch = createNetworkSwitchRuntime({
|
|
83688
|
+
env: opts.env,
|
|
83689
|
+
getBoot: () => boot,
|
|
83690
|
+
...opts.overrides ? { overrides: opts.overrides } : {},
|
|
83691
|
+
swap: (next) => {
|
|
83692
|
+
const old = boot;
|
|
83693
|
+
boot = next;
|
|
83694
|
+
deps.boundaryResult = next.boundaryResult;
|
|
83695
|
+
if (next.signer) deps.signer = next.signer;
|
|
83696
|
+
else delete deps.signer;
|
|
83697
|
+
old.dispose();
|
|
83698
|
+
const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
|
|
83699
|
+
opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
|
|
83700
|
+
}
|
|
83701
|
+
});
|
|
83702
|
+
}
|
|
83703
|
+
return { deps, dispose: () => boot.dispose() };
|
|
83704
|
+
}
|
|
83705
|
+
|
|
83706
|
+
// src/server.ts
|
|
83707
|
+
var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
83708
|
+
|
|
83709
|
+
// src/tools/loan.ts
|
|
83710
|
+
var import_zod = require("zod");
|
|
83711
|
+
var import_ethers41 = require("ethers");
|
|
83712
|
+
|
|
83713
|
+
// src/util/format.ts
|
|
83714
|
+
function bigintReplacer(_key, value) {
|
|
83715
|
+
if (typeof value === "bigint") return value.toString();
|
|
83716
|
+
return value;
|
|
83717
|
+
}
|
|
83718
|
+
function serialize(data) {
|
|
83719
|
+
return JSON.stringify(data, bigintReplacer, 2);
|
|
83720
|
+
}
|
|
83721
|
+
|
|
83722
|
+
// src/tools/_helpers.ts
|
|
83723
|
+
function registerBoundaryTool(server, name, config, handler) {
|
|
83724
|
+
server.registerTool(name, config, handler);
|
|
83725
|
+
}
|
|
83726
|
+
function renderError(error) {
|
|
83727
|
+
const lines = [`ERROR [${error.code}]: ${error.message}`];
|
|
83728
|
+
if (error.source) lines.push(`source: ${error.source}`);
|
|
83729
|
+
return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
|
|
83730
|
+
}
|
|
83731
|
+
function renderEnvelope(env) {
|
|
83732
|
+
if (!env.ok) return renderError(env.error);
|
|
83733
|
+
const parts = [serialize(env.data)];
|
|
83734
|
+
if (env.warnings.length > 0) {
|
|
83735
|
+
parts.push(
|
|
83736
|
+
"WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
|
|
83737
|
+
);
|
|
83738
|
+
}
|
|
83739
|
+
parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
|
|
83740
|
+
return { content: [{ type: "text", text: parts.join("\n\n") }] };
|
|
83741
|
+
}
|
|
83742
|
+
function validationFailed(problem) {
|
|
83743
|
+
return renderError(boundaryError("VALIDATION_FAILED", problem));
|
|
83744
|
+
}
|
|
83745
|
+
function resourceJson(env) {
|
|
83746
|
+
if (!env.ok) return serialize({ error: env.error });
|
|
83747
|
+
return serialize({ data: env.data, warnings: env.warnings, source: env.source });
|
|
83748
|
+
}
|
|
83749
|
+
function resourceErrorJson(error) {
|
|
83750
|
+
return serialize({ error });
|
|
83751
|
+
}
|
|
83752
|
+
function requireConfirmation(confirmed, actionLabel) {
|
|
83753
|
+
if (confirmed === true) return null;
|
|
83754
|
+
return {
|
|
83755
|
+
content: [
|
|
83756
|
+
{
|
|
83757
|
+
type: "text",
|
|
83758
|
+
text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
|
|
83759
|
+
This is an irreversible, fund-moving action. A human must explicitly authorize it.
|
|
83760
|
+
Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
|
|
83761
|
+
}
|
|
83762
|
+
],
|
|
83763
|
+
isError: true
|
|
83764
|
+
};
|
|
83765
|
+
}
|
|
83766
|
+
function envStamp(b) {
|
|
83767
|
+
if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
|
|
83768
|
+
const w = b.boundary.world();
|
|
83769
|
+
const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
|
|
83770
|
+
return `environment: ${w.network} \u2014 ${money}`;
|
|
83771
|
+
}
|
|
83772
|
+
async function guardedWrite(getB, fn) {
|
|
83773
|
+
const result = await guarded(fn);
|
|
83774
|
+
const stamp = envStamp(getB());
|
|
83775
|
+
const content = result.content.map(
|
|
83776
|
+
(c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
|
|
83777
|
+
|
|
83778
|
+
${stamp}` } : c
|
|
83779
|
+
);
|
|
83780
|
+
return { ...result, content };
|
|
83781
|
+
}
|
|
83782
|
+
async function guarded(fn) {
|
|
83783
|
+
try {
|
|
83784
|
+
return await fn();
|
|
83785
|
+
} catch (e) {
|
|
83786
|
+
return renderError(
|
|
83787
|
+
boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
|
|
83788
|
+
details: { stack: e.stack }
|
|
83789
|
+
})
|
|
83790
|
+
);
|
|
83791
|
+
}
|
|
83792
|
+
}
|
|
83793
|
+
|
|
83794
|
+
// src/util/validate.ts
|
|
83795
|
+
var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
83796
|
+
var SATS_SANITY_CAP = 1e10;
|
|
83797
|
+
var UCD_SANITY_CAP = 1e9;
|
|
83798
|
+
function checkPositionIdHex(id, label = "Position ID") {
|
|
83799
|
+
if (!POSITION_ID_RE.test(id)) {
|
|
83800
|
+
return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
|
|
83801
|
+
}
|
|
83802
|
+
return null;
|
|
83803
|
+
}
|
|
83804
|
+
function checkUcdAmount(amount, label = "Amount") {
|
|
83805
|
+
if (!Number.isFinite(amount) || amount <= 0) {
|
|
83806
|
+
return `${label} must be a positive finite number (got ${amount}).`;
|
|
83807
|
+
}
|
|
83808
|
+
if (amount > UCD_SANITY_CAP) {
|
|
83809
|
+
return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
|
|
83810
|
+
}
|
|
83811
|
+
if (amount > 0 && amount < 1e-6) {
|
|
83812
|
+
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
83813
|
+
}
|
|
83814
|
+
const decimals = amount.toString().split(".")[1];
|
|
83815
|
+
if (decimals && decimals.length > 6) {
|
|
83816
|
+
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
83817
|
+
}
|
|
83818
|
+
return null;
|
|
83819
|
+
}
|
|
83820
|
+
function checkSatsAmount(sats, label = "Amount") {
|
|
83821
|
+
if (!Number.isInteger(sats) || sats <= 0) {
|
|
83822
|
+
return `${label} must be a positive integer (satoshis), got ${sats}.`;
|
|
83823
|
+
}
|
|
83824
|
+
if (sats > SATS_SANITY_CAP) {
|
|
83825
|
+
return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
|
|
83826
|
+
}
|
|
83827
|
+
return null;
|
|
83828
|
+
}
|
|
83829
|
+
function checkSelectedTerm(months, label = "Term") {
|
|
83830
|
+
if (!Number.isInteger(months) || months <= 0) {
|
|
83831
|
+
return `${label} must be a positive integer (months), got ${months}.`;
|
|
83832
|
+
}
|
|
83833
|
+
if (months > 120) {
|
|
83834
|
+
return `${label} ${months} months exceeds the 10-year sanity cap.`;
|
|
83835
|
+
}
|
|
83836
|
+
return null;
|
|
83837
|
+
}
|
|
83838
|
+
|
|
83839
|
+
// src/tools/loan.ts
|
|
83840
|
+
var LATENCY_NOTES = {
|
|
83841
|
+
mock: "Instant in this practice world.",
|
|
83842
|
+
real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
|
|
83843
|
+
};
|
|
83844
|
+
var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
|
|
83845
|
+
var confirmedSchema = import_zod.z.boolean().optional().describe(
|
|
83846
|
+
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
83847
|
+
);
|
|
83848
|
+
var DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
83849
|
+
readOnlyHint: false,
|
|
83850
|
+
destructiveHint: true,
|
|
83851
|
+
idempotentHint: false,
|
|
83852
|
+
openWorldHint: true
|
|
83853
|
+
};
|
|
83854
|
+
function registerLoanTools(server, getB, adapter2 = "real") {
|
|
83855
|
+
const LATENCY_NOTE = LATENCY_NOTES[adapter2];
|
|
83856
|
+
registerBoundaryTool(
|
|
83857
|
+
server,
|
|
83858
|
+
"loan_create",
|
|
83859
|
+
{
|
|
83860
|
+
title: "Create a new lending position",
|
|
83861
|
+
description: `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
83862
|
+
inputSchema: {
|
|
83863
|
+
selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
|
|
83864
|
+
confirmed: confirmedSchema
|
|
83865
|
+
},
|
|
83866
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83867
|
+
},
|
|
83868
|
+
async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
83869
|
+
const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
|
|
83870
|
+
if (gate) return gate;
|
|
83871
|
+
const problem = checkSelectedTerm(selectedTerm);
|
|
83872
|
+
if (problem) return validationFailed(problem);
|
|
83873
|
+
const b = getB();
|
|
83874
|
+
if (!b.ok) return renderError(b.error);
|
|
83875
|
+
return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
|
|
83876
|
+
})
|
|
83877
|
+
);
|
|
83878
|
+
registerBoundaryTool(
|
|
83879
|
+
server,
|
|
83880
|
+
"loan_mint",
|
|
83881
|
+
{
|
|
83882
|
+
title: "Mint UCD against a position",
|
|
83883
|
+
description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
83884
|
+
inputSchema: {
|
|
83885
|
+
positionId: positionIdSchema,
|
|
83886
|
+
amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
|
|
83887
|
+
confirmed: confirmedSchema
|
|
83888
|
+
},
|
|
83889
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83890
|
+
},
|
|
83891
|
+
async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
|
|
83892
|
+
const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
|
|
83893
|
+
if (gate) return gate;
|
|
83894
|
+
const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
|
|
83895
|
+
if (problem) return validationFailed(problem);
|
|
83896
|
+
const b = getB();
|
|
83897
|
+
if (!b.ok) return renderError(b.error);
|
|
83898
|
+
return renderEnvelope(
|
|
83899
|
+
await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
|
|
83900
|
+
);
|
|
83901
|
+
})
|
|
83902
|
+
);
|
|
83903
|
+
registerBoundaryTool(
|
|
83904
|
+
server,
|
|
83905
|
+
"loan_pay",
|
|
83906
|
+
{
|
|
83907
|
+
title: "Make a UCD payment toward a position's debt",
|
|
83908
|
+
description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
83909
|
+
inputSchema: {
|
|
83910
|
+
positionId: positionIdSchema,
|
|
83911
|
+
amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
|
|
83912
|
+
repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
|
|
83913
|
+
confirmed: confirmedSchema
|
|
83914
|
+
},
|
|
83915
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83916
|
+
},
|
|
83917
|
+
async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
|
|
83918
|
+
if (repayAll === true === (amountUcd !== void 0)) {
|
|
83919
|
+
return validationFailed("provide exactly one of amountUcd or repayAll: true");
|
|
83920
|
+
}
|
|
83921
|
+
const gate = requireConfirmation(
|
|
83922
|
+
confirmed,
|
|
83923
|
+
repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
|
|
83924
|
+
);
|
|
83925
|
+
if (gate) return gate;
|
|
83926
|
+
const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
|
|
83927
|
+
if (problem) return validationFailed(problem);
|
|
83928
|
+
const b = getB();
|
|
83929
|
+
if (!b.ok) return renderError(b.error);
|
|
83930
|
+
let amountUcdWei;
|
|
83931
|
+
if (repayAll) {
|
|
83932
|
+
const detail = await b.boundary.getPosition(positionId);
|
|
83933
|
+
if (!detail.ok) return renderError(detail.error);
|
|
83934
|
+
if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
|
|
83935
|
+
amountUcdWei = detail.data.debtUcdWei;
|
|
83936
|
+
} else {
|
|
83937
|
+
amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
|
|
83938
|
+
}
|
|
83939
|
+
return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
|
|
83940
|
+
})
|
|
83941
|
+
);
|
|
83942
|
+
registerBoundaryTool(
|
|
83943
|
+
server,
|
|
83944
|
+
"loan_extend",
|
|
83945
|
+
{
|
|
83946
|
+
title: "Extend / renew a position's term",
|
|
83947
|
+
description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
83948
|
+
inputSchema: {
|
|
83949
|
+
positionId: positionIdSchema,
|
|
83950
|
+
selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
|
|
83951
|
+
confirmed: confirmedSchema
|
|
83952
|
+
},
|
|
83953
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83954
|
+
},
|
|
83955
|
+
async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
83956
|
+
const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
|
|
83957
|
+
if (gate) return gate;
|
|
83958
|
+
const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
|
|
83959
|
+
if (problem) return validationFailed(problem);
|
|
83960
|
+
const b = getB();
|
|
83961
|
+
if (!b.ok) return renderError(b.error);
|
|
83962
|
+
return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
|
|
83963
|
+
})
|
|
83964
|
+
);
|
|
83965
|
+
registerBoundaryTool(
|
|
83966
|
+
server,
|
|
83967
|
+
"loan_withdraw",
|
|
83968
|
+
{
|
|
83969
|
+
title: "Withdraw BTC from a position vault",
|
|
83970
|
+
description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
|
|
83971
|
+
inputSchema: {
|
|
83972
|
+
positionId: positionIdSchema,
|
|
83973
|
+
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
|
|
83974
|
+
amountSats: import_zod.z.number().int().positive().describe(
|
|
83975
|
+
"GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. amountSats may be up to the whole available balance (a full sweep leaves 0 sats; anything above available reverts TargetExceedsInputValue). position_status.maxWithdrawableSats is a ready-to-use value that already leaves the default fee aside."
|
|
83976
|
+
),
|
|
83977
|
+
networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
|
|
83978
|
+
confirmed: confirmedSchema
|
|
83979
|
+
},
|
|
83980
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83981
|
+
},
|
|
83982
|
+
async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
|
|
83983
|
+
const gate = requireConfirmation(
|
|
83984
|
+
confirmed,
|
|
83985
|
+
`withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
|
|
83986
|
+
);
|
|
83987
|
+
if (gate) return gate;
|
|
83988
|
+
const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
|
|
83989
|
+
if (problem) return validationFailed(problem);
|
|
83990
|
+
const b = getB();
|
|
83991
|
+
if (!b.ok) return renderError(b.error);
|
|
83992
|
+
return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
|
|
83993
|
+
})
|
|
83994
|
+
);
|
|
83995
|
+
registerBoundaryTool(
|
|
83996
|
+
server,
|
|
83997
|
+
"loan_allowlist_destination",
|
|
83998
|
+
{
|
|
83999
|
+
title: "Allowlist a BTC withdrawal destination",
|
|
84000
|
+
description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
|
|
84001
|
+
inputSchema: {
|
|
84002
|
+
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
|
|
84003
|
+
confirmed: confirmedSchema
|
|
84004
|
+
},
|
|
84005
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
84006
|
+
},
|
|
84007
|
+
async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
|
|
84008
|
+
const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
|
|
84009
|
+
if (gate) return gate;
|
|
84010
|
+
const b = getB();
|
|
84011
|
+
if (!b.ok) return renderError(b.error);
|
|
84012
|
+
return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
|
|
84013
|
+
})
|
|
84014
|
+
);
|
|
84015
|
+
registerBoundaryTool(
|
|
84016
|
+
server,
|
|
84017
|
+
"loan_delegation_setup",
|
|
84018
|
+
{
|
|
84019
|
+
title: "Install delegation on the Safe (one owner ceremony)",
|
|
84020
|
+
description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
|
|
84021
|
+
inputSchema: {
|
|
84022
|
+
btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
|
|
84023
|
+
confirmed: confirmedSchema
|
|
84024
|
+
},
|
|
84025
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
84026
|
+
},
|
|
84027
|
+
async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
|
|
84028
|
+
const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
|
|
84029
|
+
if (gate) return gate;
|
|
84030
|
+
const b = getB();
|
|
84031
|
+
if (!b.ok) return renderError(b.error);
|
|
84032
|
+
return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
|
|
84033
|
+
})
|
|
84034
|
+
);
|
|
84035
|
+
registerBoundaryTool(
|
|
84036
|
+
server,
|
|
84037
|
+
"loan_delegation_grant",
|
|
84038
|
+
{
|
|
84039
|
+
title: "Grant the agent per-position scopes (owners sign)",
|
|
84040
|
+
description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
|
|
84041
|
+
inputSchema: {
|
|
84042
|
+
positionId: positionIdSchema,
|
|
84043
|
+
renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
|
|
84044
|
+
repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
|
|
84045
|
+
mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
|
|
84046
|
+
confirmed: confirmedSchema
|
|
84047
|
+
},
|
|
84048
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
84049
|
+
},
|
|
84050
|
+
async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
|
|
84051
|
+
const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
|
|
84052
|
+
if (gate) return gate;
|
|
84053
|
+
const b = getB();
|
|
84054
|
+
if (!b.ok) return renderError(b.error);
|
|
84055
|
+
return renderEnvelope(
|
|
84056
|
+
await b.boundary.delegationGrant({
|
|
84057
|
+
positionId,
|
|
84058
|
+
renew: renew ?? false,
|
|
84059
|
+
repay: repay ?? false,
|
|
84060
|
+
mintFloorBps: mintFloorBps ?? null
|
|
84061
|
+
})
|
|
84062
|
+
);
|
|
84063
|
+
})
|
|
84064
|
+
);
|
|
84065
|
+
registerBoundaryTool(
|
|
84066
|
+
server,
|
|
84067
|
+
"loan_recover_stale_spend",
|
|
84068
|
+
{
|
|
84069
|
+
title: "Recover a stale BTC reservation via LIT-attested proof",
|
|
84070
|
+
description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
|
|
84071
|
+
inputSchema: {
|
|
84072
|
+
positionId: positionIdSchema,
|
|
84073
|
+
utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
|
|
84074
|
+
utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
|
|
84075
|
+
invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
|
|
84076
|
+
minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
|
|
84077
|
+
},
|
|
84078
|
+
annotations: {
|
|
84079
|
+
readOnlyHint: false,
|
|
84080
|
+
destructiveHint: false,
|
|
84081
|
+
idempotentHint: true,
|
|
84082
|
+
openWorldHint: true
|
|
84083
|
+
}
|
|
84084
|
+
},
|
|
84085
|
+
async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
|
|
84086
|
+
const problem = checkPositionIdHex(positionId);
|
|
84087
|
+
if (problem) return validationFailed(problem);
|
|
84088
|
+
const b = getB();
|
|
84089
|
+
if (!b.ok) return renderError(b.error);
|
|
84090
|
+
return renderEnvelope(
|
|
84091
|
+
await b.boundary.recoverStaleSpend({
|
|
84092
|
+
positionId,
|
|
84093
|
+
utxoTxid,
|
|
84094
|
+
utxoVout,
|
|
84095
|
+
invalidatorTxid,
|
|
84096
|
+
...minConfirmations !== void 0 ? { minConfirmations } : {}
|
|
84097
|
+
})
|
|
84098
|
+
);
|
|
84099
|
+
})
|
|
84100
|
+
);
|
|
84101
|
+
}
|
|
84102
|
+
|
|
84103
|
+
// src/tools/position.ts
|
|
84104
|
+
var import_zod2 = require("zod");
|
|
84105
|
+
var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
|
|
84106
|
+
var POSITION_STATES = [
|
|
84107
|
+
"PENDING_DEPOSIT",
|
|
84108
|
+
"PENDING_MINT",
|
|
84109
|
+
"ACTIVE",
|
|
84110
|
+
"EXPIRED",
|
|
84111
|
+
"LIQUIDATABLE",
|
|
84112
|
+
"LIQUIDATED",
|
|
84113
|
+
"REPAID",
|
|
84114
|
+
"CLOSED"
|
|
84115
|
+
];
|
|
84116
|
+
function registerPositionTools(server, getB) {
|
|
84117
|
+
registerBoundaryTool(
|
|
84118
|
+
server,
|
|
84119
|
+
"position_status",
|
|
84120
|
+
{
|
|
84121
|
+
title: "Get a position's full status",
|
|
84122
|
+
description: "Return detailed status for a single position: chain facts (debt, term, expiry, state), live collateral (confirmed sats + per-transaction pending deposits, plus maxWithdrawableSats \u2014 directly usable as a withdrawal amountSats), and a basis-carrying valuation (maxMintableUcd is directly usable as amountUcd). If a withdrawal reservation was already spent on Bitcoin but availableSats still shows it deducted, run loan_recover_stale_spend to release the redundant hold. Any `reading` notes in the result are authoritative interpretation instructions for that exact payload \u2014 follow them." + fieldGuide("state", "availableSats", "minConfirmations", "pendingDeposits", "maxWithdrawableSats", "maxMintableUcd", "debtUcdWei"),
|
|
84123
|
+
inputSchema: {
|
|
84124
|
+
id: positionIdSchema2
|
|
84125
|
+
}
|
|
84126
|
+
},
|
|
84127
|
+
async ({ id }) => guarded(async () => {
|
|
84128
|
+
const problem = checkPositionIdHex(id);
|
|
84129
|
+
if (problem) return validationFailed(problem);
|
|
84130
|
+
const b = getB();
|
|
84131
|
+
if (!b.ok) return renderError(b.error);
|
|
84132
|
+
return renderEnvelope(await b.boundary.getPosition(id));
|
|
84133
|
+
})
|
|
84134
|
+
);
|
|
84135
|
+
registerBoundaryTool(
|
|
84136
|
+
server,
|
|
84137
|
+
"position_list",
|
|
84138
|
+
{
|
|
84139
|
+
title: "List lending positions",
|
|
84140
|
+
description: "List positions with optional filters. `borrower` and `state` COMBINE (logical AND); with no filter, returns active positions. Rows are the INDEXER's view \u2014 `state` here is an indexer snapshot that can lag the chain; position_status reads the chain and is authoritative for one position." + fieldGuide("state", "debtUcdWei", "indexedHealth"),
|
|
84141
|
+
inputSchema: {
|
|
84142
|
+
borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
|
|
84143
|
+
state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
|
|
84144
|
+
page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
|
|
84145
|
+
pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
|
|
84146
|
+
}
|
|
84147
|
+
},
|
|
84148
|
+
async ({ borrower, state, page, pageSize }) => guarded(async () => {
|
|
84149
|
+
if (state !== void 0 && !POSITION_STATES.includes(state)) {
|
|
84150
|
+
return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
|
|
84151
|
+
}
|
|
84152
|
+
const b = getB();
|
|
84153
|
+
if (!b.ok) return renderError(b.error);
|
|
84154
|
+
const filter2 = {
|
|
84155
|
+
page,
|
|
84156
|
+
pageSize,
|
|
84157
|
+
...borrower !== void 0 ? { borrower } : {},
|
|
84158
|
+
...state !== void 0 ? { state } : {}
|
|
84159
|
+
};
|
|
84160
|
+
if (filter2.borrower === void 0 && filter2.state === void 0) {
|
|
84161
|
+
return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
|
|
84162
|
+
}
|
|
84163
|
+
return renderEnvelope(await b.boundary.listPositions(filter2));
|
|
84164
|
+
})
|
|
84165
|
+
);
|
|
84166
|
+
registerBoundaryTool(
|
|
84167
|
+
server,
|
|
84168
|
+
"position_events",
|
|
84169
|
+
{
|
|
84170
|
+
title: "Get a position's event history",
|
|
84171
|
+
description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
|
|
84172
|
+
inputSchema: {
|
|
84173
|
+
id: positionIdSchema2
|
|
84174
|
+
}
|
|
84175
|
+
},
|
|
84176
|
+
async ({ id }) => guarded(async () => {
|
|
84177
|
+
const problem = checkPositionIdHex(id);
|
|
84178
|
+
if (problem) return validationFailed(problem);
|
|
84179
|
+
const b = getB();
|
|
84180
|
+
if (!b.ok) return renderError(b.error);
|
|
84181
|
+
return renderEnvelope(await b.boundary.getPositionEvents(id));
|
|
84182
|
+
})
|
|
84183
|
+
);
|
|
84184
|
+
registerBoundaryTool(
|
|
84185
|
+
server,
|
|
84186
|
+
"position_pending_withdrawals",
|
|
84187
|
+
{
|
|
84188
|
+
title: "List a position's pending BTC withdrawal reservations",
|
|
84189
|
+
description: "Query the spend authorizer for BTC withdrawal reservations on a position. Each entry has txid/vout, satoshis, and target address (txid/vout feed recovery).",
|
|
84190
|
+
inputSchema: {
|
|
84191
|
+
id: positionIdSchema2
|
|
84192
|
+
}
|
|
84193
|
+
},
|
|
84194
|
+
async ({ id }) => guarded(async () => {
|
|
84195
|
+
const problem = checkPositionIdHex(id);
|
|
84196
|
+
if (problem) return validationFailed(problem);
|
|
84197
|
+
const b = getB();
|
|
84198
|
+
if (!b.ok) return renderError(b.error);
|
|
84199
|
+
return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
|
|
84200
|
+
})
|
|
84201
|
+
);
|
|
84202
|
+
}
|
|
84203
|
+
|
|
84204
|
+
// src/tools/btc.ts
|
|
84205
|
+
var import_zod3 = require("zod");
|
|
84206
|
+
function registerBtcTools(server, getB) {
|
|
84207
|
+
registerBoundaryTool(
|
|
84208
|
+
server,
|
|
84209
|
+
"btc_balance",
|
|
84210
|
+
{
|
|
84211
|
+
title: "Get BTC balance for an address",
|
|
84212
|
+
description: "Query the confirmed BTC balance for an address (source-tagged).",
|
|
84213
|
+
inputSchema: {
|
|
84214
|
+
address: import_zod3.z.string().min(1).describe("BTC address to query")
|
|
84215
|
+
}
|
|
84216
|
+
},
|
|
84217
|
+
async ({ address }) => guarded(async () => {
|
|
84218
|
+
const b = getB();
|
|
84219
|
+
if (!b.ok) return renderError(b.error);
|
|
84220
|
+
return renderEnvelope(await b.boundary.getBitcoinBalance(address));
|
|
84221
|
+
})
|
|
84222
|
+
);
|
|
84223
|
+
registerBoundaryTool(
|
|
84224
|
+
server,
|
|
84225
|
+
"btc_price",
|
|
84226
|
+
{
|
|
84227
|
+
title: "Get the current BTC price",
|
|
84228
|
+
description: "Return the current BTC price (USD, 8 decimals) from the price oracle.",
|
|
84229
|
+
inputSchema: {}
|
|
84230
|
+
},
|
|
84231
|
+
async () => guarded(async () => {
|
|
84232
|
+
const b = getB();
|
|
84233
|
+
if (!b.ok) return renderError(b.error);
|
|
84234
|
+
return renderEnvelope(await b.boundary.getBitcoinPrice());
|
|
84235
|
+
})
|
|
84236
|
+
);
|
|
84237
|
+
}
|
|
84238
|
+
|
|
84239
|
+
// src/tools/protocol.ts
|
|
84240
|
+
function registerProtocolTools(server, getB) {
|
|
84241
|
+
registerBoundaryTool(
|
|
84242
|
+
server,
|
|
84243
|
+
"protocol_status",
|
|
84244
|
+
{
|
|
84245
|
+
title: "Get protocol configuration and status",
|
|
84246
|
+
description: "Return protocol status: pause flag, mint LTV limit (ltvBps), liquidation threshold (liquidationThresholdBps \u2014 a COLLATERAL RATIO in bps, i.e. collateralValue/debt, so 11000 = 110%; note this is the inverse basis of ltvBps which is debt/collateral), deposit confirmation threshold, BTC network.",
|
|
84247
|
+
inputSchema: {}
|
|
84248
|
+
},
|
|
84249
|
+
async () => guarded(async () => {
|
|
84250
|
+
const b = getB();
|
|
84251
|
+
if (!b.ok) return renderError(b.error);
|
|
84252
|
+
return renderEnvelope(await b.boundary.getProtocolStatus());
|
|
84253
|
+
})
|
|
84254
|
+
);
|
|
84255
|
+
registerBoundaryTool(
|
|
84256
|
+
server,
|
|
84257
|
+
"protocol_terms",
|
|
84258
|
+
{
|
|
84259
|
+
title: "List available loan terms with fees",
|
|
84260
|
+
description: "Return all configured loan terms (in months) with their fees. Term length: 12 months = exactly 365 days; any other term = N \xD7 30-day months. originationFeeBps: % of a mint, ADDED to debt. extensionFeeRateBps: the renewal fee CEILING as % of outstanding debt PER RENEWAL (a flat rate, NOT per month); the charged fee is ADDED TO DEBT and reduced by origination fees already paid this term.",
|
|
84261
|
+
inputSchema: {}
|
|
84262
|
+
},
|
|
84263
|
+
async () => guarded(async () => {
|
|
84264
|
+
const b = getB();
|
|
84265
|
+
if (!b.ok) return renderError(b.error);
|
|
84266
|
+
return renderEnvelope(await b.boundary.getTerms());
|
|
84267
|
+
})
|
|
84268
|
+
);
|
|
84269
|
+
}
|
|
84270
|
+
|
|
84271
|
+
// src/tools/psm.ts
|
|
84272
|
+
var import_zod4 = require("zod");
|
|
84273
|
+
var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
|
|
84274
|
+
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
84275
|
+
);
|
|
84276
|
+
var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
|
|
84277
|
+
readOnlyHint: false,
|
|
84278
|
+
destructiveHint: true,
|
|
84279
|
+
idempotentHint: false,
|
|
84280
|
+
openWorldHint: true
|
|
84068
84281
|
};
|
|
84069
|
-
|
|
84282
|
+
function registerPsmTools(server, getB) {
|
|
84283
|
+
registerBoundaryTool(
|
|
84284
|
+
server,
|
|
84285
|
+
"psm_quote",
|
|
84286
|
+
{
|
|
84287
|
+
title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
|
|
84288
|
+
description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) 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.",
|
|
84289
|
+
inputSchema: {
|
|
84290
|
+
direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = get UCD for USDC (contract swap); 'to-usdc' = get USDC back for UCD (contract redeem)"),
|
|
84291
|
+
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
|
|
84292
|
+
},
|
|
84293
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
|
|
84294
|
+
},
|
|
84295
|
+
async ({ direction, amount }) => guarded(async () => {
|
|
84296
|
+
const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
|
|
84297
|
+
const problem = checkUcdAmount(amount, label);
|
|
84298
|
+
if (problem) return validationFailed(problem);
|
|
84299
|
+
const b = getB();
|
|
84300
|
+
if (!b.ok) return renderError(b.error);
|
|
84301
|
+
return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
|
|
84302
|
+
})
|
|
84303
|
+
);
|
|
84304
|
+
registerBoundaryTool(
|
|
84305
|
+
server,
|
|
84306
|
+
"psm_swap",
|
|
84307
|
+
{
|
|
84308
|
+
title: "Exchange UCD \u2194 USDC through the PSM",
|
|
84309
|
+
description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC 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 USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc 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; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
|
|
84310
|
+
inputSchema: {
|
|
84311
|
+
direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = pay USDC, get UCD (contract swap); 'to-usdc' = pay UCD, get USDC back (contract redeem)"),
|
|
84312
|
+
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
|
|
84313
|
+
confirmed: confirmedSchema2
|
|
84314
|
+
},
|
|
84315
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
|
|
84316
|
+
},
|
|
84317
|
+
async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
|
|
84318
|
+
const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
|
|
84319
|
+
const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
|
|
84320
|
+
const gate = requireConfirmation(
|
|
84321
|
+
confirmed,
|
|
84322
|
+
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
|
|
84323
|
+
);
|
|
84324
|
+
if (gate) return gate;
|
|
84325
|
+
const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
|
|
84326
|
+
if (problem) return validationFailed(problem);
|
|
84327
|
+
const b = getB();
|
|
84328
|
+
if (!b.ok) return renderError(b.error);
|
|
84329
|
+
return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
|
|
84330
|
+
})
|
|
84331
|
+
);
|
|
84332
|
+
}
|
|
84070
84333
|
|
|
84071
|
-
|
|
84072
|
-
|
|
84073
|
-
|
|
84074
|
-
-
|
|
84075
|
-
-
|
|
84076
|
-
-
|
|
84077
|
-
-
|
|
84078
|
-
-
|
|
84079
|
-
-
|
|
84080
|
-
-
|
|
84081
|
-
|
|
84082
|
-
-
|
|
84083
|
-
-
|
|
84084
|
-
-
|
|
84085
|
-
-
|
|
84334
|
+
// src/tools/mock-control.ts
|
|
84335
|
+
var import_zod5 = require("zod");
|
|
84336
|
+
var ACTIONS = [
|
|
84337
|
+
"submit-deposit",
|
|
84338
|
+
"confirm-deposit",
|
|
84339
|
+
"confirm-spend-consumed",
|
|
84340
|
+
"advance-time",
|
|
84341
|
+
"set-btc-price",
|
|
84342
|
+
"set-paused",
|
|
84343
|
+
"set-wallet",
|
|
84344
|
+
"liquidate",
|
|
84345
|
+
"deploy-safe",
|
|
84346
|
+
"revoke-agent",
|
|
84347
|
+
"inject-fault",
|
|
84348
|
+
"clear-fault",
|
|
84349
|
+
"psm-set-paused",
|
|
84350
|
+
"psm-set-redeem-enabled",
|
|
84351
|
+
"psm-set-reserves",
|
|
84352
|
+
"psm-set-fees",
|
|
84353
|
+
"psm-mint-usdc"
|
|
84354
|
+
];
|
|
84355
|
+
function requireField(value, name, action) {
|
|
84356
|
+
if (value === void 0) {
|
|
84357
|
+
throw new Error(`action '${action}' requires '${name}'`);
|
|
84358
|
+
}
|
|
84359
|
+
return value;
|
|
84360
|
+
}
|
|
84361
|
+
function run(control, a, chainId) {
|
|
84362
|
+
switch (a.action) {
|
|
84363
|
+
case "submit-deposit": {
|
|
84364
|
+
const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
|
|
84365
|
+
return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
|
|
84366
|
+
}
|
|
84367
|
+
case "confirm-deposit": {
|
|
84368
|
+
const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
|
|
84369
|
+
return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
|
|
84370
|
+
}
|
|
84371
|
+
case "confirm-spend-consumed": {
|
|
84372
|
+
control.confirmSpendConsumed(
|
|
84373
|
+
requireField(a.txid, "txid", a.action),
|
|
84374
|
+
requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
|
|
84375
|
+
requireField(a.confirmations, "confirmations", a.action)
|
|
84376
|
+
);
|
|
84377
|
+
return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
|
|
84378
|
+
}
|
|
84379
|
+
case "advance-time": {
|
|
84380
|
+
control.advanceTime(requireField(a.seconds, "seconds", a.action));
|
|
84381
|
+
return { simulated: "virtual clock advanced", seconds: a.seconds };
|
|
84382
|
+
}
|
|
84383
|
+
case "set-btc-price": {
|
|
84384
|
+
control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
|
|
84385
|
+
return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
|
|
84386
|
+
}
|
|
84387
|
+
case "set-paused": {
|
|
84388
|
+
control.setPaused(requireField(a.paused, "paused", a.action));
|
|
84389
|
+
return { simulated: "protocol pause flag set", paused: a.paused };
|
|
84390
|
+
}
|
|
84391
|
+
case "set-wallet": {
|
|
84392
|
+
control.setWalletStance(requireField(a.stance, "stance", a.action));
|
|
84393
|
+
return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
|
|
84394
|
+
}
|
|
84395
|
+
case "liquidate": {
|
|
84396
|
+
control.liquidate(requireField(a.positionId, "positionId", a.action));
|
|
84397
|
+
return { simulated: "liquidation executed", positionId: a.positionId };
|
|
84398
|
+
}
|
|
84399
|
+
case "deploy-safe": {
|
|
84400
|
+
const safe = control.deploySafe({
|
|
84401
|
+
owners: requireField(a.owners, "owners", a.action),
|
|
84402
|
+
threshold: requireField(a.threshold, "threshold", a.action),
|
|
84403
|
+
chainId
|
|
84404
|
+
});
|
|
84405
|
+
return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
|
|
84406
|
+
}
|
|
84407
|
+
case "revoke-agent": {
|
|
84408
|
+
const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
|
|
84409
|
+
return {
|
|
84410
|
+
simulated: "agent revoked and BURNED forever (AR-1 \u2014 plan 09 test lever; on the real protocol the owners or the deny-only registrar revoke)",
|
|
84411
|
+
...r
|
|
84412
|
+
};
|
|
84413
|
+
}
|
|
84414
|
+
case "inject-fault": {
|
|
84415
|
+
control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
|
|
84416
|
+
return { simulated: "fault armed", faultKey: a.faultKey };
|
|
84417
|
+
}
|
|
84418
|
+
case "clear-fault": {
|
|
84419
|
+
control.clearFault(requireField(a.faultKey, "faultKey", a.action));
|
|
84420
|
+
return { simulated: "fault cleared", faultKey: a.faultKey };
|
|
84421
|
+
}
|
|
84422
|
+
case "psm-set-paused": {
|
|
84423
|
+
control.psmSetPaused(requireField(a.paused, "paused", a.action));
|
|
84424
|
+
return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
|
|
84425
|
+
}
|
|
84426
|
+
case "psm-set-redeem-enabled": {
|
|
84427
|
+
control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
|
|
84428
|
+
return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
|
|
84429
|
+
}
|
|
84430
|
+
case "psm-set-reserves": {
|
|
84431
|
+
control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
|
|
84432
|
+
return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
|
|
84433
|
+
}
|
|
84434
|
+
case "psm-mint-usdc": {
|
|
84435
|
+
const r = control.psmMintUsdc(
|
|
84436
|
+
requireField(a.holder, "holder", a.action),
|
|
84437
|
+
requireField(a.usdcUnits, "usdcUnits", a.action)
|
|
84438
|
+
);
|
|
84439
|
+
return {
|
|
84440
|
+
simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
|
|
84441
|
+
holder: a.holder,
|
|
84442
|
+
minted: a.usdcUnits,
|
|
84443
|
+
newBalanceUnits: r.newBalanceUnits
|
|
84444
|
+
};
|
|
84445
|
+
}
|
|
84446
|
+
case "psm-set-fees": {
|
|
84447
|
+
control.psmSetFees({
|
|
84448
|
+
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
84449
|
+
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
84450
|
+
});
|
|
84451
|
+
return {
|
|
84452
|
+
simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
|
|
84453
|
+
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
84454
|
+
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
84455
|
+
};
|
|
84456
|
+
}
|
|
84457
|
+
}
|
|
84458
|
+
}
|
|
84459
|
+
function registerMockControlTool(server, control, chainId = 1337) {
|
|
84460
|
+
registerBoundaryTool(
|
|
84461
|
+
server,
|
|
84462
|
+
"mock_control",
|
|
84463
|
+
{
|
|
84464
|
+
title: "SIMULATOR control (mock world only)",
|
|
84465
|
+
description: "Drive the simulated rest-of-the-world of the MOCK protocol: broadcast/confirm BTC deposits, confirm reserved spends, advance the virtual clock, set the oracle price, pause the protocol, liquidate, arm/clear faults, and drive the simulated PSM (pause, redeemEnabled, reserves, fees, practice-USDC mint). This tool exists ONLY against the mock adapter \u2014 nothing here touches or ever exists on the real protocol.",
|
|
84466
|
+
inputSchema: {
|
|
84467
|
+
action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
|
|
84468
|
+
positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
|
|
84469
|
+
txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
84470
|
+
sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
|
|
84471
|
+
confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
84472
|
+
invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
|
|
84473
|
+
seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
|
|
84474
|
+
priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
|
|
84475
|
+
paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
|
|
84476
|
+
stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
|
|
84477
|
+
owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
|
|
84478
|
+
threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
|
|
84479
|
+
safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
|
|
84480
|
+
faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
|
|
84481
|
+
faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
|
|
84482
|
+
enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
|
|
84483
|
+
reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
|
|
84484
|
+
entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
|
|
84485
|
+
exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
|
|
84486
|
+
holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
|
|
84487
|
+
usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
|
|
84488
|
+
},
|
|
84489
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
|
|
84490
|
+
},
|
|
84491
|
+
async (args) => guarded(async () => {
|
|
84492
|
+
let result;
|
|
84493
|
+
try {
|
|
84494
|
+
result = run(control, args, chainId);
|
|
84495
|
+
} catch (e) {
|
|
84496
|
+
return validationFailed(e.message);
|
|
84497
|
+
}
|
|
84498
|
+
if (result === void 0) {
|
|
84499
|
+
return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
|
|
84500
|
+
}
|
|
84501
|
+
return { content: [{ type: "text", text: serialize(result) }] };
|
|
84502
|
+
})
|
|
84503
|
+
);
|
|
84504
|
+
}
|
|
84086
84505
|
|
|
84087
|
-
|
|
84088
|
-
|
|
84089
|
-
|
|
84090
|
-
|
|
84091
|
-
|
|
84506
|
+
// src/tools/signer.ts
|
|
84507
|
+
var import_zod6 = require("zod");
|
|
84508
|
+
var import_ethers42 = require("ethers");
|
|
84509
|
+
var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
84510
|
+
var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
|
|
84511
|
+
var EXTERNAL_ONLY_MODES = ["external"];
|
|
84512
|
+
var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
|
|
84513
|
+
function looksSecretShaped(value) {
|
|
84514
|
+
return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
|
|
84515
|
+
}
|
|
84516
|
+
var SECRET_REFUSAL = "That value looks like a password or key. NEVER paste secrets into the conversation \u2014 they would enter the model context and transcripts. To provide keystore material, say 'unlock my keystore' (a secure local page opens and the password goes directly to the server), or set DH_KEYSTORE_PATH/DH_KEYSTORE_PASSWORD in the server environment.";
|
|
84517
|
+
function registerSignerTool(server, getRuntime, opts) {
|
|
84518
|
+
const externalOnly = opts?.externalOnly === true;
|
|
84519
|
+
const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
|
|
84520
|
+
const description = externalOnly ? "Inspect or manage how operations are authorized. This build is EXTERNAL-WALLET-ONLY: every operation is approved in YOUR OWN wallet (browser wallet, or mobile via WalletConnect); the server can never sign by itself. Actions: 'status' (what is active, what is connected \u2014 start here), 'use' (mode 'external' \u2014 the only mode this build offers), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'connect' (run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out: the FULL wallet flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect." : "Pick or inspect the authorization mode by conversation \u2014 no config files. Modes: 'external' = you approve each operation in YOUR OWN wallet (browser popup, or mobile via WalletConnect); 'keystore' = a local keystore signs automatically after each confirmation; 'safe' = operate AS a Safe smart-account (provide safeAddress; owners and threshold are discovered, never typed; operations are authorized by owner signatures); 'safe-module' = a Safe WITH DELEGATION: owners approve ONCE (loan_delegation_setup), then the keystore key acts as the Safe's agent for day-to-day operations \u2014 withdrawals and new destinations always remain owner-quorum acts; 'mock-simulated' = the test-world simulated ceremony. Actions: 'status' (what is active, what is ready, what is missing \u2014 start here), 'use' (switch mode), 'reset-borrower' (identity swap ONLY \u2014 unbinds the discovered identity but keeps the wallet connection and login alive; it is NOT a disconnect), 'unlock-keystore' (opens the secure local page for the password \u2014 NEVER paste passwords into chat), 'connect' (external mode, real protocol: run the one-time login signature in your wallet so authenticated reads work \u2014 reads never open wallet popups on their own), 'disconnect' (log out of the external wallet: the FULL flush \u2014 ends approval-page sessions and WalletConnect, discards and revokes the login token, unbinds the identity; reconnecting requires opening the page and signing again). Synonyms users may say: 'use my own wallet / MetaMask / my phone' \u2192 external; 'sign automatically / no popups' \u2192 keystore; 'use our Safe / multisig / company wallet' \u2192 safe; 'disconnect / log out / sign out / forget my wallet / remove my wallet' \u2192 disconnect.";
|
|
84521
|
+
registerBoundaryTool(
|
|
84522
|
+
server,
|
|
84523
|
+
"signer_setup",
|
|
84524
|
+
{
|
|
84525
|
+
title: "Choose how operations are authorized",
|
|
84526
|
+
description,
|
|
84527
|
+
inputSchema: {
|
|
84528
|
+
action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
|
|
84529
|
+
mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
|
|
84530
|
+
...externalOnly ? {} : {
|
|
84531
|
+
safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
|
|
84532
|
+
}
|
|
84533
|
+
},
|
|
84534
|
+
annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
|
|
84535
|
+
},
|
|
84536
|
+
async ({ action, mode, safeAddress }) => guarded(async () => {
|
|
84537
|
+
const runtime = getRuntime();
|
|
84538
|
+
if (!runtime) {
|
|
84539
|
+
return renderError(
|
|
84540
|
+
boundaryError(
|
|
84541
|
+
"SIGNER_UNAVAILABLE",
|
|
84542
|
+
"no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
|
|
84543
|
+
)
|
|
84544
|
+
);
|
|
84545
|
+
}
|
|
84546
|
+
const { manager, bridge } = runtime;
|
|
84547
|
+
if (mode !== void 0 && !offeredModes.includes(mode)) {
|
|
84548
|
+
return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
|
|
84549
|
+
}
|
|
84550
|
+
if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
|
|
84551
|
+
return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
|
|
84552
|
+
}
|
|
84553
|
+
if (action === "status") {
|
|
84554
|
+
await bridge.start();
|
|
84555
|
+
const s = manager.status();
|
|
84556
|
+
return ok({
|
|
84557
|
+
...s,
|
|
84558
|
+
// Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
|
|
84559
|
+
// identity is known. borrower = a persisted binding; candidate = a live
|
|
84560
|
+
// wallet connection in THIS process only.
|
|
84561
|
+
identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
|
|
84562
|
+
approvalPageUrl: bridge.url(),
|
|
84563
|
+
hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
|
|
84564
|
+
});
|
|
84565
|
+
}
|
|
84566
|
+
if (action === "use") {
|
|
84567
|
+
if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
|
|
84568
|
+
const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
|
|
84569
|
+
if (!r.ok) return validationFailed(r.reason);
|
|
84570
|
+
if (mode === "safe-module") {
|
|
84571
|
+
const s = manager.status();
|
|
84572
|
+
return ok({
|
|
84573
|
+
mode,
|
|
84574
|
+
safe: s.safe,
|
|
84575
|
+
agent: s.keystoreAddress,
|
|
84576
|
+
next: "This session operates AS the Safe with DELEGATION: the keystore key is the AGENT. One owner ceremony installs it (loan_delegation_setup \u2014 enables the module, binds the agent, pre-approves BTC destinations); afterwards create/mint/pay/extend run agent-solo (per-position grants via loan_delegation_grant, a quorum signature). The agent can NEVER withdraw alone, add destinations, or manage the module \u2014 withdrawals still gather the owners for a short signing burst. See guide topic 'delegation'."
|
|
84577
|
+
});
|
|
84578
|
+
}
|
|
84579
|
+
if (mode === "safe") {
|
|
84580
|
+
const s = manager.status();
|
|
84581
|
+
return ok({
|
|
84582
|
+
mode,
|
|
84583
|
+
safe: s.safe,
|
|
84584
|
+
next: "This session now operates AS the Safe. Operations are authorized by owner signatures (this phase: the local keystore owner signs; it also submits transactions). BTC withdrawals additionally need the destination allowlisted first \u2014 see loan_allowlist_destination."
|
|
84585
|
+
});
|
|
84586
|
+
}
|
|
84587
|
+
if (mode === "external") {
|
|
84588
|
+
await bridge.start();
|
|
84589
|
+
return ok({
|
|
84590
|
+
mode,
|
|
84591
|
+
approvalPageUrl: bridge.url(),
|
|
84592
|
+
next: "Open the approval page and connect your wallet (browser extension, or 'Use a mobile wallet' for WalletConnect). Each operation will then ask for your approval there."
|
|
84593
|
+
});
|
|
84594
|
+
}
|
|
84595
|
+
return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
|
|
84596
|
+
}
|
|
84597
|
+
if (action === "connect") {
|
|
84598
|
+
if (!runtime.connect) {
|
|
84599
|
+
return validationFailed(
|
|
84600
|
+
"action 'connect' applies to the real protocol's external mode (lit-ops login). This adapter has no separate login step \u2014 pick a mode with 'use' and writes will ceremony as needed."
|
|
84601
|
+
);
|
|
84602
|
+
}
|
|
84603
|
+
const r = await runtime.connect();
|
|
84604
|
+
if (!r.ok) return validationFailed(r.reason);
|
|
84605
|
+
const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
|
|
84606
|
+
return ok({
|
|
84607
|
+
connected: true,
|
|
84608
|
+
address: r.address,
|
|
84609
|
+
login,
|
|
84610
|
+
next: (login === "cached-session" ? "Logged in via a still-valid CACHED session \u2014 no wallet signature was requested. To force a full logout first, use 'disconnect'. " : "Logged in with a FRESH wallet signature. ") + "Authenticated reads and writes now run as this wallet. Each write still asks for approval in your wallet."
|
|
84611
|
+
});
|
|
84612
|
+
}
|
|
84613
|
+
if (action === "disconnect") {
|
|
84614
|
+
if (!runtime.disconnect) {
|
|
84615
|
+
return validationFailed(
|
|
84616
|
+
"this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
|
|
84617
|
+
);
|
|
84618
|
+
}
|
|
84619
|
+
const report = await runtime.disconnect();
|
|
84620
|
+
const f = report.flushed;
|
|
84621
|
+
const tokenLine = !report.hadLogin ? "login token: none existed" : f.upstreamRevoked >= f.loginSessions ? `login token: discarded from memory AND revoked at the service (${f.upstreamRevoked} revoked)` : `login token: discarded from this process's memory; ${f.upstreamRevoked}/${f.loginSessions} could be revoked at the service \u2014 an unrevoked token stays valid upstream until its natural expiry (it was never stored on disk)`;
|
|
84622
|
+
return ok({
|
|
84623
|
+
disconnected: true,
|
|
84624
|
+
mode: manager.mode(),
|
|
84625
|
+
flushed: {
|
|
84626
|
+
...f,
|
|
84627
|
+
note: tokenLine
|
|
84628
|
+
},
|
|
84629
|
+
whatThisServerCannotRevoke: "Your wallet's own site permission for the approval-page origin \u2014 revoke it wallet-side (MetaMask: Settings \u2192 Connections / Connected sites \u2192 remove this site).",
|
|
84630
|
+
// Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
|
|
84631
|
+
// relationship; the OAuth session is a separate thing with its own revocation.
|
|
84632
|
+
// Neither claims to do the other's job.
|
|
84633
|
+
...bridge.isHosted() ? {
|
|
84634
|
+
oauthSession: "This disconnect ends the WALLET relationship only. Your assistant's connection to this MCP server (the OAuth session) stays alive until you revoke it on the claude.ai side (connector settings) \u2014 and revoking THAT does not disconnect your wallet here."
|
|
84635
|
+
} : {},
|
|
84636
|
+
next: `Wallet disconnected \u2014 mode stays '${manager.mode()}'. Reconnecting requires opening the approval page again (signer_setup 'status' shows the link) and a fresh wallet signature ('connect').`
|
|
84637
|
+
});
|
|
84638
|
+
}
|
|
84639
|
+
if (action === "reset-borrower") {
|
|
84640
|
+
manager.resetBorrower();
|
|
84641
|
+
return ok({
|
|
84642
|
+
reset: true,
|
|
84643
|
+
next: "The borrowing identity is unbound \u2014 the next connected wallet (or keystore) that signs becomes the borrower. NOTE: this is an identity swap, NOT a disconnect \u2014 any wallet connection and login session remain alive; use 'disconnect' to log out fully."
|
|
84644
|
+
});
|
|
84645
|
+
}
|
|
84646
|
+
await bridge.start();
|
|
84647
|
+
const unlockUrl = bridge.unlockUrl();
|
|
84648
|
+
return ok({
|
|
84649
|
+
unlockPageUrl: unlockUrl,
|
|
84650
|
+
next: "Open this local page and enter the keystore password THERE (never in chat). Paste an encrypted keystore JSON or generate a fresh one, then say 'use keystore'."
|
|
84651
|
+
});
|
|
84652
|
+
})
|
|
84653
|
+
);
|
|
84654
|
+
}
|
|
84655
|
+
function ok(data) {
|
|
84656
|
+
return { content: [{ type: "text", text: serialize(data) }] };
|
|
84657
|
+
}
|
|
84092
84658
|
|
|
84093
84659
|
// src/tools/guide.ts
|
|
84094
|
-
|
|
84660
|
+
var import_zod7 = require("zod");
|
|
84661
|
+
function registerGuideTool(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
|
|
84662
|
+
const content = buildGuideContent(deployment);
|
|
84663
|
+
const index = buildGuideIndex(deployment);
|
|
84095
84664
|
registerBoundaryTool(
|
|
84096
84665
|
server,
|
|
84097
84666
|
"guide",
|
|
@@ -84105,26 +84674,31 @@ function registerGuideTool(server) {
|
|
|
84105
84674
|
},
|
|
84106
84675
|
async ({ topic }) => guarded(async () => {
|
|
84107
84676
|
if (topic === void 0 || topic === "") {
|
|
84108
|
-
return { content: [{ type: "text", text:
|
|
84677
|
+
return { content: [{ type: "text", text: index }] };
|
|
84109
84678
|
}
|
|
84110
84679
|
if (!GUIDE_TOPICS.includes(topic)) {
|
|
84111
84680
|
return validationFailed(`unknown guide topic '${topic}' \u2014 available: ${GUIDE_TOPICS.join(" | ")}`);
|
|
84112
84681
|
}
|
|
84113
|
-
return { content: [{ type: "text", text:
|
|
84682
|
+
return { content: [{ type: "text", text: content[topic] }] };
|
|
84114
84683
|
})
|
|
84115
84684
|
);
|
|
84116
84685
|
}
|
|
84117
|
-
function registerGuideResources(server) {
|
|
84686
|
+
function registerGuideResources(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
|
|
84687
|
+
const content = buildGuideContent(deployment);
|
|
84688
|
+
const index = buildGuideIndex(deployment);
|
|
84118
84689
|
for (const topic of GUIDE_TOPICS) {
|
|
84119
84690
|
server.resource(`guide-${topic}`, `guide://${topic}`, async () => ({
|
|
84120
|
-
contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text:
|
|
84691
|
+
contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: content[topic] }]
|
|
84121
84692
|
}));
|
|
84122
84693
|
}
|
|
84123
84694
|
server.resource("guide-index", "guide://index", async () => ({
|
|
84124
|
-
contents: [{ uri: "guide://index", mimeType: "text/markdown", text:
|
|
84695
|
+
contents: [{ uri: "guide://index", mimeType: "text/markdown", text: index }]
|
|
84125
84696
|
}));
|
|
84126
84697
|
}
|
|
84127
|
-
function
|
|
84698
|
+
function onboardAuthorizationLine(deployment) {
|
|
84699
|
+
return deployment.signerModes.includes("keystore") ? "if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. " : "this build authorizes with MY OWN WALLET and nothing else, so offer the wallet walkthrough (guide 'connect-wallet') \u2014 never an automatic-signing alternative it does not have \u2014 and then help me open my first position. ";
|
|
84700
|
+
}
|
|
84701
|
+
function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
|
|
84128
84702
|
server.prompt(
|
|
84129
84703
|
"onboard-me",
|
|
84130
84704
|
"Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
|
|
@@ -84134,7 +84708,7 @@ function registerGuidePrompts(server) {
|
|
|
84134
84708
|
role: "user",
|
|
84135
84709
|
content: {
|
|
84136
84710
|
type: "text",
|
|
84137
|
-
text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason;
|
|
84711
|
+
text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; " + onboardAuthorizationLine(deployment) + "Ask before every operation; never assume confirmation."
|
|
84138
84712
|
}
|
|
84139
84713
|
}
|
|
84140
84714
|
]
|
|
@@ -84370,8 +84944,10 @@ function registerBoundaryInfoResource(server, getB) {
|
|
|
84370
84944
|
);
|
|
84371
84945
|
}
|
|
84372
84946
|
|
|
84947
|
+
// src/version.ts
|
|
84948
|
+
var SERVER_VERSION = "0.5.11";
|
|
84949
|
+
|
|
84373
84950
|
// src/server.ts
|
|
84374
|
-
var SERVER_VERSION = "0.5.3";
|
|
84375
84951
|
var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
|
|
84376
84952
|
var CONNECTOR_INSTRUCTIONS = SERVER_INSTRUCTIONS + " HOSTED CONNECTOR TIER: this server is the hosted claude.ai connector. Signer modes are external-wallet ONLY \u2014 keystore mode is ABSENT from this build (structurally, not disabled); the server never holds a key, and every fund-moving action needs a fresh signature from the user's own wallet. Each tenant's world is isolated by wallet identity; network_switch moves ONLY this tenant, within the networks this deployment serves (the refusal states the rollout truth). The login session lives in server memory only \u2014 a server restart or idle eviction means signing in again; that is the no-data-at-rest property, not a fault. Trust ledger and cadence: guide topic 'connector'.";
|
|
84377
84953
|
function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
|
|
@@ -84391,9 +84967,9 @@ function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
|
|
|
84391
84967
|
registerPositionResource(server, getB);
|
|
84392
84968
|
registerProtocolResources(server, getB);
|
|
84393
84969
|
registerBoundaryInfoResource(server, getB);
|
|
84394
|
-
registerGuideTool(server);
|
|
84395
|
-
registerGuideResources(server);
|
|
84396
|
-
registerGuidePrompts(server);
|
|
84970
|
+
registerGuideTool(server, deps.deployment);
|
|
84971
|
+
registerGuideResources(server, deps.deployment);
|
|
84972
|
+
registerGuidePrompts(server, deps.deployment);
|
|
84397
84973
|
if (deps.mockControl) {
|
|
84398
84974
|
registerMockControlTool(server, deps.mockControl, deps.chainId);
|
|
84399
84975
|
}
|
|
@@ -84411,8 +84987,43 @@ var DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1e3;
|
|
|
84411
84987
|
var DEFAULT_WORLD_IDLE_MS = 60 * 60 * 1e3;
|
|
84412
84988
|
var DEFAULT_TENANT_PER_MIN = 120;
|
|
84413
84989
|
var DEFAULT_GLOBAL_PER_MIN = 600;
|
|
84990
|
+
var DEFAULT_MAX_TENANTS = 200;
|
|
84991
|
+
var DEFAULT_MAX_SESSIONS_PER_TENANT = 16;
|
|
84992
|
+
var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
|
|
84993
|
+
var DEFAULT_TRUST_PROXY_HOPS = 1;
|
|
84994
|
+
function normalizePublicOrigin(raw) {
|
|
84995
|
+
const trimmed = raw.trim().replace(/\/+$/, "");
|
|
84996
|
+
let url2;
|
|
84997
|
+
try {
|
|
84998
|
+
url2 = new URL(trimmed);
|
|
84999
|
+
} catch {
|
|
85000
|
+
throw new Error(
|
|
85001
|
+
`connector: publicOrigin is not a valid URL (${trimmed.length} chars). The value is not echoed here \u2014 see below for why.`
|
|
85002
|
+
);
|
|
85003
|
+
}
|
|
85004
|
+
const problems = [];
|
|
85005
|
+
if (url2.protocol !== "https:" && url2.protocol !== "http:") problems.push(`scheme '${url2.protocol}' (want http or https)`);
|
|
85006
|
+
if (url2.username !== "" || url2.password !== "") problems.push("embedded credentials");
|
|
85007
|
+
if (url2.pathname !== "/" && url2.pathname !== "") problems.push("a path");
|
|
85008
|
+
if (url2.search !== "") problems.push("a query string");
|
|
85009
|
+
if (url2.hash !== "") problems.push("a fragment");
|
|
85010
|
+
if (problems.length > 0) {
|
|
85011
|
+
throw new Error(
|
|
85012
|
+
`connector: publicOrigin must be a bare origin (scheme + host only) \u2014 found ${problems.join(", ")} in '${url2.protocol}//${url2.host}\u2026' (value redacted). It becomes the OAuth issuer and the base of every approval-page URL, so a wrong shape mints links that fail their own Host check rather than degrading.`
|
|
85013
|
+
);
|
|
85014
|
+
}
|
|
85015
|
+
return url2.origin;
|
|
85016
|
+
}
|
|
85017
|
+
function requireSafeCount(value, fallback, name, min) {
|
|
85018
|
+
if (value === void 0) return fallback;
|
|
85019
|
+
if (!Number.isSafeInteger(value) || value < min) {
|
|
85020
|
+
throw new Error(`connector: ${name}=${String(value)} must be a safe integer >= ${min}`);
|
|
85021
|
+
}
|
|
85022
|
+
return value;
|
|
85023
|
+
}
|
|
84414
85024
|
var RATE_WINDOW_MS = 60 * 1e3;
|
|
84415
|
-
function composeConnector(opts,
|
|
85025
|
+
function composeConnector(opts, rawPublicOrigin) {
|
|
85026
|
+
const publicOrigin = normalizePublicOrigin(rawPublicOrigin);
|
|
84416
85027
|
const allowedNetworks = opts.allowedNetworks ?? ["sepolia"];
|
|
84417
85028
|
if (allowedNetworks.length === 0) throw new Error("connector service: allowedNetworks must name at least one network");
|
|
84418
85029
|
const launchNetwork = allowedNetworks[0];
|
|
@@ -84421,6 +85032,10 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84421
85032
|
const worldIdleMs = opts.idle?.worldMs ?? DEFAULT_WORLD_IDLE_MS;
|
|
84422
85033
|
const tenantPerMin = opts.rateLimits?.tenantPerMin ?? DEFAULT_TENANT_PER_MIN;
|
|
84423
85034
|
const globalPerMin = opts.rateLimits?.globalPerMin ?? DEFAULT_GLOBAL_PER_MIN;
|
|
85035
|
+
const maxTenants = requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
|
|
85036
|
+
const trustProxyHops = requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
|
|
85037
|
+
const maxSessionsPerTenant = requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
|
|
85038
|
+
const maxBodyBytes = requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
|
|
84424
85039
|
const worlds = /* @__PURE__ */ new Map();
|
|
84425
85040
|
const readyWorlds = /* @__PURE__ */ new Map();
|
|
84426
85041
|
const sessions = /* @__PURE__ */ new Map();
|
|
@@ -84450,7 +85065,7 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84450
85065
|
}
|
|
84451
85066
|
async function buildWorld(tenantKey) {
|
|
84452
85067
|
const stores = /* @__PURE__ */ new Map();
|
|
84453
|
-
const mountId = (0,
|
|
85068
|
+
const mountId = (0, import_node_crypto10.randomUUID)().replaceAll("-", "");
|
|
84454
85069
|
const overrides = {
|
|
84455
85070
|
externalOnly: true,
|
|
84456
85071
|
allowedNetworks,
|
|
@@ -84492,6 +85107,17 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84492
85107
|
process.stderr.write(`[dh-mcp-connector] ${why}: world for tenant ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} disposed
|
|
84493
85108
|
`);
|
|
84494
85109
|
}
|
|
85110
|
+
function tenantsWithSessions() {
|
|
85111
|
+
const held = /* @__PURE__ */ new Set();
|
|
85112
|
+
for (const session of sessions.values()) held.add(session.tenant);
|
|
85113
|
+
return held;
|
|
85114
|
+
}
|
|
85115
|
+
function isReclaimable(tenantKey, world, held) {
|
|
85116
|
+
if (held.has(tenantKey)) return false;
|
|
85117
|
+
const bridge = world.deps.signer?.bridge;
|
|
85118
|
+
if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
|
|
85119
|
+
return true;
|
|
85120
|
+
}
|
|
84495
85121
|
function sweepService() {
|
|
84496
85122
|
const now = clock();
|
|
84497
85123
|
for (const [sid, session] of [...sessions]) {
|
|
@@ -84500,18 +85126,43 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84500
85126
|
void session.transport.close().catch(() => void 0);
|
|
84501
85127
|
}
|
|
84502
85128
|
}
|
|
85129
|
+
const held = tenantsWithSessions();
|
|
84503
85130
|
for (const [tenantKey, world] of [...readyWorlds]) {
|
|
84504
|
-
|
|
84505
|
-
if (hasSession) continue;
|
|
84506
|
-
const bridge = world.deps.signer?.bridge;
|
|
84507
|
-
if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) continue;
|
|
85131
|
+
if (!isReclaimable(tenantKey, world, held)) continue;
|
|
84508
85132
|
if (now - (lastActivity.get(tenantKey) ?? 0) <= worldIdleMs) continue;
|
|
84509
85133
|
dropWorld(tenantKey, world, "idle eviction");
|
|
84510
85134
|
}
|
|
84511
85135
|
}
|
|
85136
|
+
function reclaimIdleWorld() {
|
|
85137
|
+
const held = tenantsWithSessions();
|
|
85138
|
+
let victimKey = null;
|
|
85139
|
+
let victim = null;
|
|
85140
|
+
let oldest = Number.POSITIVE_INFINITY;
|
|
85141
|
+
for (const [tenantKey, world] of readyWorlds) {
|
|
85142
|
+
if (!isReclaimable(tenantKey, world, held)) continue;
|
|
85143
|
+
const activeAt = lastActivity.get(tenantKey) ?? 0;
|
|
85144
|
+
if (activeAt < oldest) {
|
|
85145
|
+
oldest = activeAt;
|
|
85146
|
+
victimKey = tenantKey;
|
|
85147
|
+
victim = world;
|
|
85148
|
+
}
|
|
85149
|
+
}
|
|
85150
|
+
if (victimKey === null || victim === null) return false;
|
|
85151
|
+
dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
|
|
85152
|
+
return true;
|
|
85153
|
+
}
|
|
85154
|
+
class TenantCapacityError extends Error {
|
|
85155
|
+
}
|
|
84512
85156
|
function worldFor(tenantKey) {
|
|
84513
85157
|
let w = worlds.get(tenantKey);
|
|
84514
85158
|
if (!w) {
|
|
85159
|
+
if (worlds.size >= maxTenants && !reclaimIdleWorld()) {
|
|
85160
|
+
return Promise.reject(
|
|
85161
|
+
new TenantCapacityError(
|
|
85162
|
+
`this connector is at its tenant ceiling (${maxTenants} concurrent wallets) and every slot is held by an ACTIVE tenant \u2014 an open MCP session, a live approval page, or a pending signature. Idle slots are reclaimed automatically as soon as one frees; retry shortly`
|
|
85163
|
+
)
|
|
85164
|
+
);
|
|
85165
|
+
}
|
|
84515
85166
|
w = buildWorld(tenantKey).catch((e) => {
|
|
84516
85167
|
worlds.delete(tenantKey);
|
|
84517
85168
|
throw e;
|
|
@@ -84520,16 +85171,75 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84520
85171
|
}
|
|
84521
85172
|
return w;
|
|
84522
85173
|
}
|
|
85174
|
+
function evictExcessSessions(tenantKey) {
|
|
85175
|
+
const mine = [...sessions].filter(([, s]) => s.tenant === tenantKey).sort((a, b) => a[1].lastSeen - b[1].lastSeen);
|
|
85176
|
+
for (let i = 0; i <= mine.length - maxSessionsPerTenant; i += 1) {
|
|
85177
|
+
const [sid, session] = mine[i];
|
|
85178
|
+
sessions.delete(sid);
|
|
85179
|
+
void session.transport.close().catch(() => void 0);
|
|
85180
|
+
process.stderr.write(
|
|
85181
|
+
`[dh-mcp-connector] session cap (${maxSessionsPerTenant}/tenant): oldest session for ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} closed to admit a new one
|
|
85182
|
+
`
|
|
85183
|
+
);
|
|
85184
|
+
}
|
|
85185
|
+
}
|
|
84523
85186
|
function deny(res, status, message) {
|
|
84524
85187
|
res.writeHead(status, { "content-type": "application/json" }).end(
|
|
84525
85188
|
JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message }, id: null })
|
|
84526
85189
|
);
|
|
84527
85190
|
}
|
|
84528
|
-
|
|
84529
|
-
|
|
84530
|
-
|
|
84531
|
-
|
|
84532
|
-
|
|
85191
|
+
function readBodyText(req) {
|
|
85192
|
+
return new Promise((resolve, reject) => {
|
|
85193
|
+
let raw = "";
|
|
85194
|
+
let bytes = 0;
|
|
85195
|
+
let settled = false;
|
|
85196
|
+
req.setEncoding("utf8");
|
|
85197
|
+
req.on("data", (chunk) => {
|
|
85198
|
+
if (settled) return;
|
|
85199
|
+
bytes += Buffer.byteLength(chunk, "utf8");
|
|
85200
|
+
if (bytes > maxBodyBytes) {
|
|
85201
|
+
settled = true;
|
|
85202
|
+
req.pause();
|
|
85203
|
+
resolve({ overflow: bytes });
|
|
85204
|
+
return;
|
|
85205
|
+
}
|
|
85206
|
+
raw += chunk;
|
|
85207
|
+
});
|
|
85208
|
+
req.on("end", () => {
|
|
85209
|
+
if (settled) return;
|
|
85210
|
+
settled = true;
|
|
85211
|
+
resolve({ text: raw });
|
|
85212
|
+
});
|
|
85213
|
+
req.on("error", (e) => {
|
|
85214
|
+
if (settled) return;
|
|
85215
|
+
settled = true;
|
|
85216
|
+
reject(e);
|
|
85217
|
+
});
|
|
85218
|
+
});
|
|
85219
|
+
}
|
|
85220
|
+
function refuseOversizedBody(req, res, why) {
|
|
85221
|
+
res.setHeader("Connection", "close");
|
|
85222
|
+
deny(res, 413, `request body too large (${why}) \u2014 this MCP endpoint accepts at most ${maxBodyBytes} bytes per JSON-RPC message`);
|
|
85223
|
+
res.once("finish", () => req.destroy());
|
|
85224
|
+
}
|
|
85225
|
+
async function readCappedBody(req, res) {
|
|
85226
|
+
const declared = Number(req.headers["content-length"]);
|
|
85227
|
+
if (Number.isFinite(declared) && declared > maxBodyBytes) {
|
|
85228
|
+
refuseOversizedBody(req, res, `declared ${declared} bytes`);
|
|
85229
|
+
return null;
|
|
85230
|
+
}
|
|
85231
|
+
const read = await readBodyText(req);
|
|
85232
|
+
if ("overflow" in read) {
|
|
85233
|
+
refuseOversizedBody(req, res, `exceeded the cap after ${read.overflow} bytes`);
|
|
85234
|
+
return null;
|
|
85235
|
+
}
|
|
85236
|
+
if (read.text.length === 0) return { body: void 0 };
|
|
85237
|
+
try {
|
|
85238
|
+
return { body: JSON.parse(read.text) };
|
|
85239
|
+
} catch {
|
|
85240
|
+
deny(res, 400, "request body is not valid JSON");
|
|
85241
|
+
return null;
|
|
85242
|
+
}
|
|
84533
85243
|
}
|
|
84534
85244
|
async function handle(req, res) {
|
|
84535
85245
|
const url2 = new URL(req.url ?? "/", "http://connector.local");
|
|
@@ -84553,6 +85263,10 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84553
85263
|
}
|
|
84554
85264
|
const tenant = await authImpl.tenant(req);
|
|
84555
85265
|
if (!tenant) {
|
|
85266
|
+
res.setHeader(
|
|
85267
|
+
"WWW-Authenticate",
|
|
85268
|
+
`Bearer resource_metadata="${publicOrigin}/.well-known/oauth-protected-resource"`
|
|
85269
|
+
);
|
|
84556
85270
|
deny(res, 401, "unauthorized \u2014 connect this MCP server through its authorization flow first");
|
|
84557
85271
|
return;
|
|
84558
85272
|
}
|
|
@@ -84574,6 +85288,12 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84574
85288
|
return;
|
|
84575
85289
|
}
|
|
84576
85290
|
session.lastSeen = clock();
|
|
85291
|
+
if (req.method === "POST") {
|
|
85292
|
+
const read2 = await readCappedBody(req, res);
|
|
85293
|
+
if (!read2) return;
|
|
85294
|
+
await session.transport.handleRequest(req, res, read2.body);
|
|
85295
|
+
return;
|
|
85296
|
+
}
|
|
84577
85297
|
await session.transport.handleRequest(req, res);
|
|
84578
85298
|
return;
|
|
84579
85299
|
}
|
|
@@ -84581,22 +85301,29 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84581
85301
|
deny(res, 400, "missing mcp-session-id \u2014 initialize first");
|
|
84582
85302
|
return;
|
|
84583
85303
|
}
|
|
84584
|
-
|
|
84585
|
-
|
|
84586
|
-
|
|
84587
|
-
} catch {
|
|
84588
|
-
deny(res, 400, "request body is not valid JSON");
|
|
84589
|
-
return;
|
|
84590
|
-
}
|
|
85304
|
+
const read = await readCappedBody(req, res);
|
|
85305
|
+
if (!read) return;
|
|
85306
|
+
const body = read.body;
|
|
84591
85307
|
if (!(0, import_types4.isInitializeRequest)(body)) {
|
|
84592
85308
|
deny(res, 400, "missing mcp-session-id \u2014 the only session-less request is initialize");
|
|
84593
85309
|
return;
|
|
84594
85310
|
}
|
|
84595
|
-
|
|
85311
|
+
let world;
|
|
85312
|
+
try {
|
|
85313
|
+
world = await worldFor(tenantKey);
|
|
85314
|
+
} catch (e) {
|
|
85315
|
+
if (e instanceof TenantCapacityError) {
|
|
85316
|
+
res.setHeader("Retry-After", "60");
|
|
85317
|
+
deny(res, 503, e.message);
|
|
85318
|
+
return;
|
|
85319
|
+
}
|
|
85320
|
+
throw e;
|
|
85321
|
+
}
|
|
84596
85322
|
const mcp = createServer2(world.deps, CONNECTOR_INSTRUCTIONS);
|
|
84597
85323
|
const transport = new import_streamableHttp.StreamableHTTPServerTransport({
|
|
84598
|
-
sessionIdGenerator: () => (0,
|
|
85324
|
+
sessionIdGenerator: () => (0, import_node_crypto10.randomUUID)(),
|
|
84599
85325
|
onsessioninitialized: (sessionId) => {
|
|
85326
|
+
evictExcessSessions(tenantKey);
|
|
84600
85327
|
sessions.set(sessionId, { transport, tenant: tenantKey, lastSeen: clock() });
|
|
84601
85328
|
}
|
|
84602
85329
|
});
|
|
@@ -84619,6 +85346,7 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84619
85346
|
});
|
|
84620
85347
|
}
|
|
84621
85348
|
const app = (0, import_express.default)();
|
|
85349
|
+
app.set("trust proxy", trustProxyHops);
|
|
84622
85350
|
app.use((_req, res, next) => {
|
|
84623
85351
|
if (!allowGlobal()) {
|
|
84624
85352
|
deny(res, 429, `rate limit: this connector exceeded ${globalPerMin} requests/minute across all clients \u2014 a shared-capacity protection; wait for the minute window to pass and retry`);
|
|
@@ -84677,7 +85405,38 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84677
85405
|
const r = siwe.wcStatus(String(req.query["flowId"] ?? ""));
|
|
84678
85406
|
res.status(r.status).json(r.body);
|
|
84679
85407
|
});
|
|
84680
|
-
|
|
85408
|
+
const authMd = renderAuthMd({
|
|
85409
|
+
publicOrigin,
|
|
85410
|
+
networks: allowedNetworks,
|
|
85411
|
+
walletConnectEnabled: wcLeg !== void 0
|
|
85412
|
+
});
|
|
85413
|
+
app.get("/auth.md", (_req, res) => {
|
|
85414
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
85415
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
85416
|
+
res.setHeader("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'; base-uri 'none'");
|
|
85417
|
+
res.type("text/markdown; charset=utf-8").send(authMd);
|
|
85418
|
+
});
|
|
85419
|
+
app.get("/.well-known/oauth-protected-resource", (_req, res) => {
|
|
85420
|
+
res.json({
|
|
85421
|
+
resource: `${publicOrigin}/mcp`,
|
|
85422
|
+
authorization_servers: [`${publicOrigin}/`],
|
|
85423
|
+
scopes_supported: [],
|
|
85424
|
+
bearer_methods_supported: ["header"],
|
|
85425
|
+
resource_name: "Diamond Hands",
|
|
85426
|
+
resource_documentation: `${publicOrigin}/auth.md`
|
|
85427
|
+
});
|
|
85428
|
+
});
|
|
85429
|
+
app.use(
|
|
85430
|
+
(0, import_router.mcpAuthRouter)({
|
|
85431
|
+
provider: siwe,
|
|
85432
|
+
issuerUrl: new URL(publicOrigin),
|
|
85433
|
+
// Keep the SDK's own fallback document in agreement with the one above
|
|
85434
|
+
// rather than contradicting it.
|
|
85435
|
+
resourceServerUrl: new URL(`${publicOrigin}/mcp`),
|
|
85436
|
+
scopesSupported: [],
|
|
85437
|
+
resourceName: "Diamond Hands"
|
|
85438
|
+
})
|
|
85439
|
+
);
|
|
84681
85440
|
authImpl = {
|
|
84682
85441
|
tenant(req) {
|
|
84683
85442
|
const header = req.headers.authorization;
|
|
@@ -84717,6 +85476,11 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84717
85476
|
};
|
|
84718
85477
|
}
|
|
84719
85478
|
async function startConnectorService(opts) {
|
|
85479
|
+
if (opts.publicOrigin !== void 0) normalizePublicOrigin(opts.publicOrigin);
|
|
85480
|
+
requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
|
|
85481
|
+
requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
|
|
85482
|
+
requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
|
|
85483
|
+
requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
|
|
84720
85484
|
const httpServer = (0, import_node_http.createServer)();
|
|
84721
85485
|
const host = opts.host ?? "127.0.0.1";
|
|
84722
85486
|
await new Promise((resolve, reject) => {
|
|
@@ -84725,7 +85489,8 @@ async function startConnectorService(opts) {
|
|
|
84725
85489
|
});
|
|
84726
85490
|
const addr = httpServer.address();
|
|
84727
85491
|
if (addr === null || typeof addr === "string") throw new Error("connector service: no bound address");
|
|
84728
|
-
const
|
|
85492
|
+
const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
|
85493
|
+
const publicOrigin = opts.publicOrigin ?? `http://${authority}:${addr.port}`;
|
|
84729
85494
|
const composed = composeConnector(opts, publicOrigin);
|
|
84730
85495
|
httpServer.on("request", composed.app);
|
|
84731
85496
|
return {
|
|
@@ -84762,11 +85527,20 @@ async function main() {
|
|
|
84762
85527
|
}
|
|
84763
85528
|
}
|
|
84764
85529
|
const publicOrigin = process.env["DH_CONNECTOR_PUBLIC_ORIGIN"];
|
|
85530
|
+
const rawHops = process.env["DH_CONNECTOR_TRUST_PROXY_HOPS"]?.trim();
|
|
85531
|
+
let trustProxyHops;
|
|
85532
|
+
if (rawHops !== void 0 && rawHops !== "") {
|
|
85533
|
+
trustProxyHops = Number(rawHops);
|
|
85534
|
+
if (!Number.isSafeInteger(trustProxyHops) || trustProxyHops < 0) {
|
|
85535
|
+
throw new Error(`DH_CONNECTOR_TRUST_PROXY_HOPS='${rawHops}' must be a non-negative integer`);
|
|
85536
|
+
}
|
|
85537
|
+
}
|
|
84765
85538
|
const service = await startConnectorService({
|
|
84766
85539
|
env: process.env,
|
|
84767
85540
|
port,
|
|
84768
85541
|
...process.env["DH_CONNECTOR_HOST"] ? { host: process.env["DH_CONNECTOR_HOST"] } : {},
|
|
84769
85542
|
...publicOrigin ? { publicOrigin } : {},
|
|
85543
|
+
...trustProxyHops !== void 0 ? { trustProxyHops } : {},
|
|
84770
85544
|
allowedNetworks: networks2
|
|
84771
85545
|
});
|
|
84772
85546
|
process.stderr.write(
|