shine-solana/shine/scripts/governance_token/_common.js

89 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const readline = require("readline");
const { Keypair, PublicKey, clusterApiUrl } = require("@solana/web3.js");
function parseEnvConfig(configPath) {
const raw = fs.readFileSync(configPath, "utf8");
const out = {};
for (const line of raw.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eq = trimmed.indexOf("=");
if (eq === -1) continue;
const key = trimmed.slice(0, eq).trim();
let val = trimmed.slice(eq + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
val = val.replace(/\$HOME/g, process.env.HOME || "");
out[key] = val;
}
return out;
}
function assertRequired(cfg, key) {
if (!cfg[key]) throw new Error(`В конфиге отсутствует обязательный параметр: ${key}`);
}
function resolveConfigPath(argvPath) {
return argvPath
? path.resolve(argvPath)
: path.resolve(__dirname, "governance_token.config.env");
}
function loadKeypair(filePath) {
const arr = JSON.parse(fs.readFileSync(filePath, "utf8"));
return Keypair.fromSecretKey(Uint8Array.from(arr));
}
function saveKeypair(filePath, keypair) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(Array.from(keypair.secretKey)));
}
function parseCluster(cluster) {
if (cluster === "devnet" || cluster === "mainnet-beta" || cluster === "testnet") {
return clusterApiUrl(cluster);
}
return cluster;
}
function nowStamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}-${p(
d.getMinutes()
)}-${p(d.getSeconds())}`;
}
async function askYes(prompt) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) => rl.question(prompt, resolve));
rl.close();
return answer.trim() === "yes";
}
function toPublicKey(v, fieldName) {
try {
return new PublicKey(v);
} catch (_) {
throw new Error(`Некорректный pubkey в ${fieldName}: ${v}`);
}
}
module.exports = {
parseEnvConfig,
assertRequired,
resolveConfigPath,
loadKeypair,
saveKeypair,
parseCluster,
nowStamp,
askYes,
toPublicKey,
};