@upshiftfinance/cli 0.0.0-stage → 0.1.0

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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +185 -2
  3. package/lib/bin.d.ts +2 -0
  4. package/lib/bin.js +19 -0
  5. package/lib/commands/chain.d.ts +2 -0
  6. package/lib/commands/chain.js +42 -0
  7. package/lib/commands/config.d.ts +2 -0
  8. package/lib/commands/config.js +107 -0
  9. package/lib/commands/docs.d.ts +2 -0
  10. package/lib/commands/docs.js +407 -0
  11. package/lib/commands/init.d.ts +2 -0
  12. package/lib/commands/init.js +124 -0
  13. package/lib/commands/login.d.ts +2 -0
  14. package/lib/commands/login.js +57 -0
  15. package/lib/commands/ops.d.ts +2 -0
  16. package/lib/commands/ops.js +149 -0
  17. package/lib/commands/points.d.ts +2 -0
  18. package/lib/commands/points.js +52 -0
  19. package/lib/commands/profile.d.ts +2 -0
  20. package/lib/commands/profile.js +82 -0
  21. package/lib/commands/rpc.d.ts +11 -0
  22. package/lib/commands/rpc.js +93 -0
  23. package/lib/commands/skill.d.ts +2 -0
  24. package/lib/commands/skill.js +83 -0
  25. package/lib/commands/user.d.ts +2 -0
  26. package/lib/commands/user.js +93 -0
  27. package/lib/commands/vault.d.ts +2 -0
  28. package/lib/commands/vault.js +326 -0
  29. package/lib/commands/whoami.d.ts +2 -0
  30. package/lib/commands/whoami.js +45 -0
  31. package/lib/index.d.ts +2 -0
  32. package/lib/index.js +9 -0
  33. package/lib/lib/flags.d.ts +14 -0
  34. package/lib/lib/flags.js +46 -0
  35. package/lib/lib/output.d.ts +7 -0
  36. package/lib/lib/output.js +218 -0
  37. package/lib/lib/prompts.d.ts +24 -0
  38. package/lib/lib/prompts.js +51 -0
  39. package/lib/lib/resolve-vault.d.ts +10 -0
  40. package/lib/lib/resolve-vault.js +137 -0
  41. package/lib/lib/version.d.ts +2 -0
  42. package/lib/lib/version.js +27 -0
  43. package/lib/lib/watch.d.ts +4 -0
  44. package/lib/lib/watch.js +38 -0
  45. package/lib/main.d.ts +3 -0
  46. package/lib/main.js +55 -0
  47. package/lib/notify-update.d.ts +1 -0
  48. package/lib/notify-update.js +38 -0
  49. package/package.json +67 -3
  50. package/skills/upshift.md +212 -0
@@ -0,0 +1,326 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerVault = registerVault;
4
+ const config_1 = require("@upshiftfinance/config");
5
+ const flags_1 = require("../lib/flags");
6
+ const output_1 = require("../lib/output");
7
+ const resolve_vault_1 = require("../lib/resolve-vault");
8
+ const watch_1 = require("../lib/watch");
9
+ function resolveChain(flags) {
10
+ return (0, config_1.getDefaultChainId)({
11
+ cliRpcChainId: flags.chain,
12
+ profileName: flags.profile,
13
+ });
14
+ }
15
+ async function buildSdk(flags) {
16
+ return (0, config_1.createSDK)({
17
+ profileName: flags.profile,
18
+ chainId: flags.chain,
19
+ cliRpcUrl: flags.rpc,
20
+ });
21
+ }
22
+ function toNumber(v) {
23
+ if (typeof v === 'number' && Number.isFinite(v))
24
+ return v;
25
+ if (typeof v === 'string' && v !== '' && !Number.isNaN(Number(v))) {
26
+ return Number(v);
27
+ }
28
+ return undefined;
29
+ }
30
+ function toBigNumeric(v) {
31
+ if (typeof v === 'number' || typeof v === 'string')
32
+ return v;
33
+ if (v !== null && typeof v === 'object' && 'normalized' in v) {
34
+ const n = v.normalized;
35
+ if (typeof n === 'string' || typeof n === 'number')
36
+ return n;
37
+ }
38
+ return undefined;
39
+ }
40
+ function registerVault(program) {
41
+ const vault = program.command('vault').description('Vault read commands');
42
+ vault
43
+ .command('list')
44
+ .description('List known vault names with their address and chain id')
45
+ .action(async function () {
46
+ const flags = (0, flags_1.readGlobalFlags)(this);
47
+ await (0, output_1.runCommand)('vault.list', config_1.schemas.VaultListSchema, flags, async () => {
48
+ const vaults = await (0, resolve_vault_1.listKnownVaults)(flags.chain);
49
+ return { vaults };
50
+ });
51
+ });
52
+ vault
53
+ .command('get <vault>')
54
+ .description('Vault metadata for an address or name (e.g. eth-coreusdc)')
55
+ .action(async function (vaultInput) {
56
+ const flags = (0, flags_1.readGlobalFlags)(this);
57
+ await (0, output_1.runCommand)('vault.get', config_1.schemas.VaultGetSchema, flags, async () => {
58
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
59
+ const sdk = await buildSdk(flags);
60
+ const raw = (await sdk.vaultsModule.getVault({
61
+ vault: resolved.address,
62
+ chainId: resolved.chainId,
63
+ }));
64
+ return {
65
+ address: resolved.address,
66
+ chainId: resolved.chainId,
67
+ ...raw,
68
+ };
69
+ });
70
+ });
71
+ vault
72
+ .command('apy <vault>')
73
+ .description('Current and annualized APY')
74
+ .action(async function (vaultInput) {
75
+ const flags = (0, flags_1.readGlobalFlags)(this);
76
+ await (0, output_1.runCommand)('vault.apy', config_1.schemas.VaultApySchema, flags, async () => {
77
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
78
+ const sdk = await buildSdk(flags);
79
+ sdk.switchNetwork(resolved.chainId);
80
+ const current = await sdk.vaultsModule.getVaultApy({
81
+ vault: resolved.address,
82
+ });
83
+ const annualized = await sdk.vaultsModule
84
+ .getVaultAnnualizedApy(resolved.address)
85
+ .catch(() => undefined);
86
+ const currentApy = Array.isArray(current)
87
+ ? toNumber(current[0]?.value)
88
+ : toNumber(current?.value);
89
+ const annualizedApy = annualized && typeof annualized === 'object' && 'apy' in annualized
90
+ ? toNumber(annualized.apy)
91
+ : undefined;
92
+ return {
93
+ address: resolved.address,
94
+ chainId: resolved.chainId,
95
+ currentApy,
96
+ annualizedApy,
97
+ asOf: new Date().toISOString(),
98
+ };
99
+ });
100
+ });
101
+ vault
102
+ .command('tvl <vault>')
103
+ .description('Total value locked')
104
+ .action(async function (vaultInput) {
105
+ const flags = (0, flags_1.readGlobalFlags)(this);
106
+ await (0, output_1.runCommand)('vault.tvl', config_1.schemas.VaultTvlSchema, flags, async () => {
107
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
108
+ const sdk = await buildSdk(flags);
109
+ const result = await sdk.vaultsModule.getVaultTvl({
110
+ vault: resolved.address,
111
+ chainId: resolved.chainId,
112
+ });
113
+ const first = Array.isArray(result) ? result[0] : result;
114
+ const tvl = toBigNumeric(first?.value);
115
+ if (tvl === undefined) {
116
+ throw new Error(`Vault ${resolved.address} returned an unrecognised TVL shape.`);
117
+ }
118
+ return {
119
+ address: resolved.address,
120
+ chainId: resolved.chainId,
121
+ tvl,
122
+ asOf: new Date().toISOString(),
123
+ };
124
+ });
125
+ });
126
+ vault
127
+ .command('positions <vault>')
128
+ .description("A wallet's positions in a vault (pass --user; empty without it)")
129
+ .option('--user <wallet>', 'wallet to read positions for')
130
+ .action(async function (vaultInput) {
131
+ const flags = (0, flags_1.readGlobalFlags)(this);
132
+ const opts = this.opts();
133
+ await (0, output_1.runCommand)('vault.positions', config_1.schemas.VaultPositionsSchema, flags, async () => {
134
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
135
+ const sdk = await buildSdk(flags);
136
+ const raw = (await sdk.vaultsModule.getVaultPositions({
137
+ vault: resolved.address,
138
+ wallet: opts.user,
139
+ chainId: resolved.chainId,
140
+ }));
141
+ return {
142
+ address: resolved.address,
143
+ chainId: resolved.chainId,
144
+ user: opts.user,
145
+ positions: Array.isArray(raw) ? raw : [raw],
146
+ };
147
+ });
148
+ });
149
+ vault
150
+ .command('loans <vault>')
151
+ .description('Outstanding loans funded by the vault')
152
+ .action(async function (vaultInput) {
153
+ const flags = (0, flags_1.readGlobalFlags)(this);
154
+ await (0, output_1.runCommand)('vault.loans', config_1.schemas.VaultLoansSchema, flags, async () => {
155
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
156
+ const sdk = await buildSdk(flags);
157
+ const raw = (await sdk.vaultsModule.getVaultLoans({
158
+ vault: resolved.address,
159
+ chainId: resolved.chainId,
160
+ }));
161
+ return {
162
+ address: resolved.address,
163
+ chainId: resolved.chainId,
164
+ loans: Array.isArray(raw) ? raw : [raw],
165
+ };
166
+ });
167
+ });
168
+ vault
169
+ .command('allocations <vault>')
170
+ .description('Allocations across underlying strategies')
171
+ .action(async function (vaultInput) {
172
+ const flags = (0, flags_1.readGlobalFlags)(this);
173
+ await (0, output_1.runCommand)('vault.allocations', config_1.schemas.VaultAllocationsSchema, flags, async () => {
174
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
175
+ const sdk = await buildSdk(flags);
176
+ const raw = (await sdk.vaultsModule.getVaultAllocations({
177
+ vault: resolved.address,
178
+ chainId: resolved.chainId,
179
+ }));
180
+ return {
181
+ address: resolved.address,
182
+ chainId: resolved.chainId,
183
+ allocations: Array.isArray(raw) ? raw : [raw],
184
+ };
185
+ });
186
+ });
187
+ vault
188
+ .command('redemptions <vault>')
189
+ .description('Open + historical redemption requests (optionally one wallet via --user)')
190
+ .option('--user <wallet>', 'filter to a single wallet')
191
+ .option('--lookback-blocks <n>', 'how far back to scan for history', (v) => Number(v))
192
+ .action(async function (vaultInput) {
193
+ const flags = (0, flags_1.readGlobalFlags)(this);
194
+ const opts = this.opts();
195
+ await (0, output_1.runCommand)('vault.redemptions', config_1.schemas.VaultRedemptionsSchema, flags, async () => {
196
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
197
+ const sdk = await buildSdk(flags);
198
+ const wallet = opts.user;
199
+ const [availableRaw, historyRaw] = await Promise.all([
200
+ sdk.vaultsModule.getVaultAvailableRedemptions({
201
+ vault: resolved.address,
202
+ wallet,
203
+ chainId: resolved.chainId,
204
+ }),
205
+ sdk.vaultsModule.getVaultRedemptionHistory({
206
+ vault: resolved.address,
207
+ wallet,
208
+ chainId: resolved.chainId,
209
+ lookbackBlocks: opts.lookbackBlocks,
210
+ }),
211
+ ]);
212
+ return {
213
+ address: resolved.address,
214
+ chainId: resolved.chainId,
215
+ user: opts.user,
216
+ available: Array.isArray(availableRaw)
217
+ ? availableRaw
218
+ : [availableRaw],
219
+ history: Array.isArray(historyRaw)
220
+ ? historyRaw
221
+ : [historyRaw],
222
+ };
223
+ });
224
+ });
225
+ vault
226
+ .command('history <vault>')
227
+ .description('Historical TVL / APY timeseries')
228
+ .option('--days <n>', 'lookback window (days)', (v) => Number(v))
229
+ .action(async function (vaultInput) {
230
+ const flags = (0, flags_1.readGlobalFlags)(this);
231
+ const opts = this.opts();
232
+ await (0, output_1.runCommand)('vault.history', config_1.schemas.VaultHistorySchema, flags, async () => {
233
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
234
+ const sdk = await buildSdk(flags);
235
+ sdk.switchNetwork(resolved.chainId);
236
+ const raw = (await sdk.vaultsModule.getVaultHistoricalTimeseries({
237
+ vault: resolved.address,
238
+ nDays: opts.days,
239
+ }));
240
+ return {
241
+ address: resolved.address,
242
+ chainId: resolved.chainId,
243
+ series: Array.isArray(raw) ? raw : [raw],
244
+ };
245
+ });
246
+ });
247
+ vault
248
+ .command('summary <vault>')
249
+ .description('Composite summary (metadata + APY + TVL)')
250
+ .action(async function (vaultInput) {
251
+ const flags = (0, flags_1.readGlobalFlags)(this);
252
+ await (0, output_1.runCommand)('vault.summary', config_1.schemas.VaultSummarySchema, flags, async () => {
253
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
254
+ const sdk = await buildSdk(flags);
255
+ sdk.switchNetwork(resolved.chainId);
256
+ const raw = (await sdk.vaultsModule.getVaultSummary(resolved.address));
257
+ return {
258
+ address: resolved.address,
259
+ chainId: resolved.chainId,
260
+ ...raw,
261
+ };
262
+ });
263
+ });
264
+ vault
265
+ .command('pending-redemptions <vault>')
266
+ .description('Backend redemption queue: liquidity sufficiency and per-due-date breakdown')
267
+ .option('--past-days <n>', 'days of already-due redemptions', (v) => Number(v))
268
+ .option('--future-days <n>', 'days of upcoming redemptions', (v) => Number(v))
269
+ .option('--watch <seconds>', 'poll and re-render every N seconds')
270
+ .action(async function (vaultInput) {
271
+ const flags = (0, flags_1.readGlobalFlags)(this);
272
+ const opts = this.opts();
273
+ await (0, watch_1.runWatched)('vault.pending-redemptions', config_1.schemas.PendingRedemptionsSchema, flags, opts.watch, async () => {
274
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
275
+ const sdk = await (0, config_1.createSDK)({
276
+ profileName: flags.profile,
277
+ chainId: resolved.chainId,
278
+ cliRpcUrl: flags.rpc,
279
+ });
280
+ sdk.switchNetwork(resolved.chainId);
281
+ const raw = await sdk.vaultsModule.getVaultPendingRedemptions({
282
+ vault: resolved.address,
283
+ pastDays: opts.pastDays,
284
+ futureDays: opts.futureDays,
285
+ });
286
+ return {
287
+ address: resolved.address,
288
+ chainId: resolved.chainId,
289
+ ...raw,
290
+ };
291
+ });
292
+ });
293
+ vault
294
+ .command('pnl-history <vault>')
295
+ .description('Unrealized-PnL snapshot series for a vault, newest first')
296
+ .option('--limit <n>', 'max snapshots to return (1-1000)', (v) => Number(v))
297
+ .action(async function (vaultInput) {
298
+ const flags = (0, flags_1.readGlobalFlags)(this);
299
+ const opts = this.opts();
300
+ await (0, output_1.runCommand)('vault.pnl-history', config_1.schemas.VaultPnlHistorySchema, flags, async () => {
301
+ const resolved = await (0, resolve_vault_1.resolveVault)(vaultInput, resolveChain(flags));
302
+ const sdk = await buildSdk(flags);
303
+ const snapshots = await sdk.getVaultUnrealizedPnlHistory({
304
+ vault: resolved.address,
305
+ limit: opts.limit,
306
+ });
307
+ return {
308
+ address: resolved.address,
309
+ chainId: resolved.chainId,
310
+ snapshots,
311
+ };
312
+ });
313
+ });
314
+ vault
315
+ .command('pnl-latest')
316
+ .description('Latest unrealized-PnL snapshot for every vault the backend tracks')
317
+ .action(async function () {
318
+ const flags = (0, flags_1.readGlobalFlags)(this);
319
+ await (0, output_1.runCommand)('vault.pnl-latest', config_1.schemas.PnlLatestSchema, flags, async () => {
320
+ const sdk = await buildSdk(flags);
321
+ const snapshots = await sdk.getLatestUnrealizedPnl();
322
+ return { snapshots };
323
+ });
324
+ });
325
+ }
326
+ //# sourceMappingURL=vault.js.map
@@ -0,0 +1,2 @@
1
+ import type { Command } from 'commander';
2
+ export declare function registerWhoami(program: Command): void;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerWhoami = registerWhoami;
4
+ const config_1 = require("@upshiftfinance/config");
5
+ const flags_1 = require("../lib/flags");
6
+ const output_1 = require("../lib/output");
7
+ const version_1 = require("../lib/version");
8
+ function resolveApiKeyStatus() {
9
+ if ((0, config_1.readEnv)('API_KEY')) {
10
+ return { present: true, source: 'env' };
11
+ }
12
+ try {
13
+ const session = (0, config_1.readSession)();
14
+ if (session?.apiKey) {
15
+ return {
16
+ present: true,
17
+ source: 'session',
18
+ sessionExpiresAt: new Date(session.expiresAt).toISOString(),
19
+ };
20
+ }
21
+ }
22
+ catch {
23
+ }
24
+ return { present: false, source: 'none' };
25
+ }
26
+ function registerWhoami(program) {
27
+ program
28
+ .command('whoami')
29
+ .description('Print the active profile, chain, API key status, and versions')
30
+ .action(async function () {
31
+ const flags = (0, flags_1.readGlobalFlags)(this);
32
+ await (0, output_1.runCommand)('whoami', config_1.schemas.WhoamiSchema, flags, async () => {
33
+ const cfg = (0, config_1.loadConfig)();
34
+ return {
35
+ profile: flags.profile ?? cfg.defaultProfile,
36
+ defaultChainId: flags.chain ?? cfg.defaultChainId,
37
+ configDir: (0, config_1.activeConfigDir)(),
38
+ cliVersion: (0, version_1.getCliVersion)(),
39
+ sdkVersion: (0, version_1.getSdkVersion)(),
40
+ apiKey: resolveApiKeyStatus(),
41
+ };
42
+ });
43
+ });
44
+ }
45
+ //# sourceMappingURL=whoami.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { notifyOfUpdate } from './notify-update';
2
+ export { buildProgram, main } from './main';
package/lib/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.main = exports.buildProgram = exports.notifyOfUpdate = void 0;
4
+ var notify_update_1 = require("./notify-update");
5
+ Object.defineProperty(exports, "notifyOfUpdate", { enumerable: true, get: function () { return notify_update_1.notifyOfUpdate; } });
6
+ var main_1 = require("./main");
7
+ Object.defineProperty(exports, "buildProgram", { enumerable: true, get: function () { return main_1.buildProgram; } });
8
+ Object.defineProperty(exports, "main", { enumerable: true, get: function () { return main_1.main; } });
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ import { Command } from 'commander';
2
+ export declare function parseChainId(value: string): number;
3
+ export interface GlobalFlags {
4
+ json: boolean;
5
+ csv: boolean;
6
+ noColor: boolean;
7
+ verbose: boolean;
8
+ chain?: number;
9
+ rpc?: string;
10
+ profile?: string;
11
+ configDir?: string;
12
+ }
13
+ export declare function registerGlobalOptions(program: Command): void;
14
+ export declare function readGlobalFlags(cmd: Command): GlobalFlags;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseChainId = parseChainId;
4
+ exports.registerGlobalOptions = registerGlobalOptions;
5
+ exports.readGlobalFlags = readGlobalFlags;
6
+ const config_1 = require("@upshiftfinance/config");
7
+ const commander_1 = require("commander");
8
+ function parseChainId(value) {
9
+ const trimmed = value.trim();
10
+ const chainId = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;
11
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) {
12
+ throw new config_1.UpshiftConfigError('INVALID_INPUT', `--chain must be a positive integer chain id, received "${value}"`, 'Pass a numeric chain id, e.g. --chain 1 (Ethereum) or --chain 8453 (Base). Run `upshift chain list` to see supported ids.');
13
+ }
14
+ return chainId;
15
+ }
16
+ function registerGlobalOptions(program) {
17
+ program
18
+ .addOption(new commander_1.Option('--json', 'print the JSON envelope on stdout'))
19
+ .addOption(new commander_1.Option('--csv', 'print CSV (tabular commands only)'))
20
+ .addOption(new commander_1.Option('--no-color', 'disable ANSI colors'))
21
+ .addOption(new commander_1.Option('--verbose', 'verbose diagnostics on stderr'))
22
+ .option('--chain <id>', 'chain id for this call', parseChainId)
23
+ .option('--rpc <url>', 'RPC URL override (pair with --chain)')
24
+ .option('--profile <name>', 'named profile to activate')
25
+ .option('--config-dir <path>', 'override ~/.upshift')
26
+ .hook('preAction', (thisCommand) => {
27
+ const opts = thisCommand.opts();
28
+ if (typeof opts.configDir === 'string' && opts.configDir.length > 0) {
29
+ process.env.UPSHIFT_CONFIG_DIR = opts.configDir;
30
+ }
31
+ });
32
+ }
33
+ function readGlobalFlags(cmd) {
34
+ const opts = cmd.optsWithGlobals();
35
+ return {
36
+ json: Boolean(opts.json),
37
+ csv: Boolean(opts.csv),
38
+ noColor: opts.color === false,
39
+ verbose: Boolean(opts.verbose),
40
+ chain: typeof opts.chain === 'number' ? opts.chain : undefined,
41
+ rpc: typeof opts.rpc === 'string' ? opts.rpc : undefined,
42
+ profile: typeof opts.profile === 'string' ? opts.profile : undefined,
43
+ configDir: typeof opts.configDir === 'string' ? opts.configDir : undefined,
44
+ };
45
+ }
46
+ //# sourceMappingURL=flags.js.map
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+ import { schemas } from '@upshiftfinance/config';
3
+ import { GlobalFlags } from './flags';
4
+ export declare function printSuccess<TSchema extends z.ZodTypeAny>(command: string, schema: TSchema, data: z.infer<TSchema>, flags: GlobalFlags, durationMs?: number): void;
5
+ export declare function printError(command: string, err: unknown, flags: GlobalFlags, durationMs?: number): void;
6
+ export declare function runCommand<TSchema extends z.ZodTypeAny>(command: string, schema: TSchema, flags: GlobalFlags, handler: () => Promise<z.infer<TSchema>>): Promise<void>;
7
+ export { schemas };
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.schemas = void 0;
7
+ exports.printSuccess = printSuccess;
8
+ exports.printError = printError;
9
+ exports.runCommand = runCommand;
10
+ const cli_table3_1 = __importDefault(require("cli-table3"));
11
+ const kleur_1 = __importDefault(require("kleur"));
12
+ const zod_1 = require("zod");
13
+ const config_1 = require("@upshiftfinance/config");
14
+ Object.defineProperty(exports, "schemas", { enumerable: true, get: function () { return config_1.schemas; } });
15
+ function configureColor(flags) {
16
+ if (flags.noColor || !process.stdout.isTTY) {
17
+ kleur_1.default.enabled = false;
18
+ }
19
+ }
20
+ function metaNow(flags, durationMs) {
21
+ return {
22
+ chainId: flags.chain,
23
+ durationMs,
24
+ generatedAt: new Date().toISOString(),
25
+ };
26
+ }
27
+ function writeStdout(s) {
28
+ process.stdout.write(s);
29
+ if (!s.endsWith('\n'))
30
+ process.stdout.write('\n');
31
+ }
32
+ function renderHumanData(data) {
33
+ if (data === null || data === undefined)
34
+ return '(no data)';
35
+ if (typeof data !== 'object')
36
+ return String(data);
37
+ if (Array.isArray(data)) {
38
+ if (data.length === 0)
39
+ return '(empty list)';
40
+ if (typeof data[0] === 'object' && data[0] !== null) {
41
+ const cols = Array.from(new Set(data.flatMap((row) => Object.keys(row))));
42
+ const table = new cli_table3_1.default({ head: cols });
43
+ for (const row of data) {
44
+ const r = row;
45
+ table.push(cols.map((c) => formatScalar(r[c])));
46
+ }
47
+ return table.toString();
48
+ }
49
+ return data.map((v) => `- ${formatScalar(v)}`).join('\n');
50
+ }
51
+ const entries = Object.entries(data);
52
+ if (entries.length === 1 && Array.isArray(entries[0][1])) {
53
+ return renderHumanData(entries[0][1]);
54
+ }
55
+ const longest = entries.reduce((m, [k]) => Math.max(m, k.length), 0);
56
+ return entries
57
+ .map(([k, v]) => `${kleur_1.default.dim(k.padEnd(longest))} ${formatNested(v)}`)
58
+ .join('\n');
59
+ }
60
+ function formatNested(v) {
61
+ if (v === null || v === undefined)
62
+ return kleur_1.default.dim('(none)');
63
+ if (typeof v !== 'object')
64
+ return formatScalar(v);
65
+ return JSON.stringify(v);
66
+ }
67
+ function formatScalar(v) {
68
+ if (v === null || v === undefined)
69
+ return '';
70
+ if (typeof v === 'boolean')
71
+ return v ? 'true' : 'false';
72
+ return String(v);
73
+ }
74
+ function printSuccess(command, schema, data, flags, durationMs) {
75
+ configureColor(flags);
76
+ const validated = schema.parse(data);
77
+ const envelope = {
78
+ schemaVersion: 1,
79
+ command,
80
+ ok: true,
81
+ data: validated,
82
+ meta: metaNow(flags, durationMs),
83
+ };
84
+ if (flags.json) {
85
+ writeStdout(JSON.stringify(envelope));
86
+ return;
87
+ }
88
+ if (flags.csv && Array.isArray(validated)) {
89
+ writeStdout(toCsv(validated));
90
+ return;
91
+ }
92
+ writeStdout(renderHumanData(validated));
93
+ }
94
+ function printError(command, err, flags, durationMs) {
95
+ configureColor(flags);
96
+ const cfgErr = asUpshiftConfigError(err);
97
+ const rpcErr = inferRpcHttpError(err);
98
+ const authErr = inferAuthError(err);
99
+ const code = cfgErr?.code ?? authErr?.code ?? rpcErr?.code ?? inferCode(err);
100
+ const message = err instanceof Error ? err.message : String(err);
101
+ const remediation = cfgErr?.remediation ?? authErr?.remediation ?? rpcErr?.remediation;
102
+ const envelope = {
103
+ schemaVersion: 1,
104
+ command,
105
+ ok: false,
106
+ error: { code, message, remediation },
107
+ meta: metaNow(flags, durationMs),
108
+ };
109
+ if (flags.json) {
110
+ writeStdout(JSON.stringify(envelope));
111
+ return;
112
+ }
113
+ const out = [];
114
+ out.push(`${kleur_1.default.red().bold('Error')} ${kleur_1.default.bold(code)}`);
115
+ out.push(message);
116
+ if (remediation)
117
+ out.push(kleur_1.default.cyan(`Hint: ${remediation}`));
118
+ process.stderr.write(out.join('\n') + '\n');
119
+ }
120
+ function asUpshiftConfigError(err) {
121
+ if (err instanceof config_1.UpshiftConfigError)
122
+ return err;
123
+ if (err !== null &&
124
+ typeof err === 'object' &&
125
+ 'code' in err &&
126
+ 'name' in err &&
127
+ err.name === 'UpshiftConfigError') {
128
+ return err;
129
+ }
130
+ return null;
131
+ }
132
+ function inferCode(err) {
133
+ if (err instanceof zod_1.z.ZodError)
134
+ return 'SCHEMA_MISMATCH';
135
+ if (err instanceof Error && err.name === 'SyntaxError')
136
+ return 'PARSE_ERROR';
137
+ return 'INTERNAL';
138
+ }
139
+ function inferAuthError(err) {
140
+ const code = err !== null && typeof err === 'object'
141
+ ? err.code
142
+ : undefined;
143
+ if (code === 'AUTH_UNAUTHORIZED') {
144
+ return {
145
+ code: 'API_KEY_MISSING',
146
+ remediation: 'The Upshift backend rejected this request — no API key was sent, or the one supplied is invalid or expired. Run `upshift login` to unlock your keystore, or check UPSHIFT_API_KEY.',
147
+ };
148
+ }
149
+ if (code === 'AUTH_FORBIDDEN') {
150
+ return {
151
+ code: 'API_KEY_FORBIDDEN',
152
+ remediation: 'The API key is valid but not permitted for this endpoint. Use a key with the required scope (admin endpoints need an admin key); retrying will not help.',
153
+ };
154
+ }
155
+ return undefined;
156
+ }
157
+ function inferRpcHttpError(err) {
158
+ if (!(err instanceof Error))
159
+ return undefined;
160
+ const msg = err.message;
161
+ if (/\b403 Forbidden\b/.test(msg)) {
162
+ return {
163
+ code: 'RPC_FORBIDDEN',
164
+ remediation: 'The configured RPC returned 403. Common cause: an Alchemy/Infura key with an Origin/IP allowlist restriction. ' +
165
+ 'Either remove the restriction in your provider dashboard, set a different `rpcs.<chainId>` ' +
166
+ '(see `upshift config set rpcs.<chainId> <url>`), or unset it to fall back to a public RPC.',
167
+ };
168
+ }
169
+ if (/\b401 Unauthorized\b/.test(msg)) {
170
+ return {
171
+ code: 'RPC_UNAUTHORIZED',
172
+ remediation: 'The configured RPC returned 401. The API key is missing or invalid. ' +
173
+ 'Update your `rpcs.<chainId>` value or unset it to fall back to a public RPC.',
174
+ };
175
+ }
176
+ if (/\b429\b/.test(msg) && /rate ?limit|too many/i.test(msg)) {
177
+ return {
178
+ code: 'RPC_RATE_LIMITED',
179
+ remediation: 'The configured RPC is rate-limiting requests. Slow down, upgrade your provider plan, ' +
180
+ 'or set a different `rpcs.<chainId>` value.',
181
+ };
182
+ }
183
+ return undefined;
184
+ }
185
+ function toCsv(rows) {
186
+ if (rows.length === 0)
187
+ return '';
188
+ const first = rows[0];
189
+ if (typeof first !== 'object' || first === null) {
190
+ return rows.map((r) => csvCell(r)).join('\n');
191
+ }
192
+ const cols = Array.from(new Set(rows.flatMap((row) => Object.keys(row))));
193
+ const head = cols.map(csvCell).join(',');
194
+ const body = rows
195
+ .map((row) => cols
196
+ .map((c) => csvCell(row[c]))
197
+ .join(','))
198
+ .join('\n');
199
+ return `${head}\n${body}`;
200
+ }
201
+ function csvCell(v) {
202
+ if (v === null || v === undefined)
203
+ return '';
204
+ const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
205
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
206
+ }
207
+ async function runCommand(command, schema, flags, handler) {
208
+ const start = Date.now();
209
+ try {
210
+ const data = await handler();
211
+ printSuccess(command, schema, data, flags, Date.now() - start);
212
+ }
213
+ catch (err) {
214
+ printError(command, err, flags, Date.now() - start);
215
+ process.exitCode = 1;
216
+ }
217
+ }
218
+ //# sourceMappingURL=output.js.map