@degenly/agent 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +143 -2
- package/SKILL.md +90 -0
- package/dist/api.js +242 -0
- package/dist/cli.js +780 -0
- package/dist/client.js +213 -0
- package/dist/demo/fill.js +143 -0
- package/dist/demo/store.js +144 -0
- package/dist/keys.js +138 -0
- package/dist/mcp.js +272 -0
- package/dist/sanitize.js +35 -0
- package/dist/sign.js +162 -0
- package/dist/tools/confirm.js +84 -0
- package/dist/tools/live-read.js +338 -0
- package/dist/tools/live-trade.js +173 -0
- package/dist/tx.js +417 -0
- package/docs/clients.md +73 -0
- package/npm-shrinkwrap.json +2508 -0
- package/package.json +52 -4
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { LIVE_NOTE } from "../cli.js";
|
|
2
|
+
import { createLiveClient, liveHint, loadCredentials, resolveApiBase } from "../client.js";
|
|
3
|
+
import { parseTokenRow, list } from "../api.js";
|
|
4
|
+
import { SOL_DECIMALS, SOL_MINT, formatUnits, parseSol } from "../demo/fill.js";
|
|
5
|
+
import { loadWallet } from "../keys.js";
|
|
6
|
+
import { cleanText, isMint, untrustedName, untrustedSymbol } from "../sanitize.js";
|
|
7
|
+
import { isSolanaAddress } from "../sign.js";
|
|
8
|
+
/** A token mint argument: base58, 32-44 chars (./sanitize.ts) AND 32 bytes; never a name / symbol. */
|
|
9
|
+
export function isLiveMint(v) {
|
|
10
|
+
return isMint(v) && isSolanaAddress(v);
|
|
11
|
+
}
|
|
12
|
+
/** Must equal `API_PRIORITY_MAX_LAMPORTS` (degenly/src/config/apiConstants.ts:144): what the server adds to each buy. */
|
|
13
|
+
export const API_PRIORITY_MAX_LAMPORTS = 5000000n;
|
|
14
|
+
export const LEDGER_MAX = 100;
|
|
15
|
+
const BPS_FULL = 10000n;
|
|
16
|
+
const LOCAL_HINTS = {
|
|
17
|
+
MINT_REQUIRED: "Pass the token's mint address (base58, 32-44 chars). Names and symbols are not accepted.",
|
|
18
|
+
BAD_AMOUNT: "SOL amount as a decimal string, e.g. 0.1 (more than 0, at most 9 decimals).",
|
|
19
|
+
BAD_PERCENT: "Use all, or a percent above 0 and up to 100, e.g. 50%.",
|
|
20
|
+
BAD_ARGS: "Wrong arguments for this tool.",
|
|
21
|
+
TOO_SMALL: "The amount rounds to 0 raw units. Use a larger amount.",
|
|
22
|
+
TOKEN_NOT_FOUND: "Degenly has no Solana token with this mint.",
|
|
23
|
+
NO_HOLD: "The agent wallet holds none of this token (or less than requested). Check: degenly_live_holdings.",
|
|
24
|
+
BAD_QUOTE: "Degenly sent a quote this package cannot use. Nothing was signed or sent.",
|
|
25
|
+
LIVE_NOT_READY: "Live tools need an agent wallet and an API key on this computer. Run: degenly setup --owner <main wallet>, pair on degenly.app/bot, then degenly login.",
|
|
26
|
+
};
|
|
27
|
+
export function liveAnswer(fields) {
|
|
28
|
+
return { ok: true, mode: "live", note: LIVE_NOTE, ...fields };
|
|
29
|
+
}
|
|
30
|
+
export function liveError(error, extra = {}) {
|
|
31
|
+
return { ok: false, mode: "live", note: LIVE_NOTE, error, hint: LOCAL_HINTS[error] ?? liveHint(error), ...extra };
|
|
32
|
+
}
|
|
33
|
+
/** A server refusal as is: its stable code + its scalar fields (scope, limitLamports, reason, …) + HTTP status. */
|
|
34
|
+
export function fromServer(r) {
|
|
35
|
+
return liveError(r.error, { ...r.fields, status: r.status, ...(r.retryAfterMs !== undefined ? { retryAfterMs: r.retryAfterMs } : {}) });
|
|
36
|
+
}
|
|
37
|
+
/** Wallet + API key + API base, all local. No network. */
|
|
38
|
+
export function openLive(d) {
|
|
39
|
+
if (d.homeError)
|
|
40
|
+
return { ok: false, error: d.homeError, missing: ["a valid DEGENLY_HOME (or unset it)"] };
|
|
41
|
+
const missing = [];
|
|
42
|
+
const w = loadWallet(d.home);
|
|
43
|
+
if (!w.ok)
|
|
44
|
+
missing.push(w.error === "NO_WALLET" ? "agent wallet: run degenly setup --owner <main wallet address>" : "agent wallet file is not valid (~/.degenly/agent-wallet.json)");
|
|
45
|
+
const c = loadCredentials(d.home);
|
|
46
|
+
if (!c.ok)
|
|
47
|
+
missing.push(c.error === "NOT_LOGGED_IN" ? "API key: pair on degenly.app/bot, then run degenly login" : "API key file is not valid: run degenly login again");
|
|
48
|
+
const b = resolveApiBase(d.env);
|
|
49
|
+
if (!b.ok)
|
|
50
|
+
missing.push("DEGENLY_API_BASE must be an https:// origin");
|
|
51
|
+
if (!w.ok || !c.ok || !b.ok) {
|
|
52
|
+
const error = !w.ok ? w.error : !c.ok ? c.error : "BAD_API_BASE";
|
|
53
|
+
return { ok: false, error, missing, ...(w.ok ? { address: w.wallet.address } : {}) };
|
|
54
|
+
}
|
|
55
|
+
return { ok: true, ctx: { wallet: w.wallet, base: b.base, now: d.now, client: createLiveClient({ fetch: d.fetch, base: b.base, apiKey: c.apiKey, signer: w.wallet, now: d.now }) } };
|
|
56
|
+
}
|
|
57
|
+
export function liveReady(d) {
|
|
58
|
+
return openLive(d).ok;
|
|
59
|
+
}
|
|
60
|
+
function notReady(o) {
|
|
61
|
+
return liveError(o.error, { missing: o.missing, ...(o.address !== undefined ? { address: o.address } : {}) });
|
|
62
|
+
}
|
|
63
|
+
// ---- shared reads ------------------------------------------------------------------------------
|
|
64
|
+
function isObj(v) {
|
|
65
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
66
|
+
}
|
|
67
|
+
const UINT = /^\d+$/;
|
|
68
|
+
function num(v) {
|
|
69
|
+
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
|
|
70
|
+
}
|
|
71
|
+
function str(v) {
|
|
72
|
+
return typeof v === "string" ? v : undefined;
|
|
73
|
+
}
|
|
74
|
+
export async function fetchToken(ctx, mint) {
|
|
75
|
+
const r = await ctx.client.request("GET", `/v1/data/tokens?${new URLSearchParams({ mints: mint }).toString()}`);
|
|
76
|
+
if (!r.ok)
|
|
77
|
+
return { ok: false, answer: fromServer(r) };
|
|
78
|
+
const token = list(r.data.data, parseTokenRow).find((t) => t.mint === mint);
|
|
79
|
+
return token ? { ok: true, token } : { ok: false, answer: liveError("TOKEN_NOT_FOUND", { mint }) };
|
|
80
|
+
}
|
|
81
|
+
export async function fetchHoldings(ctx) {
|
|
82
|
+
const r = await ctx.client.request("GET", "/v1/data/holdings");
|
|
83
|
+
if (!r.ok)
|
|
84
|
+
return { ok: false, answer: fromServer(r) };
|
|
85
|
+
const d = r.data.data;
|
|
86
|
+
if (!isObj(d) || typeof d.sol !== "string" || !UINT.test(d.sol) || !Array.isArray(d.tokens))
|
|
87
|
+
return { ok: false, answer: liveError("BAD_RESPONSE") };
|
|
88
|
+
const tokens = [];
|
|
89
|
+
for (const t of d.tokens) {
|
|
90
|
+
if (!isObj(t) || !isMint(t.mint) || typeof t.raw !== "string" || !UINT.test(t.raw) || typeof t.decimals !== "number" || !Number.isInteger(t.decimals) || t.decimals < 0 || t.decimals > 18)
|
|
91
|
+
continue;
|
|
92
|
+
tokens.push({ mint: t.mint, raw: BigInt(t.raw), decimals: t.decimals });
|
|
93
|
+
}
|
|
94
|
+
const fetchedAt = num(r.data.fetchedAt);
|
|
95
|
+
return { ok: true, solLamports: BigInt(d.sol), tokens, ...(fetchedAt !== undefined ? { fetchedAt } : {}) };
|
|
96
|
+
}
|
|
97
|
+
/** "all" → 10000; "50" / "50%" / "12.5%" → basis points; anything else → undefined. */
|
|
98
|
+
export function percentBps(v) {
|
|
99
|
+
const s = v.trim().toLowerCase();
|
|
100
|
+
if (s === "all" || s === "max")
|
|
101
|
+
return BPS_FULL;
|
|
102
|
+
const m = /^(\d{1,3})(?:\.(\d{1,2}))?%?$/.exec(s);
|
|
103
|
+
if (!m)
|
|
104
|
+
return undefined;
|
|
105
|
+
const bps = BigInt(m[1] ?? "0") * 100n + BigInt((m[2] ?? "").padEnd(2, "0") || "0");
|
|
106
|
+
return bps > 0n && bps <= BPS_FULL ? bps : undefined;
|
|
107
|
+
}
|
|
108
|
+
/** What a sell of `amount` (all / N%) of the agent wallet's holding is, in raw token units. */
|
|
109
|
+
export async function sellRaw(ctx, mint, amount) {
|
|
110
|
+
const bps = percentBps(amount);
|
|
111
|
+
if (bps === undefined)
|
|
112
|
+
return { ok: false, answer: liveError("BAD_PERCENT") };
|
|
113
|
+
const h = await fetchHoldings(ctx);
|
|
114
|
+
if (!h.ok)
|
|
115
|
+
return h;
|
|
116
|
+
const held = h.tokens.find((t) => t.mint === mint);
|
|
117
|
+
if (!held || held.raw <= 0n)
|
|
118
|
+
return { ok: false, answer: liveError("NO_HOLD", { mint }) };
|
|
119
|
+
const raw = (held.raw * bps) / BPS_FULL;
|
|
120
|
+
return raw > 0n ? { ok: true, raw, decimals: held.decimals } : { ok: false, answer: liveError("TOO_SMALL") };
|
|
121
|
+
}
|
|
122
|
+
function parseLiveQuote(v) {
|
|
123
|
+
if (!isObj(v) || !isObj(v.cost))
|
|
124
|
+
return undefined;
|
|
125
|
+
const side = v.side;
|
|
126
|
+
if (side !== "buy" && side !== "sell")
|
|
127
|
+
return undefined;
|
|
128
|
+
const requestId = str(v.requestId);
|
|
129
|
+
const inputMint = str(v.inputMint);
|
|
130
|
+
const outputMint = str(v.outputMint);
|
|
131
|
+
const inAmount = str(v.inAmount);
|
|
132
|
+
const outAmount = str(v.outAmount);
|
|
133
|
+
const minOutAmount = str(v.minOutAmount);
|
|
134
|
+
const inDecimals = num(v.inDecimals);
|
|
135
|
+
const outDecimals = num(v.outDecimals);
|
|
136
|
+
const feeBps = num(v.cost.degenlyFeeBps);
|
|
137
|
+
const networkLamports = num(v.cost.networkAndPriorityLamports);
|
|
138
|
+
const expiresInMs = num(v.expiresInMs);
|
|
139
|
+
if (!requestId || !inputMint || !outputMint || !inAmount || !outAmount || !minOutAmount)
|
|
140
|
+
return undefined;
|
|
141
|
+
if (![inAmount, outAmount, minOutAmount].every((x) => UINT.test(x)))
|
|
142
|
+
return undefined;
|
|
143
|
+
if (inDecimals === undefined || outDecimals === undefined || feeBps === undefined || networkLamports === undefined || expiresInMs === undefined)
|
|
144
|
+
return undefined;
|
|
145
|
+
const slippagePct = num(v.slippageAppliedPct);
|
|
146
|
+
const priceImpactPct = num(v.cost.priceImpactPct);
|
|
147
|
+
const transaction = str(v.transaction);
|
|
148
|
+
return {
|
|
149
|
+
requestId: cleanText(requestId, 64),
|
|
150
|
+
side,
|
|
151
|
+
inputMint,
|
|
152
|
+
outputMint,
|
|
153
|
+
inAmount,
|
|
154
|
+
outAmount,
|
|
155
|
+
minOutAmount,
|
|
156
|
+
inDecimals,
|
|
157
|
+
outDecimals,
|
|
158
|
+
feeBps,
|
|
159
|
+
networkLamports,
|
|
160
|
+
expiresInMs,
|
|
161
|
+
tradingEnabled: v.tradingEnabled === true,
|
|
162
|
+
...(slippagePct !== undefined ? { slippagePct } : {}),
|
|
163
|
+
...(priceImpactPct !== undefined ? { priceImpactPct } : {}),
|
|
164
|
+
...(transaction !== undefined && transaction !== "" ? { transaction } : {}),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** One `/v1/quote` for the agent wallet, checked against what was asked (side, mints, amount). */
|
|
168
|
+
export async function fetchQuote(ctx, mint, side, amountRaw, decimals) {
|
|
169
|
+
const params = new URLSearchParams({ mint, side, amount: amountRaw.toString(), decimals: String(decimals) });
|
|
170
|
+
const r = await ctx.client.request("GET", `/v1/quote?${params.toString()}`);
|
|
171
|
+
const receivedAt = ctx.now();
|
|
172
|
+
if (!r.ok)
|
|
173
|
+
return { ok: false, answer: fromServer(r) };
|
|
174
|
+
const q = parseLiveQuote(r.data.quote);
|
|
175
|
+
const want = side === "buy" ? { i: SOL_MINT, o: mint } : { i: mint, o: SOL_MINT };
|
|
176
|
+
if (!q || q.side !== side || q.inputMint !== want.i || q.outputMint !== want.o || q.inAmount !== amountRaw.toString())
|
|
177
|
+
return { ok: false, answer: liveError("BAD_QUOTE") };
|
|
178
|
+
return { ok: true, q, receivedAt };
|
|
179
|
+
}
|
|
180
|
+
/** The facts of a quote an agent / human reads (no transaction bytes). */
|
|
181
|
+
export function quoteFacts(q, mint, decimals) {
|
|
182
|
+
const buy = q.side === "buy";
|
|
183
|
+
return {
|
|
184
|
+
side: q.side,
|
|
185
|
+
mint,
|
|
186
|
+
in: buy ? formatUnits(q.inAmount, SOL_DECIMALS) : formatUnits(q.inAmount, decimals),
|
|
187
|
+
out: buy ? formatUnits(q.outAmount, decimals) : formatUnits(q.outAmount, SOL_DECIMALS),
|
|
188
|
+
minOut: buy ? formatUnits(q.minOutAmount, decimals) : formatUnits(q.minOutAmount, SOL_DECIMALS),
|
|
189
|
+
inRaw: q.inAmount,
|
|
190
|
+
outRaw: q.outAmount,
|
|
191
|
+
feeBps: q.feeBps,
|
|
192
|
+
networkSol: formatUnits(BigInt(Math.max(0, Math.floor(q.networkLamports))), SOL_DECIMALS),
|
|
193
|
+
...(q.slippagePct !== undefined ? { slippagePct: q.slippagePct } : {}),
|
|
194
|
+
...(q.priceImpactPct !== undefined ? { priceImpactPct: q.priceImpactPct } : {}),
|
|
195
|
+
validForMs: q.expiresInMs,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** `limits` of a whoami answer when the server sends them (decimal lamport strings); undefined otherwise. */
|
|
199
|
+
export function whoamiLimits(data) {
|
|
200
|
+
const l = data.limits;
|
|
201
|
+
if (!isObj(l))
|
|
202
|
+
return undefined;
|
|
203
|
+
const per = str(l.perTradeLamports);
|
|
204
|
+
const day = str(l.dailyLamports);
|
|
205
|
+
if (per === undefined || day === undefined || !UINT.test(per) || !UINT.test(day))
|
|
206
|
+
return undefined;
|
|
207
|
+
const used = str(l.usedLamports);
|
|
208
|
+
return { perTradeLamports: BigInt(per), dailyLamports: BigInt(day), ...(used !== undefined && UINT.test(used) ? { usedLamports: BigInt(used) } : {}) };
|
|
209
|
+
}
|
|
210
|
+
export function confirmMode(env) {
|
|
211
|
+
return (env.DEGENLY_CONFIRM ?? "").trim().toLowerCase() === "off" ? "off" : "on";
|
|
212
|
+
}
|
|
213
|
+
export function createLiveRead(d) {
|
|
214
|
+
const withCtx = async (f) => {
|
|
215
|
+
const o = openLive(d);
|
|
216
|
+
if (!o.ok)
|
|
217
|
+
return notReady(o);
|
|
218
|
+
return f(o.ctx);
|
|
219
|
+
};
|
|
220
|
+
return {
|
|
221
|
+
whoami: () => withCtx(async (ctx) => {
|
|
222
|
+
const r = await ctx.client.request("GET", "/v1/whoami");
|
|
223
|
+
if (!r.ok)
|
|
224
|
+
return fromServer(r);
|
|
225
|
+
const wallet = typeof r.data.wallet === "string" ? r.data.wallet : "";
|
|
226
|
+
if (wallet !== ctx.wallet.address)
|
|
227
|
+
return liveError("KEY_WALLET_MISMATCH", { address: ctx.wallet.address });
|
|
228
|
+
const lim = whoamiLimits(r.data);
|
|
229
|
+
return liveAnswer({
|
|
230
|
+
wallet,
|
|
231
|
+
keyId: typeof r.data.keyId === "string" ? cleanText(r.data.keyId, 64) : undefined,
|
|
232
|
+
serverTs: num(r.data.serverTs),
|
|
233
|
+
apiBase: ctx.base,
|
|
234
|
+
confirm: confirmMode(d.env),
|
|
235
|
+
limits: lim ? { perTradeSol: formatUnits(lim.perTradeLamports, SOL_DECIMALS), dailySol: formatUnits(lim.dailyLamports, SOL_DECIMALS) } : "unknown",
|
|
236
|
+
});
|
|
237
|
+
}),
|
|
238
|
+
token: (mint) => withCtx(async (ctx) => {
|
|
239
|
+
if (!isLiveMint(mint))
|
|
240
|
+
return liveError("MINT_REQUIRED");
|
|
241
|
+
const t = await fetchToken(ctx, mint);
|
|
242
|
+
if (!t.ok)
|
|
243
|
+
return t.answer;
|
|
244
|
+
const k = t.token;
|
|
245
|
+
const warnings = [];
|
|
246
|
+
if (k.freezeAuthorityDisabled === false)
|
|
247
|
+
warnings.push("Freeze authority is enabled: this token can be frozen and may not be sellable.");
|
|
248
|
+
if (k.mintAuthorityDisabled === false)
|
|
249
|
+
warnings.push("Mint authority is enabled: more of this token can be created.");
|
|
250
|
+
return liveAnswer({
|
|
251
|
+
mint: k.mint,
|
|
252
|
+
name: untrustedName(k.name),
|
|
253
|
+
symbol: untrustedSymbol(k.symbol),
|
|
254
|
+
decimals: k.decimals,
|
|
255
|
+
usdPrice: k.usdPrice,
|
|
256
|
+
mcapUsd: k.mcapUsd,
|
|
257
|
+
liquidityUsd: k.liquidityUsd,
|
|
258
|
+
mintAuthorityDisabled: k.mintAuthorityDisabled,
|
|
259
|
+
freezeAuthorityDisabled: k.freezeAuthorityDisabled,
|
|
260
|
+
warnings,
|
|
261
|
+
});
|
|
262
|
+
}),
|
|
263
|
+
price: (mint) => withCtx(async (ctx) => {
|
|
264
|
+
if (!isLiveMint(mint))
|
|
265
|
+
return liveError("MINT_REQUIRED");
|
|
266
|
+
const r = await ctx.client.request("GET", `/v1/data/prices?${new URLSearchParams({ mints: mint }).toString()}`);
|
|
267
|
+
if (!r.ok)
|
|
268
|
+
return fromServer(r);
|
|
269
|
+
const row = Array.isArray(r.data.data) ? r.data.data.find((x) => isObj(x) && x.mint === mint) : undefined;
|
|
270
|
+
const usdPrice = row ? num(row.usdPrice) : undefined;
|
|
271
|
+
if (usdPrice === undefined)
|
|
272
|
+
return liveError("TOKEN_NOT_FOUND", { mint });
|
|
273
|
+
return liveAnswer({ mint, usdPrice });
|
|
274
|
+
}),
|
|
275
|
+
holdings: () => withCtx(async (ctx) => {
|
|
276
|
+
const h = await fetchHoldings(ctx);
|
|
277
|
+
if (!h.ok)
|
|
278
|
+
return h.answer;
|
|
279
|
+
return liveAnswer({
|
|
280
|
+
wallet: ctx.wallet.address,
|
|
281
|
+
sol: formatUnits(h.solLamports, SOL_DECIMALS),
|
|
282
|
+
solLamports: h.solLamports.toString(),
|
|
283
|
+
tokens: h.tokens.map((t) => ({ mint: t.mint, amount: formatUnits(t.raw, t.decimals), raw: t.raw.toString(), decimals: t.decimals })),
|
|
284
|
+
...(h.fetchedAt !== undefined ? { fetchedAt: h.fetchedAt } : {}),
|
|
285
|
+
});
|
|
286
|
+
}),
|
|
287
|
+
ledger: (limit = 20) => withCtx(async (ctx) => {
|
|
288
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > LEDGER_MAX)
|
|
289
|
+
return liveError("BAD_ARGS", { hint: `limit must be 1-${LEDGER_MAX}.` });
|
|
290
|
+
const r = await ctx.client.request("GET", "/v1/data/ledger");
|
|
291
|
+
if (!r.ok)
|
|
292
|
+
return fromServer(r);
|
|
293
|
+
const rows = (Array.isArray(r.data.rows) ? r.data.rows : []).filter(isObj).slice(0, limit).map((x) => ({
|
|
294
|
+
signature: typeof x.signature === "string" ? cleanText(x.signature, 100) : undefined,
|
|
295
|
+
side: x.side === "buy" || x.side === "sell" ? x.side : undefined,
|
|
296
|
+
inputMint: isMint(x.inputMint) ? x.inputMint : undefined,
|
|
297
|
+
outputMint: isMint(x.outputMint) ? x.outputMint : undefined,
|
|
298
|
+
volumeUsd: num(x.volumeUsd),
|
|
299
|
+
feeBps: num(x.feeBps),
|
|
300
|
+
at: num(x.createdAt) !== undefined ? new Date(num(x.createdAt) ?? 0).toISOString() : undefined,
|
|
301
|
+
}));
|
|
302
|
+
return liveAnswer({ wallet: ctx.wallet.address, count: rows.length, rows });
|
|
303
|
+
}),
|
|
304
|
+
quote: (mint, side, amount) => withCtx(async (ctx) => {
|
|
305
|
+
if (!isLiveMint(mint) || mint === SOL_MINT)
|
|
306
|
+
return liveError("MINT_REQUIRED");
|
|
307
|
+
if (side !== "buy" && side !== "sell")
|
|
308
|
+
return liveError("BAD_ARGS", { hint: "Side must be buy or sell." });
|
|
309
|
+
let raw;
|
|
310
|
+
let decimals;
|
|
311
|
+
let name;
|
|
312
|
+
let symbol;
|
|
313
|
+
const t = await fetchToken(ctx, mint);
|
|
314
|
+
if (!t.ok)
|
|
315
|
+
return t.answer;
|
|
316
|
+
name = t.token.name;
|
|
317
|
+
symbol = t.token.symbol;
|
|
318
|
+
if (side === "buy") {
|
|
319
|
+
const l = parseSol(amount);
|
|
320
|
+
if (l === undefined)
|
|
321
|
+
return liveError("BAD_AMOUNT");
|
|
322
|
+
raw = l;
|
|
323
|
+
decimals = t.token.decimals;
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
const s = await sellRaw(ctx, mint, amount);
|
|
327
|
+
if (!s.ok)
|
|
328
|
+
return s.answer;
|
|
329
|
+
raw = s.raw;
|
|
330
|
+
decimals = s.decimals;
|
|
331
|
+
}
|
|
332
|
+
const lq = await fetchQuote(ctx, mint, side, raw, decimals);
|
|
333
|
+
if (!lq.ok)
|
|
334
|
+
return lq.answer;
|
|
335
|
+
return liveAnswer({ quoteOnly: true, name: untrustedName(name), symbol: untrustedSymbol(symbol), ...quoteFacts(lq.q, mint, decimals), tradingEnabled: lq.q.tradingEnabled });
|
|
336
|
+
}),
|
|
337
|
+
};
|
|
338
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { SOL_DECIMALS, SOL_MINT, formatUnits, parseSol } from "../demo/fill.js";
|
|
2
|
+
import { untrustedName, untrustedSymbol } from "../sanitize.js";
|
|
3
|
+
import { base64ToBytes, bytesToBase64, checkAgentTx, signTransactionFor } from "../tx.js";
|
|
4
|
+
import { CONFIRM_OFF_HINT, requestConfirmation } from "./confirm.js";
|
|
5
|
+
import { API_PRIORITY_MAX_LAMPORTS, fetchQuote, fetchToken, fromServer, isLiveMint, liveAnswer, liveError, openLive, quoteFacts, sellRaw, whoamiLimits, } from "./live-read.js";
|
|
6
|
+
export const TRADE_HINTS = {
|
|
7
|
+
LOCAL_LIMIT_UNKNOWN: "Degenly did not send this agent wallet's spending limit, so the package refuses the buy (fail closed). Nothing was quoted or sent.",
|
|
8
|
+
LOCAL_SPEND_LIMIT: "Above the spending limit set on degenly.app/bot (checked on this computer before anything was sent). Only the wallet owner can change it there.",
|
|
9
|
+
TX_NOT_FOR_WALLET: "The quoted transaction is not for this agent wallet. Nothing was signed or sent.",
|
|
10
|
+
TX_INVALID: "The quoted transaction could not be read with certainty. Nothing was signed or sent.",
|
|
11
|
+
TX_PROGRAM_NOT_ALLOWED: "The quoted transaction calls a program that is not on the swap allow-list (the same list degenly.app checks). Nothing was signed or sent.",
|
|
12
|
+
TX_UNEXPECTED_TRANSFER: "The quoted transaction would move funds from the agent wallet to an address the agent wallet does not own. Nothing was signed or sent.",
|
|
13
|
+
TX_INSTRUCTION_NOT_ALLOWED: "The quoted transaction asks the agent wallet for an instruction a swap never needs. Nothing was signed or sent.",
|
|
14
|
+
CANCELLED: "The trade was not confirmed (declined, closed or timed out). Nothing was signed or sent.",
|
|
15
|
+
CONFIRM_UNSUPPORTED: CONFIRM_OFF_HINT,
|
|
16
|
+
EXECUTE_OUTCOME_UNKNOWN: "The trade was sent but no answer came back. It may have gone through. Do NOT retry: check degenly_live_holdings and degenly_live_ledger first.",
|
|
17
|
+
TRADE_FAILED: "Degenly / Jupiter did not complete the trade (see failReason). Get a new quote before trying again.",
|
|
18
|
+
TRADING_DISABLED: "Live trading is switched off on Degenly right now. Nothing was signed or sent.",
|
|
19
|
+
};
|
|
20
|
+
function tradeError(error, extra = {}) {
|
|
21
|
+
const a = liveError(error, extra);
|
|
22
|
+
return TRADE_HINTS[error] !== undefined && extra.hint === undefined ? { ...a, hint: TRADE_HINTS[error] } : a;
|
|
23
|
+
}
|
|
24
|
+
/** DGAJ22: DEGENLY_CONFIRM=off is not honoured for a non-default DEGENLY_API_BASE. */
|
|
25
|
+
function customApiOffHint(base) {
|
|
26
|
+
return `DEGENLY_API_BASE points to ${base}, not degenly.app, and DEGENLY_CONFIRM=off is set. Trades to another server always need the confirmation form, so nothing was signed or sent. Remove DEGENLY_API_BASE unless you set it yourself on purpose.`;
|
|
27
|
+
}
|
|
28
|
+
function isObj(v) {
|
|
29
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
30
|
+
}
|
|
31
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
32
|
+
const UINT = /^\d+$/;
|
|
33
|
+
/** Local limit check of one buy. undefined = allowed. */
|
|
34
|
+
async function localLimit(ctx, lamports) {
|
|
35
|
+
const r = await ctx.client.request("GET", "/v1/whoami");
|
|
36
|
+
if (!r.ok)
|
|
37
|
+
return fromServer(r);
|
|
38
|
+
if (r.data.wallet !== ctx.wallet.address)
|
|
39
|
+
return liveError("KEY_WALLET_MISMATCH", { address: ctx.wallet.address });
|
|
40
|
+
const lim = whoamiLimits(r.data);
|
|
41
|
+
if (!lim)
|
|
42
|
+
return tradeError("LOCAL_LIMIT_UNKNOWN");
|
|
43
|
+
const cost = lamports + API_PRIORITY_MAX_LAMPORTS;
|
|
44
|
+
if (cost > lim.perTradeLamports)
|
|
45
|
+
return tradeError("LOCAL_SPEND_LIMIT", { scope: "trade", limitSol: formatUnits(lim.perTradeLamports, SOL_DECIMALS) });
|
|
46
|
+
const used = lim.usedLamports ?? 0n;
|
|
47
|
+
if (used + cost > lim.dailyLamports)
|
|
48
|
+
return tradeError("LOCAL_SPEND_LIMIT", { scope: "day", limitSol: formatUnits(lim.dailyLamports, SOL_DECIMALS), usedSol: formatUnits(used, SOL_DECIMALS) });
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
export function createLiveTrade(d, elicitor) {
|
|
52
|
+
// one live trade at a time (an MCP client may send calls in parallel)
|
|
53
|
+
let chain = Promise.resolve();
|
|
54
|
+
const serial = (f) => {
|
|
55
|
+
const run = chain.then(f, f);
|
|
56
|
+
chain = run.catch(() => undefined);
|
|
57
|
+
return run;
|
|
58
|
+
};
|
|
59
|
+
const trade = async (mint, side, amountArg) => {
|
|
60
|
+
// 1. inputs (no network): a mint address only (base58, 32-44 chars, decodes to 32 bytes)
|
|
61
|
+
if (!isLiveMint(mint) || mint === SOL_MINT)
|
|
62
|
+
return liveError("MINT_REQUIRED");
|
|
63
|
+
let lamports;
|
|
64
|
+
if (side === "buy") {
|
|
65
|
+
lamports = parseSol(amountArg);
|
|
66
|
+
if (lamports === undefined)
|
|
67
|
+
return liveError("BAD_AMOUNT");
|
|
68
|
+
}
|
|
69
|
+
else if (!/^(all|max|\d{1,3}(\.\d{1,2})?%?)$/i.test(amountArg.trim())) {
|
|
70
|
+
return liveError("BAD_PERCENT");
|
|
71
|
+
}
|
|
72
|
+
// 2. local files
|
|
73
|
+
const o = openLive(d);
|
|
74
|
+
if (!o.ok)
|
|
75
|
+
return liveError(o.error, { missing: o.missing });
|
|
76
|
+
const ctx = o.ctx;
|
|
77
|
+
// 3. local limit (buy)
|
|
78
|
+
if (side === "buy" && lamports !== undefined) {
|
|
79
|
+
const refused = await localLimit(ctx, lamports);
|
|
80
|
+
if (refused)
|
|
81
|
+
return refused;
|
|
82
|
+
}
|
|
83
|
+
// 4. token facts + the quote this call signs
|
|
84
|
+
const t = await fetchToken(ctx, mint);
|
|
85
|
+
if (!t.ok)
|
|
86
|
+
return t.answer;
|
|
87
|
+
let raw;
|
|
88
|
+
let decimals = t.token.decimals;
|
|
89
|
+
if (side === "buy")
|
|
90
|
+
raw = lamports ?? 0n;
|
|
91
|
+
else {
|
|
92
|
+
const s = await sellRaw(ctx, mint, amountArg);
|
|
93
|
+
if (!s.ok)
|
|
94
|
+
return s.answer;
|
|
95
|
+
raw = s.raw;
|
|
96
|
+
decimals = s.decimals;
|
|
97
|
+
}
|
|
98
|
+
const lq = await fetchQuote(ctx, mint, side, raw, decimals);
|
|
99
|
+
if (!lq.ok)
|
|
100
|
+
return lq.answer;
|
|
101
|
+
const q = lq.q;
|
|
102
|
+
const facts = quoteFacts(q, mint, decimals);
|
|
103
|
+
const named = { name: untrustedName(t.token.name), symbol: untrustedSymbol(t.token.symbol) };
|
|
104
|
+
if (!q.tradingEnabled)
|
|
105
|
+
return tradeError("TRADING_DISABLED", { ...named, ...facts });
|
|
106
|
+
const bytes = q.transaction !== undefined ? base64ToBytes(q.transaction) : undefined;
|
|
107
|
+
if (!bytes)
|
|
108
|
+
return liveError("BAD_QUOTE");
|
|
109
|
+
// DGAJ22: the package's own check of the quoted bytes (allow-list + transfer rule), before the human is asked;
|
|
110
|
+
// signTransactionFor runs it again right before signing.
|
|
111
|
+
const checked = checkAgentTx(bytes, ctx.wallet.address);
|
|
112
|
+
if (!checked.ok)
|
|
113
|
+
return tradeError(checked.error);
|
|
114
|
+
// 5. the human confirms (the summary names a non-default server on its first line)
|
|
115
|
+
const outcome = await requestConfirmation(elicitor(), {
|
|
116
|
+
side,
|
|
117
|
+
mint,
|
|
118
|
+
name: t.token.name,
|
|
119
|
+
symbol: t.token.symbol,
|
|
120
|
+
inText: String(facts.in),
|
|
121
|
+
outText: String(facts.out),
|
|
122
|
+
minOutText: String(facts.minOut),
|
|
123
|
+
feeBps: q.feeBps,
|
|
124
|
+
networkSol: String(facts.networkSol),
|
|
125
|
+
...(q.slippagePct !== undefined ? { slippagePct: q.slippagePct } : {}),
|
|
126
|
+
...(q.priceImpactPct !== undefined ? { priceImpactPct: q.priceImpactPct } : {}),
|
|
127
|
+
apiBase: ctx.base,
|
|
128
|
+
}, d.env);
|
|
129
|
+
if (outcome === "custom_api_off")
|
|
130
|
+
return tradeError("CUSTOM_API_NEEDS_CONFIRM", { apiBase: ctx.base, hint: customApiOffHint(ctx.base) });
|
|
131
|
+
if (outcome === "unsupported")
|
|
132
|
+
return tradeError("CONFIRM_UNSUPPORTED", { ...named, ...facts });
|
|
133
|
+
if (outcome === "declined")
|
|
134
|
+
return tradeError("CANCELLED", { ...named, ...facts });
|
|
135
|
+
// 6. sign + ONE execute (no retry)
|
|
136
|
+
const signed = signTransactionFor(bytes, ctx.wallet);
|
|
137
|
+
if (!signed.ok)
|
|
138
|
+
return tradeError(signed.error);
|
|
139
|
+
const r = await ctx.client.request("POST", "/v1/execute", JSON.stringify({ signedTransaction: bytesToBase64(signed.signed), requestId: q.requestId }));
|
|
140
|
+
if (!r.ok) {
|
|
141
|
+
if (r.error === "NETWORK")
|
|
142
|
+
return tradeError("EXECUTE_OUTCOME_UNKNOWN", { ...named, mint, side });
|
|
143
|
+
// a 5xx after the send (e.g. 500 INTERNAL, 503 UPSTREAM_UNAVAILABLE): the outcome is unknown too, never retried
|
|
144
|
+
if (r.status >= 500)
|
|
145
|
+
return tradeError("EXECUTE_OUTCOME_UNKNOWN", { ...named, mint, side, serverError: r.error, status: r.status });
|
|
146
|
+
return fromServer(r);
|
|
147
|
+
}
|
|
148
|
+
const res = isObj(r.data.result) ? r.data.result : {};
|
|
149
|
+
const signature = str(res.signature);
|
|
150
|
+
const status = res.status;
|
|
151
|
+
const inRaw = str(res.totalInputAmount) ?? str(res.inputAmountResult);
|
|
152
|
+
const outRaw = str(res.totalOutputAmount) ?? str(res.outputAmountResult);
|
|
153
|
+
const amounts = {
|
|
154
|
+
...(inRaw !== undefined && UINT.test(inRaw) ? { spent: side === "buy" ? formatUnits(inRaw, SOL_DECIMALS) : formatUnits(inRaw, decimals), spentRaw: inRaw } : {}),
|
|
155
|
+
...(outRaw !== undefined && UINT.test(outRaw) ? { received: side === "buy" ? formatUnits(outRaw, decimals) : formatUnits(outRaw, SOL_DECIMALS), receivedRaw: outRaw } : {}),
|
|
156
|
+
};
|
|
157
|
+
if (status === "confirmed" && signature !== undefined) {
|
|
158
|
+
return liveAnswer({ side, mint, ...named, status: "confirmed", txSignature: signature, ...amounts, confirm: outcome === "skipped_off" ? "off" : "human" });
|
|
159
|
+
}
|
|
160
|
+
return tradeError("TRADE_FAILED", {
|
|
161
|
+
side,
|
|
162
|
+
mint,
|
|
163
|
+
...named,
|
|
164
|
+
failReason: str(res.failReason) ?? "unknown",
|
|
165
|
+
failCode: str(res.failCode),
|
|
166
|
+
...(signature !== undefined ? { txSignature: signature } : {}),
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
return {
|
|
170
|
+
buy: (mint, sol) => serial(() => trade(mint, "buy", sol)),
|
|
171
|
+
sell: (mint, amount) => serial(() => trade(mint, "sell", amount)),
|
|
172
|
+
};
|
|
173
|
+
}
|