@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-embed.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
|
}
|
|
@@ -40625,19 +40625,208 @@ module.exports = __toCommonJS(connector_embed_exports);
|
|
|
40625
40625
|
|
|
40626
40626
|
// src/connector/service.ts
|
|
40627
40627
|
var import_node_http = require("http");
|
|
40628
|
-
var
|
|
40628
|
+
var import_node_crypto10 = require("crypto");
|
|
40629
40629
|
var import_express = __toESM(require("express"));
|
|
40630
40630
|
var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
40631
40631
|
var import_router = require("@modelcontextprotocol/sdk/server/auth/router.js");
|
|
40632
40632
|
var import_types4 = require("@modelcontextprotocol/sdk/types.js");
|
|
40633
40633
|
|
|
40634
|
+
// src/connector/auth-md.ts
|
|
40635
|
+
var CHAIN_IDS = { mainnet: 1, sepolia: 11155111 };
|
|
40636
|
+
function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled }) {
|
|
40637
|
+
const origin2 = publicOrigin.replace(/\/+$/, "");
|
|
40638
|
+
const launchNetwork = networks2[0];
|
|
40639
|
+
if (launchNetwork === void 0) {
|
|
40640
|
+
throw new Error("renderAuthMd: networks must name at least one network");
|
|
40641
|
+
}
|
|
40642
|
+
const chainId = CHAIN_IDS[launchNetwork];
|
|
40643
|
+
if (chainId === void 0) {
|
|
40644
|
+
throw new Error(
|
|
40645
|
+
`renderAuthMd: no chain id known for network '${launchNetwork}' \u2014 allowed: ${Object.keys(CHAIN_IDS).join(", ")}`
|
|
40646
|
+
);
|
|
40647
|
+
}
|
|
40648
|
+
const isMainnet = launchNetwork === "mainnet";
|
|
40649
|
+
const wcLine = walletConnectEnabled ? "" : " **Mobile WalletConnect sign-in is not enabled on this deployment** \u2014 browser extension or own-key only.";
|
|
40650
|
+
const agentAuth = {
|
|
40651
|
+
agent_auth: {
|
|
40652
|
+
skill: "operate-position",
|
|
40653
|
+
register_uri: `${origin2}/register`,
|
|
40654
|
+
authorization_servers: [`${origin2}/`],
|
|
40655
|
+
resource: `${origin2}/mcp`,
|
|
40656
|
+
methods: [
|
|
40657
|
+
{
|
|
40658
|
+
type: "oauth2",
|
|
40659
|
+
registration: "rfc7591-dynamic-client-registration",
|
|
40660
|
+
register_uri: `${origin2}/register`,
|
|
40661
|
+
authorization_uri: `${origin2}/authorize`,
|
|
40662
|
+
token_uri: `${origin2}/token`,
|
|
40663
|
+
revocation_uri: `${origin2}/revoke`,
|
|
40664
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
40665
|
+
response_types_supported: ["code"],
|
|
40666
|
+
code_challenge_methods_supported: ["S256"],
|
|
40667
|
+
token_endpoint_auth_methods_supported: ["client_secret_post", "none"],
|
|
40668
|
+
bearer_methods_supported: ["header"],
|
|
40669
|
+
identity_types_supported: ["wallet_signature"],
|
|
40670
|
+
wallet_signature: {
|
|
40671
|
+
standard: "EIP-4361",
|
|
40672
|
+
chain_id: chainId,
|
|
40673
|
+
credential_types_supported: ["access_token", "refresh_token"]
|
|
40674
|
+
}
|
|
40675
|
+
}
|
|
40676
|
+
]
|
|
40677
|
+
}
|
|
40678
|
+
};
|
|
40679
|
+
return `# auth.md
|
|
40680
|
+
|
|
40681
|
+
> Agent authentication and registration for Diamond Hands \u2014 a self-custodial Bitcoin
|
|
40682
|
+
> line of credit. Lock native BTC in an isolated L1 vault, mint UCD against it, keep
|
|
40683
|
+
> the Bitcoin.
|
|
40684
|
+
|
|
40685
|
+
This document is for **autonomous agents** that operate a Bitcoin-collateralized UCD
|
|
40686
|
+
position on behalf of the person who owns the wallet. It is generated from this
|
|
40687
|
+
deployment's live configuration, so the endpoints and the chain id below are the ones
|
|
40688
|
+
actually being served.
|
|
40689
|
+
|
|
40690
|
+
## Agent service
|
|
40691
|
+
|
|
40692
|
+
| | |
|
|
40693
|
+
|---|---|
|
|
40694
|
+
| Protocol | Model Context Protocol (MCP), streamable HTTP |
|
|
40695
|
+
| Endpoint | \`${origin2}/mcp\` |
|
|
40696
|
+
| Network | ${isMainnet ? "Ethereum mainnet (chain id 1) \u2014 real BTC, real UCD" : `${launchNetwork} (chain id ${chainId}) \u2014 test network, test funds`} |
|
|
40697
|
+
| Protected resource metadata | ${origin2}/.well-known/oauth-protected-resource |
|
|
40698
|
+
| Authorization server metadata | ${origin2}/.well-known/oauth-authorization-server |
|
|
40699
|
+
|
|
40700
|
+
\`\`\`json
|
|
40701
|
+
{
|
|
40702
|
+
"mcpServers": {
|
|
40703
|
+
"diamond-hands": {
|
|
40704
|
+
"type": "http",
|
|
40705
|
+
"url": "${origin2}/mcp"
|
|
40706
|
+
}
|
|
40707
|
+
}
|
|
40708
|
+
}
|
|
40709
|
+
\`\`\`
|
|
40710
|
+
|
|
40711
|
+
## agent_auth
|
|
40712
|
+
|
|
40713
|
+
\`\`\`json
|
|
40714
|
+
${JSON.stringify(agentAuth, null, 2)}
|
|
40715
|
+
\`\`\`
|
|
40716
|
+
|
|
40717
|
+
### The registration flow, end to end
|
|
40718
|
+
|
|
40719
|
+
1. **Register.** \`POST ${origin2}/register\` \u2014 RFC 7591 dynamic client registration,
|
|
40720
|
+
open, no pre-shared credential. You receive a \`client_id\`.
|
|
40721
|
+
2. **Authorize.** Send the user to \`${origin2}/authorize\` with \`response_type=code\`,
|
|
40722
|
+
your \`client_id\`, \`redirect_uri\`, and a PKCE \`code_challenge\` (\`S256\` \u2014
|
|
40723
|
+
required).
|
|
40724
|
+
3. **Sign in.** One Sign-In-with-Ethereum signature (EIP-4361) over a message this
|
|
40725
|
+
server minted for that flow. Nothing you supply is parsed back \u2014 the server verifies
|
|
40726
|
+
against its own canonical text, and pins the chain id itself. A person signs this in
|
|
40727
|
+
a browser wallet extension; an agent holding its own key signs the same message
|
|
40728
|
+
through the flow's JSON endpoints.${wcLine}
|
|
40729
|
+
4. **Exchange.** \`POST ${origin2}/token\` with the code and your \`code_verifier\`. You
|
|
40730
|
+
get an access token and a refresh token.
|
|
40731
|
+
5. **Call.** Send the access token to \`${origin2}/mcp\` as
|
|
40732
|
+
\`Authorization: Bearer <token>\`. Unauthenticated calls answer \`401\` with a
|
|
40733
|
+
JSON-RPC error, not a redirect.
|
|
40734
|
+
|
|
40735
|
+
### What the credential is, and is not
|
|
40736
|
+
|
|
40737
|
+
The **wallet address is the account.** There are no passwords, no email addresses, and
|
|
40738
|
+
no user database. Registration creates an OAuth client, not a Diamond Hands account \u2014
|
|
40739
|
+
there is nothing to delete, and no personal data is collected.
|
|
40740
|
+
|
|
40741
|
+
The access token proves **session identity only**. It can read what that address could
|
|
40742
|
+
already read, and it can *stage* a fund-moving operation \u2014 arm a mint, a repayment, a
|
|
40743
|
+
withdrawal \u2014 but it can never complete one: each of those terminates in a wallet
|
|
40744
|
+
signature over that specific operation, which the token cannot produce. So it is not a
|
|
40745
|
+
read-only credential, and it is not a spending one either. A stolen token cannot spend.
|
|
40746
|
+
|
|
40747
|
+
- Access token: ~1 hour. Refresh token: rotating, expires after inactivity.
|
|
40748
|
+
- All authorization state is held **in memory**. A service restart ends every session
|
|
40749
|
+
and the user signs in again. Nothing is persisted at rest.
|
|
40750
|
+
- \`scopes_supported\` is empty and tokens are minted with no scopes \u2014 this
|
|
40751
|
+
authorization server does not implement scoped access. Do not request a scope; you
|
|
40752
|
+
will not receive one.
|
|
40753
|
+
|
|
40754
|
+
### Who holds the wallet \u2014 read this before you rely on the approval step
|
|
40755
|
+
|
|
40756
|
+
This protocol authenticates **addresses, not people**. It cannot tell whether a
|
|
40757
|
+
signature came from a person clicking a wallet extension or from software holding a key,
|
|
40758
|
+
and it does not try to. Two arrangements are supported, and they have **materially
|
|
40759
|
+
different guarantees**. Be clear which one you are.
|
|
40760
|
+
|
|
40761
|
+
**1. You act for a person, on their wallet.** The human owns the position and signs each
|
|
40762
|
+
operation themselves. This is the arrangement the approval page is designed for: every
|
|
40763
|
+
fund-moving step raises a card the person reads and approves, and you cannot proceed
|
|
40764
|
+
without them. Your token gives you reads and the ability to *stage* a ceremony \u2014 never
|
|
40765
|
+
to complete one.
|
|
40766
|
+
|
|
40767
|
+
**2. You hold your own key and own your own position.** Nothing here treats you
|
|
40768
|
+
differently: you sign in with your key, you create and fund your own vault, you borrow
|
|
40769
|
+
against your own BTC. But then **you are the approver.** The approval card's "Approve
|
|
40770
|
+
ONLY if you initiated this exact BTC withdrawal" is addressed to a human reader, and
|
|
40771
|
+
there is no human in this arrangement. Do not present that step to your operator as
|
|
40772
|
+
independent oversight \u2014 it is not; you are satisfying it yourself.
|
|
40773
|
+
|
|
40774
|
+
What actually bounds arrangement 2 is **on-chain, not in this service**: a BTC
|
|
40775
|
+
withdrawal can only go to an address already on the position's on-chain allowlist, and
|
|
40776
|
+
adding one takes a separate, fully decodable transaction plus the registry's delay \u2014
|
|
40777
|
+
read live from the contract at execution${isMainnet ? " (24 hours on mainnet today)" : ""}.
|
|
40778
|
+
Treat that allowlist as your real safety boundary, and put an address on it
|
|
40779
|
+
deliberately.
|
|
40780
|
+
|
|
40781
|
+
**3. Acting on someone else's position with your own key** \u2014 a delegated agent key \u2014 is
|
|
40782
|
+
**not offered on this endpoint yet.** If you need it, do not attempt to approximate it
|
|
40783
|
+
by holding a person's key; contact us.
|
|
40784
|
+
|
|
40785
|
+
If your operator has asked you to run unattended, you are in arrangement 2. Say so
|
|
40786
|
+
plainly to them, and do not describe the approval step as human review.
|
|
40787
|
+
|
|
40788
|
+
### Flows this service does not offer
|
|
40789
|
+
|
|
40790
|
+
Stated plainly so a scanner does not infer otherwise: there is **no** ID-JAG
|
|
40791
|
+
(\`urn:ietf:params:oauth:token-type:id-jag\`) identity-assertion flow, **no**
|
|
40792
|
+
verified-email flow, and **no** anonymous flow. The only identity type is a wallet
|
|
40793
|
+
signature.
|
|
40794
|
+
|
|
40795
|
+
## Public data needs no credential
|
|
40796
|
+
|
|
40797
|
+
Protocol data \u2014 live loans, terms, the peg stability module \u2014 is public. Start at
|
|
40798
|
+
<https://app.diamondhands.credit/llms.txt>, or request any app page with
|
|
40799
|
+
\`Accept: text/markdown\`.
|
|
40800
|
+
|
|
40801
|
+
## Local alternative
|
|
40802
|
+
|
|
40803
|
+
An agent on the user's own machine can skip this service and talk to the protocol
|
|
40804
|
+
directly through the published MCP server, which carries the same tools:
|
|
40805
|
+
|
|
40806
|
+
- \`npx -y @gvnrdao/dh-mcp\` (requires Node \u2265 18)
|
|
40807
|
+
- \`curl -fsSL https://assets.gvnr.xyz/dh-mcp/install.sh | sh\` (self-contained binary)
|
|
40808
|
+
- Claude Desktop bundle and checksums: <https://assets.gvnr.xyz/dh-mcp/>
|
|
40809
|
+
|
|
40810
|
+
## Contact
|
|
40811
|
+
|
|
40812
|
+
Security contact and disclosure policy:
|
|
40813
|
+
<https://app.diamondhands.credit/.well-known/security.txt>
|
|
40814
|
+
|
|
40815
|
+
Do not probe \`POST /register\` or \`/authorize\` during passive scans. This document,
|
|
40816
|
+
the protected-resource metadata, and the authorization-server metadata are the safe
|
|
40817
|
+
source of truth.
|
|
40818
|
+
`;
|
|
40819
|
+
}
|
|
40820
|
+
|
|
40634
40821
|
// src/connector/siwe-oauth.ts
|
|
40635
|
-
var
|
|
40822
|
+
var import_node_crypto2 = require("crypto");
|
|
40636
40823
|
var import_ethers = require("ethers");
|
|
40637
40824
|
var import_errors = require("@modelcontextprotocol/sdk/server/auth/errors.js");
|
|
40638
40825
|
|
|
40639
40826
|
// src/connector/siwe-page.ts
|
|
40640
|
-
function renderSiwePage(
|
|
40827
|
+
function renderSiwePage(opts) {
|
|
40828
|
+
const { flowId, redirectHost, nonce } = opts;
|
|
40829
|
+
const clientName = clampClientName(opts.clientName);
|
|
40641
40830
|
return `<!DOCTYPE html>
|
|
40642
40831
|
<html>
|
|
40643
40832
|
<head>
|
|
@@ -40651,6 +40840,26 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
|
|
|
40651
40840
|
#status { margin-top: 1rem; color: #444; min-height: 1.5rem; }
|
|
40652
40841
|
.err { color: #b00020; }
|
|
40653
40842
|
.note { font-size: 0.85rem; color: #666; margin-top: 2rem; }
|
|
40843
|
+
/* "position: relative" is load-bearing, not cosmetic: it puts the consent box in its
|
|
40844
|
+
own stacking context so it paints ABOVE the inline content of the paragraph before
|
|
40845
|
+
it. Without it, a client name built from stacked combining marks overflows its line
|
|
40846
|
+
box downward and paints over this text \u2014 the CSS painting order draws every block
|
|
40847
|
+
background first, then all inline content in tree order. */
|
|
40848
|
+
.dest { background: #fff8e1; border-left: 3px solid #c77700; padding: 0.7rem 0.9rem; font-size: 0.9rem; position: relative; }
|
|
40849
|
+
/* The destination must stay legible under a host the attacker chose the length of:
|
|
40850
|
+
"overflow-wrap: anywhere" lets it wrap mid-label (a dot is not a break opportunity),
|
|
40851
|
+
and the isolate keeps any bidi control inside from reordering the sentence around
|
|
40852
|
+
it. splitRedirectHost has already bounded the length; this bounds the geometry. */
|
|
40853
|
+
.dest code { font-family: ui-monospace, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
|
|
40854
|
+
.dest .host-head { color: #5a5a5a; }
|
|
40855
|
+
.dest .host-tail { font-weight: 700; color: #000; }
|
|
40856
|
+
/* The elision is NOT decoration \u2014 it is the page admitting it withheld characters, so
|
|
40857
|
+
it must be as visible as the text it replaced. */
|
|
40858
|
+
.dest .host-cut { color: #c77700; font-weight: 700; font-style: normal; }
|
|
40859
|
+
/* The attacker-chosen name is clipped to a fixed box: bounded characters alone do not
|
|
40860
|
+
bound HEIGHT (combining marks stack vertically), and an isolate stops an unpaired
|
|
40861
|
+
RTL override inside the name from reversing the rest of the sentence. */
|
|
40862
|
+
.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; }
|
|
40654
40863
|
#qr { max-width: 16rem; margin-top: 1rem; }
|
|
40655
40864
|
#qr svg { width: 100%; height: auto; }
|
|
40656
40865
|
#wc-uri { font-size: 0.7rem; word-break: break-all; color: #888; }
|
|
@@ -40658,14 +40867,15 @@ button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right:
|
|
|
40658
40867
|
</head>
|
|
40659
40868
|
<body>
|
|
40660
40869
|
<h1>Sign in to Diamond Hands</h1>
|
|
40661
|
-
<p><
|
|
40870
|
+
<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>
|
|
40871
|
+
<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>
|
|
40662
40872
|
<button id="connect">Browser wallet</button>
|
|
40663
40873
|
<button id="wc">Mobile wallet (QR)</button>
|
|
40664
40874
|
<div id="status"></div>
|
|
40665
40875
|
<div id="qr"></div>
|
|
40666
40876
|
<p id="wc-uri"></p>
|
|
40667
40877
|
<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>
|
|
40668
|
-
<script>
|
|
40878
|
+
<script nonce="${nonce}">
|
|
40669
40879
|
const FLOW = ${JSON.stringify(flowId)};
|
|
40670
40880
|
const statusEl = document.getElementById("status");
|
|
40671
40881
|
function show(text, isErr) { statusEl.textContent = text; statusEl.className = isErr ? "err" : ""; }
|
|
@@ -40736,6 +40946,46 @@ document.getElementById("wc").addEventListener("click", async () => {
|
|
|
40736
40946
|
function escapeHtml(s) {
|
|
40737
40947
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
40738
40948
|
}
|
|
40949
|
+
var MAX_CLIENT_NAME_CHARS = 64;
|
|
40950
|
+
var HOST_TAIL_CHARS = 48;
|
|
40951
|
+
var HOST_HEAD_CHARS = 12;
|
|
40952
|
+
var HOST_TAIL_LABELS = 3;
|
|
40953
|
+
var HOST_ELISION_FLOOR = 12;
|
|
40954
|
+
var MAX_HOST_DISPLAY_CHARS = HOST_HEAD_CHARS + HOST_TAIL_CHARS + 24;
|
|
40955
|
+
function splitRedirectHost(host) {
|
|
40956
|
+
const labels = host.split(".");
|
|
40957
|
+
const labelTail = labels.slice(-HOST_TAIL_LABELS).join(".");
|
|
40958
|
+
const tailStart = Math.max(host.length - labelTail.length, host.length - HOST_TAIL_CHARS, 0);
|
|
40959
|
+
const tail = host.slice(tailStart);
|
|
40960
|
+
const fullHead = host.slice(0, tailStart);
|
|
40961
|
+
if (fullHead.length <= HOST_HEAD_CHARS + HOST_ELISION_FLOOR) return { head: fullHead, elided: 0, tail };
|
|
40962
|
+
return { head: fullHead.slice(0, HOST_HEAD_CHARS), elided: fullHead.length - HOST_HEAD_CHARS, tail };
|
|
40963
|
+
}
|
|
40964
|
+
function renderRedirectHost(host) {
|
|
40965
|
+
const { head, elided, tail } = splitRedirectHost(host);
|
|
40966
|
+
const cut = elided === 0 ? "" : `<span class="host-cut">\u2026+${elided} chars\u2026</span>`;
|
|
40967
|
+
return `<span class="host-head">${escapeHtml(head)}</span>${cut}<span class="host-tail">${escapeHtml(tail)}</span>`;
|
|
40968
|
+
}
|
|
40969
|
+
function clampClientName(name) {
|
|
40970
|
+
const points = [...name];
|
|
40971
|
+
if (points.length <= MAX_CLIENT_NAME_CHARS) return name;
|
|
40972
|
+
return `${points.slice(0, MAX_CLIENT_NAME_CHARS - 1).join("")}\u2026`;
|
|
40973
|
+
}
|
|
40974
|
+
|
|
40975
|
+
// src/util/page-headers.ts
|
|
40976
|
+
var import_node_crypto = require("crypto");
|
|
40977
|
+
function htmlPageSecurityHeaders() {
|
|
40978
|
+
const nonce = (0, import_node_crypto.randomBytes)(16).toString("base64");
|
|
40979
|
+
return {
|
|
40980
|
+
nonce,
|
|
40981
|
+
headers: {
|
|
40982
|
+
"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'`,
|
|
40983
|
+
"X-Frame-Options": "DENY",
|
|
40984
|
+
"Referrer-Policy": "no-referrer",
|
|
40985
|
+
"X-Content-Type-Options": "nosniff"
|
|
40986
|
+
}
|
|
40987
|
+
};
|
|
40988
|
+
}
|
|
40739
40989
|
|
|
40740
40990
|
// src/connector/siwe-oauth.ts
|
|
40741
40991
|
var FLOW_TTL_MS = 10 * 60 * 1e3;
|
|
@@ -40764,6 +41014,12 @@ var SiweOAuthProvider = class {
|
|
|
40764
41014
|
return {
|
|
40765
41015
|
getClient: (clientId) => clients.get(clientId),
|
|
40766
41016
|
registerClient: (client) => {
|
|
41017
|
+
const name = client.client_name;
|
|
41018
|
+
if (name !== void 0 && [...name].length > MAX_CLIENT_NAME_CHARS) {
|
|
41019
|
+
throw new import_errors.InvalidClientMetadataError(
|
|
41020
|
+
`client_name is ${[...name].length} characters \u2014 this authorization server displays it on a consent screen and accepts at most ${MAX_CLIENT_NAME_CHARS}`
|
|
41021
|
+
);
|
|
41022
|
+
}
|
|
40767
41023
|
while (clients.size >= maxClients) {
|
|
40768
41024
|
const oldest = clients.keys().next().value;
|
|
40769
41025
|
if (oldest === void 0) break;
|
|
@@ -40774,12 +41030,28 @@ var SiweOAuthProvider = class {
|
|
|
40774
41030
|
}
|
|
40775
41031
|
};
|
|
40776
41032
|
}
|
|
40777
|
-
/** SDK authorize handler → we render the SIWE sign-in page for this flow.
|
|
41033
|
+
/** SDK authorize handler → we render the SIWE sign-in page for this flow.
|
|
41034
|
+
*
|
|
41035
|
+
* C-45: the page is a PUBLIC sign-in surface served ahead of any host helmet, so this
|
|
41036
|
+
* response carries its own security headers, and the page names the redirect HOST —
|
|
41037
|
+
* the consent fact that open registration makes `client_name` unable to carry. */
|
|
40778
41038
|
async authorize(client, params, res) {
|
|
40779
41039
|
this.sweep();
|
|
40780
|
-
const flowId = (0,
|
|
41040
|
+
const flowId = (0, import_node_crypto2.randomBytes)(16).toString("hex");
|
|
40781
41041
|
this.flows.set(flowId, { clientId: client.client_id, params, createdAt: this.clock() });
|
|
40782
|
-
|
|
41042
|
+
const page = htmlPageSecurityHeaders();
|
|
41043
|
+
for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
|
|
41044
|
+
res.status(200).type("html").send(
|
|
41045
|
+
renderSiwePage({
|
|
41046
|
+
flowId,
|
|
41047
|
+
clientName: client.client_name ?? client.client_id,
|
|
41048
|
+
// Parseable by the time authorize() runs: the SDK validates every registered
|
|
41049
|
+
// redirect_uri (SafeUrlSchema) and, for a request-supplied one, URL.canParse
|
|
41050
|
+
// plus a registered-URI match — so this constructor cannot throw here.
|
|
41051
|
+
redirectHost: new URL(params.redirectUri).host,
|
|
41052
|
+
nonce: page.nonce
|
|
41053
|
+
})
|
|
41054
|
+
);
|
|
40783
41055
|
}
|
|
40784
41056
|
/** Page step 1: the wallet reported its address — mint the CANONICAL SIWE message.
|
|
40785
41057
|
* Re-calling rebinds (the user switched wallet accounts before signing). The chain id
|
|
@@ -40796,7 +41068,7 @@ var SiweOAuthProvider = class {
|
|
|
40796
41068
|
mintSiweMessage(checksummedAddress) {
|
|
40797
41069
|
const origin2 = this.opts.origin();
|
|
40798
41070
|
const domain = new URL(origin2).host;
|
|
40799
|
-
const nonce = (0,
|
|
41071
|
+
const nonce = (0, import_node_crypto2.randomBytes)(8).toString("hex");
|
|
40800
41072
|
return `${domain} wants you to sign in with your Ethereum account:
|
|
40801
41073
|
${checksummedAddress}
|
|
40802
41074
|
|
|
@@ -40895,7 +41167,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
|
|
|
40895
41167
|
void transport.close().catch(() => void 0);
|
|
40896
41168
|
return;
|
|
40897
41169
|
}
|
|
40898
|
-
const code = (0,
|
|
41170
|
+
const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
|
|
40899
41171
|
this.codes.set(code, {
|
|
40900
41172
|
clientId: flow.clientId,
|
|
40901
41173
|
address: checksummed,
|
|
@@ -40962,7 +41234,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
|
|
|
40962
41234
|
return { ok: false, status: 401, reason: "the signature does not match the connected wallet address" };
|
|
40963
41235
|
}
|
|
40964
41236
|
this.deleteFlow(flowId, flow);
|
|
40965
|
-
const code = (0,
|
|
41237
|
+
const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
|
|
40966
41238
|
this.codes.set(code, {
|
|
40967
41239
|
clientId: flow.clientId,
|
|
40968
41240
|
address: flow.siwe.address,
|
|
@@ -41020,8 +41292,8 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
|
|
|
41020
41292
|
if (r && r.clientId === client.client_id) this.refresh.delete(request.token);
|
|
41021
41293
|
}
|
|
41022
41294
|
mintTokens(address, clientId) {
|
|
41023
|
-
const accessToken = (0,
|
|
41024
|
-
const refreshToken = (0,
|
|
41295
|
+
const accessToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
|
|
41296
|
+
const refreshToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
|
|
41025
41297
|
this.access.set(accessToken, { address, clientId, expiresAt: Math.floor(this.clock() / 1e3) + ACCESS_TTL_S });
|
|
41026
41298
|
this.refresh.set(refreshToken, { address, clientId, lastUsed: this.clock() });
|
|
41027
41299
|
return { access_token: accessToken, token_type: "bearer", expires_in: ACCESS_TTL_S, refresh_token: refreshToken };
|
|
@@ -41267,7 +41539,7 @@ var fs6 = __toESM(require("fs"));
|
|
|
41267
41539
|
var import_ethers40 = require("ethers");
|
|
41268
41540
|
|
|
41269
41541
|
// src/boundary/index.ts
|
|
41270
|
-
var
|
|
41542
|
+
var import_node_crypto9 = require("crypto");
|
|
41271
41543
|
var fs5 = __toESM(require("fs"));
|
|
41272
41544
|
var os2 = __toESM(require("os"));
|
|
41273
41545
|
var path4 = __toESM(require("path"));
|
|
@@ -42291,7 +42563,7 @@ var DEFAULT_SEED = {
|
|
|
42291
42563
|
};
|
|
42292
42564
|
|
|
42293
42565
|
// src/boundary/upstream/mock/world.ts
|
|
42294
|
-
var
|
|
42566
|
+
var import_node_crypto3 = require("crypto");
|
|
42295
42567
|
var import_ethers3 = require("ethers");
|
|
42296
42568
|
|
|
42297
42569
|
// src/signer/safe.ts
|
|
@@ -42495,7 +42767,7 @@ var World = class {
|
|
|
42495
42767
|
nextId(prefix) {
|
|
42496
42768
|
this.state.counter += 1;
|
|
42497
42769
|
const n = this.state.counter;
|
|
42498
|
-
const hash = (0,
|
|
42770
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
|
|
42499
42771
|
return { n, hash };
|
|
42500
42772
|
}
|
|
42501
42773
|
nextTxRef() {
|
|
@@ -42775,11 +43047,10 @@ var World = class {
|
|
|
42775
43047
|
const spend = BigInt(p.amountSats);
|
|
42776
43048
|
const fee = BigInt(p.networkFeeSats);
|
|
42777
43049
|
const available = this.availableSats(p.positionId);
|
|
42778
|
-
if (spend
|
|
42779
|
-
const maxSpend = available > fee ? available - fee : 0n;
|
|
43050
|
+
if (spend > available) {
|
|
42780
43051
|
return {
|
|
42781
43052
|
ok: false,
|
|
42782
|
-
reason: `withdrawal of ${spend.toString()} sats
|
|
43053
|
+
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)`
|
|
42783
43054
|
};
|
|
42784
43055
|
}
|
|
42785
43056
|
const debt = BigInt(pos.debtUcdWei);
|
|
@@ -43375,7 +43646,7 @@ var WorldStore = class {
|
|
|
43375
43646
|
};
|
|
43376
43647
|
|
|
43377
43648
|
// src/boundary/upstream/mock/signer.ts
|
|
43378
|
-
var
|
|
43649
|
+
var import_node_crypto4 = require("crypto");
|
|
43379
43650
|
function mockSign(op, borrower, stance) {
|
|
43380
43651
|
if (stance === "decline") {
|
|
43381
43652
|
return {
|
|
@@ -43390,7 +43661,7 @@ function mockSign(op, borrower, stance) {
|
|
|
43390
43661
|
signer: borrower,
|
|
43391
43662
|
action: op.action,
|
|
43392
43663
|
card: op.card,
|
|
43393
|
-
digest: (0,
|
|
43664
|
+
digest: (0, import_node_crypto4.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
|
|
43394
43665
|
}
|
|
43395
43666
|
};
|
|
43396
43667
|
}
|
|
@@ -44662,7 +44933,7 @@ var MockUpstreamPlugin = class {
|
|
|
44662
44933
|
};
|
|
44663
44934
|
|
|
44664
44935
|
// src/boundary/upstream/mock/external-ceremony.ts
|
|
44665
|
-
var
|
|
44936
|
+
var import_node_crypto5 = require("crypto");
|
|
44666
44937
|
var import_node_child_process = require("child_process");
|
|
44667
44938
|
var import_ethers10 = require("ethers");
|
|
44668
44939
|
|
|
@@ -44855,7 +45126,7 @@ var ExternalCeremony = class {
|
|
|
44855
45126
|
validateUnsignedTx({ ...p.tx }, p.expected, this.deps.vctx);
|
|
44856
45127
|
const card = cardForTx(p.tx);
|
|
44857
45128
|
const outcome = await this.request({
|
|
44858
|
-
id: (0,
|
|
45129
|
+
id: (0, import_node_crypto5.randomUUID)(),
|
|
44859
45130
|
kind: "transaction",
|
|
44860
45131
|
action: p.action,
|
|
44861
45132
|
card,
|
|
@@ -44900,7 +45171,7 @@ var ExternalCeremony = class {
|
|
|
44900
45171
|
message
|
|
44901
45172
|
};
|
|
44902
45173
|
const outcome = await this.request({
|
|
44903
|
-
id: (0,
|
|
45174
|
+
id: (0, import_node_crypto5.randomUUID)(),
|
|
44904
45175
|
kind: "typed-data",
|
|
44905
45176
|
action: "login",
|
|
44906
45177
|
card: cardForTypedData("login", typedData),
|
|
@@ -44928,7 +45199,7 @@ var ExternalCeremony = class {
|
|
|
44928
45199
|
});
|
|
44929
45200
|
const card = cardForTypedData(p.action, typedData);
|
|
44930
45201
|
const outcome = await this.request({
|
|
44931
|
-
id: (0,
|
|
45202
|
+
id: (0, import_node_crypto5.randomUUID)(),
|
|
44932
45203
|
kind: "typed-data",
|
|
44933
45204
|
action: p.action,
|
|
44934
45205
|
card,
|
|
@@ -45103,7 +45374,7 @@ var KeystoreCeremony = class {
|
|
|
45103
45374
|
};
|
|
45104
45375
|
|
|
45105
45376
|
// src/boundary/upstream/mock/safe-ceremony.ts
|
|
45106
|
-
var
|
|
45377
|
+
var import_node_crypto6 = require("crypto");
|
|
45107
45378
|
var import_ethers12 = require("ethers");
|
|
45108
45379
|
init_tx_validator();
|
|
45109
45380
|
|
|
@@ -45404,7 +45675,7 @@ var SafeCeremony = class {
|
|
|
45404
45675
|
const primaryType = Object.keys(build.payload.types)[0];
|
|
45405
45676
|
const outcome = await bridge.requestSignatureCollection(
|
|
45406
45677
|
{
|
|
45407
|
-
id: (0,
|
|
45678
|
+
id: (0, import_node_crypto6.randomUUID)(),
|
|
45408
45679
|
kind: "typed-data",
|
|
45409
45680
|
action,
|
|
45410
45681
|
card: build.card,
|
|
@@ -51960,9 +52231,9 @@ var init_deployment_addresses = __esm2({
|
|
|
51960
52231
|
reason: "Shared upgrade script: LiquidationManagerModule implementation update"
|
|
51961
52232
|
},
|
|
51962
52233
|
BTCSpendAuthorizer: {
|
|
51963
|
-
previousImplementation: "
|
|
51964
|
-
newImplementation: "
|
|
51965
|
-
upgradedAt: "2026-
|
|
52234
|
+
previousImplementation: "0xdd3DFaEc50d6214d57eA64e8b76ff318b501607b",
|
|
52235
|
+
newImplementation: "0xf3282B5A1AE6428ee1b08cfaAF4EB4e198877484",
|
|
52236
|
+
upgradedAt: "2026-09-06T15:03:13.627Z",
|
|
51966
52237
|
upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
|
|
51967
52238
|
reason: "Shared upgrade script: BTCSpendAuthorizer implementation update"
|
|
51968
52239
|
},
|
|
@@ -52028,6 +52299,13 @@ var init_deployment_addresses = __esm2({
|
|
|
52028
52299
|
upgradedAt: "2026-07-07T16:56:49.844Z",
|
|
52029
52300
|
upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
|
|
52030
52301
|
reason: "Shared upgrade script: BitcoinWithdrawalAddressRegistry implementation update"
|
|
52302
|
+
},
|
|
52303
|
+
AgentDelegationRegistry: {
|
|
52304
|
+
previousImplementation: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
|
|
52305
|
+
newImplementation: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
|
|
52306
|
+
upgradedAt: "2026-09-06T15:06:02.814Z",
|
|
52307
|
+
upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
|
|
52308
|
+
reason: "Reconciled implementation from chain"
|
|
52031
52309
|
}
|
|
52032
52310
|
},
|
|
52033
52311
|
history: {
|
|
@@ -52113,7 +52391,7 @@ var init_deployment_addresses = __esm2({
|
|
|
52113
52391
|
LIQUIDATION_MANAGER_MODULE: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76",
|
|
52114
52392
|
LIQUIDATION_MANAGER_MODULE_IMPL: "0xCe7587C47094BBb3dCa13D7a2299Ec9beA6cd759",
|
|
52115
52393
|
BTC_SPEND_AUTHORIZER: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
|
|
52116
|
-
BTC_SPEND_AUTHORIZER_IMPL: "
|
|
52394
|
+
BTC_SPEND_AUTHORIZER_IMPL: "0xf3282B5A1AE6428ee1b08cfaAF4EB4e198877484",
|
|
52117
52395
|
UPGRADE_VALIDATOR: "0x592e650edD9bA26ecc407989fdd6F9cdcDeC27A6",
|
|
52118
52396
|
UPGRADE_VALIDATOR_IMPL: "0x9E70e1D07AB11ac9dD37B67AA091Efe97d7Ed84b",
|
|
52119
52397
|
BITCOIN_PROVIDER_REGISTRY: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
|
|
@@ -59231,12 +59509,12 @@ async function reconcileAuthorizedSpend(spend, esploraBaseUrl, httpGetJson = def
|
|
|
59231
59509
|
{ txid: spend.txid, vout: spend.vout }
|
|
59232
59510
|
);
|
|
59233
59511
|
}
|
|
59234
|
-
if (spend.targetAmount
|
|
59512
|
+
if (spend.targetAmount > spend.satoshis) {
|
|
59235
59513
|
return {
|
|
59236
59514
|
spend,
|
|
59237
59515
|
status: "CORRUPT",
|
|
59238
59516
|
onChainOutputValue,
|
|
59239
|
-
reason: `Authorized targetAmount ${spend.targetAmount} sats
|
|
59517
|
+
reason: `Authorized targetAmount ${spend.targetAmount} sats exceeds the ${spend.satoshis}-sat aggregate input value \u2014 the contract could never have authorized this`
|
|
59240
59518
|
};
|
|
59241
59519
|
}
|
|
59242
59520
|
const outspendRes = await httpGetJson(
|
|
@@ -80000,7 +80278,7 @@ var EoaDHSigner = class {
|
|
|
80000
80278
|
};
|
|
80001
80279
|
|
|
80002
80280
|
// src/signer/external-eoa.ts
|
|
80003
|
-
var
|
|
80281
|
+
var import_node_crypto7 = require("crypto");
|
|
80004
80282
|
var import_ethers38 = require("ethers");
|
|
80005
80283
|
|
|
80006
80284
|
// src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
|
|
@@ -80094,7 +80372,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80094
80372
|
let used = { quantumTs: initialTs, fields: initial.fields };
|
|
80095
80373
|
const outcome = await this.deps.bridge.requestSignature(
|
|
80096
80374
|
{
|
|
80097
|
-
id: (0,
|
|
80375
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80098
80376
|
kind: "personal-sign",
|
|
80099
80377
|
action: spec.action,
|
|
80100
80378
|
card: initial.card,
|
|
@@ -80128,7 +80406,7 @@ var ExternalEoaDHSigner = class {
|
|
|
80128
80406
|
const approved = toApprovedTx(outerTx, this.deps.chainId);
|
|
80129
80407
|
const gas = outerTx.gasLimit != null ? import_ethers38.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
|
|
80130
80408
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80131
|
-
id: (0,
|
|
80409
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80132
80410
|
kind: "transaction",
|
|
80133
80411
|
action: ctx.action,
|
|
80134
80412
|
card: ctx.card,
|
|
@@ -80179,15 +80457,22 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80179
80457
|
}
|
|
80180
80458
|
const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
|
|
80181
80459
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80182
|
-
id: (0,
|
|
80460
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80183
80461
|
kind: "personal-sign",
|
|
80184
|
-
action: "btc-withdrawal
|
|
80462
|
+
action: "btc-withdrawal EXECUTE step (blind hash)",
|
|
80185
80463
|
card: [
|
|
80186
|
-
"BLIND SIGNATURE \u2014 BTC withdrawal
|
|
80464
|
+
"BLIND SIGNATURE \u2014 BTC withdrawal, EXECUTE step",
|
|
80187
80465
|
`hash: ${hashHex}`,
|
|
80188
80466
|
"This hash is built inside the SDK and its contents CANNOT be decoded or verified by this page",
|
|
80189
80467
|
"(identical to how diamondhands.credit signs withdrawals).",
|
|
80190
|
-
"Approve ONLY if you initiated this exact BTC withdrawal in the conversation."
|
|
80468
|
+
"Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
|
|
80469
|
+
"",
|
|
80470
|
+
"SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
|
|
80471
|
+
`raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
|
|
80472
|
+
"under a minute and often nearer twenty seconds \u2014 far less than the approval page",
|
|
80473
|
+
"itself allows. If it expires the signature is refused, the withdrawal does not",
|
|
80474
|
+
"complete, and the reserved coins stay reserved until that is cleared. Decline and",
|
|
80475
|
+
"start again rather than signing something you have not finished reading."
|
|
80191
80476
|
],
|
|
80192
80477
|
expectedSigner: this.deps.borrower,
|
|
80193
80478
|
chainId: this.deps.chainId,
|
|
@@ -80210,7 +80495,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80210
80495
|
message: value
|
|
80211
80496
|
};
|
|
80212
80497
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80213
|
-
id: (0,
|
|
80498
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80214
80499
|
kind: "typed-data",
|
|
80215
80500
|
action: "login",
|
|
80216
80501
|
card: cardForTypedData("login", typedData),
|
|
@@ -80236,7 +80521,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
|
|
|
80236
80521
|
const card = cardForTx(approved);
|
|
80237
80522
|
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));
|
|
80238
80523
|
const outcome = await this.deps.bridge.requestSignature({
|
|
80239
|
-
id: (0,
|
|
80524
|
+
id: (0, import_node_crypto7.randomUUID)(),
|
|
80240
80525
|
kind: "transaction",
|
|
80241
80526
|
action: describeFn(approved.data),
|
|
80242
80527
|
card,
|
|
@@ -81120,10 +81405,10 @@ var RealUpstreamPlugin = class {
|
|
|
81120
81405
|
// src/boundary/upstream/shared/external-bridge/bridge.ts
|
|
81121
81406
|
var fs4 = __toESM(require("fs"));
|
|
81122
81407
|
var http3 = __toESM(require("http"));
|
|
81123
|
-
var
|
|
81408
|
+
var import_node_crypto8 = require("crypto");
|
|
81124
81409
|
|
|
81125
81410
|
// src/boundary/upstream/shared/external-bridge/approval-page.ts
|
|
81126
|
-
function renderApprovalPage(sessionId) {
|
|
81411
|
+
function renderApprovalPage(sessionId, nonce) {
|
|
81127
81412
|
return `<!doctype html>
|
|
81128
81413
|
<html lang="en">
|
|
81129
81414
|
<head>
|
|
@@ -81173,15 +81458,17 @@ function renderApprovalPage(sessionId) {
|
|
|
81173
81458
|
</div>
|
|
81174
81459
|
</div>
|
|
81175
81460
|
</main>
|
|
81176
|
-
<script>
|
|
81461
|
+
<script nonce="${nonce}">
|
|
81177
81462
|
${PAGE_CRYPTO_JS}
|
|
81178
81463
|
</script>
|
|
81179
|
-
<script>
|
|
81464
|
+
<script nonce="${nonce}">
|
|
81180
81465
|
"use strict";
|
|
81181
81466
|
const SESSION = ${JSON.stringify(sessionId)};
|
|
81182
81467
|
// One-time token leaves the address bar (and history) immediately.
|
|
81183
81468
|
// Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
|
|
81184
81469
|
// at loopback root ("/") and under a hosted tenant mount ("/approval/<id>/").
|
|
81470
|
+
// EVERY endpoint reference goes through BASE \u2014 an origin-absolute "/x" resolves to the
|
|
81471
|
+
// ORIGIN root, which on a mount is the host, not the bridge, and 404s silently.
|
|
81185
81472
|
const BASE = location.pathname.replace(/[^/]*$/, "");
|
|
81186
81473
|
history.replaceState(null, "", location.pathname);
|
|
81187
81474
|
|
|
@@ -81253,14 +81540,14 @@ async function connect() {
|
|
|
81253
81540
|
// wallet's own state transition and can report the stale value.
|
|
81254
81541
|
async function onAccountsChanged(accounts) {
|
|
81255
81542
|
account = (accounts && accounts[0]) || null;
|
|
81256
|
-
await post("
|
|
81543
|
+
await post(BASE + "wallet-event", { account: account, chainId: chainId });
|
|
81257
81544
|
showWallet();
|
|
81258
81545
|
clearRequest("Wallet changed \u2014 pending request invalidated.");
|
|
81259
81546
|
}
|
|
81260
81547
|
|
|
81261
81548
|
async function onChainChanged(cid) {
|
|
81262
81549
|
chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
|
|
81263
|
-
await post("
|
|
81550
|
+
await post(BASE + "wallet-event", { account: account, chainId: chainId });
|
|
81264
81551
|
showWallet();
|
|
81265
81552
|
clearRequest("Network changed \u2014 pending request invalidated.");
|
|
81266
81553
|
}
|
|
@@ -81368,7 +81655,7 @@ connect();
|
|
|
81368
81655
|
</body>
|
|
81369
81656
|
</html>`;
|
|
81370
81657
|
}
|
|
81371
|
-
function renderUnlockPage(sessionId) {
|
|
81658
|
+
function renderUnlockPage(sessionId, nonce) {
|
|
81372
81659
|
return `<!doctype html>
|
|
81373
81660
|
<html lang="en">
|
|
81374
81661
|
<head>
|
|
@@ -81410,7 +81697,7 @@ function renderUnlockPage(sessionId) {
|
|
|
81410
81697
|
<div id="status" class="status"></div>
|
|
81411
81698
|
</div>
|
|
81412
81699
|
</main>
|
|
81413
|
-
<script>
|
|
81700
|
+
<script nonce="${nonce}">
|
|
81414
81701
|
"use strict";
|
|
81415
81702
|
const SESSION = ${JSON.stringify(sessionId)};
|
|
81416
81703
|
// Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
|
|
@@ -81468,7 +81755,7 @@ var SignatureBridge = class {
|
|
|
81468
81755
|
/** Started state independent of the transport binding (mounted bridges own no server). */
|
|
81469
81756
|
started = false;
|
|
81470
81757
|
mount;
|
|
81471
|
-
token = (0,
|
|
81758
|
+
token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81472
81759
|
/** Hosted mounts: when the current page token was minted (rotation basis). */
|
|
81473
81760
|
tokenMintedAt = 0;
|
|
81474
81761
|
/** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
|
|
@@ -81505,7 +81792,7 @@ var SignatureBridge = class {
|
|
|
81505
81792
|
unlockUrl() {
|
|
81506
81793
|
if (!this.started) throw new Error("bridge is not started");
|
|
81507
81794
|
if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
|
|
81508
|
-
this.unlockToken = (0,
|
|
81795
|
+
this.unlockToken = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81509
81796
|
return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
|
|
81510
81797
|
}
|
|
81511
81798
|
/** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
|
|
@@ -81546,7 +81833,7 @@ var SignatureBridge = class {
|
|
|
81546
81833
|
if (this.mount) {
|
|
81547
81834
|
const now = this.clock();
|
|
81548
81835
|
if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
|
|
81549
|
-
this.token = (0,
|
|
81836
|
+
this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81550
81837
|
this.tokenMintedAt = now;
|
|
81551
81838
|
}
|
|
81552
81839
|
return `${this.mount.baseUrl}/?t=${this.token}`;
|
|
@@ -81762,7 +82049,7 @@ var SignatureBridge = class {
|
|
|
81762
82049
|
this.server = null;
|
|
81763
82050
|
this.started = false;
|
|
81764
82051
|
this.wallet = null;
|
|
81765
|
-
this.token = (0,
|
|
82052
|
+
this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81766
82053
|
this.tokenMintedAt = 0;
|
|
81767
82054
|
if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
|
|
81768
82055
|
void this.wcTransport?.close().catch(() => void 0);
|
|
@@ -81832,10 +82119,11 @@ var SignatureBridge = class {
|
|
|
81832
82119
|
this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
|
|
81833
82120
|
return;
|
|
81834
82121
|
}
|
|
81835
|
-
const sessionId = (0,
|
|
82122
|
+
const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
81836
82123
|
this.sessions.set(sessionId, { wallet: null, sse: null });
|
|
81837
|
-
|
|
81838
|
-
res.
|
|
82124
|
+
const page = htmlPageSecurityHeaders();
|
|
82125
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
|
|
82126
|
+
res.end(renderApprovalPage(sessionId, page.nonce));
|
|
81839
82127
|
}
|
|
81840
82128
|
/** Target-network hints for the page's chain self-heal (session-gated). */
|
|
81841
82129
|
serveConfig(url2, res) {
|
|
@@ -81895,9 +82183,10 @@ var SignatureBridge = class {
|
|
|
81895
82183
|
return;
|
|
81896
82184
|
}
|
|
81897
82185
|
this.unlockToken = null;
|
|
81898
|
-
this.unlockSession = (0,
|
|
81899
|
-
|
|
81900
|
-
res.
|
|
82186
|
+
this.unlockSession = (0, import_node_crypto8.randomBytes)(24).toString("hex");
|
|
82187
|
+
const page = htmlPageSecurityHeaders();
|
|
82188
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
|
|
82189
|
+
res.end(renderUnlockPage(this.unlockSession, page.nonce));
|
|
81901
82190
|
}
|
|
81902
82191
|
async onUnlockSubmit(body, res) {
|
|
81903
82192
|
if (!this.keystoreUnlock) {
|
|
@@ -82143,7 +82432,7 @@ function createBoundary(config, opts) {
|
|
|
82143
82432
|
"createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
|
|
82144
82433
|
);
|
|
82145
82434
|
}
|
|
82146
|
-
const configFingerprint = (0,
|
|
82435
|
+
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);
|
|
82147
82436
|
if (opts?.ceremony) {
|
|
82148
82437
|
const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
|
|
82149
82438
|
const boundary2 = new BoundaryCore({
|
|
@@ -82312,7 +82601,7 @@ async function createRealBoundary(config, wallet, overrides) {
|
|
|
82312
82601
|
}
|
|
82313
82602
|
const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
|
|
82314
82603
|
await plugin.initWriteSdk();
|
|
82315
|
-
const configFingerprint = (0,
|
|
82604
|
+
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);
|
|
82316
82605
|
const capabilities = () => ({
|
|
82317
82606
|
reads: {
|
|
82318
82607
|
public: true,
|
|
@@ -82412,1239 +82701,406 @@ async function buildBoundary(configResult, overrides) {
|
|
|
82412
82701
|
return { boundaryResult: { ok: true, boundary }, signer, dispose };
|
|
82413
82702
|
}
|
|
82414
82703
|
|
|
82415
|
-
// src/
|
|
82416
|
-
var
|
|
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
|
-
|
|
82470
|
-
|
|
82471
|
-
|
|
82472
|
-
|
|
82473
|
-
|
|
82474
|
-
|
|
82475
|
-
|
|
82704
|
+
// src/boundary/field-glossary.ts
|
|
82705
|
+
var FIELD_GLOSSARY = {
|
|
82706
|
+
// ---- identity / envelope structure ----
|
|
82707
|
+
positionId: "the position's 32-byte id (0x\u202664 hex) \u2014 the input every position_* tool takes",
|
|
82708
|
+
borrower: "the Ethereum address that owns the position (the borrowing identity)",
|
|
82709
|
+
vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
|
|
82710
|
+
pkpId: "internal id of the programmable key pair holding BTC custody for this position",
|
|
82711
|
+
id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
|
|
82712
|
+
kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
|
|
82713
|
+
fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
|
|
82714
|
+
// ---- position facts (chain) ----
|
|
82715
|
+
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",
|
|
82716
|
+
termMonths: "the current term length in months",
|
|
82717
|
+
totalTermMonths: "cumulative months across the original term plus every extension",
|
|
82718
|
+
createdAt: "ISO timestamp the position was created",
|
|
82719
|
+
expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
|
|
82720
|
+
previousExpiryAt: "the expiry before the latest extension (null when never extended)",
|
|
82721
|
+
lastUpdatedAt: "ISO timestamp of the last state change",
|
|
82722
|
+
debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
|
|
82723
|
+
// ---- indexed health (indexer snapshot) ----
|
|
82724
|
+
indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
|
|
82725
|
+
collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
|
|
82726
|
+
healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
|
|
82727
|
+
asOf: "ISO timestamp the indexer snapshot was computed",
|
|
82728
|
+
basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
|
|
82729
|
+
// ---- collateral (live BTC view) ----
|
|
82730
|
+
collateral: "the live Bitcoin-side view of the position's vault",
|
|
82731
|
+
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",
|
|
82732
|
+
availableSource: "which source served availableSats (null when degraded)",
|
|
82733
|
+
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",
|
|
82734
|
+
txid: "Bitcoin transaction id",
|
|
82735
|
+
sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
|
|
82736
|
+
confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
|
|
82737
|
+
minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
|
|
82738
|
+
pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
|
|
82739
|
+
maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
|
|
82740
|
+
// ---- valuation ----
|
|
82741
|
+
valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
|
|
82742
|
+
btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82743
|
+
priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82744
|
+
priceSource: "which oracle served the price",
|
|
82745
|
+
collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
|
|
82746
|
+
currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
|
|
82747
|
+
maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
|
|
82748
|
+
liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
|
|
82749
|
+
maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
|
|
82750
|
+
maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
|
|
82751
|
+
liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
|
|
82752
|
+
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",
|
|
82753
|
+
// ---- list envelope ----
|
|
82754
|
+
items: "the rows of this page",
|
|
82755
|
+
page: "1-based page number of this response",
|
|
82756
|
+
pageSize: "requested rows per page",
|
|
82757
|
+
total: "total rows matching the filter across all pages",
|
|
82758
|
+
// ---- events ----
|
|
82759
|
+
positionCreated: "creation events (seq, time, selected term)",
|
|
82760
|
+
seq: "the event's sequence number within the position's history (ordering key)",
|
|
82761
|
+
at: "ISO timestamp of the event",
|
|
82762
|
+
selectedTerm: "term length chosen, in months",
|
|
82763
|
+
mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
|
|
82764
|
+
amountUcdWei: "the event's UCD amount in wei",
|
|
82765
|
+
feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
|
|
82766
|
+
payments: "repayment events: when and how much UCD was paid back",
|
|
82767
|
+
type: "the payment's kind label as indexed (e.g. partial/full)",
|
|
82768
|
+
renewals: "extension events: added term, extension fee, and the new expiry",
|
|
82769
|
+
extensionTerm: "months added by this extension",
|
|
82770
|
+
extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
|
|
82771
|
+
newExpiryAt: "the expiry after this extension (ISO)",
|
|
82772
|
+
withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
|
|
82773
|
+
amountSats: "the withdrawal amount in satoshis",
|
|
82774
|
+
networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
|
|
82775
|
+
targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
|
|
82776
|
+
liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
|
|
82777
|
+
other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
|
|
82778
|
+
totalEvents: "total events across all groups",
|
|
82779
|
+
// ---- pending withdrawals ----
|
|
82780
|
+
vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
|
|
82781
|
+
satoshis: "the reserved amount in satoshis",
|
|
82782
|
+
// ---- protocol status / terms ----
|
|
82783
|
+
paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
|
|
82784
|
+
ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
|
|
82785
|
+
btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
|
|
82786
|
+
terms: "the offered term tiers with their fee rates",
|
|
82787
|
+
months: "the tier's term length in months",
|
|
82788
|
+
originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
|
|
82789
|
+
extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
|
|
82790
|
+
// ---- psm quote ----
|
|
82791
|
+
direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
|
|
82792
|
+
contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
|
|
82793
|
+
amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
|
|
82794
|
+
amountInToken: "the token you pay with",
|
|
82795
|
+
amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
|
|
82796
|
+
amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
|
|
82797
|
+
amountOutToken: "the token you receive",
|
|
82798
|
+
amountOutUnit: "the smallest-unit name of amountOut",
|
|
82799
|
+
fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
|
|
82800
|
+
amount: "the amount of the item it sits on, in that item's stated unit/token",
|
|
82801
|
+
token: "the token the amount is denominated in",
|
|
82802
|
+
bps: "the rate in basis points (100 bps = 1%)",
|
|
82803
|
+
reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
|
|
82804
|
+
available: "how much of the reserve is available, in its stated unit",
|
|
82805
|
+
unit: "the smallest-unit name for the amount it sits on",
|
|
82806
|
+
human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
|
|
82807
|
+
executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
|
|
82808
|
+
};
|
|
82809
|
+
function fieldGuide(...fields) {
|
|
82810
|
+
const lines = fields.map((f) => {
|
|
82811
|
+
const meaning = FIELD_GLOSSARY[f];
|
|
82812
|
+
if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
|
|
82813
|
+
return `${f} = ${meaning}`;
|
|
82814
|
+
});
|
|
82815
|
+
return ` Field guide: ${lines.join("; ")}.`;
|
|
82476
82816
|
}
|
|
82817
|
+
function renderFieldGlossaryTopic() {
|
|
82818
|
+
const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
|
|
82819
|
+
return `# Reading the data \u2014 every field, its exact meaning
|
|
82477
82820
|
|
|
82478
|
-
|
|
82479
|
-
|
|
82480
|
-
|
|
82481
|
-
|
|
82482
|
-
var import_zod = require("zod");
|
|
82483
|
-
var import_ethers41 = require("ethers");
|
|
82821
|
+
The payload's fields and notes are AUTHORITATIVE. State what they say; never speculate
|
|
82822
|
+
past them; when the data does not carry something, say "the data does not carry X".
|
|
82823
|
+
Conditional \`reading\` notes in a payload are instructions for interpreting that exact
|
|
82824
|
+
response \u2014 follow them over any prior assumption.
|
|
82484
82825
|
|
|
82485
|
-
|
|
82486
|
-
function bigintReplacer(_key, value) {
|
|
82487
|
-
if (typeof value === "bigint") return value.toString();
|
|
82488
|
-
return value;
|
|
82489
|
-
}
|
|
82490
|
-
function serialize(data) {
|
|
82491
|
-
return JSON.stringify(data, bigintReplacer, 2);
|
|
82826
|
+
${lines.join("\n")}`;
|
|
82492
82827
|
}
|
|
82493
82828
|
|
|
82494
|
-
// src/
|
|
82495
|
-
|
|
82496
|
-
|
|
82829
|
+
// src/guide/content.ts
|
|
82830
|
+
var GUIDE_TOPICS = [
|
|
82831
|
+
"getting-started",
|
|
82832
|
+
"first-setup",
|
|
82833
|
+
"connect-wallet",
|
|
82834
|
+
"lifecycle",
|
|
82835
|
+
"fees",
|
|
82836
|
+
"psm",
|
|
82837
|
+
"authorization",
|
|
82838
|
+
"safe",
|
|
82839
|
+
"delegation",
|
|
82840
|
+
"safety",
|
|
82841
|
+
"switch-network",
|
|
82842
|
+
"connector",
|
|
82843
|
+
"troubleshooting",
|
|
82844
|
+
"glossary",
|
|
82845
|
+
"reading-data"
|
|
82846
|
+
];
|
|
82847
|
+
var GUIDE_SIGNER_MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
82848
|
+
var EXTERNAL_ONLY_SIGNER_MODES = ["external"];
|
|
82849
|
+
function offers(d, mode) {
|
|
82850
|
+
return d.signerModes.includes(mode);
|
|
82497
82851
|
}
|
|
82498
|
-
function
|
|
82499
|
-
|
|
82500
|
-
if (error.source) lines.push(`source: ${error.source}`);
|
|
82501
|
-
return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
|
|
82852
|
+
function signerModeSourceClause(d) {
|
|
82853
|
+
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`";
|
|
82502
82854
|
}
|
|
82503
|
-
|
|
82504
|
-
|
|
82505
|
-
|
|
82506
|
-
|
|
82507
|
-
|
|
82508
|
-
|
|
82509
|
-
|
|
82855
|
+
var LOCAL_GUIDE_DEPLOYMENT = {
|
|
82856
|
+
tier: "local",
|
|
82857
|
+
networks: ["sepolia", "mainnet"],
|
|
82858
|
+
// A local install constructs the whole signer runtime: the real adapter offers
|
|
82859
|
+
// external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
|
|
82860
|
+
// speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
|
|
82861
|
+
// on the real adapter these modes refuse") carry the narrower adapter axis.
|
|
82862
|
+
signerModes: GUIDE_SIGNER_MODES
|
|
82863
|
+
};
|
|
82864
|
+
function servedNetworks(d) {
|
|
82865
|
+
if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
|
|
82866
|
+
const mainnet = d.networks.includes("mainnet");
|
|
82867
|
+
const sepolia = d.networks.includes("sepolia");
|
|
82868
|
+
if (mainnet && sepolia) {
|
|
82869
|
+
return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
|
|
82510
82870
|
}
|
|
82511
|
-
|
|
82512
|
-
|
|
82871
|
+
if (mainnet) {
|
|
82872
|
+
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";
|
|
82873
|
+
}
|
|
82874
|
+
return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
|
|
82513
82875
|
}
|
|
82514
|
-
function
|
|
82515
|
-
|
|
82876
|
+
function connectorStatusTruth(d) {
|
|
82877
|
+
if (d.tier === "hosted") {
|
|
82878
|
+
return `**STATUS TRUTH (say this first when asked):** this session IS the hosted
|
|
82879
|
+
connector \u2014 the user is already on it, so there is nothing to install and no URL to hand
|
|
82880
|
+
out. It serves ${servedNetworks(d)}. State that money reality unprompted, and never
|
|
82881
|
+
promise a network, a tier or a timing this deployment does not already serve.`;
|
|
82882
|
+
}
|
|
82883
|
+
return `**STATUS TRUTH (say this first when asked):** this session is a LOCAL install,
|
|
82884
|
+
not the hosted connector. Whether a public connector URL is being served today is the
|
|
82885
|
+
operator's rollout decision and this build cannot see it \u2014 so never assert that one is
|
|
82886
|
+
available, and never assert that one is not. If the user already has a URL, everything
|
|
82887
|
+
below describes what they get; otherwise the local install paths (\`first-setup\`) are the
|
|
82888
|
+
way in. Never promise availability or timing.`;
|
|
82516
82889
|
}
|
|
82517
|
-
function
|
|
82518
|
-
if (
|
|
82519
|
-
|
|
82890
|
+
function connectorNetworkTruth(d) {
|
|
82891
|
+
if (d.tier === "hosted") {
|
|
82892
|
+
return `And it serves only the networks its deployment is rolled out to \u2014 this one
|
|
82893
|
+
serves ${servedNetworks(d)}. Which networks a deployment is rolled out to is the
|
|
82894
|
+
operator's deploy decision, never a hidden knob \u2014 and it is not a field of
|
|
82895
|
+
\`boundary://info\`, whose capabilities block reports the world THIS session is on right
|
|
82896
|
+
now (network, chainId, practiceWorld) plus the read/write/signer planes. \`network_switch\`
|
|
82897
|
+
is what states the rollout: asked for a network this deployment is not rolled out to, it
|
|
82898
|
+
refuses and names the ones it is.`;
|
|
82899
|
+
}
|
|
82900
|
+
return `And any connector deployment serves only the networks it is rolled out to \u2014
|
|
82901
|
+
which ones is the operator's deploy decision, never a hidden knob. Do not go looking for
|
|
82902
|
+
that list in \`boundary://info\`: its capabilities block reports the world THIS session is
|
|
82903
|
+
on (network, chainId, practiceWorld) plus the read/write/signer planes, never another
|
|
82904
|
+
deployment's rollout. \`network_switch\` is what states it \u2014 asked for a network a
|
|
82905
|
+
deployment is not rolled out to, it refuses and names the ones it is. This local build
|
|
82906
|
+
cannot see another deployment's rollout at all: ask that server, never assume.`;
|
|
82520
82907
|
}
|
|
82521
|
-
function
|
|
82522
|
-
|
|
82908
|
+
function connectorInstallNote(d) {
|
|
82909
|
+
if (d.tier === "hosted") {
|
|
82910
|
+
return `(The user is ALREADY on the fourth, zero-install path \u2014 the claude.ai
|
|
82911
|
+
connector \u2014 so none of the above is needed HERE; those paths are for other machines.
|
|
82912
|
+
Truth and trust model: \`guide connector\`.)`;
|
|
82913
|
+
}
|
|
82914
|
+
return `(A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented in this
|
|
82915
|
+
build. Whether it is publicly served today is the operator's rollout decision and this
|
|
82916
|
+
session cannot see it: do not assert either way. Truth and trust model:
|
|
82917
|
+
\`guide connector\`.)`;
|
|
82523
82918
|
}
|
|
82524
|
-
function
|
|
82525
|
-
if (
|
|
82526
|
-
|
|
82527
|
-
|
|
82528
|
-
|
|
82529
|
-
|
|
82530
|
-
|
|
82531
|
-
|
|
82532
|
-
|
|
82533
|
-
|
|
82534
|
-
],
|
|
82535
|
-
isError: true
|
|
82536
|
-
};
|
|
82919
|
+
function connectorTroubleshootingRow(d) {
|
|
82920
|
+
if (d.tier === "hosted") {
|
|
82921
|
+
return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 that is THIS
|
|
82922
|
+
session. Nothing to install, no URL to look up; it serves ${servedNetworks(d)}. Full
|
|
82923
|
+
truth: \`guide connector\`.`;
|
|
82924
|
+
}
|
|
82925
|
+
return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 this session is
|
|
82926
|
+
a local install, not that tier. Whether a public URL is being served today is the
|
|
82927
|
+
operator's rollout decision and this build cannot see it: do not assert either way. The
|
|
82928
|
+
local install paths work regardless. Full truth: \`guide connector\`.`;
|
|
82537
82929
|
}
|
|
82538
|
-
function
|
|
82539
|
-
if (
|
|
82540
|
-
|
|
82541
|
-
|
|
82542
|
-
|
|
82930
|
+
function approvalPageLocation(d) {
|
|
82931
|
+
if (d.tier === "hosted") {
|
|
82932
|
+
return `its URL is ALSO in the tool result. On this hosted tier the page is served by
|
|
82933
|
+
the connector itself over HTTPS on its own public origin, so ANY browser reaches it,
|
|
82934
|
+
including a phone's. The link carries a one-time session token \u2014 treat it as a secret,
|
|
82935
|
+
never forward it, and check the address bar shows that same origin before connecting a
|
|
82936
|
+
wallet.`;
|
|
82937
|
+
}
|
|
82938
|
+
return `its URL is ALSO in the tool result. On this local install the page is served by
|
|
82939
|
+
the server's own loopback listener (127.0.0.1): it exists only on the machine the
|
|
82940
|
+
server runs on, so open it there \u2014 no other device can reach it.`;
|
|
82543
82941
|
}
|
|
82544
|
-
|
|
82545
|
-
|
|
82546
|
-
const stamp = envStamp(getB());
|
|
82547
|
-
const content = result.content.map(
|
|
82548
|
-
(c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
|
|
82549
|
-
|
|
82550
|
-
${stamp}` } : c
|
|
82551
|
-
);
|
|
82552
|
-
return { ...result, content };
|
|
82942
|
+
function switchNetworkHeadline(d) {
|
|
82943
|
+
return d.networks.length > 1 ? "sepolia \u2194 mainnet by conversation (real adapter)" : `${d.networks[0]} ONLY on this deployment (real adapter)`;
|
|
82553
82944
|
}
|
|
82554
|
-
|
|
82555
|
-
|
|
82556
|
-
return
|
|
82557
|
-
|
|
82558
|
-
|
|
82559
|
-
|
|
82560
|
-
|
|
82561
|
-
|
|
82562
|
-
|
|
82563
|
-
}
|
|
82945
|
+
function switchNetworkRules(d) {
|
|
82946
|
+
if (d.networks.length > 1) {
|
|
82947
|
+
return `- \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
|
|
82948
|
+
the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
|
|
82949
|
+
- NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
|
|
82950
|
+
A sepolia position does not exist on mainnet and vice versa.
|
|
82951
|
+
- Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
|
|
82952
|
+
and every one still requires the user's explicit confirmation plus the signer
|
|
82953
|
+
ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
|
|
82954
|
+
}
|
|
82955
|
+
const only = d.networks[0];
|
|
82956
|
+
const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
|
|
82957
|
+
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.";
|
|
82958
|
+
return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
|
|
82959
|
+
network this deployment is rolled out to \u2014 every other target is REFUSED with that
|
|
82960
|
+
rollout truth. There is nothing to switch TO here; never offer the user another world.
|
|
82961
|
+
Money reality: ${money}.
|
|
82962
|
+
- State is per-network by construction: positions, vaults, signer bindings and logins
|
|
82963
|
+
belong to ${only} and would not exist anywhere else.
|
|
82964
|
+
- Fund-moving loan operations run on ${only}, each still requiring the user's explicit
|
|
82965
|
+
confirmation plus the signer ceremony.
|
|
82966
|
+
- ${psm}`;
|
|
82564
82967
|
}
|
|
82565
|
-
|
|
82566
|
-
|
|
82567
|
-
|
|
82568
|
-
|
|
82569
|
-
|
|
82570
|
-
function checkPositionIdHex(id, label = "Position ID") {
|
|
82571
|
-
if (!POSITION_ID_RE.test(id)) {
|
|
82572
|
-
return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
|
|
82968
|
+
function wrongNetworkTroubleshootingRow(d) {
|
|
82969
|
+
if (d.networks.length > 1) {
|
|
82970
|
+
return `- **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
|
|
82971
|
+
(human-confirmed card; nothing carries across networks). Mock: the world is pinned by
|
|
82972
|
+
config \u2014 no switch exists there.`;
|
|
82573
82973
|
}
|
|
82574
|
-
return
|
|
82974
|
+
return `- **Wrong network / asks for another one** \u2014 this deployment is rolled out to
|
|
82975
|
+
${d.networks[0]} alone, so \`network_switch\` refuses every other target with that
|
|
82976
|
+
rollout truth. Relay the refusal; do not suggest a world this service does not serve.`;
|
|
82575
82977
|
}
|
|
82576
|
-
function
|
|
82577
|
-
if (
|
|
82578
|
-
return
|
|
82579
|
-
}
|
|
82580
|
-
if (amount > UCD_SANITY_CAP) {
|
|
82581
|
-
return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
|
|
82582
|
-
}
|
|
82583
|
-
if (amount > 0 && amount < 1e-6) {
|
|
82584
|
-
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
82585
|
-
}
|
|
82586
|
-
const decimals = amount.toString().split(".")[1];
|
|
82587
|
-
if (decimals && decimals.length > 6) {
|
|
82588
|
-
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
82978
|
+
function switchNetworkIndexLine(d) {
|
|
82979
|
+
if (d.networks.length > 1) {
|
|
82980
|
+
return "- switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated";
|
|
82589
82981
|
}
|
|
82590
|
-
|
|
82982
|
+
const only = d.networks[0];
|
|
82983
|
+
const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
|
|
82984
|
+
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`;
|
|
82591
82985
|
}
|
|
82592
|
-
function
|
|
82593
|
-
if (
|
|
82594
|
-
|
|
82595
|
-
|
|
82596
|
-
|
|
82597
|
-
|
|
82598
|
-
|
|
82599
|
-
|
|
82986
|
+
function psmAvailabilityNote(d) {
|
|
82987
|
+
if (d.networks.includes("sepolia")) return "";
|
|
82988
|
+
return `**Not executable on this deployment.** The PSM write port refuses on every network
|
|
82989
|
+
but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
|
|
82990
|
+
\`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
|
|
82991
|
+
the mechanism, not an offer: say so before a user plans around it.
|
|
82992
|
+
|
|
82993
|
+
`;
|
|
82600
82994
|
}
|
|
82601
|
-
function
|
|
82602
|
-
|
|
82603
|
-
|
|
82604
|
-
|
|
82605
|
-
|
|
82606
|
-
|
|
82607
|
-
|
|
82608
|
-
|
|
82995
|
+
function authorizationModeBullets(d) {
|
|
82996
|
+
const bullets = [];
|
|
82997
|
+
if (offers(d, "external")) {
|
|
82998
|
+
bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
|
|
82999
|
+
mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
|
|
83000
|
+
is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
|
|
83001
|
+
The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
|
|
83002
|
+
approval page states plainly it CANNOT decode. Never extend the card promise over
|
|
83003
|
+
that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
|
|
83004
|
+
}
|
|
83005
|
+
if (offers(d, "keystore")) {
|
|
83006
|
+
bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
|
|
83007
|
+
Real adapter and mock.`);
|
|
83008
|
+
}
|
|
83009
|
+
if (offers(d, "safe") || offers(d, "safe-module")) {
|
|
83010
|
+
bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
|
|
83011
|
+
refuse with that true reason (their planes ship in their own deliveries).`);
|
|
83012
|
+
}
|
|
83013
|
+
if (offers(d, "mock-simulated")) {
|
|
83014
|
+
bullets.push(` - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).`);
|
|
83015
|
+
}
|
|
83016
|
+
return bullets.join("\n");
|
|
83017
|
+
}
|
|
83018
|
+
function keystoreAbsenceParagraph(d) {
|
|
83019
|
+
if (offers(d, "keystore")) return "";
|
|
83020
|
+
return `
|
|
83021
|
+
**There is no keystore mode on this build.** It is ABSENT, not disabled: the provider
|
|
83022
|
+
is never constructed, so no key material can exist server-side and there is nothing to
|
|
83023
|
+
unlock. "Sign automatically, without popups" is impossible here \u2014 say that true reason
|
|
83024
|
+
instead of describing a keystore, and never ask for a password.
|
|
83025
|
+
`;
|
|
83026
|
+
}
|
|
83027
|
+
function keystoreAbsenceBullet() {
|
|
83028
|
+
return `- **"Sign automatically / no popups" cannot happen here** \u2014 there is no keystore mode
|
|
83029
|
+
on this build. It is ABSENT, not disabled: the provider is never constructed, so no key
|
|
83030
|
+
material can exist server-side and nothing can be unlocked. Give that true reason, and
|
|
83031
|
+
never ask for a password.`;
|
|
82609
83032
|
}
|
|
83033
|
+
var GUIDE_TOPIC_SOURCES = {
|
|
83034
|
+
"getting-started": `# Diamond Hands \u2014 what this is
|
|
82610
83035
|
|
|
82611
|
-
|
|
82612
|
-
|
|
82613
|
-
|
|
82614
|
-
real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
|
|
82615
|
-
};
|
|
82616
|
-
var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
|
|
82617
|
-
var confirmedSchema = import_zod.z.boolean().optional().describe(
|
|
82618
|
-
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
82619
|
-
);
|
|
82620
|
-
var DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
82621
|
-
readOnlyHint: false,
|
|
82622
|
-
destructiveHint: true,
|
|
82623
|
-
idempotentHint: false,
|
|
82624
|
-
openWorldHint: true
|
|
82625
|
-
};
|
|
82626
|
-
function registerLoanTools(server, getB, adapter2 = "real") {
|
|
82627
|
-
const LATENCY_NOTE = LATENCY_NOTES[adapter2];
|
|
82628
|
-
registerBoundaryTool(
|
|
82629
|
-
server,
|
|
82630
|
-
"loan_create",
|
|
82631
|
-
{
|
|
82632
|
-
title: "Create a new lending position",
|
|
82633
|
-
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).`,
|
|
82634
|
-
inputSchema: {
|
|
82635
|
-
selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
|
|
82636
|
-
confirmed: confirmedSchema
|
|
82637
|
-
},
|
|
82638
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82639
|
-
},
|
|
82640
|
-
async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
82641
|
-
const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
|
|
82642
|
-
if (gate) return gate;
|
|
82643
|
-
const problem = checkSelectedTerm(selectedTerm);
|
|
82644
|
-
if (problem) return validationFailed(problem);
|
|
82645
|
-
const b = getB();
|
|
82646
|
-
if (!b.ok) return renderError(b.error);
|
|
82647
|
-
return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
|
|
82648
|
-
})
|
|
82649
|
-
);
|
|
82650
|
-
registerBoundaryTool(
|
|
82651
|
-
server,
|
|
82652
|
-
"loan_mint",
|
|
82653
|
-
{
|
|
82654
|
-
title: "Mint UCD against a position",
|
|
82655
|
-
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).`,
|
|
82656
|
-
inputSchema: {
|
|
82657
|
-
positionId: positionIdSchema,
|
|
82658
|
-
amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
|
|
82659
|
-
confirmed: confirmedSchema
|
|
82660
|
-
},
|
|
82661
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82662
|
-
},
|
|
82663
|
-
async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
|
|
82664
|
-
const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
|
|
82665
|
-
if (gate) return gate;
|
|
82666
|
-
const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
|
|
82667
|
-
if (problem) return validationFailed(problem);
|
|
82668
|
-
const b = getB();
|
|
82669
|
-
if (!b.ok) return renderError(b.error);
|
|
82670
|
-
return renderEnvelope(
|
|
82671
|
-
await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
|
|
82672
|
-
);
|
|
82673
|
-
})
|
|
82674
|
-
);
|
|
82675
|
-
registerBoundaryTool(
|
|
82676
|
-
server,
|
|
82677
|
-
"loan_pay",
|
|
82678
|
-
{
|
|
82679
|
-
title: "Make a UCD payment toward a position's debt",
|
|
82680
|
-
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).`,
|
|
82681
|
-
inputSchema: {
|
|
82682
|
-
positionId: positionIdSchema,
|
|
82683
|
-
amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
|
|
82684
|
-
repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
|
|
82685
|
-
confirmed: confirmedSchema
|
|
82686
|
-
},
|
|
82687
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82688
|
-
},
|
|
82689
|
-
async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
|
|
82690
|
-
if (repayAll === true === (amountUcd !== void 0)) {
|
|
82691
|
-
return validationFailed("provide exactly one of amountUcd or repayAll: true");
|
|
82692
|
-
}
|
|
82693
|
-
const gate = requireConfirmation(
|
|
82694
|
-
confirmed,
|
|
82695
|
-
repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
|
|
82696
|
-
);
|
|
82697
|
-
if (gate) return gate;
|
|
82698
|
-
const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
|
|
82699
|
-
if (problem) return validationFailed(problem);
|
|
82700
|
-
const b = getB();
|
|
82701
|
-
if (!b.ok) return renderError(b.error);
|
|
82702
|
-
let amountUcdWei;
|
|
82703
|
-
if (repayAll) {
|
|
82704
|
-
const detail = await b.boundary.getPosition(positionId);
|
|
82705
|
-
if (!detail.ok) return renderError(detail.error);
|
|
82706
|
-
if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
|
|
82707
|
-
amountUcdWei = detail.data.debtUcdWei;
|
|
82708
|
-
} else {
|
|
82709
|
-
amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
|
|
82710
|
-
}
|
|
82711
|
-
return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
|
|
82712
|
-
})
|
|
82713
|
-
);
|
|
82714
|
-
registerBoundaryTool(
|
|
82715
|
-
server,
|
|
82716
|
-
"loan_extend",
|
|
82717
|
-
{
|
|
82718
|
-
title: "Extend / renew a position's term",
|
|
82719
|
-
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).`,
|
|
82720
|
-
inputSchema: {
|
|
82721
|
-
positionId: positionIdSchema,
|
|
82722
|
-
selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
|
|
82723
|
-
confirmed: confirmedSchema
|
|
82724
|
-
},
|
|
82725
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82726
|
-
},
|
|
82727
|
-
async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
82728
|
-
const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
|
|
82729
|
-
if (gate) return gate;
|
|
82730
|
-
const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
|
|
82731
|
-
if (problem) return validationFailed(problem);
|
|
82732
|
-
const b = getB();
|
|
82733
|
-
if (!b.ok) return renderError(b.error);
|
|
82734
|
-
return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
|
|
82735
|
-
})
|
|
82736
|
-
);
|
|
82737
|
-
registerBoundaryTool(
|
|
82738
|
-
server,
|
|
82739
|
-
"loan_withdraw",
|
|
82740
|
-
{
|
|
82741
|
-
title: "Withdraw BTC from a position vault",
|
|
82742
|
-
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).`,
|
|
82743
|
-
inputSchema: {
|
|
82744
|
-
positionId: positionIdSchema,
|
|
82745
|
-
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
|
|
82746
|
-
amountSats: import_zod.z.number().int().positive().describe(
|
|
82747
|
-
"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."
|
|
82748
|
-
),
|
|
82749
|
-
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"),
|
|
82750
|
-
confirmed: confirmedSchema
|
|
82751
|
-
},
|
|
82752
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82753
|
-
},
|
|
82754
|
-
async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
|
|
82755
|
-
const gate = requireConfirmation(
|
|
82756
|
-
confirmed,
|
|
82757
|
-
`withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
|
|
82758
|
-
);
|
|
82759
|
-
if (gate) return gate;
|
|
82760
|
-
const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
|
|
82761
|
-
if (problem) return validationFailed(problem);
|
|
82762
|
-
const b = getB();
|
|
82763
|
-
if (!b.ok) return renderError(b.error);
|
|
82764
|
-
return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
|
|
82765
|
-
})
|
|
82766
|
-
);
|
|
82767
|
-
registerBoundaryTool(
|
|
82768
|
-
server,
|
|
82769
|
-
"loan_allowlist_destination",
|
|
82770
|
-
{
|
|
82771
|
-
title: "Allowlist a BTC withdrawal destination",
|
|
82772
|
-
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).`,
|
|
82773
|
-
inputSchema: {
|
|
82774
|
-
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
|
|
82775
|
-
confirmed: confirmedSchema
|
|
82776
|
-
},
|
|
82777
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82778
|
-
},
|
|
82779
|
-
async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
|
|
82780
|
-
const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
|
|
82781
|
-
if (gate) return gate;
|
|
82782
|
-
const b = getB();
|
|
82783
|
-
if (!b.ok) return renderError(b.error);
|
|
82784
|
-
return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
|
|
82785
|
-
})
|
|
82786
|
-
);
|
|
82787
|
-
registerBoundaryTool(
|
|
82788
|
-
server,
|
|
82789
|
-
"loan_delegation_setup",
|
|
82790
|
-
{
|
|
82791
|
-
title: "Install delegation on the Safe (one owner ceremony)",
|
|
82792
|
-
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).`,
|
|
82793
|
-
inputSchema: {
|
|
82794
|
-
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)"),
|
|
82795
|
-
confirmed: confirmedSchema
|
|
82796
|
-
},
|
|
82797
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82798
|
-
},
|
|
82799
|
-
async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
|
|
82800
|
-
const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
|
|
82801
|
-
if (gate) return gate;
|
|
82802
|
-
const b = getB();
|
|
82803
|
-
if (!b.ok) return renderError(b.error);
|
|
82804
|
-
return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
|
|
82805
|
-
})
|
|
82806
|
-
);
|
|
82807
|
-
registerBoundaryTool(
|
|
82808
|
-
server,
|
|
82809
|
-
"loan_delegation_grant",
|
|
82810
|
-
{
|
|
82811
|
-
title: "Grant the agent per-position scopes (owners sign)",
|
|
82812
|
-
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).`,
|
|
82813
|
-
inputSchema: {
|
|
82814
|
-
positionId: positionIdSchema,
|
|
82815
|
-
renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
|
|
82816
|
-
repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
|
|
82817
|
-
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"),
|
|
82818
|
-
confirmed: confirmedSchema
|
|
82819
|
-
},
|
|
82820
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
82821
|
-
},
|
|
82822
|
-
async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
|
|
82823
|
-
const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
|
|
82824
|
-
if (gate) return gate;
|
|
82825
|
-
const b = getB();
|
|
82826
|
-
if (!b.ok) return renderError(b.error);
|
|
82827
|
-
return renderEnvelope(
|
|
82828
|
-
await b.boundary.delegationGrant({
|
|
82829
|
-
positionId,
|
|
82830
|
-
renew: renew ?? false,
|
|
82831
|
-
repay: repay ?? false,
|
|
82832
|
-
mintFloorBps: mintFloorBps ?? null
|
|
82833
|
-
})
|
|
82834
|
-
);
|
|
82835
|
-
})
|
|
82836
|
-
);
|
|
82837
|
-
registerBoundaryTool(
|
|
82838
|
-
server,
|
|
82839
|
-
"loan_recover_stale_spend",
|
|
82840
|
-
{
|
|
82841
|
-
title: "Recover a stale BTC reservation via LIT-attested proof",
|
|
82842
|
-
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.",
|
|
82843
|
-
inputSchema: {
|
|
82844
|
-
positionId: positionIdSchema,
|
|
82845
|
-
utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
|
|
82846
|
-
utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
|
|
82847
|
-
invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
|
|
82848
|
-
minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
|
|
82849
|
-
},
|
|
82850
|
-
annotations: {
|
|
82851
|
-
readOnlyHint: false,
|
|
82852
|
-
destructiveHint: false,
|
|
82853
|
-
idempotentHint: true,
|
|
82854
|
-
openWorldHint: true
|
|
82855
|
-
}
|
|
82856
|
-
},
|
|
82857
|
-
async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
|
|
82858
|
-
const problem = checkPositionIdHex(positionId);
|
|
82859
|
-
if (problem) return validationFailed(problem);
|
|
82860
|
-
const b = getB();
|
|
82861
|
-
if (!b.ok) return renderError(b.error);
|
|
82862
|
-
return renderEnvelope(
|
|
82863
|
-
await b.boundary.recoverStaleSpend({
|
|
82864
|
-
positionId,
|
|
82865
|
-
utxoTxid,
|
|
82866
|
-
utxoVout,
|
|
82867
|
-
invalidatorTxid,
|
|
82868
|
-
...minConfirmations !== void 0 ? { minConfirmations } : {}
|
|
82869
|
-
})
|
|
82870
|
-
);
|
|
82871
|
-
})
|
|
82872
|
-
);
|
|
82873
|
-
}
|
|
83036
|
+
Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
|
|
83037
|
+
without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
|
|
83038
|
+
against it, pay it back whenever you like, and take your BTC out again.
|
|
82874
83039
|
|
|
82875
|
-
|
|
82876
|
-
|
|
83040
|
+
**Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
|
|
83041
|
+
topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
|
|
83042
|
+
\`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
|
|
83043
|
+
are enabled (and the true reason when not), and which signer modes this build offers;
|
|
83044
|
+
never promise a capability it does not list. The money truth has THREE cases:
|
|
83045
|
+
- Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
|
|
83046
|
+
- Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
|
|
83047
|
+
the test network: real ceremonies and signatures, PRACTICE money (test funds).
|
|
83048
|
+
- Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
|
|
83049
|
+
explicitly arms them; the capabilities block states which applies.
|
|
83050
|
+
SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
|
|
82877
83051
|
|
|
82878
|
-
|
|
82879
|
-
|
|
82880
|
-
|
|
82881
|
-
|
|
82882
|
-
|
|
82883
|
-
vaultAddress: "the position's Bitcoin custody address; its BTC balance is the COLLATERAL, not the loan",
|
|
82884
|
-
pkpId: "internal id of the programmable key pair holding BTC custody for this position",
|
|
82885
|
-
id: "identifier of the item it sits on (e.g. a source id like 'chain-rpc')",
|
|
82886
|
-
kind: "category label of the item it sits on (e.g. a source kind like 'chain' or an event kind)",
|
|
82887
|
-
fetchedAt: "ISO timestamp when this source was read \u2014 freshness, not a business date",
|
|
82888
|
-
// ---- position facts (chain) ----
|
|
82889
|
-
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",
|
|
82890
|
-
termMonths: "the current term length in months",
|
|
82891
|
-
totalTermMonths: "cumulative months across the original term plus every extension",
|
|
82892
|
-
createdAt: "ISO timestamp the position was created",
|
|
82893
|
-
expiryAt: "ISO timestamp the current term ends \u2014 extensions move it",
|
|
82894
|
-
previousExpiryAt: "the expiry before the latest extension (null when never extended)",
|
|
82895
|
-
lastUpdatedAt: "ISO timestamp of the last state change",
|
|
82896
|
-
debtUcdWei: "current UCD debt in wei (18 decimals); 0 means debt-free, NOT closed",
|
|
82897
|
-
// ---- indexed health (indexer snapshot) ----
|
|
82898
|
-
indexedHealth: "indexer-computed health snapshot; null when the indexer lags \u2014 the chain facts still stand",
|
|
82899
|
-
collateralRatioBps: "collateralValue/debt in basis points (indexer convention) \u2014 the INVERSE of currentLtvBps",
|
|
82900
|
-
healthFactor: "indexer health metric; higher = safer (a display aid, not a chain gate)",
|
|
82901
|
-
asOf: "ISO timestamp the indexer snapshot was computed",
|
|
82902
|
-
basis: "what this value is computed from \u2014 e.g. 'indexer-snapshot' provenance, or the amount a fee applies to",
|
|
82903
|
-
// ---- collateral (live BTC view) ----
|
|
82904
|
-
collateral: "the live Bitcoin-side view of the position's vault",
|
|
82905
|
-
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",
|
|
82906
|
-
availableSource: "which source served availableSats (null when degraded)",
|
|
82907
|
-
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",
|
|
82908
|
-
txid: "Bitcoin transaction id",
|
|
82909
|
-
sats: "amount in satoshis (1 BTC = 100,000,000 sats)",
|
|
82910
|
-
confirmations: "this transaction's CURRENT confirmation count (live, per transaction)",
|
|
82911
|
-
minConfirmations: "the protocol's REQUIRED confirmation threshold \u2014 a PARAMETER, never a live count; compare each pendingDeposits[].confirmations against it",
|
|
82912
|
-
pendingWithdrawalsCount: "how many BTC withdrawal reservations are outstanding (null only when degraded)",
|
|
82913
|
-
maxWithdrawableSats: "directly usable as loan_withdraw amountSats: availableSats minus the default network fee, tightened by the liquidation floor while debt is outstanding",
|
|
82914
|
-
// ---- valuation ----
|
|
82915
|
-
valuation: "price-based derived values; null when availableSats is unknown or the price source is degraded",
|
|
82916
|
-
btcPriceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82917
|
-
priceUsd8: "BTC price in USD with 8 implied decimals (e.g. 6500000000000 = $65,000)",
|
|
82918
|
-
priceSource: "which oracle served the price",
|
|
82919
|
-
collateralValueUcdWei: "availableSats valued at the price, in UCD wei",
|
|
82920
|
-
currentLtvBps: "debt/collateralValue in basis points; null when collateral value is 0. INVERSE of collateralRatioBps",
|
|
82921
|
-
maxLtvBps: "the protocol's published mint ceiling in bps; null when the surface publishes none (real mainnet)",
|
|
82922
|
-
liquidationThresholdBps: "the contracts' liquidation gate (collateral-ratio bps) \u2014 liquidatable is judged against THIS",
|
|
82923
|
-
maxMintableUcdWei: "the mint ceiling in UCD wei; null (never invented) when maxLtvBps is unknown",
|
|
82924
|
-
maxMintableUcd: "the SAME ceiling as a directly-usable loan_mint amountUcd value",
|
|
82925
|
-
liquidatable: "true when the position can be liquidated RIGHT NOW per the chain's own rules",
|
|
82926
|
-
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",
|
|
82927
|
-
// ---- list envelope ----
|
|
82928
|
-
items: "the rows of this page",
|
|
82929
|
-
page: "1-based page number of this response",
|
|
82930
|
-
pageSize: "requested rows per page",
|
|
82931
|
-
total: "total rows matching the filter across all pages",
|
|
82932
|
-
// ---- events ----
|
|
82933
|
-
positionCreated: "creation events (seq, time, selected term)",
|
|
82934
|
-
seq: "the event's sequence number within the position's history (ordering key)",
|
|
82935
|
-
at: "ISO timestamp of the event",
|
|
82936
|
-
selectedTerm: "term length chosen, in months",
|
|
82937
|
-
mints: "borrow events: amount minted and the origination fee ADDED TO DEBT",
|
|
82938
|
-
amountUcdWei: "the event's UCD amount in wei",
|
|
82939
|
-
feeUcdWei: "the origination fee in UCD wei \u2014 added to debt, never deducted from what you receive",
|
|
82940
|
-
payments: "repayment events: when and how much UCD was paid back",
|
|
82941
|
-
type: "the payment's kind label as indexed (e.g. partial/full)",
|
|
82942
|
-
renewals: "extension events: added term, extension fee, and the new expiry",
|
|
82943
|
-
extensionTerm: "months added by this extension",
|
|
82944
|
-
extensionFeeUcdWei: "extension fee in UCD wei \u2014 added to debt",
|
|
82945
|
-
newExpiryAt: "the expiry after this extension (ISO)",
|
|
82946
|
-
withdrawals: "BTC withdrawal events (sats, network fee, target address, txid)",
|
|
82947
|
-
amountSats: "the withdrawal amount in satoshis",
|
|
82948
|
-
networkFeeSats: "the Bitcoin network fee in satoshis, paid from the vault",
|
|
82949
|
-
targetAddress: "the Bitcoin address that received (or will receive) the withdrawal",
|
|
82950
|
-
liquidations: "liquidation events: when the position was liquidated (empty for healthy positions)",
|
|
82951
|
-
other: "event kinds this build does not group \u2014 listed so nothing is silently dropped",
|
|
82952
|
-
totalEvents: "total events across all groups",
|
|
82953
|
-
// ---- pending withdrawals ----
|
|
82954
|
-
vout: "the output index of the reserved UTXO (with txid, feeds loan_recover_stale_spend)",
|
|
82955
|
-
satoshis: "the reserved amount in satoshis",
|
|
82956
|
-
// ---- protocol status / terms ----
|
|
82957
|
-
paused: "the lending protocol's pause switch \u2014 true means fund-moving operations refuse",
|
|
82958
|
-
ltvBps: "published max mint LTV in bps; null when the surface publishes none (real mainnet)",
|
|
82959
|
-
btcNetwork: "which Bitcoin network custody runs on (mainnet | testnet | regtest)",
|
|
82960
|
-
terms: "the offered term tiers with their fee rates",
|
|
82961
|
-
months: "the tier's term length in months",
|
|
82962
|
-
originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
|
|
82963
|
-
extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
|
|
82964
|
-
// ---- psm quote ----
|
|
82965
|
-
direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
|
|
82966
|
-
contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
|
|
82967
|
-
amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
|
|
82968
|
-
amountInToken: "the token you pay with",
|
|
82969
|
-
amountInUnit: "the smallest-unit name of amountIn (unit trap: USDC has 6 decimals, UCD 18)",
|
|
82970
|
-
amountOut: "what you receive AFTER fees, in amountOutUnit of amountOutToken",
|
|
82971
|
-
amountOutToken: "the token you receive",
|
|
82972
|
-
amountOutUnit: "the smallest-unit name of amountOut",
|
|
82973
|
-
fee: "the fee charged on this exchange \u2014 note its token: entry fee in UCD, exit fee in the stablecoin",
|
|
82974
|
-
amount: "the amount of the item it sits on, in that item's stated unit/token",
|
|
82975
|
-
token: "the token the amount is denominated in",
|
|
82976
|
-
bps: "the rate in basis points (100 bps = 1%)",
|
|
82977
|
-
reserves: "live reserves backing this direction right now \u2014 read fresh, never cached",
|
|
82978
|
-
available: "how much of the reserve is available, in its stated unit",
|
|
82979
|
-
unit: "the smallest-unit name for the amount it sits on",
|
|
82980
|
-
human: "a pre-written plain-language summary of this quote \u2014 safe to read to the user as-is",
|
|
82981
|
-
executionFloorNote: "the mandatory slippage floor, stated: execution requires a minimum-out; drift past it refuses rather than delivering less"
|
|
82982
|
-
};
|
|
82983
|
-
function fieldGuide(...fields) {
|
|
82984
|
-
const lines = fields.map((f) => {
|
|
82985
|
-
const meaning = FIELD_GLOSSARY[f];
|
|
82986
|
-
if (!meaning) throw new Error(`fieldGuide: '${f}' has no FIELD_GLOSSARY entry`);
|
|
82987
|
-
return `${f} = ${meaning}`;
|
|
82988
|
-
});
|
|
82989
|
-
return ` Field guide: ${lines.join("; ")}.`;
|
|
82990
|
-
}
|
|
82991
|
-
function renderFieldGlossaryTopic() {
|
|
82992
|
-
const lines = Object.entries(FIELD_GLOSSARY).map(([f, m]) => `- \`${f}\` \u2014 ${m}`);
|
|
82993
|
-
return `# Reading the data \u2014 every field, its exact meaning
|
|
83052
|
+
A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
|
|
83053
|
+
authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
|
|
83054
|
+
calls. Every operation that moves funds requires the user's explicit confirmation
|
|
83055
|
+
(\`confirmed: true\`) \u2014 nothing is ever silent.`,
|
|
83056
|
+
"first-setup": (d) => `# First setup \u2014 from zero to ready, by conversation only
|
|
82994
83057
|
|
|
82995
|
-
|
|
82996
|
-
|
|
82997
|
-
|
|
82998
|
-
|
|
83058
|
+
Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
|
|
83059
|
+
\u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
|
|
83060
|
+
host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
|
|
83061
|
+
developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
|
|
83062
|
+
install matrix. ${connectorInstallNote(d)}
|
|
82999
83063
|
|
|
83000
|
-
|
|
83001
|
-
}
|
|
83064
|
+
Nothing needs a config file. Three steps:
|
|
83002
83065
|
|
|
83003
|
-
|
|
83004
|
-
|
|
83005
|
-
|
|
83006
|
-
|
|
83007
|
-
"PENDING_MINT",
|
|
83008
|
-
"ACTIVE",
|
|
83009
|
-
"EXPIRED",
|
|
83010
|
-
"LIQUIDATABLE",
|
|
83011
|
-
"LIQUIDATED",
|
|
83012
|
-
"REPAID",
|
|
83013
|
-
"CLOSED"
|
|
83014
|
-
];
|
|
83015
|
-
function registerPositionTools(server, getB) {
|
|
83016
|
-
registerBoundaryTool(
|
|
83017
|
-
server,
|
|
83018
|
-
"position_status",
|
|
83019
|
-
{
|
|
83020
|
-
title: "Get a position's full status",
|
|
83021
|
-
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"),
|
|
83022
|
-
inputSchema: {
|
|
83023
|
-
id: positionIdSchema2
|
|
83024
|
-
}
|
|
83025
|
-
},
|
|
83026
|
-
async ({ id }) => guarded(async () => {
|
|
83027
|
-
const problem = checkPositionIdHex(id);
|
|
83028
|
-
if (problem) return validationFailed(problem);
|
|
83029
|
-
const b = getB();
|
|
83030
|
-
if (!b.ok) return renderError(b.error);
|
|
83031
|
-
return renderEnvelope(await b.boundary.getPosition(id));
|
|
83032
|
-
})
|
|
83033
|
-
);
|
|
83034
|
-
registerBoundaryTool(
|
|
83035
|
-
server,
|
|
83036
|
-
"position_list",
|
|
83037
|
-
{
|
|
83038
|
-
title: "List lending positions",
|
|
83039
|
-
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"),
|
|
83040
|
-
inputSchema: {
|
|
83041
|
-
borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
|
|
83042
|
-
state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
|
|
83043
|
-
page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
|
|
83044
|
-
pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
|
|
83045
|
-
}
|
|
83046
|
-
},
|
|
83047
|
-
async ({ borrower, state, page, pageSize }) => guarded(async () => {
|
|
83048
|
-
if (state !== void 0 && !POSITION_STATES.includes(state)) {
|
|
83049
|
-
return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
|
|
83050
|
-
}
|
|
83051
|
-
const b = getB();
|
|
83052
|
-
if (!b.ok) return renderError(b.error);
|
|
83053
|
-
const filter2 = {
|
|
83054
|
-
page,
|
|
83055
|
-
pageSize,
|
|
83056
|
-
...borrower !== void 0 ? { borrower } : {},
|
|
83057
|
-
...state !== void 0 ? { state } : {}
|
|
83058
|
-
};
|
|
83059
|
-
if (filter2.borrower === void 0 && filter2.state === void 0) {
|
|
83060
|
-
return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
|
|
83061
|
-
}
|
|
83062
|
-
return renderEnvelope(await b.boundary.listPositions(filter2));
|
|
83063
|
-
})
|
|
83064
|
-
);
|
|
83065
|
-
registerBoundaryTool(
|
|
83066
|
-
server,
|
|
83067
|
-
"position_events",
|
|
83068
|
-
{
|
|
83069
|
-
title: "Get a position's event history",
|
|
83070
|
-
description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
|
|
83071
|
-
inputSchema: {
|
|
83072
|
-
id: positionIdSchema2
|
|
83073
|
-
}
|
|
83074
|
-
},
|
|
83075
|
-
async ({ id }) => guarded(async () => {
|
|
83076
|
-
const problem = checkPositionIdHex(id);
|
|
83077
|
-
if (problem) return validationFailed(problem);
|
|
83078
|
-
const b = getB();
|
|
83079
|
-
if (!b.ok) return renderError(b.error);
|
|
83080
|
-
return renderEnvelope(await b.boundary.getPositionEvents(id));
|
|
83081
|
-
})
|
|
83082
|
-
);
|
|
83083
|
-
registerBoundaryTool(
|
|
83084
|
-
server,
|
|
83085
|
-
"position_pending_withdrawals",
|
|
83086
|
-
{
|
|
83087
|
-
title: "List a position's pending BTC withdrawal reservations",
|
|
83088
|
-
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).",
|
|
83089
|
-
inputSchema: {
|
|
83090
|
-
id: positionIdSchema2
|
|
83091
|
-
}
|
|
83092
|
-
},
|
|
83093
|
-
async ({ id }) => guarded(async () => {
|
|
83094
|
-
const problem = checkPositionIdHex(id);
|
|
83095
|
-
if (problem) return validationFailed(problem);
|
|
83096
|
-
const b = getB();
|
|
83097
|
-
if (!b.ok) return renderError(b.error);
|
|
83098
|
-
return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
|
|
83099
|
-
})
|
|
83100
|
-
);
|
|
83101
|
-
}
|
|
83066
|
+
**1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
|
|
83067
|
+
\`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
|
|
83068
|
+
(practice money) or mainnet (real money); whether writes are enabled here and which
|
|
83069
|
+
signer modes exist; current terms (\`protocol_terms\`).
|
|
83102
83070
|
|
|
83103
|
-
|
|
83104
|
-
|
|
83105
|
-
|
|
83106
|
-
|
|
83107
|
-
|
|
83108
|
-
|
|
83109
|
-
|
|
83110
|
-
|
|
83111
|
-
|
|
83112
|
-
|
|
83113
|
-
|
|
83114
|
-
|
|
83115
|
-
|
|
83116
|
-
|
|
83117
|
-
|
|
83118
|
-
|
|
83119
|
-
|
|
83120
|
-
|
|
83121
|
-
|
|
83122
|
-
|
|
83123
|
-
|
|
83124
|
-
|
|
83125
|
-
|
|
83126
|
-
|
|
83127
|
-
|
|
83128
|
-
inputSchema: {}
|
|
83129
|
-
},
|
|
83130
|
-
async () => guarded(async () => {
|
|
83131
|
-
const b = getB();
|
|
83132
|
-
if (!b.ok) return renderError(b.error);
|
|
83133
|
-
return renderEnvelope(await b.boundary.getBitcoinPrice());
|
|
83134
|
-
})
|
|
83135
|
-
);
|
|
83136
|
-
}
|
|
83071
|
+
**2. Choose HOW to authorize operations** (the user's choice, made by talking):
|
|
83072
|
+
- **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
|
|
83073
|
+
on the real adapter and the mock. The approval page auto-opens in the browser (its URL
|
|
83074
|
+
is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
|
|
83075
|
+
/ pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
|
|
83076
|
+
their own wallet. The first verified signature binds their wallet address as the
|
|
83077
|
+
borrower. Full walkthrough: \`guide connect-wallet\`.
|
|
83078
|
+
${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
|
|
83079
|
+
signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
|
|
83080
|
+
\`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
|
|
83081
|
+
LOCAL PAGE opens where the user types the password or generates a fresh keystore.
|
|
83082
|
+
NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
|
|
83083
|
+
them to use the unlock page instead.` : keystoreAbsenceBullet()}
|
|
83084
|
+
${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
|
|
83085
|
+
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
|
|
83086
|
+
surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
|
|
83087
|
+
\`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
|
|
83088
|
+
- Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
|
|
83089
|
+
- **No signer is also a valid start:** every public read works without one \u2014
|
|
83090
|
+
\`position_list {borrower}\` with the user's address needs no signer and no login.
|
|
83091
|
+
${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
|
|
83092
|
+
talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
|
|
83093
|
+
the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
|
|
83094
|
+
\`network_switch\` refuses every other target with that rollout truth. See
|
|
83095
|
+
\`guide switch-network\`; never offer a world this service does not serve.`}
|
|
83137
83096
|
|
|
83138
|
-
|
|
83139
|
-
|
|
83140
|
-
|
|
83141
|
-
|
|
83142
|
-
"protocol_status",
|
|
83143
|
-
{
|
|
83144
|
-
title: "Get protocol configuration and status",
|
|
83145
|
-
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.",
|
|
83146
|
-
inputSchema: {}
|
|
83147
|
-
},
|
|
83148
|
-
async () => guarded(async () => {
|
|
83149
|
-
const b = getB();
|
|
83150
|
-
if (!b.ok) return renderError(b.error);
|
|
83151
|
-
return renderEnvelope(await b.boundary.getProtocolStatus());
|
|
83152
|
-
})
|
|
83153
|
-
);
|
|
83154
|
-
registerBoundaryTool(
|
|
83155
|
-
server,
|
|
83156
|
-
"protocol_terms",
|
|
83157
|
-
{
|
|
83158
|
-
title: "List available loan terms with fees",
|
|
83159
|
-
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.",
|
|
83160
|
-
inputSchema: {}
|
|
83161
|
-
},
|
|
83162
|
-
async () => guarded(async () => {
|
|
83163
|
-
const b = getB();
|
|
83164
|
-
if (!b.ok) return renderError(b.error);
|
|
83165
|
-
return renderEnvelope(await b.boundary.getTerms());
|
|
83166
|
-
})
|
|
83167
|
-
);
|
|
83168
|
-
}
|
|
83169
|
-
|
|
83170
|
-
// src/tools/psm.ts
|
|
83171
|
-
var import_zod4 = require("zod");
|
|
83172
|
-
var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
|
|
83173
|
-
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
83174
|
-
);
|
|
83175
|
-
var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
|
|
83176
|
-
readOnlyHint: false,
|
|
83177
|
-
destructiveHint: true,
|
|
83178
|
-
idempotentHint: false,
|
|
83179
|
-
openWorldHint: true
|
|
83180
|
-
};
|
|
83181
|
-
function registerPsmTools(server, getB) {
|
|
83182
|
-
registerBoundaryTool(
|
|
83183
|
-
server,
|
|
83184
|
-
"psm_quote",
|
|
83185
|
-
{
|
|
83186
|
-
title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
|
|
83187
|
-
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.",
|
|
83188
|
-
inputSchema: {
|
|
83189
|
-
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)"),
|
|
83190
|
-
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
|
|
83191
|
-
},
|
|
83192
|
-
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
|
|
83193
|
-
},
|
|
83194
|
-
async ({ direction, amount }) => guarded(async () => {
|
|
83195
|
-
const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
|
|
83196
|
-
const problem = checkUcdAmount(amount, label);
|
|
83197
|
-
if (problem) return validationFailed(problem);
|
|
83198
|
-
const b = getB();
|
|
83199
|
-
if (!b.ok) return renderError(b.error);
|
|
83200
|
-
return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
|
|
83201
|
-
})
|
|
83202
|
-
);
|
|
83203
|
-
registerBoundaryTool(
|
|
83204
|
-
server,
|
|
83205
|
-
"psm_swap",
|
|
83206
|
-
{
|
|
83207
|
-
title: "Exchange UCD \u2194 USDC through the PSM",
|
|
83208
|
-
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).",
|
|
83209
|
-
inputSchema: {
|
|
83210
|
-
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)"),
|
|
83211
|
-
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
|
|
83212
|
-
confirmed: confirmedSchema2
|
|
83213
|
-
},
|
|
83214
|
-
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
|
|
83215
|
-
},
|
|
83216
|
-
async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
|
|
83217
|
-
const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
|
|
83218
|
-
const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
|
|
83219
|
-
const gate = requireConfirmation(
|
|
83220
|
-
confirmed,
|
|
83221
|
-
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
|
|
83222
|
-
);
|
|
83223
|
-
if (gate) return gate;
|
|
83224
|
-
const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
|
|
83225
|
-
if (problem) return validationFailed(problem);
|
|
83226
|
-
const b = getB();
|
|
83227
|
-
if (!b.ok) return renderError(b.error);
|
|
83228
|
-
return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
|
|
83229
|
-
})
|
|
83230
|
-
);
|
|
83231
|
-
}
|
|
83232
|
-
|
|
83233
|
-
// src/tools/mock-control.ts
|
|
83234
|
-
var import_zod5 = require("zod");
|
|
83235
|
-
var ACTIONS = [
|
|
83236
|
-
"submit-deposit",
|
|
83237
|
-
"confirm-deposit",
|
|
83238
|
-
"confirm-spend-consumed",
|
|
83239
|
-
"advance-time",
|
|
83240
|
-
"set-btc-price",
|
|
83241
|
-
"set-paused",
|
|
83242
|
-
"set-wallet",
|
|
83243
|
-
"liquidate",
|
|
83244
|
-
"deploy-safe",
|
|
83245
|
-
"revoke-agent",
|
|
83246
|
-
"inject-fault",
|
|
83247
|
-
"clear-fault",
|
|
83248
|
-
"psm-set-paused",
|
|
83249
|
-
"psm-set-redeem-enabled",
|
|
83250
|
-
"psm-set-reserves",
|
|
83251
|
-
"psm-set-fees",
|
|
83252
|
-
"psm-mint-usdc"
|
|
83253
|
-
];
|
|
83254
|
-
function requireField(value, name, action) {
|
|
83255
|
-
if (value === void 0) {
|
|
83256
|
-
throw new Error(`action '${action}' requires '${name}'`);
|
|
83257
|
-
}
|
|
83258
|
-
return value;
|
|
83259
|
-
}
|
|
83260
|
-
function run(control, a, chainId) {
|
|
83261
|
-
switch (a.action) {
|
|
83262
|
-
case "submit-deposit": {
|
|
83263
|
-
const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
|
|
83264
|
-
return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
|
|
83265
|
-
}
|
|
83266
|
-
case "confirm-deposit": {
|
|
83267
|
-
const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
|
|
83268
|
-
return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
|
|
83269
|
-
}
|
|
83270
|
-
case "confirm-spend-consumed": {
|
|
83271
|
-
control.confirmSpendConsumed(
|
|
83272
|
-
requireField(a.txid, "txid", a.action),
|
|
83273
|
-
requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
|
|
83274
|
-
requireField(a.confirmations, "confirmations", a.action)
|
|
83275
|
-
);
|
|
83276
|
-
return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
|
|
83277
|
-
}
|
|
83278
|
-
case "advance-time": {
|
|
83279
|
-
control.advanceTime(requireField(a.seconds, "seconds", a.action));
|
|
83280
|
-
return { simulated: "virtual clock advanced", seconds: a.seconds };
|
|
83281
|
-
}
|
|
83282
|
-
case "set-btc-price": {
|
|
83283
|
-
control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
|
|
83284
|
-
return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
|
|
83285
|
-
}
|
|
83286
|
-
case "set-paused": {
|
|
83287
|
-
control.setPaused(requireField(a.paused, "paused", a.action));
|
|
83288
|
-
return { simulated: "protocol pause flag set", paused: a.paused };
|
|
83289
|
-
}
|
|
83290
|
-
case "set-wallet": {
|
|
83291
|
-
control.setWalletStance(requireField(a.stance, "stance", a.action));
|
|
83292
|
-
return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
|
|
83293
|
-
}
|
|
83294
|
-
case "liquidate": {
|
|
83295
|
-
control.liquidate(requireField(a.positionId, "positionId", a.action));
|
|
83296
|
-
return { simulated: "liquidation executed", positionId: a.positionId };
|
|
83297
|
-
}
|
|
83298
|
-
case "deploy-safe": {
|
|
83299
|
-
const safe = control.deploySafe({
|
|
83300
|
-
owners: requireField(a.owners, "owners", a.action),
|
|
83301
|
-
threshold: requireField(a.threshold, "threshold", a.action),
|
|
83302
|
-
chainId
|
|
83303
|
-
});
|
|
83304
|
-
return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
|
|
83305
|
-
}
|
|
83306
|
-
case "revoke-agent": {
|
|
83307
|
-
const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
|
|
83308
|
-
return {
|
|
83309
|
-
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)",
|
|
83310
|
-
...r
|
|
83311
|
-
};
|
|
83312
|
-
}
|
|
83313
|
-
case "inject-fault": {
|
|
83314
|
-
control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
|
|
83315
|
-
return { simulated: "fault armed", faultKey: a.faultKey };
|
|
83316
|
-
}
|
|
83317
|
-
case "clear-fault": {
|
|
83318
|
-
control.clearFault(requireField(a.faultKey, "faultKey", a.action));
|
|
83319
|
-
return { simulated: "fault cleared", faultKey: a.faultKey };
|
|
83320
|
-
}
|
|
83321
|
-
case "psm-set-paused": {
|
|
83322
|
-
control.psmSetPaused(requireField(a.paused, "paused", a.action));
|
|
83323
|
-
return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
|
|
83324
|
-
}
|
|
83325
|
-
case "psm-set-redeem-enabled": {
|
|
83326
|
-
control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
|
|
83327
|
-
return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
|
|
83328
|
-
}
|
|
83329
|
-
case "psm-set-reserves": {
|
|
83330
|
-
control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
|
|
83331
|
-
return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
|
|
83332
|
-
}
|
|
83333
|
-
case "psm-mint-usdc": {
|
|
83334
|
-
const r = control.psmMintUsdc(
|
|
83335
|
-
requireField(a.holder, "holder", a.action),
|
|
83336
|
-
requireField(a.usdcUnits, "usdcUnits", a.action)
|
|
83337
|
-
);
|
|
83338
|
-
return {
|
|
83339
|
-
simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
|
|
83340
|
-
holder: a.holder,
|
|
83341
|
-
minted: a.usdcUnits,
|
|
83342
|
-
newBalanceUnits: r.newBalanceUnits
|
|
83343
|
-
};
|
|
83344
|
-
}
|
|
83345
|
-
case "psm-set-fees": {
|
|
83346
|
-
control.psmSetFees({
|
|
83347
|
-
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
83348
|
-
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
83349
|
-
});
|
|
83350
|
-
return {
|
|
83351
|
-
simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
|
|
83352
|
-
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
83353
|
-
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
83354
|
-
};
|
|
83355
|
-
}
|
|
83356
|
-
}
|
|
83357
|
-
}
|
|
83358
|
-
function registerMockControlTool(server, control, chainId = 1337) {
|
|
83359
|
-
registerBoundaryTool(
|
|
83360
|
-
server,
|
|
83361
|
-
"mock_control",
|
|
83362
|
-
{
|
|
83363
|
-
title: "SIMULATOR control (mock world only)",
|
|
83364
|
-
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.",
|
|
83365
|
-
inputSchema: {
|
|
83366
|
-
action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
|
|
83367
|
-
positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
|
|
83368
|
-
txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
83369
|
-
sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
|
|
83370
|
-
confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
83371
|
-
invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
|
|
83372
|
-
seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
|
|
83373
|
-
priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
|
|
83374
|
-
paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
|
|
83375
|
-
stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
|
|
83376
|
-
owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
|
|
83377
|
-
threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
|
|
83378
|
-
safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
|
|
83379
|
-
faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
|
|
83380
|
-
faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
|
|
83381
|
-
enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
|
|
83382
|
-
reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
|
|
83383
|
-
entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
|
|
83384
|
-
exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
|
|
83385
|
-
holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
|
|
83386
|
-
usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
|
|
83387
|
-
},
|
|
83388
|
-
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
|
|
83389
|
-
},
|
|
83390
|
-
async (args) => guarded(async () => {
|
|
83391
|
-
let result;
|
|
83392
|
-
try {
|
|
83393
|
-
result = run(control, args, chainId);
|
|
83394
|
-
} catch (e) {
|
|
83395
|
-
return validationFailed(e.message);
|
|
83396
|
-
}
|
|
83397
|
-
if (result === void 0) {
|
|
83398
|
-
return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
|
|
83399
|
-
}
|
|
83400
|
-
return { content: [{ type: "text", text: serialize(result) }] };
|
|
83401
|
-
})
|
|
83402
|
-
);
|
|
83403
|
-
}
|
|
83404
|
-
|
|
83405
|
-
// src/tools/signer.ts
|
|
83406
|
-
var import_zod6 = require("zod");
|
|
83407
|
-
var import_ethers42 = require("ethers");
|
|
83408
|
-
var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
83409
|
-
var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
|
|
83410
|
-
var EXTERNAL_ONLY_MODES = ["external"];
|
|
83411
|
-
var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
|
|
83412
|
-
function looksSecretShaped(value) {
|
|
83413
|
-
return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
|
|
83414
|
-
}
|
|
83415
|
-
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.";
|
|
83416
|
-
function registerSignerTool(server, getRuntime, opts) {
|
|
83417
|
-
const externalOnly = opts?.externalOnly === true;
|
|
83418
|
-
const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
|
|
83419
|
-
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.";
|
|
83420
|
-
registerBoundaryTool(
|
|
83421
|
-
server,
|
|
83422
|
-
"signer_setup",
|
|
83423
|
-
{
|
|
83424
|
-
title: "Choose how operations are authorized",
|
|
83425
|
-
description,
|
|
83426
|
-
inputSchema: {
|
|
83427
|
-
action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
|
|
83428
|
-
mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
|
|
83429
|
-
...externalOnly ? {} : {
|
|
83430
|
-
safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
|
|
83431
|
-
}
|
|
83432
|
-
},
|
|
83433
|
-
annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
|
|
83434
|
-
},
|
|
83435
|
-
async ({ action, mode, safeAddress }) => guarded(async () => {
|
|
83436
|
-
const runtime = getRuntime();
|
|
83437
|
-
if (!runtime) {
|
|
83438
|
-
return renderError(
|
|
83439
|
-
boundaryError(
|
|
83440
|
-
"SIGNER_UNAVAILABLE",
|
|
83441
|
-
"no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
|
|
83442
|
-
)
|
|
83443
|
-
);
|
|
83444
|
-
}
|
|
83445
|
-
const { manager, bridge } = runtime;
|
|
83446
|
-
if (mode !== void 0 && !offeredModes.includes(mode)) {
|
|
83447
|
-
return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
|
|
83448
|
-
}
|
|
83449
|
-
if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
|
|
83450
|
-
return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
|
|
83451
|
-
}
|
|
83452
|
-
if (action === "status") {
|
|
83453
|
-
await bridge.start();
|
|
83454
|
-
const s = manager.status();
|
|
83455
|
-
return ok({
|
|
83456
|
-
...s,
|
|
83457
|
-
// Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
|
|
83458
|
-
// identity is known. borrower = a persisted binding; candidate = a live
|
|
83459
|
-
// wallet connection in THIS process only.
|
|
83460
|
-
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",
|
|
83461
|
-
approvalPageUrl: bridge.url(),
|
|
83462
|
-
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.`
|
|
83463
|
-
});
|
|
83464
|
-
}
|
|
83465
|
-
if (action === "use") {
|
|
83466
|
-
if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
|
|
83467
|
-
const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
|
|
83468
|
-
if (!r.ok) return validationFailed(r.reason);
|
|
83469
|
-
if (mode === "safe-module") {
|
|
83470
|
-
const s = manager.status();
|
|
83471
|
-
return ok({
|
|
83472
|
-
mode,
|
|
83473
|
-
safe: s.safe,
|
|
83474
|
-
agent: s.keystoreAddress,
|
|
83475
|
-
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'."
|
|
83476
|
-
});
|
|
83477
|
-
}
|
|
83478
|
-
if (mode === "safe") {
|
|
83479
|
-
const s = manager.status();
|
|
83480
|
-
return ok({
|
|
83481
|
-
mode,
|
|
83482
|
-
safe: s.safe,
|
|
83483
|
-
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."
|
|
83484
|
-
});
|
|
83485
|
-
}
|
|
83486
|
-
if (mode === "external") {
|
|
83487
|
-
await bridge.start();
|
|
83488
|
-
return ok({
|
|
83489
|
-
mode,
|
|
83490
|
-
approvalPageUrl: bridge.url(),
|
|
83491
|
-
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."
|
|
83492
|
-
});
|
|
83493
|
-
}
|
|
83494
|
-
return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
|
|
83495
|
-
}
|
|
83496
|
-
if (action === "connect") {
|
|
83497
|
-
if (!runtime.connect) {
|
|
83498
|
-
return validationFailed(
|
|
83499
|
-
"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."
|
|
83500
|
-
);
|
|
83501
|
-
}
|
|
83502
|
-
const r = await runtime.connect();
|
|
83503
|
-
if (!r.ok) return validationFailed(r.reason);
|
|
83504
|
-
const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
|
|
83505
|
-
return ok({
|
|
83506
|
-
connected: true,
|
|
83507
|
-
address: r.address,
|
|
83508
|
-
login,
|
|
83509
|
-
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."
|
|
83510
|
-
});
|
|
83511
|
-
}
|
|
83512
|
-
if (action === "disconnect") {
|
|
83513
|
-
if (!runtime.disconnect) {
|
|
83514
|
-
return validationFailed(
|
|
83515
|
-
"this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
|
|
83516
|
-
);
|
|
83517
|
-
}
|
|
83518
|
-
const report = await runtime.disconnect();
|
|
83519
|
-
const f = report.flushed;
|
|
83520
|
-
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)`;
|
|
83521
|
-
return ok({
|
|
83522
|
-
disconnected: true,
|
|
83523
|
-
mode: manager.mode(),
|
|
83524
|
-
flushed: {
|
|
83525
|
-
...f,
|
|
83526
|
-
note: tokenLine
|
|
83527
|
-
},
|
|
83528
|
-
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).",
|
|
83529
|
-
// Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
|
|
83530
|
-
// relationship; the OAuth session is a separate thing with its own revocation.
|
|
83531
|
-
// Neither claims to do the other's job.
|
|
83532
|
-
...bridge.isHosted() ? {
|
|
83533
|
-
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."
|
|
83534
|
-
} : {},
|
|
83535
|
-
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').`
|
|
83536
|
-
});
|
|
83537
|
-
}
|
|
83538
|
-
if (action === "reset-borrower") {
|
|
83539
|
-
manager.resetBorrower();
|
|
83540
|
-
return ok({
|
|
83541
|
-
reset: true,
|
|
83542
|
-
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."
|
|
83543
|
-
});
|
|
83544
|
-
}
|
|
83545
|
-
await bridge.start();
|
|
83546
|
-
const unlockUrl = bridge.unlockUrl();
|
|
83547
|
-
return ok({
|
|
83548
|
-
unlockPageUrl: unlockUrl,
|
|
83549
|
-
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'."
|
|
83550
|
-
});
|
|
83551
|
-
})
|
|
83552
|
-
);
|
|
83553
|
-
}
|
|
83554
|
-
function ok(data) {
|
|
83555
|
-
return { content: [{ type: "text", text: serialize(data) }] };
|
|
83556
|
-
}
|
|
83557
|
-
|
|
83558
|
-
// src/tools/guide.ts
|
|
83559
|
-
var import_zod7 = require("zod");
|
|
83560
|
-
|
|
83561
|
-
// src/guide/content.ts
|
|
83562
|
-
var GUIDE_TOPICS = [
|
|
83563
|
-
"getting-started",
|
|
83564
|
-
"first-setup",
|
|
83565
|
-
"connect-wallet",
|
|
83566
|
-
"lifecycle",
|
|
83567
|
-
"fees",
|
|
83568
|
-
"psm",
|
|
83569
|
-
"authorization",
|
|
83570
|
-
"safe",
|
|
83571
|
-
"delegation",
|
|
83572
|
-
"safety",
|
|
83573
|
-
"switch-network",
|
|
83574
|
-
"connector",
|
|
83575
|
-
"troubleshooting",
|
|
83576
|
-
"glossary",
|
|
83577
|
-
"reading-data"
|
|
83578
|
-
];
|
|
83579
|
-
var GUIDE_CONTENT = {
|
|
83580
|
-
"getting-started": `# Diamond Hands \u2014 what this is
|
|
83581
|
-
|
|
83582
|
-
Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
|
|
83583
|
-
without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
|
|
83584
|
-
against it, pay it back whenever you like, and take your BTC out again.
|
|
83585
|
-
|
|
83586
|
-
**Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
|
|
83587
|
-
topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
|
|
83588
|
-
\`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
|
|
83589
|
-
are enabled (and the true reason when not), and which signer modes this build offers;
|
|
83590
|
-
never promise a capability it does not list. The money truth has THREE cases:
|
|
83591
|
-
- Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
|
|
83592
|
-
- Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
|
|
83593
|
-
the test network: real ceremonies and signatures, PRACTICE money (test funds).
|
|
83594
|
-
- Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
|
|
83595
|
-
explicitly arms them; the capabilities block states which applies.
|
|
83596
|
-
SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
|
|
83597
|
-
|
|
83598
|
-
A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
|
|
83599
|
-
authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
|
|
83600
|
-
calls. Every operation that moves funds requires the user's explicit confirmation
|
|
83601
|
-
(\`confirmed: true\`) \u2014 nothing is ever silent.`,
|
|
83602
|
-
"first-setup": `# First setup \u2014 from zero to ready, by conversation only
|
|
83603
|
-
|
|
83604
|
-
Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
|
|
83605
|
-
\u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
|
|
83606
|
-
host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
|
|
83607
|
-
developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
|
|
83608
|
-
install matrix. (A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented
|
|
83609
|
-
but NOT yet publicly served; its rollout is operator-gated. Truth and trust model:
|
|
83610
|
-
\`guide connector\`.)
|
|
83611
|
-
|
|
83612
|
-
Nothing needs a config file. Three steps:
|
|
83613
|
-
|
|
83614
|
-
**1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
|
|
83615
|
-
\`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
|
|
83616
|
-
(practice money) or mainnet (real money); whether writes are enabled here and which
|
|
83617
|
-
signer modes exist; current terms (\`protocol_terms\`).
|
|
83618
|
-
|
|
83619
|
-
**2. Choose HOW to authorize operations** (the user's choice, made by talking):
|
|
83620
|
-
- **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
|
|
83621
|
-
on the real adapter and the mock. The approval page auto-opens in the browser (its URL
|
|
83622
|
-
is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
|
|
83623
|
-
/ pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
|
|
83624
|
-
their own wallet. The first verified signature binds their wallet address as the
|
|
83625
|
-
borrower. Full walkthrough: \`guide connect-wallet\`.
|
|
83626
|
-
- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
|
|
83627
|
-
signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
|
|
83628
|
-
\`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
|
|
83629
|
-
LOCAL PAGE opens where the user types the password or generates a fresh keystore.
|
|
83630
|
-
NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
|
|
83631
|
-
them to use the unlock page instead.
|
|
83632
|
-
- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
|
|
83633
|
-
real adapter they refuse with that true reason. Try them in a mock world.
|
|
83634
|
-
- Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
|
|
83635
|
-
- **No signer is also a valid start:** every public read works without one \u2014
|
|
83636
|
-
\`position_list {borrower}\` with the user's address needs no signer and no login.
|
|
83637
|
-
- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
|
|
83638
|
-
talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
|
|
83639
|
-
the money reality after any switch.
|
|
83640
|
-
|
|
83641
|
-
**3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
|
|
83642
|
-
\`confirmed: true\` from the user). Then deposit BTC to the vault address
|
|
83643
|
-
(practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
|
|
83644
|
-
and mint with \`loan_mint\`.
|
|
83097
|
+
**3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
|
|
83098
|
+
\`confirmed: true\` from the user). Then deposit BTC to the vault address
|
|
83099
|
+
(practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
|
|
83100
|
+
and mint with \`loan_mint\`.
|
|
83645
83101
|
|
|
83646
83102
|
The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
|
|
83647
|
-
"connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
|
|
83103
|
+
"connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
|
|
83648
83104
|
|
|
83649
83105
|
External mode means the user approves every operation in their OWN wallet \u2014 a browser
|
|
83650
83106
|
extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
|
|
@@ -83652,17 +83108,19 @@ the mock.
|
|
|
83652
83108
|
|
|
83653
83109
|
**The walkthrough:**
|
|
83654
83110
|
1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
|
|
83655
|
-
desktop browser;
|
|
83656
|
-
same machine the server runs on).
|
|
83111
|
+
desktop browser; ${approvalPageLocation(d)}
|
|
83657
83112
|
2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
|
|
83658
83113
|
WalletConnect QR code or paste the pairing code.
|
|
83659
83114
|
3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
|
|
83660
83115
|
login ceremony explicitly (one typed-data signature in the wallet).
|
|
83661
83116
|
4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
|
|
83662
83117
|
across sessions (\`signer_setup reset-borrower\` unbinds it).
|
|
83663
|
-
5. From then on, every fund-moving operation shows an approval card in the wallet
|
|
83664
|
-
decoded from the exact
|
|
83665
|
-
|
|
83118
|
+
5. From then on, every fund-moving operation shows an approval card in the wallet. For
|
|
83119
|
+
TRANSACTIONS that card is decoded from the exact bytes being signed \u2014 what you read
|
|
83120
|
+
IS what executes. The ONE exception is the BTC withdrawal, which signs an opaque
|
|
83121
|
+
32-byte hash the page states plainly it CANNOT decode (honesty note below); say so
|
|
83122
|
+
before those popups, never "what you read is what executes". Declining always safely
|
|
83123
|
+
cancels.
|
|
83666
83124
|
|
|
83667
83125
|
**Popup cadence \u2014 exactly this many wallet interactions per operation:**
|
|
83668
83126
|
|
|
@@ -83674,7 +83132,7 @@ the mock.
|
|
|
83674
83132
|
| repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
|
|
83675
83133
|
| extend | 1 personal-sign + 1 tx |
|
|
83676
83134
|
| allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
|
|
83677
|
-
| withdraw BTC |
|
|
83135
|
+
| withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
|
|
83678
83136
|
| PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
|
|
83679
83137
|
|
|
83680
83138
|
**Honesty notes (say these plainly):**
|
|
@@ -83685,10 +83143,19 @@ the mock.
|
|
|
83685
83143
|
authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
|
|
83686
83144
|
surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
|
|
83687
83145
|
login means "wait and retry", not a wallet failure.
|
|
83688
|
-
- **Withdraw-BTC under external mode
|
|
83689
|
-
|
|
83690
|
-
|
|
83691
|
-
|
|
83146
|
+
- **Withdraw-BTC under external mode has ONE blind signature, not two.** The
|
|
83147
|
+
authorization phase is EIP-712 typed data \u2014 the wallet renders position, amount and
|
|
83148
|
+
destination and the user can read it. Only the EXECUTE phase signs an opaque 32-byte
|
|
83149
|
+
hash the SDK builds internally, which the approval page shows bare and says plainly it
|
|
83150
|
+
cannot decode (the production web app signs the same way). Tell the user before that
|
|
83151
|
+
ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
|
|
83152
|
+
expect an unreadable card and click through the readable one.
|
|
83153
|
+
- **The READABLE phase can be asked for up to THREE times.** Its authorization is only
|
|
83154
|
+
valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
|
|
83155
|
+
attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
|
|
83156
|
+
back. Warn the user: a second or third identical card is the retry, NOT a duplicate
|
|
83157
|
+
charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
|
|
83158
|
+
signature. The blind execute popup happens once.
|
|
83692
83159
|
- **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
|
|
83693
83160
|
(\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
|
|
83694
83161
|
hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
|
|
@@ -83723,7 +83190,7 @@ Connections / Connected sites).`,
|
|
|
83723
83190
|
reduced by unused origination-fee credit from the current term.
|
|
83724
83191
|
6. **Withdraw BTC** \u2014 \`loan_withdraw {positionId, btcAddress, amountSats, confirmed:true}\`.
|
|
83725
83192
|
BTC sends are IRREVERSIBLE \u2014 read the address back to the user before confirming.
|
|
83726
|
-
|
|
83193
|
+
amountSats is gross (fee comes out of it) and may be the whole available balance.
|
|
83727
83194
|
7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
|
|
83728
83195
|
\`position_events\` (history), \`btc_price\`, \`protocol_status\`.
|
|
83729
83196
|
|
|
@@ -83744,9 +83211,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
|
|
|
83744
83211
|
|
|
83745
83212
|
Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
|
|
83746
83213
|
signed, amounts included. Read it back when the user asks what happened.`,
|
|
83747
|
-
psm: `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
|
|
83214
|
+
psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
|
|
83748
83215
|
|
|
83749
|
-
The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
|
|
83216
|
+
${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
|
|
83750
83217
|
directions, in user words:
|
|
83751
83218
|
|
|
83752
83219
|
- **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
|
|
@@ -83793,24 +83260,18 @@ own address. If you approve step 1 but decline step 2, the exact-amount allowanc
|
|
|
83793
83260
|
standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
|
|
83794
83261
|
On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
|
|
83795
83262
|
(the PSM-specific sepolia-only anchor; loan operations are not affected).`,
|
|
83796
|
-
authorization: `# Authorization \u2014 who signs, and what a signature means
|
|
83263
|
+
authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
|
|
83797
83264
|
|
|
83798
83265
|
Every fund-moving operation needs TWO things, always in this order:
|
|
83799
83266
|
1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
|
|
83800
83267
|
must ask, never assume.
|
|
83801
|
-
2. **A cryptographic authorization** by the chosen signer mode
|
|
83802
|
-
|
|
83803
|
-
|
|
83804
|
-
|
|
83805
|
-
|
|
83806
|
-
- \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
|
|
83807
|
-
Real adapter and mock.
|
|
83808
|
-
- \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
|
|
83809
|
-
refuse with that true reason (their planes ship in their own deliveries).
|
|
83810
|
-
- \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
|
|
83811
|
-
|
|
83268
|
+
2. **A cryptographic authorization** by the chosen signer mode. This build offers
|
|
83269
|
+
exactly ${d.signerModes.map((m) => `\`${m}\``).join(", ")} \u2014 ${signerModeSourceClause(d)}. Never
|
|
83270
|
+
describe a mode outside it:
|
|
83271
|
+
${authorizationModeBullets(d)}
|
|
83272
|
+
${keystoreAbsenceParagraph(d)}
|
|
83812
83273
|
**Reads never summon the wallet.** Public reads need no signer at all. Authenticated
|
|
83813
|
-
reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
|
|
83274
|
+
reads need a login \u2014 ${offers(d, "keystore") ? "the keystore env pair, or " : ""}an explicit "connect my wallet"
|
|
83814
83275
|
(\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
|
|
83815
83276
|
only ever caused by a write ceremony or that explicit connect. The login (one typed-data
|
|
83816
83277
|
signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
|
|
@@ -83826,9 +83287,28 @@ BOUND by the first verified signature (it persists across sessions). Connected \
|
|
|
83826
83287
|
picking external mode is a preference \u2014 a wallet still has to connect on the approval
|
|
83827
83288
|
page, and the page link comes from \`signer_setup status\`.
|
|
83828
83289
|
|
|
83829
|
-
Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat
|
|
83830
|
-
|
|
83831
|
-
|
|
83290
|
+
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."}`,
|
|
83291
|
+
// Rendered on the capability axis: a build that constructs no Safe-shaped mode must not
|
|
83292
|
+
// hand a user a setup walkthrough its `signer_setup` cannot accept (the F1/F2 class,
|
|
83293
|
+
// one topic over). The concepts a Safe owner still needs stay; the instructions go.
|
|
83294
|
+
safe: (d) => !offers(d, "safe") ? `# Safe accounts \u2014 not offered by this build
|
|
83295
|
+
|
|
83296
|
+
A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
|
|
83297
|
+
signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Diamond Hands can
|
|
83298
|
+
treat a Safe AS THE BORROWER \u2014 but not from here. This build's authorization surface is
|
|
83299
|
+
the wallet ceremony alone; \`signer_setup\` lists no Safe-shaped option, so there is
|
|
83300
|
+
nothing to set up. Say that plainly instead of walking a user through a ceremony this
|
|
83301
|
+
service cannot run.
|
|
83302
|
+
|
|
83303
|
+
**What still holds for a Safe's position anywhere:** its BTC withdrawal destination must
|
|
83304
|
+
be ALLOWLISTED first, and the allowlist delay is READ LIVE from the chain \u2014 24 hours on
|
|
83305
|
+
mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS. Owner authorizations
|
|
83306
|
+
for mint/pay/renew expire in minutes and withdrawal authorizations within the minute, so
|
|
83307
|
+
a multi-owner signing session happens TOGETHER, live.
|
|
83308
|
+
|
|
83309
|
+
**Where it does exist:** the local install's practice worlds run the Safe borrower plane
|
|
83310
|
+
end to end, and the web app (diamondhands.credit) speaks to the same chain state. A user
|
|
83311
|
+
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)
|
|
83832
83312
|
|
|
83833
83313
|
A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
|
|
83834
83314
|
signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companies and
|
|
@@ -83864,7 +83344,24 @@ expire after ~3 minutes, and withdrawal authorizations within the minute \u2014
|
|
|
83864
83344
|
owner signing session happens TOGETHER, live ("gather first, sign in one burst").
|
|
83865
83345
|
Creating a position and allowlisting a destination have NO expiry \u2014 owners can sign
|
|
83866
83346
|
those at their own pace. The ceremony guides this; never widen a window.`,
|
|
83867
|
-
delegation: `# Delegation \u2014
|
|
83347
|
+
delegation: (d) => !offers(d, "safe-module") ? `# Delegation \u2014 not offered by this build
|
|
83348
|
+
|
|
83349
|
+
Delegation is the protocol's answer to multi-owner Safes: the owners sign ONCE to install
|
|
83350
|
+
a tightly-caged AGENT key, and day-to-day work then runs without disturbing them. It is a
|
|
83351
|
+
Safe-shaped authorization plane, and this build constructs none \u2014 \`signer_setup\` lists
|
|
83352
|
+
no such option and \`loan_delegation_setup\` has no plane to install into here. Say that
|
|
83353
|
+
plainly rather than describing a ceremony this service cannot run.
|
|
83354
|
+
|
|
83355
|
+
**The cage, for a user who asks what it would mean:** an agent may create a position and
|
|
83356
|
+
\u2014 only after the owners grant it, per position \u2014 repay, renew, and mint while the
|
|
83357
|
+
post-mint collateral ratio stays at or above the floor the owners set. It can NEVER
|
|
83358
|
+
withdraw Bitcoin alone, never add or change withdrawal destinations, never touch the
|
|
83359
|
+
module or the registry, never move ETH. A stolen agent key can shuffle money WITHIN a
|
|
83360
|
+
position \u2014 never out. Revoking an agent BURNS its address forever, which is why
|
|
83361
|
+
revocation is always safe.
|
|
83362
|
+
|
|
83363
|
+
**Where it does exist:** the local install's practice worlds, pending the plane's own
|
|
83364
|
+
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
|
|
83868
83365
|
|
|
83869
83366
|
Multi-owner Safes cannot practically sign every operation inside the protocol's short
|
|
83870
83367
|
signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
|
|
@@ -83908,8 +83405,11 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
|
|
|
83908
83405
|
|
|
83909
83406
|
- **Nothing moves without you.** Every write needs \`confirmed: true\` AND the signer
|
|
83910
83407
|
ceremony. A decline anywhere cleanly cancels \u2014 declining is always safe.
|
|
83911
|
-
- **The card is the truth.** In external mode the wallet card
|
|
83912
|
-
|
|
83408
|
+
- **The card is the truth \u2014 with one named exception.** In external mode the wallet card
|
|
83409
|
+
is decoded from the exact TRANSACTION bytes being signed: what you read IS what
|
|
83410
|
+
executes. The exception is the BTC-withdraw blind signature \u2014 an opaque 32-byte hash
|
|
83411
|
+
the approval page says plainly it cannot decode (\`guide connect-wallet\`). Never
|
|
83412
|
+
extend the "what you read is what executes" promise over that one.
|
|
83913
83413
|
- **Liquidation:** if collateral value falls so the collateral ratio drops under the
|
|
83914
83414
|
liquidation threshold (\`protocol_status.liquidationThresholdBps\`, e.g. 110%), the
|
|
83915
83415
|
position can be liquidated. Watch \`position_status.valuation\` \u2014 \`currentLtvBps\` vs the
|
|
@@ -83922,23 +83422,21 @@ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Sa
|
|
|
83922
83422
|
withdrawing to a wrong address. Repaid-in-full positions release all collateral.
|
|
83923
83423
|
- **Practice vs real:** mock worlds are stated as such (\`boundary://info\`). Never let a
|
|
83924
83424
|
user believe practice gains/losses are real, or vice versa.`,
|
|
83925
|
-
"switch-network": `# Switch network \u2014
|
|
83425
|
+
"switch-network": (d) => `# Switch network \u2014 ${switchNetworkHeadline(d)}
|
|
83926
83426
|
|
|
83927
83427
|
The \`network_switch\` tool moves THIS SESSION between worlds. Check
|
|
83928
83428
|
\`boundary://info\` capabilities first: \`networkSwitch: true\` means it is available
|
|
83929
83429
|
(real adapter); in a practice sandbox (mock) the world is pinned by config \u2014 there is
|
|
83930
83430
|
no switch, and that is by design.
|
|
83931
83431
|
|
|
83432
|
+
**Served here:** ${servedNetworks(d)}. A network this deployment does not serve is
|
|
83433
|
+
refused with that reason \u2014 the tool existing is not a promise that both worlds are
|
|
83434
|
+
reachable, so never offer the user a network this deployment does not serve.
|
|
83435
|
+
|
|
83932
83436
|
**The rules, plainly:**
|
|
83933
83437
|
- \`network_switch status\` \u2014 which network is active and whether money is real. Say
|
|
83934
83438
|
this to the user BEFORE and AFTER any switch, always.
|
|
83935
|
-
|
|
83936
|
-
the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
|
|
83937
|
-
- NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
|
|
83938
|
-
A sepolia position does not exist on mainnet and vice versa.
|
|
83939
|
-
- Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
|
|
83940
|
-
and every one still requires the user's explicit confirmation plus the signer
|
|
83941
|
-
ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.
|
|
83439
|
+
${switchNetworkRules(d)}
|
|
83942
83440
|
- A pending signing ceremony blocks the switch (finish or decline it first).
|
|
83943
83441
|
- The switch is session-scoped: when the server restarts, the configured default
|
|
83944
83442
|
network returns.
|
|
@@ -83948,12 +83446,9 @@ reality in your next message. The user must never have to ask which world they a
|
|
|
83948
83446
|
// Plan 17 B1 — the hosted tier's truth, in user language. The trust ledger below is
|
|
83949
83447
|
// the plan-12 Part 0 ledger (BINDING, archive/12-remote-connector.md) — all six
|
|
83950
83448
|
// entries, verbatim-equivalent; G-CONN pins anchor phrases from every entry.
|
|
83951
|
-
connector: `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
|
|
83449
|
+
connector: (d) => `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
|
|
83952
83450
|
|
|
83953
|
-
|
|
83954
|
-
publicly served \u2014 the operator's rollout gates (a security audit, then a URL) come
|
|
83955
|
-
first. Until then there is no URL to give out, and the local install paths
|
|
83956
|
-
(\`first-setup\`) are the way in. Never promise availability or timing.
|
|
83451
|
+
${connectorStatusTruth(d)}
|
|
83957
83452
|
|
|
83958
83453
|
**What it is:** instead of installing anything, the user adds Diamond Hands to
|
|
83959
83454
|
claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
|
|
@@ -83980,9 +83475,17 @@ honestly when asked "is this safe"):
|
|
|
83980
83475
|
is never written to disk. A breach here is privacy-class, never money-class.
|
|
83981
83476
|
3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
|
|
83982
83477
|
a security concern is filed and audited for exactly this channel.
|
|
83983
|
-
4. **Tenant separation
|
|
83984
|
-
|
|
83985
|
-
|
|
83478
|
+
4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
|
|
83479
|
+
gets its own world: its own boundary, its own signer state, its own approval-page
|
|
83480
|
+
mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
|
|
83481
|
+
world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
|
|
83482
|
+
plus an earlier connection would make a different wallet this session's signer. That
|
|
83483
|
+
is signing-class, not merely privacy-class; do not tell a user it cannot be. What
|
|
83484
|
+
contains it: the mount id is freshly random per world and travels only in the user's
|
|
83485
|
+
own tool result (treat the link as a secret), and EVERY fund movement verifies the
|
|
83486
|
+
signature against that bound borrower \u2014 no key material exists server-side, so
|
|
83487
|
+
whoever reaches the page still cannot sign for anyone else. The gap is filed and
|
|
83488
|
+
audited; state it this way rather than claiming a binding that isn't there.
|
|
83986
83489
|
5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
|
|
83987
83490
|
version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
|
|
83988
83491
|
reports the exact server version.
|
|
@@ -83994,30 +83497,37 @@ honestly when asked "is this safe"):
|
|
|
83994
83497
|
|
|
83995
83498
|
**What it structurally CANNOT do:** hold keys or custody \u2014 keystore mode is ABSENT
|
|
83996
83499
|
from the connector build (not disabled: never constructed), so every fund-moving
|
|
83997
|
-
action needs a fresh signature from the user's own wallet.
|
|
83998
|
-
networks its deployment is rolled out to \u2014 this deployment serves sepolia during
|
|
83999
|
-
rollout; mainnet enablement is the operator's deploy decision, stated in capabilities
|
|
84000
|
-
by reason, never a hidden knob.
|
|
83500
|
+
action needs a fresh signature from the user's own wallet. ${connectorNetworkTruth(d)}
|
|
84001
83501
|
|
|
84002
83502
|
**Independent exits:** the web app (diamondhands.credit) and the SDK speak to the SAME
|
|
84003
83503
|
chain state. The connector going down strands nothing and gates nothing.`,
|
|
84004
|
-
troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
|
|
83504
|
+
troubleshooting: (d) => `# Troubleshooting \u2014 what error codes mean, in plain words
|
|
84005
83505
|
|
|
84006
|
-
|
|
83506
|
+
${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
|
|
84007
83507
|
keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
|
|
84008
83508
|
"connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
|
|
84009
83509
|
status\` explains what is active; \`first-setup\` step 2 has the full choice.
|
|
84010
83510
|
- **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
|
|
84011
83511
|
the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
|
|
84012
|
-
EXPIRED login refuses the same way \u2014 reconnect on the user's word.
|
|
84013
|
-
|
|
84014
|
-
|
|
84015
|
-
|
|
84016
|
-
|
|
84017
|
-
|
|
83512
|
+
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
|
|
83513
|
+
ONE remedy: the user says "connect my wallet" \u2192 \`signer_setup\` action \`connect\`
|
|
83514
|
+
(external mode). There is no keystore here to configure and no password to supply \u2014
|
|
83515
|
+
saying otherwise sends the user hunting for a setting that does not exist.
|
|
83516
|
+
\`signer_setup status\` explains what is active; \`first-setup\` step 2 has the choice.
|
|
83517
|
+
- **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
|
|
83518
|
+
the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
|
|
83519
|
+
the same way \u2014 reconnect on the user's word.`}
|
|
83520
|
+
${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
|
|
83521
|
+
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
|
|
83522
|
+
anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
|
|
83523
|
+
${wrongNetworkTroubleshootingRow(d)}
|
|
84018
83524
|
- **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
|
|
84019
|
-
SDK builds the
|
|
84020
|
-
|
|
83525
|
+
SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
|
|
83526
|
+
signature per withdrawal, not two: the authorization phase is EIP-712 typed data
|
|
83527
|
+
(\`WithdrawRequest\` \u2014 the wallet renders position, amount and destination), and only
|
|
83528
|
+
the execute phase is opaque. Warn the user before that one popup, and do not describe
|
|
83529
|
+
the typed one as blind \u2014 overstating it teaches them to expect an unreadable card and
|
|
83530
|
+
click through the readable one.
|
|
84021
83531
|
- **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
|
|
84022
83532
|
That is the broker throttle, not a wallet failure.
|
|
84023
83533
|
- **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
|
|
@@ -84032,9 +83542,7 @@ chain state. The connector going down strands nothing and gates nothing.`,
|
|
|
84032
83542
|
which source and when from. Prefer chain-sourced values; re-read before acting.
|
|
84033
83543
|
- Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
|
|
84034
83544
|
Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
|
|
84035
|
-
|
|
84036
|
-
publicly served (the operator's audit + rollout gates come first). There is no URL to
|
|
84037
|
-
give out; the local install paths work today. Full truth: \`guide connector\`.
|
|
83545
|
+
${connectorTroubleshootingRow(d)}
|
|
84038
83546
|
- **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
|
|
84039
83547
|
the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
|
|
84040
83548
|
Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
|
|
@@ -84054,7 +83562,8 @@ Synonym sets (treat these as the SAME intent):
|
|
|
84054
83562
|
- **UCD** = the dollar-pegged token you borrow ("the dollars")
|
|
84055
83563
|
- **sats** = satoshis, 1 BTC = 100,000,000 sats
|
|
84056
83564
|
- **connector** = remote = hosted tier = "claude.ai integration" = "use it without
|
|
84057
|
-
installing" \u2192 \`guide connector\` (
|
|
83565
|
+
installing" \u2192 \`guide connector\` (it states which tier THIS session is, and the
|
|
83566
|
+
trust model that comes with it)
|
|
84058
83567
|
|
|
84059
83568
|
Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
|
|
84060
83569
|
- **vault** \u2014 the position's BTC custody address. Its balance is your COLLATERAL, not
|
|
@@ -84065,39 +83574,1099 @@ Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
|
|
|
84065
83574
|
- **interest** \u2014 Diamond Hands charges FEES (origination/extension), not running
|
|
84066
83575
|
interest; see \`fees\`.
|
|
84067
83576
|
|
|
84068
|
-
Language: answer in the user's language, whatever it is. These mappings apply to meaning,
|
|
84069
|
-
not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
|
|
84070
|
-
"emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
|
|
84071
|
-
// Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
|
|
84072
|
-
// the same entries the anchor test pins against the actually-serialized fields.
|
|
84073
|
-
"reading-data": renderFieldGlossaryTopic()
|
|
83577
|
+
Language: answer in the user's language, whatever it is. These mappings apply to meaning,
|
|
83578
|
+
not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
|
|
83579
|
+
"emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
|
|
83580
|
+
// Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
|
|
83581
|
+
// the same entries the anchor test pins against the actually-serialized fields.
|
|
83582
|
+
"reading-data": renderFieldGlossaryTopic()
|
|
83583
|
+
};
|
|
83584
|
+
function renderGuideContent(deployment) {
|
|
83585
|
+
const content = {};
|
|
83586
|
+
for (const topic of GUIDE_TOPICS) {
|
|
83587
|
+
const source = GUIDE_TOPIC_SOURCES[topic];
|
|
83588
|
+
content[topic] = typeof source === "string" ? source : source(deployment);
|
|
83589
|
+
}
|
|
83590
|
+
return content;
|
|
83591
|
+
}
|
|
83592
|
+
function renderGuideIndex(deployment) {
|
|
83593
|
+
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";
|
|
83594
|
+
return `# Diamond Hands guide \u2014 topics
|
|
83595
|
+
|
|
83596
|
+
- getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
|
|
83597
|
+
- first-setup \u2014 zero to ready by conversation (authorization choice included)
|
|
83598
|
+
- connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
|
|
83599
|
+
- lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
|
|
83600
|
+
- fees \u2014 the two fee models, plainly
|
|
83601
|
+
- psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
|
|
83602
|
+
- authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
|
|
83603
|
+
${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"}
|
|
83604
|
+
${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"}
|
|
83605
|
+
- safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
|
|
83606
|
+
${switchNetworkIndexLine(deployment)}
|
|
83607
|
+
${connectorLine}
|
|
83608
|
+
- troubleshooting \u2014 error codes in plain words, with the real remedies
|
|
83609
|
+
- glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
|
|
83610
|
+
- reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
|
|
83611
|
+
|
|
83612
|
+
Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
|
|
83613
|
+
selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
|
|
83614
|
+
signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
|
|
83615
|
+
and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
|
|
83616
|
+
only mainnet is real money.`;
|
|
83617
|
+
}
|
|
83618
|
+
var deploymentKey = (d) => `${d.tier}|${d.networks.join(",")}|${d.signerModes.join(",")}`;
|
|
83619
|
+
var RENDERED = /* @__PURE__ */ new Map();
|
|
83620
|
+
function renderedGuide(deployment) {
|
|
83621
|
+
const key = deploymentKey(deployment);
|
|
83622
|
+
let rendered = RENDERED.get(key);
|
|
83623
|
+
if (!rendered) {
|
|
83624
|
+
rendered = Object.freeze({
|
|
83625
|
+
content: Object.freeze(renderGuideContent(deployment)),
|
|
83626
|
+
index: renderGuideIndex(deployment)
|
|
83627
|
+
});
|
|
83628
|
+
RENDERED.set(key, rendered);
|
|
83629
|
+
}
|
|
83630
|
+
return rendered;
|
|
83631
|
+
}
|
|
83632
|
+
function buildGuideContent(deployment) {
|
|
83633
|
+
return renderedGuide(deployment).content;
|
|
83634
|
+
}
|
|
83635
|
+
function buildGuideIndex(deployment) {
|
|
83636
|
+
return renderedGuide(deployment).index;
|
|
83637
|
+
}
|
|
83638
|
+
var GUIDE_CONTENT = buildGuideContent(LOCAL_GUIDE_DEPLOYMENT);
|
|
83639
|
+
var GUIDE_INDEX = buildGuideIndex(LOCAL_GUIDE_DEPLOYMENT);
|
|
83640
|
+
|
|
83641
|
+
// src/network-switch.ts
|
|
83642
|
+
var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
|
|
83643
|
+
function createNetworkSwitchRuntime(opts) {
|
|
83644
|
+
return {
|
|
83645
|
+
current() {
|
|
83646
|
+
const b = opts.getBoot().boundaryResult;
|
|
83647
|
+
if (!b.ok) return null;
|
|
83648
|
+
const w = b.boundary.world();
|
|
83649
|
+
return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
|
|
83650
|
+
},
|
|
83651
|
+
async switchTo(network) {
|
|
83652
|
+
const allowed = opts.overrides?.allowedNetworks;
|
|
83653
|
+
if (allowed && !allowed.includes(network)) {
|
|
83654
|
+
return {
|
|
83655
|
+
ok: false,
|
|
83656
|
+
error: boundaryError(
|
|
83657
|
+
"VALIDATION_FAILED",
|
|
83658
|
+
`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.`
|
|
83659
|
+
)
|
|
83660
|
+
};
|
|
83661
|
+
}
|
|
83662
|
+
const targetEnv = { ...opts.env, DH_NETWORK: network };
|
|
83663
|
+
const configResult = resolveBoundaryConfig(targetEnv);
|
|
83664
|
+
if (!configResult.ok) return { ok: false, error: configResult.error };
|
|
83665
|
+
const next = await buildBoundary(configResult, opts.overrides);
|
|
83666
|
+
if (!next.boundaryResult.ok) {
|
|
83667
|
+
next.dispose();
|
|
83668
|
+
return { ok: false, error: next.boundaryResult.error };
|
|
83669
|
+
}
|
|
83670
|
+
opts.swap(next);
|
|
83671
|
+
return { ok: true };
|
|
83672
|
+
}
|
|
83673
|
+
};
|
|
83674
|
+
}
|
|
83675
|
+
function guideDeployment(overrides) {
|
|
83676
|
+
return {
|
|
83677
|
+
tier: overrides?.bridgeMount ? "hosted" : "local",
|
|
83678
|
+
networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
|
|
83679
|
+
signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
|
|
83680
|
+
};
|
|
83681
|
+
}
|
|
83682
|
+
function assembleWorld(opts) {
|
|
83683
|
+
let boot = opts.boot;
|
|
83684
|
+
const deps = {
|
|
83685
|
+
boundaryResult: boot.boundaryResult,
|
|
83686
|
+
...boot.mockControl ? { mockControl: boot.mockControl } : {},
|
|
83687
|
+
...boot.signer ? { signer: boot.signer } : {},
|
|
83688
|
+
...opts.overrides?.externalOnly ? { externalOnly: true } : {},
|
|
83689
|
+
deployment: guideDeployment(opts.overrides),
|
|
83690
|
+
...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
|
|
83691
|
+
};
|
|
83692
|
+
if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
|
|
83693
|
+
deps.networkSwitch = createNetworkSwitchRuntime({
|
|
83694
|
+
env: opts.env,
|
|
83695
|
+
getBoot: () => boot,
|
|
83696
|
+
...opts.overrides ? { overrides: opts.overrides } : {},
|
|
83697
|
+
swap: (next) => {
|
|
83698
|
+
const old = boot;
|
|
83699
|
+
boot = next;
|
|
83700
|
+
deps.boundaryResult = next.boundaryResult;
|
|
83701
|
+
if (next.signer) deps.signer = next.signer;
|
|
83702
|
+
else delete deps.signer;
|
|
83703
|
+
old.dispose();
|
|
83704
|
+
const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
|
|
83705
|
+
opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
|
|
83706
|
+
}
|
|
83707
|
+
});
|
|
83708
|
+
}
|
|
83709
|
+
return { deps, dispose: () => boot.dispose() };
|
|
83710
|
+
}
|
|
83711
|
+
|
|
83712
|
+
// src/server.ts
|
|
83713
|
+
var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
83714
|
+
|
|
83715
|
+
// src/tools/loan.ts
|
|
83716
|
+
var import_zod = require("zod");
|
|
83717
|
+
var import_ethers41 = require("ethers");
|
|
83718
|
+
|
|
83719
|
+
// src/util/format.ts
|
|
83720
|
+
function bigintReplacer(_key, value) {
|
|
83721
|
+
if (typeof value === "bigint") return value.toString();
|
|
83722
|
+
return value;
|
|
83723
|
+
}
|
|
83724
|
+
function serialize(data) {
|
|
83725
|
+
return JSON.stringify(data, bigintReplacer, 2);
|
|
83726
|
+
}
|
|
83727
|
+
|
|
83728
|
+
// src/tools/_helpers.ts
|
|
83729
|
+
function registerBoundaryTool(server, name, config, handler) {
|
|
83730
|
+
server.registerTool(name, config, handler);
|
|
83731
|
+
}
|
|
83732
|
+
function renderError(error) {
|
|
83733
|
+
const lines = [`ERROR [${error.code}]: ${error.message}`];
|
|
83734
|
+
if (error.source) lines.push(`source: ${error.source}`);
|
|
83735
|
+
return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
|
|
83736
|
+
}
|
|
83737
|
+
function renderEnvelope(env) {
|
|
83738
|
+
if (!env.ok) return renderError(env.error);
|
|
83739
|
+
const parts = [serialize(env.data)];
|
|
83740
|
+
if (env.warnings.length > 0) {
|
|
83741
|
+
parts.push(
|
|
83742
|
+
"WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
|
|
83743
|
+
);
|
|
83744
|
+
}
|
|
83745
|
+
parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
|
|
83746
|
+
return { content: [{ type: "text", text: parts.join("\n\n") }] };
|
|
83747
|
+
}
|
|
83748
|
+
function validationFailed(problem) {
|
|
83749
|
+
return renderError(boundaryError("VALIDATION_FAILED", problem));
|
|
83750
|
+
}
|
|
83751
|
+
function resourceJson(env) {
|
|
83752
|
+
if (!env.ok) return serialize({ error: env.error });
|
|
83753
|
+
return serialize({ data: env.data, warnings: env.warnings, source: env.source });
|
|
83754
|
+
}
|
|
83755
|
+
function resourceErrorJson(error) {
|
|
83756
|
+
return serialize({ error });
|
|
83757
|
+
}
|
|
83758
|
+
function requireConfirmation(confirmed, actionLabel) {
|
|
83759
|
+
if (confirmed === true) return null;
|
|
83760
|
+
return {
|
|
83761
|
+
content: [
|
|
83762
|
+
{
|
|
83763
|
+
type: "text",
|
|
83764
|
+
text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
|
|
83765
|
+
This is an irreversible, fund-moving action. A human must explicitly authorize it.
|
|
83766
|
+
Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
|
|
83767
|
+
}
|
|
83768
|
+
],
|
|
83769
|
+
isError: true
|
|
83770
|
+
};
|
|
83771
|
+
}
|
|
83772
|
+
function envStamp(b) {
|
|
83773
|
+
if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
|
|
83774
|
+
const w = b.boundary.world();
|
|
83775
|
+
const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
|
|
83776
|
+
return `environment: ${w.network} \u2014 ${money}`;
|
|
83777
|
+
}
|
|
83778
|
+
async function guardedWrite(getB, fn) {
|
|
83779
|
+
const result = await guarded(fn);
|
|
83780
|
+
const stamp = envStamp(getB());
|
|
83781
|
+
const content = result.content.map(
|
|
83782
|
+
(c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
|
|
83783
|
+
|
|
83784
|
+
${stamp}` } : c
|
|
83785
|
+
);
|
|
83786
|
+
return { ...result, content };
|
|
83787
|
+
}
|
|
83788
|
+
async function guarded(fn) {
|
|
83789
|
+
try {
|
|
83790
|
+
return await fn();
|
|
83791
|
+
} catch (e) {
|
|
83792
|
+
return renderError(
|
|
83793
|
+
boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
|
|
83794
|
+
details: { stack: e.stack }
|
|
83795
|
+
})
|
|
83796
|
+
);
|
|
83797
|
+
}
|
|
83798
|
+
}
|
|
83799
|
+
|
|
83800
|
+
// src/util/validate.ts
|
|
83801
|
+
var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
83802
|
+
var SATS_SANITY_CAP = 1e10;
|
|
83803
|
+
var UCD_SANITY_CAP = 1e9;
|
|
83804
|
+
function checkPositionIdHex(id, label = "Position ID") {
|
|
83805
|
+
if (!POSITION_ID_RE.test(id)) {
|
|
83806
|
+
return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
|
|
83807
|
+
}
|
|
83808
|
+
return null;
|
|
83809
|
+
}
|
|
83810
|
+
function checkUcdAmount(amount, label = "Amount") {
|
|
83811
|
+
if (!Number.isFinite(amount) || amount <= 0) {
|
|
83812
|
+
return `${label} must be a positive finite number (got ${amount}).`;
|
|
83813
|
+
}
|
|
83814
|
+
if (amount > UCD_SANITY_CAP) {
|
|
83815
|
+
return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
|
|
83816
|
+
}
|
|
83817
|
+
if (amount > 0 && amount < 1e-6) {
|
|
83818
|
+
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
83819
|
+
}
|
|
83820
|
+
const decimals = amount.toString().split(".")[1];
|
|
83821
|
+
if (decimals && decimals.length > 6) {
|
|
83822
|
+
return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
|
|
83823
|
+
}
|
|
83824
|
+
return null;
|
|
83825
|
+
}
|
|
83826
|
+
function checkSatsAmount(sats, label = "Amount") {
|
|
83827
|
+
if (!Number.isInteger(sats) || sats <= 0) {
|
|
83828
|
+
return `${label} must be a positive integer (satoshis), got ${sats}.`;
|
|
83829
|
+
}
|
|
83830
|
+
if (sats > SATS_SANITY_CAP) {
|
|
83831
|
+
return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
|
|
83832
|
+
}
|
|
83833
|
+
return null;
|
|
83834
|
+
}
|
|
83835
|
+
function checkSelectedTerm(months, label = "Term") {
|
|
83836
|
+
if (!Number.isInteger(months) || months <= 0) {
|
|
83837
|
+
return `${label} must be a positive integer (months), got ${months}.`;
|
|
83838
|
+
}
|
|
83839
|
+
if (months > 120) {
|
|
83840
|
+
return `${label} ${months} months exceeds the 10-year sanity cap.`;
|
|
83841
|
+
}
|
|
83842
|
+
return null;
|
|
83843
|
+
}
|
|
83844
|
+
|
|
83845
|
+
// src/tools/loan.ts
|
|
83846
|
+
var LATENCY_NOTES = {
|
|
83847
|
+
mock: "Instant in this practice world.",
|
|
83848
|
+
real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
|
|
83849
|
+
};
|
|
83850
|
+
var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
|
|
83851
|
+
var confirmedSchema = import_zod.z.boolean().optional().describe(
|
|
83852
|
+
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
83853
|
+
);
|
|
83854
|
+
var DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
83855
|
+
readOnlyHint: false,
|
|
83856
|
+
destructiveHint: true,
|
|
83857
|
+
idempotentHint: false,
|
|
83858
|
+
openWorldHint: true
|
|
83859
|
+
};
|
|
83860
|
+
function registerLoanTools(server, getB, adapter2 = "real") {
|
|
83861
|
+
const LATENCY_NOTE = LATENCY_NOTES[adapter2];
|
|
83862
|
+
registerBoundaryTool(
|
|
83863
|
+
server,
|
|
83864
|
+
"loan_create",
|
|
83865
|
+
{
|
|
83866
|
+
title: "Create a new lending position",
|
|
83867
|
+
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).`,
|
|
83868
|
+
inputSchema: {
|
|
83869
|
+
selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
|
|
83870
|
+
confirmed: confirmedSchema
|
|
83871
|
+
},
|
|
83872
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83873
|
+
},
|
|
83874
|
+
async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
83875
|
+
const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
|
|
83876
|
+
if (gate) return gate;
|
|
83877
|
+
const problem = checkSelectedTerm(selectedTerm);
|
|
83878
|
+
if (problem) return validationFailed(problem);
|
|
83879
|
+
const b = getB();
|
|
83880
|
+
if (!b.ok) return renderError(b.error);
|
|
83881
|
+
return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
|
|
83882
|
+
})
|
|
83883
|
+
);
|
|
83884
|
+
registerBoundaryTool(
|
|
83885
|
+
server,
|
|
83886
|
+
"loan_mint",
|
|
83887
|
+
{
|
|
83888
|
+
title: "Mint UCD against a position",
|
|
83889
|
+
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).`,
|
|
83890
|
+
inputSchema: {
|
|
83891
|
+
positionId: positionIdSchema,
|
|
83892
|
+
amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
|
|
83893
|
+
confirmed: confirmedSchema
|
|
83894
|
+
},
|
|
83895
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83896
|
+
},
|
|
83897
|
+
async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
|
|
83898
|
+
const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
|
|
83899
|
+
if (gate) return gate;
|
|
83900
|
+
const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
|
|
83901
|
+
if (problem) return validationFailed(problem);
|
|
83902
|
+
const b = getB();
|
|
83903
|
+
if (!b.ok) return renderError(b.error);
|
|
83904
|
+
return renderEnvelope(
|
|
83905
|
+
await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers41.parseEther)(amountUcd.toString()).toString() })
|
|
83906
|
+
);
|
|
83907
|
+
})
|
|
83908
|
+
);
|
|
83909
|
+
registerBoundaryTool(
|
|
83910
|
+
server,
|
|
83911
|
+
"loan_pay",
|
|
83912
|
+
{
|
|
83913
|
+
title: "Make a UCD payment toward a position's debt",
|
|
83914
|
+
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).`,
|
|
83915
|
+
inputSchema: {
|
|
83916
|
+
positionId: positionIdSchema,
|
|
83917
|
+
amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
|
|
83918
|
+
repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
|
|
83919
|
+
confirmed: confirmedSchema
|
|
83920
|
+
},
|
|
83921
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83922
|
+
},
|
|
83923
|
+
async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
|
|
83924
|
+
if (repayAll === true === (amountUcd !== void 0)) {
|
|
83925
|
+
return validationFailed("provide exactly one of amountUcd or repayAll: true");
|
|
83926
|
+
}
|
|
83927
|
+
const gate = requireConfirmation(
|
|
83928
|
+
confirmed,
|
|
83929
|
+
repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
|
|
83930
|
+
);
|
|
83931
|
+
if (gate) return gate;
|
|
83932
|
+
const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
|
|
83933
|
+
if (problem) return validationFailed(problem);
|
|
83934
|
+
const b = getB();
|
|
83935
|
+
if (!b.ok) return renderError(b.error);
|
|
83936
|
+
let amountUcdWei;
|
|
83937
|
+
if (repayAll) {
|
|
83938
|
+
const detail = await b.boundary.getPosition(positionId);
|
|
83939
|
+
if (!detail.ok) return renderError(detail.error);
|
|
83940
|
+
if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
|
|
83941
|
+
amountUcdWei = detail.data.debtUcdWei;
|
|
83942
|
+
} else {
|
|
83943
|
+
amountUcdWei = (0, import_ethers41.parseEther)(amountUcd.toString()).toString();
|
|
83944
|
+
}
|
|
83945
|
+
return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
|
|
83946
|
+
})
|
|
83947
|
+
);
|
|
83948
|
+
registerBoundaryTool(
|
|
83949
|
+
server,
|
|
83950
|
+
"loan_extend",
|
|
83951
|
+
{
|
|
83952
|
+
title: "Extend / renew a position's term",
|
|
83953
|
+
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).`,
|
|
83954
|
+
inputSchema: {
|
|
83955
|
+
positionId: positionIdSchema,
|
|
83956
|
+
selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
|
|
83957
|
+
confirmed: confirmedSchema
|
|
83958
|
+
},
|
|
83959
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83960
|
+
},
|
|
83961
|
+
async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
|
|
83962
|
+
const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
|
|
83963
|
+
if (gate) return gate;
|
|
83964
|
+
const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
|
|
83965
|
+
if (problem) return validationFailed(problem);
|
|
83966
|
+
const b = getB();
|
|
83967
|
+
if (!b.ok) return renderError(b.error);
|
|
83968
|
+
return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
|
|
83969
|
+
})
|
|
83970
|
+
);
|
|
83971
|
+
registerBoundaryTool(
|
|
83972
|
+
server,
|
|
83973
|
+
"loan_withdraw",
|
|
83974
|
+
{
|
|
83975
|
+
title: "Withdraw BTC from a position vault",
|
|
83976
|
+
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).`,
|
|
83977
|
+
inputSchema: {
|
|
83978
|
+
positionId: positionIdSchema,
|
|
83979
|
+
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
|
|
83980
|
+
amountSats: import_zod.z.number().int().positive().describe(
|
|
83981
|
+
"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."
|
|
83982
|
+
),
|
|
83983
|
+
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"),
|
|
83984
|
+
confirmed: confirmedSchema
|
|
83985
|
+
},
|
|
83986
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
83987
|
+
},
|
|
83988
|
+
async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
|
|
83989
|
+
const gate = requireConfirmation(
|
|
83990
|
+
confirmed,
|
|
83991
|
+
`withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
|
|
83992
|
+
);
|
|
83993
|
+
if (gate) return gate;
|
|
83994
|
+
const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
|
|
83995
|
+
if (problem) return validationFailed(problem);
|
|
83996
|
+
const b = getB();
|
|
83997
|
+
if (!b.ok) return renderError(b.error);
|
|
83998
|
+
return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
|
|
83999
|
+
})
|
|
84000
|
+
);
|
|
84001
|
+
registerBoundaryTool(
|
|
84002
|
+
server,
|
|
84003
|
+
"loan_allowlist_destination",
|
|
84004
|
+
{
|
|
84005
|
+
title: "Allowlist a BTC withdrawal destination",
|
|
84006
|
+
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).`,
|
|
84007
|
+
inputSchema: {
|
|
84008
|
+
btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
|
|
84009
|
+
confirmed: confirmedSchema
|
|
84010
|
+
},
|
|
84011
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
84012
|
+
},
|
|
84013
|
+
async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
|
|
84014
|
+
const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
|
|
84015
|
+
if (gate) return gate;
|
|
84016
|
+
const b = getB();
|
|
84017
|
+
if (!b.ok) return renderError(b.error);
|
|
84018
|
+
return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
|
|
84019
|
+
})
|
|
84020
|
+
);
|
|
84021
|
+
registerBoundaryTool(
|
|
84022
|
+
server,
|
|
84023
|
+
"loan_delegation_setup",
|
|
84024
|
+
{
|
|
84025
|
+
title: "Install delegation on the Safe (one owner ceremony)",
|
|
84026
|
+
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).`,
|
|
84027
|
+
inputSchema: {
|
|
84028
|
+
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)"),
|
|
84029
|
+
confirmed: confirmedSchema
|
|
84030
|
+
},
|
|
84031
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
84032
|
+
},
|
|
84033
|
+
async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
|
|
84034
|
+
const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
|
|
84035
|
+
if (gate) return gate;
|
|
84036
|
+
const b = getB();
|
|
84037
|
+
if (!b.ok) return renderError(b.error);
|
|
84038
|
+
return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
|
|
84039
|
+
})
|
|
84040
|
+
);
|
|
84041
|
+
registerBoundaryTool(
|
|
84042
|
+
server,
|
|
84043
|
+
"loan_delegation_grant",
|
|
84044
|
+
{
|
|
84045
|
+
title: "Grant the agent per-position scopes (owners sign)",
|
|
84046
|
+
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).`,
|
|
84047
|
+
inputSchema: {
|
|
84048
|
+
positionId: positionIdSchema,
|
|
84049
|
+
renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
|
|
84050
|
+
repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
|
|
84051
|
+
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"),
|
|
84052
|
+
confirmed: confirmedSchema
|
|
84053
|
+
},
|
|
84054
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
|
|
84055
|
+
},
|
|
84056
|
+
async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
|
|
84057
|
+
const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
|
|
84058
|
+
if (gate) return gate;
|
|
84059
|
+
const b = getB();
|
|
84060
|
+
if (!b.ok) return renderError(b.error);
|
|
84061
|
+
return renderEnvelope(
|
|
84062
|
+
await b.boundary.delegationGrant({
|
|
84063
|
+
positionId,
|
|
84064
|
+
renew: renew ?? false,
|
|
84065
|
+
repay: repay ?? false,
|
|
84066
|
+
mintFloorBps: mintFloorBps ?? null
|
|
84067
|
+
})
|
|
84068
|
+
);
|
|
84069
|
+
})
|
|
84070
|
+
);
|
|
84071
|
+
registerBoundaryTool(
|
|
84072
|
+
server,
|
|
84073
|
+
"loan_recover_stale_spend",
|
|
84074
|
+
{
|
|
84075
|
+
title: "Recover a stale BTC reservation via LIT-attested proof",
|
|
84076
|
+
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.",
|
|
84077
|
+
inputSchema: {
|
|
84078
|
+
positionId: positionIdSchema,
|
|
84079
|
+
utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
|
|
84080
|
+
utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
|
|
84081
|
+
invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
|
|
84082
|
+
minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
|
|
84083
|
+
},
|
|
84084
|
+
annotations: {
|
|
84085
|
+
readOnlyHint: false,
|
|
84086
|
+
destructiveHint: false,
|
|
84087
|
+
idempotentHint: true,
|
|
84088
|
+
openWorldHint: true
|
|
84089
|
+
}
|
|
84090
|
+
},
|
|
84091
|
+
async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
|
|
84092
|
+
const problem = checkPositionIdHex(positionId);
|
|
84093
|
+
if (problem) return validationFailed(problem);
|
|
84094
|
+
const b = getB();
|
|
84095
|
+
if (!b.ok) return renderError(b.error);
|
|
84096
|
+
return renderEnvelope(
|
|
84097
|
+
await b.boundary.recoverStaleSpend({
|
|
84098
|
+
positionId,
|
|
84099
|
+
utxoTxid,
|
|
84100
|
+
utxoVout,
|
|
84101
|
+
invalidatorTxid,
|
|
84102
|
+
...minConfirmations !== void 0 ? { minConfirmations } : {}
|
|
84103
|
+
})
|
|
84104
|
+
);
|
|
84105
|
+
})
|
|
84106
|
+
);
|
|
84107
|
+
}
|
|
84108
|
+
|
|
84109
|
+
// src/tools/position.ts
|
|
84110
|
+
var import_zod2 = require("zod");
|
|
84111
|
+
var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
|
|
84112
|
+
var POSITION_STATES = [
|
|
84113
|
+
"PENDING_DEPOSIT",
|
|
84114
|
+
"PENDING_MINT",
|
|
84115
|
+
"ACTIVE",
|
|
84116
|
+
"EXPIRED",
|
|
84117
|
+
"LIQUIDATABLE",
|
|
84118
|
+
"LIQUIDATED",
|
|
84119
|
+
"REPAID",
|
|
84120
|
+
"CLOSED"
|
|
84121
|
+
];
|
|
84122
|
+
function registerPositionTools(server, getB) {
|
|
84123
|
+
registerBoundaryTool(
|
|
84124
|
+
server,
|
|
84125
|
+
"position_status",
|
|
84126
|
+
{
|
|
84127
|
+
title: "Get a position's full status",
|
|
84128
|
+
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"),
|
|
84129
|
+
inputSchema: {
|
|
84130
|
+
id: positionIdSchema2
|
|
84131
|
+
}
|
|
84132
|
+
},
|
|
84133
|
+
async ({ id }) => guarded(async () => {
|
|
84134
|
+
const problem = checkPositionIdHex(id);
|
|
84135
|
+
if (problem) return validationFailed(problem);
|
|
84136
|
+
const b = getB();
|
|
84137
|
+
if (!b.ok) return renderError(b.error);
|
|
84138
|
+
return renderEnvelope(await b.boundary.getPosition(id));
|
|
84139
|
+
})
|
|
84140
|
+
);
|
|
84141
|
+
registerBoundaryTool(
|
|
84142
|
+
server,
|
|
84143
|
+
"position_list",
|
|
84144
|
+
{
|
|
84145
|
+
title: "List lending positions",
|
|
84146
|
+
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"),
|
|
84147
|
+
inputSchema: {
|
|
84148
|
+
borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
|
|
84149
|
+
state: import_zod2.z.string().optional().describe(`Filter by state (${POSITION_STATES.join(", ")})`),
|
|
84150
|
+
page: import_zod2.z.number().int().positive().default(1).describe("Page number"),
|
|
84151
|
+
pageSize: import_zod2.z.number().int().positive().max(100).default(20).describe("Page size")
|
|
84152
|
+
}
|
|
84153
|
+
},
|
|
84154
|
+
async ({ borrower, state, page, pageSize }) => guarded(async () => {
|
|
84155
|
+
if (state !== void 0 && !POSITION_STATES.includes(state)) {
|
|
84156
|
+
return validationFailed(`state '${state}' is not a position state \u2014 allowed: ${POSITION_STATES.join(", ")}`);
|
|
84157
|
+
}
|
|
84158
|
+
const b = getB();
|
|
84159
|
+
if (!b.ok) return renderError(b.error);
|
|
84160
|
+
const filter2 = {
|
|
84161
|
+
page,
|
|
84162
|
+
pageSize,
|
|
84163
|
+
...borrower !== void 0 ? { borrower } : {},
|
|
84164
|
+
...state !== void 0 ? { state } : {}
|
|
84165
|
+
};
|
|
84166
|
+
if (filter2.borrower === void 0 && filter2.state === void 0) {
|
|
84167
|
+
return renderEnvelope(await b.boundary.listPositions({ ...filter2, activeOnly: true }));
|
|
84168
|
+
}
|
|
84169
|
+
return renderEnvelope(await b.boundary.listPositions(filter2));
|
|
84170
|
+
})
|
|
84171
|
+
);
|
|
84172
|
+
registerBoundaryTool(
|
|
84173
|
+
server,
|
|
84174
|
+
"position_events",
|
|
84175
|
+
{
|
|
84176
|
+
title: "Get a position's event history",
|
|
84177
|
+
description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
|
|
84178
|
+
inputSchema: {
|
|
84179
|
+
id: positionIdSchema2
|
|
84180
|
+
}
|
|
84181
|
+
},
|
|
84182
|
+
async ({ id }) => guarded(async () => {
|
|
84183
|
+
const problem = checkPositionIdHex(id);
|
|
84184
|
+
if (problem) return validationFailed(problem);
|
|
84185
|
+
const b = getB();
|
|
84186
|
+
if (!b.ok) return renderError(b.error);
|
|
84187
|
+
return renderEnvelope(await b.boundary.getPositionEvents(id));
|
|
84188
|
+
})
|
|
84189
|
+
);
|
|
84190
|
+
registerBoundaryTool(
|
|
84191
|
+
server,
|
|
84192
|
+
"position_pending_withdrawals",
|
|
84193
|
+
{
|
|
84194
|
+
title: "List a position's pending BTC withdrawal reservations",
|
|
84195
|
+
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).",
|
|
84196
|
+
inputSchema: {
|
|
84197
|
+
id: positionIdSchema2
|
|
84198
|
+
}
|
|
84199
|
+
},
|
|
84200
|
+
async ({ id }) => guarded(async () => {
|
|
84201
|
+
const problem = checkPositionIdHex(id);
|
|
84202
|
+
if (problem) return validationFailed(problem);
|
|
84203
|
+
const b = getB();
|
|
84204
|
+
if (!b.ok) return renderError(b.error);
|
|
84205
|
+
return renderEnvelope(await b.boundary.getPendingWithdrawals(id));
|
|
84206
|
+
})
|
|
84207
|
+
);
|
|
84208
|
+
}
|
|
84209
|
+
|
|
84210
|
+
// src/tools/btc.ts
|
|
84211
|
+
var import_zod3 = require("zod");
|
|
84212
|
+
function registerBtcTools(server, getB) {
|
|
84213
|
+
registerBoundaryTool(
|
|
84214
|
+
server,
|
|
84215
|
+
"btc_balance",
|
|
84216
|
+
{
|
|
84217
|
+
title: "Get BTC balance for an address",
|
|
84218
|
+
description: "Query the confirmed BTC balance for an address (source-tagged).",
|
|
84219
|
+
inputSchema: {
|
|
84220
|
+
address: import_zod3.z.string().min(1).describe("BTC address to query")
|
|
84221
|
+
}
|
|
84222
|
+
},
|
|
84223
|
+
async ({ address }) => guarded(async () => {
|
|
84224
|
+
const b = getB();
|
|
84225
|
+
if (!b.ok) return renderError(b.error);
|
|
84226
|
+
return renderEnvelope(await b.boundary.getBitcoinBalance(address));
|
|
84227
|
+
})
|
|
84228
|
+
);
|
|
84229
|
+
registerBoundaryTool(
|
|
84230
|
+
server,
|
|
84231
|
+
"btc_price",
|
|
84232
|
+
{
|
|
84233
|
+
title: "Get the current BTC price",
|
|
84234
|
+
description: "Return the current BTC price (USD, 8 decimals) from the price oracle.",
|
|
84235
|
+
inputSchema: {}
|
|
84236
|
+
},
|
|
84237
|
+
async () => guarded(async () => {
|
|
84238
|
+
const b = getB();
|
|
84239
|
+
if (!b.ok) return renderError(b.error);
|
|
84240
|
+
return renderEnvelope(await b.boundary.getBitcoinPrice());
|
|
84241
|
+
})
|
|
84242
|
+
);
|
|
84243
|
+
}
|
|
84244
|
+
|
|
84245
|
+
// src/tools/protocol.ts
|
|
84246
|
+
function registerProtocolTools(server, getB) {
|
|
84247
|
+
registerBoundaryTool(
|
|
84248
|
+
server,
|
|
84249
|
+
"protocol_status",
|
|
84250
|
+
{
|
|
84251
|
+
title: "Get protocol configuration and status",
|
|
84252
|
+
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.",
|
|
84253
|
+
inputSchema: {}
|
|
84254
|
+
},
|
|
84255
|
+
async () => guarded(async () => {
|
|
84256
|
+
const b = getB();
|
|
84257
|
+
if (!b.ok) return renderError(b.error);
|
|
84258
|
+
return renderEnvelope(await b.boundary.getProtocolStatus());
|
|
84259
|
+
})
|
|
84260
|
+
);
|
|
84261
|
+
registerBoundaryTool(
|
|
84262
|
+
server,
|
|
84263
|
+
"protocol_terms",
|
|
84264
|
+
{
|
|
84265
|
+
title: "List available loan terms with fees",
|
|
84266
|
+
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.",
|
|
84267
|
+
inputSchema: {}
|
|
84268
|
+
},
|
|
84269
|
+
async () => guarded(async () => {
|
|
84270
|
+
const b = getB();
|
|
84271
|
+
if (!b.ok) return renderError(b.error);
|
|
84272
|
+
return renderEnvelope(await b.boundary.getTerms());
|
|
84273
|
+
})
|
|
84274
|
+
);
|
|
84275
|
+
}
|
|
84276
|
+
|
|
84277
|
+
// src/tools/psm.ts
|
|
84278
|
+
var import_zod4 = require("zod");
|
|
84279
|
+
var confirmedSchema2 = import_zod4.z.boolean().optional().describe(
|
|
84280
|
+
"Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
|
|
84281
|
+
);
|
|
84282
|
+
var DESTRUCTIVE_WRITE_ANNOTATIONS2 = {
|
|
84283
|
+
readOnlyHint: false,
|
|
84284
|
+
destructiveHint: true,
|
|
84285
|
+
idempotentHint: false,
|
|
84286
|
+
openWorldHint: true
|
|
84074
84287
|
};
|
|
84075
|
-
|
|
84288
|
+
function registerPsmTools(server, getB) {
|
|
84289
|
+
registerBoundaryTool(
|
|
84290
|
+
server,
|
|
84291
|
+
"psm_quote",
|
|
84292
|
+
{
|
|
84293
|
+
title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
|
|
84294
|
+
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.",
|
|
84295
|
+
inputSchema: {
|
|
84296
|
+
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)"),
|
|
84297
|
+
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
|
|
84298
|
+
},
|
|
84299
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
|
|
84300
|
+
},
|
|
84301
|
+
async ({ direction, amount }) => guarded(async () => {
|
|
84302
|
+
const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
|
|
84303
|
+
const problem = checkUcdAmount(amount, label);
|
|
84304
|
+
if (problem) return validationFailed(problem);
|
|
84305
|
+
const b = getB();
|
|
84306
|
+
if (!b.ok) return renderError(b.error);
|
|
84307
|
+
return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
|
|
84308
|
+
})
|
|
84309
|
+
);
|
|
84310
|
+
registerBoundaryTool(
|
|
84311
|
+
server,
|
|
84312
|
+
"psm_swap",
|
|
84313
|
+
{
|
|
84314
|
+
title: "Exchange UCD \u2194 USDC through the PSM",
|
|
84315
|
+
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).",
|
|
84316
|
+
inputSchema: {
|
|
84317
|
+
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)"),
|
|
84318
|
+
amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
|
|
84319
|
+
confirmed: confirmedSchema2
|
|
84320
|
+
},
|
|
84321
|
+
annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
|
|
84322
|
+
},
|
|
84323
|
+
async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
|
|
84324
|
+
const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
|
|
84325
|
+
const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
|
|
84326
|
+
const gate = requireConfirmation(
|
|
84327
|
+
confirmed,
|
|
84328
|
+
`exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
|
|
84329
|
+
);
|
|
84330
|
+
if (gate) return gate;
|
|
84331
|
+
const problem = checkUcdAmount(amount, `Amount (${inputToken})`);
|
|
84332
|
+
if (problem) return validationFailed(problem);
|
|
84333
|
+
const b = getB();
|
|
84334
|
+
if (!b.ok) return renderError(b.error);
|
|
84335
|
+
return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
|
|
84336
|
+
})
|
|
84337
|
+
);
|
|
84338
|
+
}
|
|
84076
84339
|
|
|
84077
|
-
|
|
84078
|
-
|
|
84079
|
-
|
|
84080
|
-
-
|
|
84081
|
-
-
|
|
84082
|
-
-
|
|
84083
|
-
-
|
|
84084
|
-
-
|
|
84085
|
-
-
|
|
84086
|
-
-
|
|
84087
|
-
|
|
84088
|
-
-
|
|
84089
|
-
-
|
|
84090
|
-
-
|
|
84091
|
-
-
|
|
84340
|
+
// src/tools/mock-control.ts
|
|
84341
|
+
var import_zod5 = require("zod");
|
|
84342
|
+
var ACTIONS = [
|
|
84343
|
+
"submit-deposit",
|
|
84344
|
+
"confirm-deposit",
|
|
84345
|
+
"confirm-spend-consumed",
|
|
84346
|
+
"advance-time",
|
|
84347
|
+
"set-btc-price",
|
|
84348
|
+
"set-paused",
|
|
84349
|
+
"set-wallet",
|
|
84350
|
+
"liquidate",
|
|
84351
|
+
"deploy-safe",
|
|
84352
|
+
"revoke-agent",
|
|
84353
|
+
"inject-fault",
|
|
84354
|
+
"clear-fault",
|
|
84355
|
+
"psm-set-paused",
|
|
84356
|
+
"psm-set-redeem-enabled",
|
|
84357
|
+
"psm-set-reserves",
|
|
84358
|
+
"psm-set-fees",
|
|
84359
|
+
"psm-mint-usdc"
|
|
84360
|
+
];
|
|
84361
|
+
function requireField(value, name, action) {
|
|
84362
|
+
if (value === void 0) {
|
|
84363
|
+
throw new Error(`action '${action}' requires '${name}'`);
|
|
84364
|
+
}
|
|
84365
|
+
return value;
|
|
84366
|
+
}
|
|
84367
|
+
function run(control, a, chainId) {
|
|
84368
|
+
switch (a.action) {
|
|
84369
|
+
case "submit-deposit": {
|
|
84370
|
+
const txid = control.submitDeposit(requireField(a.positionId, "positionId", a.action), requireField(a.sats, "sats", a.action));
|
|
84371
|
+
return { simulated: "bitcoin deposit broadcast (0 confirmations)", txid };
|
|
84372
|
+
}
|
|
84373
|
+
case "confirm-deposit": {
|
|
84374
|
+
const r = control.confirmDeposit(requireField(a.txid, "txid", a.action), requireField(a.confirmations, "confirmations", a.action));
|
|
84375
|
+
return { simulated: "bitcoin confirmations observed", txid: a.txid, folded: r.folded };
|
|
84376
|
+
}
|
|
84377
|
+
case "confirm-spend-consumed": {
|
|
84378
|
+
control.confirmSpendConsumed(
|
|
84379
|
+
requireField(a.txid, "txid", a.action),
|
|
84380
|
+
requireField(a.invalidatorTxid, "invalidatorTxid", a.action),
|
|
84381
|
+
requireField(a.confirmations, "confirmations", a.action)
|
|
84382
|
+
);
|
|
84383
|
+
return { simulated: "reserved spend consumed on bitcoin", txid: a.txid };
|
|
84384
|
+
}
|
|
84385
|
+
case "advance-time": {
|
|
84386
|
+
control.advanceTime(requireField(a.seconds, "seconds", a.action));
|
|
84387
|
+
return { simulated: "virtual clock advanced", seconds: a.seconds };
|
|
84388
|
+
}
|
|
84389
|
+
case "set-btc-price": {
|
|
84390
|
+
control.setBtcPrice(requireField(a.priceUsd8, "priceUsd8", a.action));
|
|
84391
|
+
return { simulated: "oracle price set", priceUsd8: a.priceUsd8 };
|
|
84392
|
+
}
|
|
84393
|
+
case "set-paused": {
|
|
84394
|
+
control.setPaused(requireField(a.paused, "paused", a.action));
|
|
84395
|
+
return { simulated: "protocol pause flag set", paused: a.paused };
|
|
84396
|
+
}
|
|
84397
|
+
case "set-wallet": {
|
|
84398
|
+
control.setWalletStance(requireField(a.stance, "stance", a.action));
|
|
84399
|
+
return { simulated: "wallet signature stance set (mock ceremony)", stance: a.stance };
|
|
84400
|
+
}
|
|
84401
|
+
case "liquidate": {
|
|
84402
|
+
control.liquidate(requireField(a.positionId, "positionId", a.action));
|
|
84403
|
+
return { simulated: "liquidation executed", positionId: a.positionId };
|
|
84404
|
+
}
|
|
84405
|
+
case "deploy-safe": {
|
|
84406
|
+
const safe = control.deploySafe({
|
|
84407
|
+
owners: requireField(a.owners, "owners", a.action),
|
|
84408
|
+
threshold: requireField(a.threshold, "threshold", a.action),
|
|
84409
|
+
chainId
|
|
84410
|
+
});
|
|
84411
|
+
return { simulated: "mock Safe deployed (plan 06 test lever \u2014 on the real protocol the user brings their own Safe)", ...safe };
|
|
84412
|
+
}
|
|
84413
|
+
case "revoke-agent": {
|
|
84414
|
+
const r = control.revokeAgent(requireField(a.safeAddress, "safeAddress", a.action));
|
|
84415
|
+
return {
|
|
84416
|
+
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)",
|
|
84417
|
+
...r
|
|
84418
|
+
};
|
|
84419
|
+
}
|
|
84420
|
+
case "inject-fault": {
|
|
84421
|
+
control.injectFault(requireField(a.faultKey, "faultKey", a.action), a.faultParams ?? {});
|
|
84422
|
+
return { simulated: "fault armed", faultKey: a.faultKey };
|
|
84423
|
+
}
|
|
84424
|
+
case "clear-fault": {
|
|
84425
|
+
control.clearFault(requireField(a.faultKey, "faultKey", a.action));
|
|
84426
|
+
return { simulated: "fault cleared", faultKey: a.faultKey };
|
|
84427
|
+
}
|
|
84428
|
+
case "psm-set-paused": {
|
|
84429
|
+
control.psmSetPaused(requireField(a.paused, "paused", a.action));
|
|
84430
|
+
return { simulated: "PSM pause switch set (the PSM's OWN pause, not the lending protocol's)", paused: a.paused };
|
|
84431
|
+
}
|
|
84432
|
+
case "psm-set-redeem-enabled": {
|
|
84433
|
+
control.psmSetRedeemEnabled(requireField(a.enabled, "enabled", a.action));
|
|
84434
|
+
return { simulated: "PSM redeemEnabled switch set (kills the UCD -> USDC direction only)", enabled: a.enabled };
|
|
84435
|
+
}
|
|
84436
|
+
case "psm-set-reserves": {
|
|
84437
|
+
control.psmSetReserves(requireField(a.reserves, "reserves", a.action));
|
|
84438
|
+
return { simulated: "PSM stablecoin reserves set", reserves: a.reserves };
|
|
84439
|
+
}
|
|
84440
|
+
case "psm-mint-usdc": {
|
|
84441
|
+
const r = control.psmMintUsdc(
|
|
84442
|
+
requireField(a.holder, "holder", a.action),
|
|
84443
|
+
requireField(a.usdcUnits, "usdcUnits", a.action)
|
|
84444
|
+
);
|
|
84445
|
+
return {
|
|
84446
|
+
simulated: "practice USDC minted (mirror of the sepolia mock USDC's public self-serve mint)",
|
|
84447
|
+
holder: a.holder,
|
|
84448
|
+
minted: a.usdcUnits,
|
|
84449
|
+
newBalanceUnits: r.newBalanceUnits
|
|
84450
|
+
};
|
|
84451
|
+
}
|
|
84452
|
+
case "psm-set-fees": {
|
|
84453
|
+
control.psmSetFees({
|
|
84454
|
+
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
84455
|
+
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
84456
|
+
});
|
|
84457
|
+
return {
|
|
84458
|
+
simulated: "PSM fees set (entry fee charged in UCD; exit fee charged in USDC)",
|
|
84459
|
+
...a.entryFeeBps !== void 0 ? { entryFeeBps: a.entryFeeBps } : {},
|
|
84460
|
+
...a.exitFeeBps !== void 0 ? { exitFeeBps: a.exitFeeBps } : {}
|
|
84461
|
+
};
|
|
84462
|
+
}
|
|
84463
|
+
}
|
|
84464
|
+
}
|
|
84465
|
+
function registerMockControlTool(server, control, chainId = 1337) {
|
|
84466
|
+
registerBoundaryTool(
|
|
84467
|
+
server,
|
|
84468
|
+
"mock_control",
|
|
84469
|
+
{
|
|
84470
|
+
title: "SIMULATOR control (mock world only)",
|
|
84471
|
+
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.",
|
|
84472
|
+
inputSchema: {
|
|
84473
|
+
action: import_zod5.z.enum(ACTIONS).describe("Simulator lever to pull"),
|
|
84474
|
+
positionId: import_zod5.z.string().optional().describe("submit-deposit, liquidate"),
|
|
84475
|
+
txid: import_zod5.z.string().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
84476
|
+
sats: import_zod5.z.string().optional().describe("submit-deposit: amount in satoshis (decimal string)"),
|
|
84477
|
+
confirmations: import_zod5.z.number().int().nonnegative().optional().describe("confirm-deposit, confirm-spend-consumed"),
|
|
84478
|
+
invalidatorTxid: import_zod5.z.string().optional().describe("confirm-spend-consumed"),
|
|
84479
|
+
seconds: import_zod5.z.number().int().positive().optional().describe("advance-time"),
|
|
84480
|
+
priceUsd8: import_zod5.z.string().optional().describe("set-btc-price: USD price with 8 decimals (decimal string)"),
|
|
84481
|
+
paused: import_zod5.z.boolean().optional().describe("set-paused (protocol), psm-set-paused (PSM's own switch)"),
|
|
84482
|
+
stance: import_zod5.z.enum(["approve", "decline"]).optional().describe("set-wallet: the simulated wallet's signature stance"),
|
|
84483
|
+
owners: import_zod5.z.array(import_zod5.z.string()).optional().describe("deploy-safe: owner addresses"),
|
|
84484
|
+
threshold: import_zod5.z.number().int().positive().optional().describe("deploy-safe: required signatures (M of N)"),
|
|
84485
|
+
safeAddress: import_zod5.z.string().optional().describe("revoke-agent: the Safe whose agent is revoked (AR-1 burn)"),
|
|
84486
|
+
faultKey: import_zod5.z.string().optional().describe("inject-fault, clear-fault"),
|
|
84487
|
+
faultParams: import_zod5.z.record(import_zod5.z.unknown()).optional().describe("inject-fault params (each fault's params are required)"),
|
|
84488
|
+
enabled: import_zod5.z.boolean().optional().describe("psm-set-redeem-enabled"),
|
|
84489
|
+
reserves: import_zod5.z.string().optional().describe("psm-set-reserves: stablecoin smallest units (decimal string)"),
|
|
84490
|
+
entryFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: entry fee bps (charged in UCD)"),
|
|
84491
|
+
exitFeeBps: import_zod5.z.number().int().nonnegative().optional().describe("psm-set-fees: exit fee bps (charged in USDC, max 1000)"),
|
|
84492
|
+
holder: import_zod5.z.string().optional().describe("psm-mint-usdc: address receiving the practice USDC"),
|
|
84493
|
+
usdcUnits: import_zod5.z.string().optional().describe("psm-mint-usdc: amount in USDC smallest units (decimal string)")
|
|
84494
|
+
},
|
|
84495
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
|
|
84496
|
+
},
|
|
84497
|
+
async (args) => guarded(async () => {
|
|
84498
|
+
let result;
|
|
84499
|
+
try {
|
|
84500
|
+
result = run(control, args, chainId);
|
|
84501
|
+
} catch (e) {
|
|
84502
|
+
return validationFailed(e.message);
|
|
84503
|
+
}
|
|
84504
|
+
if (result === void 0) {
|
|
84505
|
+
return renderError(boundaryError("INTERNAL", `unhandled mock_control action '${args.action}'`));
|
|
84506
|
+
}
|
|
84507
|
+
return { content: [{ type: "text", text: serialize(result) }] };
|
|
84508
|
+
})
|
|
84509
|
+
);
|
|
84510
|
+
}
|
|
84092
84511
|
|
|
84093
|
-
|
|
84094
|
-
|
|
84095
|
-
|
|
84096
|
-
|
|
84097
|
-
|
|
84512
|
+
// src/tools/signer.ts
|
|
84513
|
+
var import_zod6 = require("zod");
|
|
84514
|
+
var import_ethers42 = require("ethers");
|
|
84515
|
+
var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
|
|
84516
|
+
var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
|
|
84517
|
+
var EXTERNAL_ONLY_MODES = ["external"];
|
|
84518
|
+
var EXTERNAL_ONLY_ACTIONS = ["status", "use", "reset-borrower", "connect", "disconnect"];
|
|
84519
|
+
function looksSecretShaped(value) {
|
|
84520
|
+
return /^0x[0-9a-fA-F]{32,}$/.test(value) || value.length >= 16 && !/\s/.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value);
|
|
84521
|
+
}
|
|
84522
|
+
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.";
|
|
84523
|
+
function registerSignerTool(server, getRuntime, opts) {
|
|
84524
|
+
const externalOnly = opts?.externalOnly === true;
|
|
84525
|
+
const offeredModes = externalOnly ? EXTERNAL_ONLY_MODES : MODES;
|
|
84526
|
+
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.";
|
|
84527
|
+
registerBoundaryTool(
|
|
84528
|
+
server,
|
|
84529
|
+
"signer_setup",
|
|
84530
|
+
{
|
|
84531
|
+
title: "Choose how operations are authorized",
|
|
84532
|
+
description,
|
|
84533
|
+
inputSchema: {
|
|
84534
|
+
action: (externalOnly ? import_zod6.z.enum(EXTERNAL_ONLY_ACTIONS) : import_zod6.z.enum(ACTIONS2)).describe("What to do \u2014 'status' explains everything"),
|
|
84535
|
+
mode: import_zod6.z.string().optional().describe(`For 'use': ${offeredModes.join(" | ")}`),
|
|
84536
|
+
...externalOnly ? {} : {
|
|
84537
|
+
safeAddress: import_zod6.z.string().optional().describe("For 'use safe'/'use safe-module': the Safe's 0x address (the borrowing identity)")
|
|
84538
|
+
}
|
|
84539
|
+
},
|
|
84540
|
+
annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false }
|
|
84541
|
+
},
|
|
84542
|
+
async ({ action, mode, safeAddress }) => guarded(async () => {
|
|
84543
|
+
const runtime = getRuntime();
|
|
84544
|
+
if (!runtime) {
|
|
84545
|
+
return renderError(
|
|
84546
|
+
boundaryError(
|
|
84547
|
+
"SIGNER_UNAVAILABLE",
|
|
84548
|
+
"no signer runtime is live \u2014 the boundary failed to boot. Fix the configuration (or recover by switching networks via network_switch), then retry."
|
|
84549
|
+
)
|
|
84550
|
+
);
|
|
84551
|
+
}
|
|
84552
|
+
const { manager, bridge } = runtime;
|
|
84553
|
+
if (mode !== void 0 && !offeredModes.includes(mode)) {
|
|
84554
|
+
return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
|
|
84555
|
+
}
|
|
84556
|
+
if (safeAddress !== void 0 && !import_ethers42.ethers.isAddress(safeAddress)) {
|
|
84557
|
+
return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
|
|
84558
|
+
}
|
|
84559
|
+
if (action === "status") {
|
|
84560
|
+
await bridge.start();
|
|
84561
|
+
const s = manager.status();
|
|
84562
|
+
return ok({
|
|
84563
|
+
...s,
|
|
84564
|
+
// Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
|
|
84565
|
+
// identity is known. borrower = a persisted binding; candidate = a live
|
|
84566
|
+
// wallet connection in THIS process only.
|
|
84567
|
+
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",
|
|
84568
|
+
approvalPageUrl: bridge.url(),
|
|
84569
|
+
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.`
|
|
84570
|
+
});
|
|
84571
|
+
}
|
|
84572
|
+
if (action === "use") {
|
|
84573
|
+
if (!mode) return validationFailed(`action 'use' requires 'mode' (${offeredModes.join(" | ")})`);
|
|
84574
|
+
const r = await manager.use(mode, safeAddress !== void 0 ? { safeAddress } : void 0);
|
|
84575
|
+
if (!r.ok) return validationFailed(r.reason);
|
|
84576
|
+
if (mode === "safe-module") {
|
|
84577
|
+
const s = manager.status();
|
|
84578
|
+
return ok({
|
|
84579
|
+
mode,
|
|
84580
|
+
safe: s.safe,
|
|
84581
|
+
agent: s.keystoreAddress,
|
|
84582
|
+
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'."
|
|
84583
|
+
});
|
|
84584
|
+
}
|
|
84585
|
+
if (mode === "safe") {
|
|
84586
|
+
const s = manager.status();
|
|
84587
|
+
return ok({
|
|
84588
|
+
mode,
|
|
84589
|
+
safe: s.safe,
|
|
84590
|
+
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."
|
|
84591
|
+
});
|
|
84592
|
+
}
|
|
84593
|
+
if (mode === "external") {
|
|
84594
|
+
await bridge.start();
|
|
84595
|
+
return ok({
|
|
84596
|
+
mode,
|
|
84597
|
+
approvalPageUrl: bridge.url(),
|
|
84598
|
+
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."
|
|
84599
|
+
});
|
|
84600
|
+
}
|
|
84601
|
+
return ok({ mode, next: mode === "keystore" ? "Keystore ready \u2014 operations sign automatically after each confirmed:true." : "Simulated ceremony active (test worlds only)." });
|
|
84602
|
+
}
|
|
84603
|
+
if (action === "connect") {
|
|
84604
|
+
if (!runtime.connect) {
|
|
84605
|
+
return validationFailed(
|
|
84606
|
+
"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."
|
|
84607
|
+
);
|
|
84608
|
+
}
|
|
84609
|
+
const r = await runtime.connect();
|
|
84610
|
+
if (!r.ok) return validationFailed(r.reason);
|
|
84611
|
+
const login = r.usedCachedSession === true ? "cached-session" : "fresh-signature";
|
|
84612
|
+
return ok({
|
|
84613
|
+
connected: true,
|
|
84614
|
+
address: r.address,
|
|
84615
|
+
login,
|
|
84616
|
+
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."
|
|
84617
|
+
});
|
|
84618
|
+
}
|
|
84619
|
+
if (action === "disconnect") {
|
|
84620
|
+
if (!runtime.disconnect) {
|
|
84621
|
+
return validationFailed(
|
|
84622
|
+
"this construction has no wallet plane to disconnect \u2014 there is no signer runtime behind this tool."
|
|
84623
|
+
);
|
|
84624
|
+
}
|
|
84625
|
+
const report = await runtime.disconnect();
|
|
84626
|
+
const f = report.flushed;
|
|
84627
|
+
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)`;
|
|
84628
|
+
return ok({
|
|
84629
|
+
disconnected: true,
|
|
84630
|
+
mode: manager.mode(),
|
|
84631
|
+
flushed: {
|
|
84632
|
+
...f,
|
|
84633
|
+
note: tokenLine
|
|
84634
|
+
},
|
|
84635
|
+
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).",
|
|
84636
|
+
// Plan 17 F2 — hosted tier: the honesty split. This verb ends the WALLET
|
|
84637
|
+
// relationship; the OAuth session is a separate thing with its own revocation.
|
|
84638
|
+
// Neither claims to do the other's job.
|
|
84639
|
+
...bridge.isHosted() ? {
|
|
84640
|
+
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."
|
|
84641
|
+
} : {},
|
|
84642
|
+
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').`
|
|
84643
|
+
});
|
|
84644
|
+
}
|
|
84645
|
+
if (action === "reset-borrower") {
|
|
84646
|
+
manager.resetBorrower();
|
|
84647
|
+
return ok({
|
|
84648
|
+
reset: true,
|
|
84649
|
+
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."
|
|
84650
|
+
});
|
|
84651
|
+
}
|
|
84652
|
+
await bridge.start();
|
|
84653
|
+
const unlockUrl = bridge.unlockUrl();
|
|
84654
|
+
return ok({
|
|
84655
|
+
unlockPageUrl: unlockUrl,
|
|
84656
|
+
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'."
|
|
84657
|
+
});
|
|
84658
|
+
})
|
|
84659
|
+
);
|
|
84660
|
+
}
|
|
84661
|
+
function ok(data) {
|
|
84662
|
+
return { content: [{ type: "text", text: serialize(data) }] };
|
|
84663
|
+
}
|
|
84098
84664
|
|
|
84099
84665
|
// src/tools/guide.ts
|
|
84100
|
-
|
|
84666
|
+
var import_zod7 = require("zod");
|
|
84667
|
+
function registerGuideTool(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
|
|
84668
|
+
const content = buildGuideContent(deployment);
|
|
84669
|
+
const index = buildGuideIndex(deployment);
|
|
84101
84670
|
registerBoundaryTool(
|
|
84102
84671
|
server,
|
|
84103
84672
|
"guide",
|
|
@@ -84111,26 +84680,31 @@ function registerGuideTool(server) {
|
|
|
84111
84680
|
},
|
|
84112
84681
|
async ({ topic }) => guarded(async () => {
|
|
84113
84682
|
if (topic === void 0 || topic === "") {
|
|
84114
|
-
return { content: [{ type: "text", text:
|
|
84683
|
+
return { content: [{ type: "text", text: index }] };
|
|
84115
84684
|
}
|
|
84116
84685
|
if (!GUIDE_TOPICS.includes(topic)) {
|
|
84117
84686
|
return validationFailed(`unknown guide topic '${topic}' \u2014 available: ${GUIDE_TOPICS.join(" | ")}`);
|
|
84118
84687
|
}
|
|
84119
|
-
return { content: [{ type: "text", text:
|
|
84688
|
+
return { content: [{ type: "text", text: content[topic] }] };
|
|
84120
84689
|
})
|
|
84121
84690
|
);
|
|
84122
84691
|
}
|
|
84123
|
-
function registerGuideResources(server) {
|
|
84692
|
+
function registerGuideResources(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
|
|
84693
|
+
const content = buildGuideContent(deployment);
|
|
84694
|
+
const index = buildGuideIndex(deployment);
|
|
84124
84695
|
for (const topic of GUIDE_TOPICS) {
|
|
84125
84696
|
server.resource(`guide-${topic}`, `guide://${topic}`, async () => ({
|
|
84126
|
-
contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text:
|
|
84697
|
+
contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: content[topic] }]
|
|
84127
84698
|
}));
|
|
84128
84699
|
}
|
|
84129
84700
|
server.resource("guide-index", "guide://index", async () => ({
|
|
84130
|
-
contents: [{ uri: "guide://index", mimeType: "text/markdown", text:
|
|
84701
|
+
contents: [{ uri: "guide://index", mimeType: "text/markdown", text: index }]
|
|
84131
84702
|
}));
|
|
84132
84703
|
}
|
|
84133
|
-
function
|
|
84704
|
+
function onboardAuthorizationLine(deployment) {
|
|
84705
|
+
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. ";
|
|
84706
|
+
}
|
|
84707
|
+
function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
|
|
84134
84708
|
server.prompt(
|
|
84135
84709
|
"onboard-me",
|
|
84136
84710
|
"Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
|
|
@@ -84140,7 +84714,7 @@ function registerGuidePrompts(server) {
|
|
|
84140
84714
|
role: "user",
|
|
84141
84715
|
content: {
|
|
84142
84716
|
type: "text",
|
|
84143
|
-
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;
|
|
84717
|
+
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."
|
|
84144
84718
|
}
|
|
84145
84719
|
}
|
|
84146
84720
|
]
|
|
@@ -84376,8 +84950,10 @@ function registerBoundaryInfoResource(server, getB) {
|
|
|
84376
84950
|
);
|
|
84377
84951
|
}
|
|
84378
84952
|
|
|
84953
|
+
// src/version.ts
|
|
84954
|
+
var SERVER_VERSION = "0.5.11";
|
|
84955
|
+
|
|
84379
84956
|
// src/server.ts
|
|
84380
|
-
var SERVER_VERSION = "0.5.3";
|
|
84381
84957
|
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.";
|
|
84382
84958
|
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'.";
|
|
84383
84959
|
function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
|
|
@@ -84397,9 +84973,9 @@ function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
|
|
|
84397
84973
|
registerPositionResource(server, getB);
|
|
84398
84974
|
registerProtocolResources(server, getB);
|
|
84399
84975
|
registerBoundaryInfoResource(server, getB);
|
|
84400
|
-
registerGuideTool(server);
|
|
84401
|
-
registerGuideResources(server);
|
|
84402
|
-
registerGuidePrompts(server);
|
|
84976
|
+
registerGuideTool(server, deps.deployment);
|
|
84977
|
+
registerGuideResources(server, deps.deployment);
|
|
84978
|
+
registerGuidePrompts(server, deps.deployment);
|
|
84403
84979
|
if (deps.mockControl) {
|
|
84404
84980
|
registerMockControlTool(server, deps.mockControl, deps.chainId);
|
|
84405
84981
|
}
|
|
@@ -84417,8 +84993,43 @@ var DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1e3;
|
|
|
84417
84993
|
var DEFAULT_WORLD_IDLE_MS = 60 * 60 * 1e3;
|
|
84418
84994
|
var DEFAULT_TENANT_PER_MIN = 120;
|
|
84419
84995
|
var DEFAULT_GLOBAL_PER_MIN = 600;
|
|
84996
|
+
var DEFAULT_MAX_TENANTS = 200;
|
|
84997
|
+
var DEFAULT_MAX_SESSIONS_PER_TENANT = 16;
|
|
84998
|
+
var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
|
|
84999
|
+
var DEFAULT_TRUST_PROXY_HOPS = 1;
|
|
85000
|
+
function normalizePublicOrigin(raw) {
|
|
85001
|
+
const trimmed = raw.trim().replace(/\/+$/, "");
|
|
85002
|
+
let url2;
|
|
85003
|
+
try {
|
|
85004
|
+
url2 = new URL(trimmed);
|
|
85005
|
+
} catch {
|
|
85006
|
+
throw new Error(
|
|
85007
|
+
`connector: publicOrigin is not a valid URL (${trimmed.length} chars). The value is not echoed here \u2014 see below for why.`
|
|
85008
|
+
);
|
|
85009
|
+
}
|
|
85010
|
+
const problems = [];
|
|
85011
|
+
if (url2.protocol !== "https:" && url2.protocol !== "http:") problems.push(`scheme '${url2.protocol}' (want http or https)`);
|
|
85012
|
+
if (url2.username !== "" || url2.password !== "") problems.push("embedded credentials");
|
|
85013
|
+
if (url2.pathname !== "/" && url2.pathname !== "") problems.push("a path");
|
|
85014
|
+
if (url2.search !== "") problems.push("a query string");
|
|
85015
|
+
if (url2.hash !== "") problems.push("a fragment");
|
|
85016
|
+
if (problems.length > 0) {
|
|
85017
|
+
throw new Error(
|
|
85018
|
+
`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.`
|
|
85019
|
+
);
|
|
85020
|
+
}
|
|
85021
|
+
return url2.origin;
|
|
85022
|
+
}
|
|
85023
|
+
function requireSafeCount(value, fallback, name, min) {
|
|
85024
|
+
if (value === void 0) return fallback;
|
|
85025
|
+
if (!Number.isSafeInteger(value) || value < min) {
|
|
85026
|
+
throw new Error(`connector: ${name}=${String(value)} must be a safe integer >= ${min}`);
|
|
85027
|
+
}
|
|
85028
|
+
return value;
|
|
85029
|
+
}
|
|
84420
85030
|
var RATE_WINDOW_MS = 60 * 1e3;
|
|
84421
|
-
function composeConnector(opts,
|
|
85031
|
+
function composeConnector(opts, rawPublicOrigin) {
|
|
85032
|
+
const publicOrigin = normalizePublicOrigin(rawPublicOrigin);
|
|
84422
85033
|
const allowedNetworks = opts.allowedNetworks ?? ["sepolia"];
|
|
84423
85034
|
if (allowedNetworks.length === 0) throw new Error("connector service: allowedNetworks must name at least one network");
|
|
84424
85035
|
const launchNetwork = allowedNetworks[0];
|
|
@@ -84427,6 +85038,10 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84427
85038
|
const worldIdleMs = opts.idle?.worldMs ?? DEFAULT_WORLD_IDLE_MS;
|
|
84428
85039
|
const tenantPerMin = opts.rateLimits?.tenantPerMin ?? DEFAULT_TENANT_PER_MIN;
|
|
84429
85040
|
const globalPerMin = opts.rateLimits?.globalPerMin ?? DEFAULT_GLOBAL_PER_MIN;
|
|
85041
|
+
const maxTenants = requireSafeCount(opts.maxTenants, DEFAULT_MAX_TENANTS, "maxTenants", 1);
|
|
85042
|
+
const trustProxyHops = requireSafeCount(opts.trustProxyHops, DEFAULT_TRUST_PROXY_HOPS, "trustProxyHops", 0);
|
|
85043
|
+
const maxSessionsPerTenant = requireSafeCount(opts.maxSessionsPerTenant, DEFAULT_MAX_SESSIONS_PER_TENANT, "maxSessionsPerTenant", 1);
|
|
85044
|
+
const maxBodyBytes = requireSafeCount(opts.maxBodyBytes, DEFAULT_MAX_BODY_BYTES, "maxBodyBytes", 1024);
|
|
84430
85045
|
const worlds = /* @__PURE__ */ new Map();
|
|
84431
85046
|
const readyWorlds = /* @__PURE__ */ new Map();
|
|
84432
85047
|
const sessions = /* @__PURE__ */ new Map();
|
|
@@ -84456,7 +85071,7 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84456
85071
|
}
|
|
84457
85072
|
async function buildWorld(tenantKey) {
|
|
84458
85073
|
const stores = /* @__PURE__ */ new Map();
|
|
84459
|
-
const mountId = (0,
|
|
85074
|
+
const mountId = (0, import_node_crypto10.randomUUID)().replaceAll("-", "");
|
|
84460
85075
|
const overrides = {
|
|
84461
85076
|
externalOnly: true,
|
|
84462
85077
|
allowedNetworks,
|
|
@@ -84498,6 +85113,17 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84498
85113
|
process.stderr.write(`[dh-mcp-connector] ${why}: world for tenant ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} disposed
|
|
84499
85114
|
`);
|
|
84500
85115
|
}
|
|
85116
|
+
function tenantsWithSessions() {
|
|
85117
|
+
const held = /* @__PURE__ */ new Set();
|
|
85118
|
+
for (const session of sessions.values()) held.add(session.tenant);
|
|
85119
|
+
return held;
|
|
85120
|
+
}
|
|
85121
|
+
function isReclaimable(tenantKey, world, held) {
|
|
85122
|
+
if (held.has(tenantKey)) return false;
|
|
85123
|
+
const bridge = world.deps.signer?.bridge;
|
|
85124
|
+
if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
|
|
85125
|
+
return true;
|
|
85126
|
+
}
|
|
84501
85127
|
function sweepService() {
|
|
84502
85128
|
const now = clock();
|
|
84503
85129
|
for (const [sid, session] of [...sessions]) {
|
|
@@ -84506,18 +85132,43 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84506
85132
|
void session.transport.close().catch(() => void 0);
|
|
84507
85133
|
}
|
|
84508
85134
|
}
|
|
85135
|
+
const held = tenantsWithSessions();
|
|
84509
85136
|
for (const [tenantKey, world] of [...readyWorlds]) {
|
|
84510
|
-
|
|
84511
|
-
if (hasSession) continue;
|
|
84512
|
-
const bridge = world.deps.signer?.bridge;
|
|
84513
|
-
if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) continue;
|
|
85137
|
+
if (!isReclaimable(tenantKey, world, held)) continue;
|
|
84514
85138
|
if (now - (lastActivity.get(tenantKey) ?? 0) <= worldIdleMs) continue;
|
|
84515
85139
|
dropWorld(tenantKey, world, "idle eviction");
|
|
84516
85140
|
}
|
|
84517
85141
|
}
|
|
85142
|
+
function reclaimIdleWorld() {
|
|
85143
|
+
const held = tenantsWithSessions();
|
|
85144
|
+
let victimKey = null;
|
|
85145
|
+
let victim = null;
|
|
85146
|
+
let oldest = Number.POSITIVE_INFINITY;
|
|
85147
|
+
for (const [tenantKey, world] of readyWorlds) {
|
|
85148
|
+
if (!isReclaimable(tenantKey, world, held)) continue;
|
|
85149
|
+
const activeAt = lastActivity.get(tenantKey) ?? 0;
|
|
85150
|
+
if (activeAt < oldest) {
|
|
85151
|
+
oldest = activeAt;
|
|
85152
|
+
victimKey = tenantKey;
|
|
85153
|
+
victim = world;
|
|
85154
|
+
}
|
|
85155
|
+
}
|
|
85156
|
+
if (victimKey === null || victim === null) return false;
|
|
85157
|
+
dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
|
|
85158
|
+
return true;
|
|
85159
|
+
}
|
|
85160
|
+
class TenantCapacityError extends Error {
|
|
85161
|
+
}
|
|
84518
85162
|
function worldFor(tenantKey) {
|
|
84519
85163
|
let w = worlds.get(tenantKey);
|
|
84520
85164
|
if (!w) {
|
|
85165
|
+
if (worlds.size >= maxTenants && !reclaimIdleWorld()) {
|
|
85166
|
+
return Promise.reject(
|
|
85167
|
+
new TenantCapacityError(
|
|
85168
|
+
`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`
|
|
85169
|
+
)
|
|
85170
|
+
);
|
|
85171
|
+
}
|
|
84521
85172
|
w = buildWorld(tenantKey).catch((e) => {
|
|
84522
85173
|
worlds.delete(tenantKey);
|
|
84523
85174
|
throw e;
|
|
@@ -84526,16 +85177,75 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84526
85177
|
}
|
|
84527
85178
|
return w;
|
|
84528
85179
|
}
|
|
85180
|
+
function evictExcessSessions(tenantKey) {
|
|
85181
|
+
const mine = [...sessions].filter(([, s]) => s.tenant === tenantKey).sort((a, b) => a[1].lastSeen - b[1].lastSeen);
|
|
85182
|
+
for (let i = 0; i <= mine.length - maxSessionsPerTenant; i += 1) {
|
|
85183
|
+
const [sid, session] = mine[i];
|
|
85184
|
+
sessions.delete(sid);
|
|
85185
|
+
void session.transport.close().catch(() => void 0);
|
|
85186
|
+
process.stderr.write(
|
|
85187
|
+
`[dh-mcp-connector] session cap (${maxSessionsPerTenant}/tenant): oldest session for ${tenantKey.slice(0, 6)}\u2026${tenantKey.slice(-4)} closed to admit a new one
|
|
85188
|
+
`
|
|
85189
|
+
);
|
|
85190
|
+
}
|
|
85191
|
+
}
|
|
84529
85192
|
function deny(res, status, message) {
|
|
84530
85193
|
res.writeHead(status, { "content-type": "application/json" }).end(
|
|
84531
85194
|
JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message }, id: null })
|
|
84532
85195
|
);
|
|
84533
85196
|
}
|
|
84534
|
-
|
|
84535
|
-
|
|
84536
|
-
|
|
84537
|
-
|
|
84538
|
-
|
|
85197
|
+
function readBodyText(req) {
|
|
85198
|
+
return new Promise((resolve, reject) => {
|
|
85199
|
+
let raw = "";
|
|
85200
|
+
let bytes = 0;
|
|
85201
|
+
let settled = false;
|
|
85202
|
+
req.setEncoding("utf8");
|
|
85203
|
+
req.on("data", (chunk) => {
|
|
85204
|
+
if (settled) return;
|
|
85205
|
+
bytes += Buffer.byteLength(chunk, "utf8");
|
|
85206
|
+
if (bytes > maxBodyBytes) {
|
|
85207
|
+
settled = true;
|
|
85208
|
+
req.pause();
|
|
85209
|
+
resolve({ overflow: bytes });
|
|
85210
|
+
return;
|
|
85211
|
+
}
|
|
85212
|
+
raw += chunk;
|
|
85213
|
+
});
|
|
85214
|
+
req.on("end", () => {
|
|
85215
|
+
if (settled) return;
|
|
85216
|
+
settled = true;
|
|
85217
|
+
resolve({ text: raw });
|
|
85218
|
+
});
|
|
85219
|
+
req.on("error", (e) => {
|
|
85220
|
+
if (settled) return;
|
|
85221
|
+
settled = true;
|
|
85222
|
+
reject(e);
|
|
85223
|
+
});
|
|
85224
|
+
});
|
|
85225
|
+
}
|
|
85226
|
+
function refuseOversizedBody(req, res, why) {
|
|
85227
|
+
res.setHeader("Connection", "close");
|
|
85228
|
+
deny(res, 413, `request body too large (${why}) \u2014 this MCP endpoint accepts at most ${maxBodyBytes} bytes per JSON-RPC message`);
|
|
85229
|
+
res.once("finish", () => req.destroy());
|
|
85230
|
+
}
|
|
85231
|
+
async function readCappedBody(req, res) {
|
|
85232
|
+
const declared = Number(req.headers["content-length"]);
|
|
85233
|
+
if (Number.isFinite(declared) && declared > maxBodyBytes) {
|
|
85234
|
+
refuseOversizedBody(req, res, `declared ${declared} bytes`);
|
|
85235
|
+
return null;
|
|
85236
|
+
}
|
|
85237
|
+
const read = await readBodyText(req);
|
|
85238
|
+
if ("overflow" in read) {
|
|
85239
|
+
refuseOversizedBody(req, res, `exceeded the cap after ${read.overflow} bytes`);
|
|
85240
|
+
return null;
|
|
85241
|
+
}
|
|
85242
|
+
if (read.text.length === 0) return { body: void 0 };
|
|
85243
|
+
try {
|
|
85244
|
+
return { body: JSON.parse(read.text) };
|
|
85245
|
+
} catch {
|
|
85246
|
+
deny(res, 400, "request body is not valid JSON");
|
|
85247
|
+
return null;
|
|
85248
|
+
}
|
|
84539
85249
|
}
|
|
84540
85250
|
async function handle(req, res) {
|
|
84541
85251
|
const url2 = new URL(req.url ?? "/", "http://connector.local");
|
|
@@ -84559,6 +85269,10 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84559
85269
|
}
|
|
84560
85270
|
const tenant = await authImpl.tenant(req);
|
|
84561
85271
|
if (!tenant) {
|
|
85272
|
+
res.setHeader(
|
|
85273
|
+
"WWW-Authenticate",
|
|
85274
|
+
`Bearer resource_metadata="${publicOrigin}/.well-known/oauth-protected-resource"`
|
|
85275
|
+
);
|
|
84562
85276
|
deny(res, 401, "unauthorized \u2014 connect this MCP server through its authorization flow first");
|
|
84563
85277
|
return;
|
|
84564
85278
|
}
|
|
@@ -84580,6 +85294,12 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84580
85294
|
return;
|
|
84581
85295
|
}
|
|
84582
85296
|
session.lastSeen = clock();
|
|
85297
|
+
if (req.method === "POST") {
|
|
85298
|
+
const read2 = await readCappedBody(req, res);
|
|
85299
|
+
if (!read2) return;
|
|
85300
|
+
await session.transport.handleRequest(req, res, read2.body);
|
|
85301
|
+
return;
|
|
85302
|
+
}
|
|
84583
85303
|
await session.transport.handleRequest(req, res);
|
|
84584
85304
|
return;
|
|
84585
85305
|
}
|
|
@@ -84587,22 +85307,29 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84587
85307
|
deny(res, 400, "missing mcp-session-id \u2014 initialize first");
|
|
84588
85308
|
return;
|
|
84589
85309
|
}
|
|
84590
|
-
|
|
84591
|
-
|
|
84592
|
-
|
|
84593
|
-
} catch {
|
|
84594
|
-
deny(res, 400, "request body is not valid JSON");
|
|
84595
|
-
return;
|
|
84596
|
-
}
|
|
85310
|
+
const read = await readCappedBody(req, res);
|
|
85311
|
+
if (!read) return;
|
|
85312
|
+
const body = read.body;
|
|
84597
85313
|
if (!(0, import_types4.isInitializeRequest)(body)) {
|
|
84598
85314
|
deny(res, 400, "missing mcp-session-id \u2014 the only session-less request is initialize");
|
|
84599
85315
|
return;
|
|
84600
85316
|
}
|
|
84601
|
-
|
|
85317
|
+
let world;
|
|
85318
|
+
try {
|
|
85319
|
+
world = await worldFor(tenantKey);
|
|
85320
|
+
} catch (e) {
|
|
85321
|
+
if (e instanceof TenantCapacityError) {
|
|
85322
|
+
res.setHeader("Retry-After", "60");
|
|
85323
|
+
deny(res, 503, e.message);
|
|
85324
|
+
return;
|
|
85325
|
+
}
|
|
85326
|
+
throw e;
|
|
85327
|
+
}
|
|
84602
85328
|
const mcp = createServer2(world.deps, CONNECTOR_INSTRUCTIONS);
|
|
84603
85329
|
const transport = new import_streamableHttp.StreamableHTTPServerTransport({
|
|
84604
|
-
sessionIdGenerator: () => (0,
|
|
85330
|
+
sessionIdGenerator: () => (0, import_node_crypto10.randomUUID)(),
|
|
84605
85331
|
onsessioninitialized: (sessionId) => {
|
|
85332
|
+
evictExcessSessions(tenantKey);
|
|
84606
85333
|
sessions.set(sessionId, { transport, tenant: tenantKey, lastSeen: clock() });
|
|
84607
85334
|
}
|
|
84608
85335
|
});
|
|
@@ -84625,6 +85352,7 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84625
85352
|
});
|
|
84626
85353
|
}
|
|
84627
85354
|
const app = (0, import_express.default)();
|
|
85355
|
+
app.set("trust proxy", trustProxyHops);
|
|
84628
85356
|
app.use((_req, res, next) => {
|
|
84629
85357
|
if (!allowGlobal()) {
|
|
84630
85358
|
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`);
|
|
@@ -84683,7 +85411,38 @@ function composeConnector(opts, publicOrigin) {
|
|
|
84683
85411
|
const r = siwe.wcStatus(String(req.query["flowId"] ?? ""));
|
|
84684
85412
|
res.status(r.status).json(r.body);
|
|
84685
85413
|
});
|
|
84686
|
-
|
|
85414
|
+
const authMd = renderAuthMd({
|
|
85415
|
+
publicOrigin,
|
|
85416
|
+
networks: allowedNetworks,
|
|
85417
|
+
walletConnectEnabled: wcLeg !== void 0
|
|
85418
|
+
});
|
|
85419
|
+
app.get("/auth.md", (_req, res) => {
|
|
85420
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
85421
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
85422
|
+
res.setHeader("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'; base-uri 'none'");
|
|
85423
|
+
res.type("text/markdown; charset=utf-8").send(authMd);
|
|
85424
|
+
});
|
|
85425
|
+
app.get("/.well-known/oauth-protected-resource", (_req, res) => {
|
|
85426
|
+
res.json({
|
|
85427
|
+
resource: `${publicOrigin}/mcp`,
|
|
85428
|
+
authorization_servers: [`${publicOrigin}/`],
|
|
85429
|
+
scopes_supported: [],
|
|
85430
|
+
bearer_methods_supported: ["header"],
|
|
85431
|
+
resource_name: "Diamond Hands",
|
|
85432
|
+
resource_documentation: `${publicOrigin}/auth.md`
|
|
85433
|
+
});
|
|
85434
|
+
});
|
|
85435
|
+
app.use(
|
|
85436
|
+
(0, import_router.mcpAuthRouter)({
|
|
85437
|
+
provider: siwe,
|
|
85438
|
+
issuerUrl: new URL(publicOrigin),
|
|
85439
|
+
// Keep the SDK's own fallback document in agreement with the one above
|
|
85440
|
+
// rather than contradicting it.
|
|
85441
|
+
resourceServerUrl: new URL(`${publicOrigin}/mcp`),
|
|
85442
|
+
scopesSupported: [],
|
|
85443
|
+
resourceName: "Diamond Hands"
|
|
85444
|
+
})
|
|
85445
|
+
);
|
|
84687
85446
|
authImpl = {
|
|
84688
85447
|
tenant(req) {
|
|
84689
85448
|
const header = req.headers.authorization;
|
|
@@ -84729,7 +85488,11 @@ var CONNECTOR_PATH_PREFIXES = [
|
|
|
84729
85488
|
"/token",
|
|
84730
85489
|
"/register",
|
|
84731
85490
|
"/revoke",
|
|
84732
|
-
"/.well-known/oauth-"
|
|
85491
|
+
"/.well-known/oauth-",
|
|
85492
|
+
// Served by composeConnector beside the OAuth metadata. Listed here so a HOST
|
|
85493
|
+
// process that embeds the connector routes it here too, instead of answering
|
|
85494
|
+
// from its own stack with its own headers.
|
|
85495
|
+
"/auth.md"
|
|
84733
85496
|
];
|
|
84734
85497
|
function isConnectorPath(pathname) {
|
|
84735
85498
|
for (const p of CONNECTOR_PATH_PREFIXES) {
|
|
@@ -84742,13 +85505,7 @@ function isConnectorPath(pathname) {
|
|
|
84742
85505
|
return false;
|
|
84743
85506
|
}
|
|
84744
85507
|
function createEmbeddedConnector(opts) {
|
|
84745
|
-
const
|
|
84746
|
-
if (!/^https?:\/\/[^/]+$/.test(origin2)) {
|
|
84747
|
-
throw new Error(
|
|
84748
|
-
`createEmbeddedConnector: publicOrigin '${opts.publicOrigin}' must be a bare origin (scheme + host, no path)`
|
|
84749
|
-
);
|
|
84750
|
-
}
|
|
84751
|
-
const composed = composeConnector(opts, origin2);
|
|
85508
|
+
const composed = composeConnector(opts, opts.publicOrigin);
|
|
84752
85509
|
return {
|
|
84753
85510
|
handler: (req, res) => {
|
|
84754
85511
|
composed.app(req, res);
|