UNPKG

pmarket-cli

Version:
112 lines 3.59 kB
import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"; import { join } from "path"; import { homedir } from "os"; import { ethers } from "ethers"; const PMARKET_CLI_DIR = '.pmarket-cli'; const CONFIG_FILE = 'config.json'; const CREDENTIALS_FILE = 'credentials.json'; const DEFAULT_RPC_PROVIDER = 'https://polygon-rpc.com'; export class ConfigService { config; credentials = null; configDir; configPath; credentialsPath; constructor() { // Allow override via environment variable for testing this.configDir = process.env.PMARKET_CONFIG_DIR || join(homedir(), PMARKET_CLI_DIR); this.configPath = join(this.configDir, CONFIG_FILE); this.credentialsPath = join(this.configDir, CREDENTIALS_FILE); this.ensureConfigDir(); this.config = this.loadOrCreateConfig(); this.loadCredentials(); } ensureConfigDir() { if (!existsSync(this.configDir)) { mkdirSync(this.configDir, { recursive: true }); } } loadOrCreateConfig() { if (existsSync(this.configPath)) { const raw = readFileSync(this.configPath, 'utf8'); return JSON.parse(raw); } const defaultConfig = { privateKey: '' }; writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 4)); return defaultConfig; } loadCredentials() { if (existsSync(this.credentialsPath)) { const raw = readFileSync(this.credentialsPath, 'utf8'); this.credentials = JSON.parse(raw); } } isConfigAvailable() { return existsSync(this.configPath); } getPrivateKey() { return this.config.privateKey; } getRpcProvider() { return DEFAULT_RPC_PROVIDER; } getFunderAddress() { if (!this.config.privateKey) { return ''; } try { const wallet = new ethers.Wallet(this.config.privateKey); return wallet.address; } catch { return ''; } } hasCredentials() { return this.credentials !== null && Boolean(this.credentials.apiKey) && Boolean(this.credentials.apiSecret) && Boolean(this.credentials.passphrase); } getCreds() { if (!this.credentials) { return null; } return { key: this.credentials.apiKey, secret: this.credentials.apiSecret, passphrase: this.credentials.passphrase }; } saveCredentials(apiKey, apiSecret, passphrase) { this.credentials = { apiKey, apiSecret, passphrase, derivedAt: new Date().toISOString() }; writeFileSync(this.credentialsPath, JSON.stringify(this.credentials, null, 4)); console.log('API credentials saved to', this.credentialsPath); } savePrivateKey(privateKey) { // Validate the private key by trying to create a wallet try { const wallet = new ethers.Wallet(privateKey); this.config.privateKey = privateKey; writeFileSync(this.configPath, JSON.stringify(this.config, null, 4)); return { success: true, address: wallet.address }; } catch { return { success: false, error: 'Invalid private key format' }; } } getConfigDir() { return this.configDir; } getConfigPath() { return this.configPath; } } //# sourceMappingURL=config.service.js.map