-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
executable file
·420 lines (380 loc) · 15.1 KB
/
utils.ts
File metadata and controls
executable file
·420 lines (380 loc) · 15.1 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { ethers } from '@paynodelabs/sdk-js';
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import pkg from './package.json';
// --- Environment (System Only) ---
// [SECURITY] This skill strictly uses system environment variables for better update persistence
// and to avoid plaintext private keys on disk. .env files are no longer supported.
if (!process.env.CLIENT_PRIVATE_KEY) {
// We don't exit here because some commands like 'check' or 'mint' provide their own helpful setup tips.
// getPrivateKey() will handle the final enforcement.
}
/**
* Centralized Configuration Loader
* [SECURITY] Consolidates environment variable access for better auditing.
* Priority: 1. System Environment Variable (B) | 2. XDG Config File (A)
*/
function loadConfig() {
const home = process.env.HOME || process.env.USERPROFILE || '';
const xdgConfigHome = process.env.XDG_CONFIG_HOME || join(home, '.config');
const xdgConfigPath = join(xdgConfigHome, 'paynode', 'config.json');
let localConfig: Record<string, string> = {};
if (fs.existsSync(xdgConfigPath)) {
try {
localConfig = JSON.parse(fs.readFileSync(xdgConfigPath, 'utf8'));
} catch { /* ignore invalid json */ }
}
return {
MARKETPLACE_URL: process.env.PAYNODE_MARKET_URL || localConfig.PAYNODE_MARKET_URL || 'https://mk.paynode.dev',
PRIVATE_KEY: process.env.CLIENT_PRIVATE_KEY || localConfig.CLIENT_PRIVATE_KEY,
CUSTOM_ROUTER: process.env.CUSTOM_ROUTER_ADDRESS || localConfig.CUSTOM_ROUTER_ADDRESS,
CUSTOM_USDC: process.env.CUSTOM_USDC_ADDRESS || localConfig.CUSTOM_USDC_ADDRESS,
RPC_URL_OVERRIDE: process.env.PAYNODE_RPC_URL || process.env.RPC_URL || localConfig.PAYNODE_RPC_URL,
RPC_TIMEOUT: Number(process.env.PAYNODE_RPC_TIMEOUT || localConfig.PAYNODE_RPC_TIMEOUT) || 15_000,
configSource: process.env.CLIENT_PRIVATE_KEY ? 'env' : (localConfig.CLIENT_PRIVATE_KEY ? 'file' : 'missing'),
configFilePath: xdgConfigPath
};
}
export const GLOBAL_CONFIG = loadConfig();
/**
* Skill version for JSON output metadata.
*/
import sdkPkg from '@paynodelabs/sdk-js/package.json';
/**
* Skill version and runtime SDK version.
*/
export const SKILL_VERSION = pkg.version;
export const SDK_VERSION = sdkPkg.version; // Dynamically resolved from installed package
/**
* Shared base options for all CLI commands.
*/
export interface BaseCliOptions {
json?: boolean;
network?: string;
rpc?: string;
rpcTimeout?: number;
confirmMainnet?: boolean;
dryRun?: boolean;
marketUrl?: string;
}
/**
* Network configuration object.
*/
export interface NetworkConfig {
provider: ethers.JsonRpcProvider;
chainId: number;
isSandbox: boolean;
rpcUrl: string;
rpcUrls: string[];
usdcAddress: string;
routerAddress: string;
networkName: string;
}
/**
* CLI config from parsed arguments (CAC managed, but kept here for type reference).
*/
export interface CliConfig {
isJson: boolean;
isHelp: boolean;
isDryRun: boolean;
confirmMainnet: boolean;
background: boolean;
output?: string;
maxAge?: number;
taskDir?: string;
taskId?: string;
rpcUrl?: string;
network?: string;
marketUrl?: string;
method?: string;
data?: string;
headers?: Record<string, string>;
params: string[];
}
/**
* Standardized Exit Codes
*/
export const EXIT_CODES = {
SUCCESS: 0,
GENERIC_ERROR: 1,
INVALID_ARGS: 2,
AUTH_FAILURE: 3,
NETWORK_ERROR: 4,
MAINNET_REJECTED: 5,
PAYMENT_FAILED: 6,
INSUFFICIENT_FUNDS: 7,
DUST_LIMIT: 8,
RPC_TIMEOUT: 9,
DUPLICATE_TRANSACTION: 10,
WRONG_CONTRACT: 11,
ORDER_MISMATCH: 12,
MISSING_RECEIPT: 13,
INTERNAL_ERROR: 14
} as const;
export const DEFAULT_TIMEOUT_MS = 15_000;
const MAX_RETRIES = 3;
/**
* Executes an async operation with exponential backoff retry.
*/
export async function withRetry<T>(
fn: () => Promise<T>,
label: string,
maxRetries = MAX_RETRIES,
quiet = false
): Promise<T> {
let lastError: Error | null = null;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error: any) {
lastError = error;
if (!isTransientError(error) || attempt >= maxRetries - 1) throw error;
const backoffMs = Math.pow(2, attempt) * 1000 * (0.5 + Math.random());
if (!quiet) console.error(`⚠️ [${label}] ${error.message}. Retry #${attempt + 1} (of ${maxRetries - 1}) in ${Math.round(backoffMs)}ms...`);
await new Promise(resolve => setTimeout(resolve, backoffMs));
}
}
throw lastError || new Error(`${label} failed after ${maxRetries} retries`);
}
function isTransientError(error: any): boolean {
const msg = (error?.message || '').toLowerCase();
const code = error?.code || '';
// --- Error Unwrap ---
// Extract the deepest cause if it's an RpcError wrapping another error
const details = error?.details;
const detailMsg = details
? (details.message || (typeof details === 'string' ? details : JSON.stringify(details))).toLowerCase()
: '';
// Never retry if it's a known non-transient failure
const isNonRetryableCode = [
'CALL_EXCEPTION',
'INVALID_ARGUMENT',
'UNSUPPORTED_OPERATION',
'ACTION_REJECTED',
'INSUFFICIENT_FUNDS'
].includes(code);
if (
isNonRetryableCode ||
msg.includes('insufficient funds') ||
msg.includes('execution reverted') ||
detailMsg.includes('insufficient funds') ||
detailMsg.includes('execution reverted')
) {
return false;
}
const isRetryableCode = [
'NETWORK_ERROR',
'SERVER_ERROR',
'TIMEOUT',
'UNKNOWN_ERROR',
'rpc_error'
].includes(code);
return (
isRetryableCode ||
msg.includes('timeout') ||
msg.includes('network') ||
msg.includes('fetch failed') ||
msg.includes('econnrefused') ||
msg.includes('econnreset') ||
msg.includes('socket hang up') ||
detailMsg.includes('timeout') ||
detailMsg.includes('network')
);
}
export const DEFAULT_TASK_DIR = process.env.PAYNODE_TASK_DIR || join(tmpdir(), 'paynode-tasks');
export const DEFAULT_MAX_AGE_SECONDS = Number(process.env.PAYNODE_MAX_AGE) || 3600;
export function generateTaskId(): string {
const ts = Date.now().toString(36);
const rand = Math.random().toString(36).substring(2, 6);
return `${ts}-${rand}`;
}
export function maskAddress(address: string): string {
if (!address || address.length < 10) return address;
return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
}
export function isInlineContent(contentType: string): boolean {
const ct = (contentType || '').split(';')[0].trim().toLowerCase();
return (
ct.startsWith('text/') ||
ct === 'application/json' ||
ct === 'application/javascript' ||
ct === 'application/xml' ||
ct === 'application/x-www-form-urlencoded'
);
}
export function cleanupOldTasks(taskDir: string, maxAgeSeconds: number): number {
try {
if (!fs.existsSync(taskDir)) return 0;
const now = Date.now();
const cutoff = now - maxAgeSeconds * 1000;
let cleaned = 0;
for (const file of fs.readdirSync(taskDir)) {
if (file.startsWith('.')) continue;
const fullPath = join(taskDir, file);
try {
const stat = fs.statSync(fullPath);
// mtimeMs can be updated by reads (depending on mount options),
// birthtimeMs is creation. Use the minimum or birthtime for safe cleanup.
const effectiveTime = Math.min(stat.mtimeMs, stat.birthtimeMs || stat.mtimeMs);
if (effectiveTime < cutoff) {
fs.unlinkSync(fullPath);
cleaned++;
}
} catch { /* skip */ }
}
return cleaned;
} catch { return 0; }
}
/**
* Validates existence and format of CLIENT_PRIVATE_KEY.
*/
export function getPrivateKey(isJson: boolean): string {
const pk: string | undefined = GLOBAL_CONFIG.PRIVATE_KEY;
if (!pk || typeof pk !== 'string') {
const msg = `CLIENT_PRIVATE_KEY not found. Please set environment (B) or create config file (A) at: ${GLOBAL_CONFIG.configFilePath}`;
reportError(msg, isJson, EXIT_CODES.AUTH_FAILURE);
}
const pkRegex = /^0x[0-9a-fA-F]{64}$/;
if (!pkRegex.test(pk)) {
reportError('Invalid CLIENT_PRIVATE_KEY format. Must be 0x-prefixed 64-hex chars.', isJson, EXIT_CODES.AUTH_FAILURE);
}
return pk;
}
/**
* Validates mainnet access.
*/
export function requireMainnetConfirmation(isSandbox: boolean, confirmMainnet: boolean, isJson: boolean): void {
if (isSandbox) return;
if (!confirmMainnet) {
reportError(
'Mainnet operation requires --confirm-mainnet flag (real USDC).',
isJson,
EXIT_CODES.MAINNET_REJECTED
);
}
}
/**
* Resolves network configuration with multi-RPC failover.
*/
export async function resolveNetwork(providedRpcUrl?: string, network?: string, timeoutMs = DEFAULT_TIMEOUT_MS, quiet = false): Promise<NetworkConfig> {
const {
PAYNODE_ROUTER_ADDRESS,
PAYNODE_ROUTER_ADDRESS_SANDBOX,
BASE_USDC_ADDRESS,
BASE_USDC_ADDRESS_SANDBOX,
BASE_RPC_URLS,
BASE_RPC_URLS_SANDBOX
} = await import('@paynodelabs/sdk-js');
const networkAlias = (network || '').toLowerCase();
const isTestnetRequest =
networkAlias === 'testnet' ||
networkAlias === 'sepolia' ||
networkAlias === 'base-sepolia' ||
networkAlias === '84532' ||
networkAlias === 'base-testnet';
const effectiveRpcUrl = providedRpcUrl || GLOBAL_CONFIG.RPC_URL_OVERRIDE;
const sdkRpcUrls = (isTestnetRequest ? (BASE_RPC_URLS_SANDBOX || []) : (BASE_RPC_URLS || []));
const rpcUrls: string[] = effectiveRpcUrl ? [effectiveRpcUrl] : sdkRpcUrls;
let lastError: Error | null = null;
let provider: ethers.JsonRpcProvider | null = null;
let chainId: bigint | null = null;
let activeRpcUrl: string | null = null;
for (const url of rpcUrls) {
try {
const tempProvider = new ethers.JsonRpcProvider(url, undefined, { staticNetwork: true, batchMaxCount: 1 });
const networkInfo = await Promise.race([
tempProvider.getNetwork(),
new Promise<never>((_, reject) => setTimeout(() => reject(new Error('RPC timeout')), timeoutMs))
]);
provider = tempProvider;
chainId = networkInfo.chainId;
activeRpcUrl = url;
break;
} catch (error: any) {
lastError = error;
if (rpcUrls.length > 1 && !quiet) console.error(`⚠️ [resolveNetwork] RPC ${url} failed: ${error.message}.`);
}
}
if (!provider || !chainId || !activeRpcUrl) {
throw new Error(`Failed to connect to any RPC in [${rpcUrls.join(', ')}]: ${lastError?.message}`);
}
const isSandbox = chainId === 84532n;
const networkName = isSandbox ? 'Base Sepolia (84532)' : 'Base L2 (8453)';
const customRouter = GLOBAL_CONFIG.CUSTOM_ROUTER;
const customUsdc = GLOBAL_CONFIG.CUSTOM_USDC;
return {
provider,
chainId: Number(chainId),
isSandbox,
rpcUrl: activeRpcUrl,
rpcUrls,
usdcAddress: customUsdc || (isSandbox ? BASE_USDC_ADDRESS_SANDBOX : BASE_USDC_ADDRESS),
routerAddress: customRouter || (isSandbox ? PAYNODE_ROUTER_ADDRESS_SANDBOX : PAYNODE_ROUTER_ADDRESS),
networkName
};
}
export function jsonEnvelope(data: Record<string, any>): string {
return JSON.stringify({
version: SKILL_VERSION,
skill_version: SKILL_VERSION,
sdk_version: SDK_VERSION,
...data
}, null, 2);
}
export function reportError(err: string | Error | any, isJson: boolean, defaultCode: number = EXIT_CODES.GENERIC_ERROR): never {
let message = typeof err === 'string' ? err : (err?.message || 'An unknown error occurred');
let exitCode = defaultCode;
let errorCode: string | undefined;
const isPayNodeException = err?.name === 'PayNodeException' ||
(err?.code && typeof err.code === 'string' && (
err.code.startsWith('paynode_') ||
err.code.startsWith('x402_') ||
(err.code === 'rpc_error' && err?.message?.toLowerCase().includes('paynode'))
));
if (isPayNodeException) {
errorCode = err.code;
// --- Defensive Unwrap ---
// If SDK masks a specific blockchain error as a generic 'rpc_error', try to recover it from details.
if (errorCode === 'rpc_error' && err.details) {
const detailMsg = (err.details.message || JSON.stringify(err.details)).toLowerCase();
if (detailMsg.includes('insufficient funds') || detailMsg.includes('execution reverted')) {
errorCode = 'insufficient_funds';
message = 'Insufficient funds for transaction gas or payment. Please verify ETH/USDC balances.';
} else if (detailMsg.includes('user rejected')) {
errorCode = 'transaction_failed';
message = 'Transaction was rejected by the wallet.';
}
}
switch (errorCode) {
case 'insufficient_funds': exitCode = EXIT_CODES.INSUFFICIENT_FUNDS; break;
case 'amount_too_low': exitCode = EXIT_CODES.DUST_LIMIT; break;
case 'rpc_error': exitCode = EXIT_CODES.RPC_TIMEOUT; break;
case 'transaction_failed': exitCode = EXIT_CODES.PAYMENT_FAILED; break;
case 'token_not_accepted': exitCode = EXIT_CODES.INVALID_ARGS; break;
case 'invalid_receipt': exitCode = EXIT_CODES.PAYMENT_FAILED; break;
case 'wrong_contract': exitCode = EXIT_CODES.WRONG_CONTRACT; break;
case 'order_mismatch': exitCode = EXIT_CODES.ORDER_MISMATCH; break;
case 'duplicate_transaction': exitCode = EXIT_CODES.DUPLICATE_TRANSACTION; break;
case 'missing_receipt': exitCode = EXIT_CODES.MISSING_RECEIPT; break;
case 'transaction_not_found': exitCode = EXIT_CODES.NETWORK_ERROR; break;
case 'internal_error': exitCode = EXIT_CODES.INTERNAL_ERROR; break;
default: exitCode = defaultCode;
}
}
if (isJson) {
console.log(jsonEnvelope({ status: 'error', message, exitCode, errorCode, details: err?.details }));
} else {
const prefix = isPayNodeException ? `🛑 [PayNode-${errorCode}]` : `❌ ERROR:`;
console.error(`${prefix} ${message} (Code: ${exitCode})`);
if (errorCode === 'insufficient_funds') {
console.error(`💡 Tip: Use 'bun run paynode-402 check' to verify ETH/USDC balances.`);
console.error(`💡 Faucet (Testnet): [console.optimism.io/faucet](https://console.optimism.io/faucet)`);
} else if (errorCode === 'amount_too_low') {
const min = err?.details?.minimum || 1000;
console.error(`💡 Tip: Minimum requirement is ${min} units.`);
}
}
process.exit(exitCode);
}