-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathlunarcrush.ts
More file actions
191 lines (165 loc) · 6.56 KB
/
Copy pathlunarcrush.ts
File metadata and controls
191 lines (165 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env bun
/**
* LunarCrush skill CLI
*
* Pay-per-call LunarCrush social/market intelligence via x402 on Stacks.
*
* Usage: bun run lunarcrush/lunarcrush.ts <subcommand> [options]
*/
import { Command } from "commander";
import { createApiClient } from "../src/lib/services/x402.service.js";
import { printJson, handleError } from "../src/lib/utils/cli.js";
// ---------------------------------------------------------------------------
// Endpoint hosts
// ---------------------------------------------------------------------------
const HOSTS = {
mainnet: "https://lunarcrush-x402-poc-prod.lunarcrush.workers.dev",
testnet: "https://lunarcrush-x402-poc.lunarcrush.workers.dev",
} as const;
type NetworkOption = keyof typeof HOSTS;
function resolveHost(networkOpt: string | undefined): { network: NetworkOption; baseUrl: string } {
const net = (networkOpt ?? "mainnet").toLowerCase();
if (net !== "mainnet" && net !== "testnet") {
throw new Error(`invalid --network "${networkOpt}". Must be "mainnet" or "testnet".`);
}
return { network: net as NetworkOption, baseUrl: HOSTS[net as NetworkOption] };
}
function normalizeSymbol(raw: string | undefined): string {
const s = String(raw ?? "").toLowerCase().trim();
if (!s) throw new Error("--symbol is required");
if (s.length > 16) throw new Error("--symbol too long (max 16 chars)");
if (!/^[a-z0-9]+$/.test(s)) throw new Error("--symbol must match [a-z0-9]+");
return s;
}
// ---------------------------------------------------------------------------
// Free-route helper (health, meta) — uses plain fetch, no payment required
// ---------------------------------------------------------------------------
async function fetchFree(baseUrl: string, path: string): Promise<unknown> {
const url = `${baseUrl}${path}`;
const res = await fetch(url, { method: "GET" });
if (!res.ok) {
throw new Error(`HTTP ${res.status} from ${url}`);
}
return res.json();
}
function decodePaymentReceipt(header: unknown): Record<string, unknown> | undefined {
if (!header) return undefined;
try {
return JSON.parse(Buffer.from(String(header), "base64").toString("utf8"));
} catch {
return undefined;
}
}
// ---------------------------------------------------------------------------
// Commander setup
// ---------------------------------------------------------------------------
const program = new Command();
program
.name("lunarcrush")
.description("Pay-per-call LunarCrush social/market intelligence via x402 on Stacks")
.version("0.0.1");
// ---------------------------------------------------------------------------
// oracle — premium combined endpoint with verdict + vibe one-liner
// ---------------------------------------------------------------------------
program
.command("oracle")
.description(
"Premium combined LunarCrush oracle for a symbol — verdict (STRONG-BUY/BUY/NEUTRAL/WATCH/AVOID), confidence (0-1), reasoning, and a vibe one-liner. One paid call, ~$0.025 USD in STX."
)
.requiredOption("--symbol <symbol>", "Crypto ticker (e.g. BTC, ETH, STX)")
.option("--network <network>", "mainnet or testnet (default: mainnet)", "mainnet")
.action(async (opts) => {
try {
const symbol = normalizeSymbol(opts.symbol);
const { network, baseUrl } = resolveHost(opts.network);
const api = await createApiClient(baseUrl, "lunarcrush.oracle");
const response = await api.request({
method: "GET",
url: `/oracle/${symbol}`,
});
const output: Record<string, unknown> = {
...((response.data as Record<string, unknown>) ?? {}),
network,
endpoint: `${baseUrl}/oracle/${symbol}`,
};
const receipt = decodePaymentReceipt(response.headers?.["payment-response"]);
if (receipt) output.payment_receipt = receipt;
printJson(output);
} catch (error) {
handleError(error);
}
});
// ---------------------------------------------------------------------------
// score
// ---------------------------------------------------------------------------
program
.command("score")
.description(
"Fetch Galaxy Score, AltRank, market cap rank, price, and 24h change for a symbol. Costs ~$0.005 USD in STX."
)
.requiredOption("--symbol <symbol>", "Crypto ticker (e.g. BTC, ETH, STX)")
.option("--network <network>", "mainnet or testnet (default: mainnet)", "mainnet")
.action(async (opts) => {
try {
const symbol = normalizeSymbol(opts.symbol);
const { network, baseUrl } = resolveHost(opts.network);
const api = await createApiClient(baseUrl, "lunarcrush.score");
const response = await api.request({
method: "GET",
url: `/galaxy-score/${symbol}`,
});
const output: Record<string, unknown> = {
...((response.data as Record<string, unknown>) ?? {}),
network,
endpoint: `${baseUrl}/galaxy-score/${symbol}`,
};
const receipt = decodePaymentReceipt(response.headers?.["payment-response"]);
if (receipt) output.payment_receipt = receipt;
printJson(output);
} catch (error) {
handleError(error);
}
});
// ---------------------------------------------------------------------------
// health
// ---------------------------------------------------------------------------
program
.command("health")
.description("Liveness probe (free).")
.option("--network <network>", "mainnet or testnet (default: mainnet)", "mainnet")
.action(async (opts) => {
try {
const { network, baseUrl } = resolveHost(opts.network);
const data = await fetchFree(baseUrl, "/health");
printJson({
network,
endpoint: `${baseUrl}/health`,
...(typeof data === "object" && data !== null ? (data as Record<string, unknown>) : {}),
});
} catch (error) {
handleError(error);
}
});
// ---------------------------------------------------------------------------
// meta
// ---------------------------------------------------------------------------
program
.command("meta")
.description(
"Fetch live endpoint catalog and current microSTX pricing (USD-pegged, recomputed hourly). Free."
)
.option("--network <network>", "mainnet or testnet (default: mainnet)", "mainnet")
.action(async (opts) => {
try {
const { network, baseUrl } = resolveHost(opts.network);
const data = await fetchFree(baseUrl, "/");
printJson({
network,
endpoint: baseUrl,
...(typeof data === "object" && data !== null ? (data as Record<string, unknown>) : {}),
});
} catch (error) {
handleError(error);
}
});
program.parse(process.argv);