difcli
Version:
CLI tool for Diffuse Prime
183 lines • 6.3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLI_NAME = void 0;
exports.getChainForType = getChainForType;
exports.getNativeTokenSymbol = getNativeTokenSymbol;
exports.getWalletNotConfiguredMessage = getWalletNotConfiguredMessage;
exports.validatePositiveAmount = validatePositiveAmount;
exports.getEffectiveVaultAddress = getEffectiveVaultAddress;
exports.requireWallet = requireWallet;
exports.getCurrentChainConfig = getCurrentChainConfig;
exports.getTokenSymbol = getTokenSymbol;
exports.getTokenDecimals = getTokenDecimals;
exports.formatTokenAmount = formatTokenAmount;
exports.parseTokenAmount = parseTokenAmount;
const chains_1 = require("viem/chains");
const chalk_1 = __importDefault(require("chalk"));
const secure_storage_1 = require("./secure-storage");
const config_1 = require("../config");
const client_utils_1 = require("./client-utils");
const viem_1 = require("viem");
exports.CLI_NAME = 'difcli';
async function getChainForType(chainType) {
switch (chainType) {
case 'berachain':
return chains_1.berachain;
case 'arbitrum':
return chains_1.arbitrum;
case 'ethereum':
return chains_1.mainnet;
case 'sonic':
return chains_1.sonic;
default:
return chains_1.berachain;
}
}
function getNativeTokenSymbol(chainType) {
switch (chainType) {
case 'berachain':
return 'BERA';
case 'arbitrum':
return 'ETH';
case 'ethereum':
return 'ETH';
case 'sonic':
return 'S';
default:
return 'ETH';
}
}
function getWalletNotConfiguredMessage() {
return chalk_1.default.yellow(`No wallet configured. Use "${exports.CLI_NAME} wallet set-private-key <key>" to set one.`);
}
function validatePositiveAmount(amount) {
if (isNaN(Number(amount)) || Number(amount) <= 0) {
console.error(chalk_1.default.red('Error: Amount must be a positive number'));
process.exit(1);
}
}
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
async function getEffectiveVaultAddress(chainType) {
const userVaultAddress = await secure_storage_1.SecureStorage.getVaultAddress(chainType);
const defaultAddress = config_1.config.chains[chainType].vaultContract;
// Use user address if set and not empty and not zero address
if (userVaultAddress && userVaultAddress.trim() !== '' && userVaultAddress.toLowerCase() !== ZERO_ADDRESS) {
return userVaultAddress;
}
// Return default only if it's not zero address
return defaultAddress.toLowerCase() === ZERO_ADDRESS ? '' : defaultAddress;
}
/**
* Validates that a wallet is configured and returns the private key
* Shows error message and exits if not configured
*/
async function requireWallet() {
const privateKey = await secure_storage_1.SecureStorage.getPrivateKey();
if (!privateKey) {
console.log(getWalletNotConfiguredMessage());
process.exit(1);
}
return privateKey;
}
/**
* Gets current chain configuration in a standardized way
*/
async function getCurrentChainConfig() {
const selectedChain = await client_utils_1.ClientFactory.getCurrentChain();
return {
chainType: selectedChain,
chainConfig: client_utils_1.ClientFactory.getChainConfig(selectedChain)
};
}
/**
* Get token symbol from contract
*/
async function getTokenSymbol(tokenContract, rpcUrl, chainType) {
const chain = await getChainForType(chainType);
const client = (0, viem_1.createPublicClient)({
chain,
transport: (0, viem_1.http)(rpcUrl),
});
try {
const symbol = await client.readContract({
address: tokenContract,
abi: viem_1.erc20Abi,
functionName: 'symbol',
});
return symbol;
}
catch (error) {
return 'TOKEN'; // Fallback if symbol can't be retrieved
}
}
/**
* Get token decimals from contract
*/
async function getTokenDecimals(tokenContract, rpcUrl, chainType) {
const chain = await getChainForType(chainType);
const client = (0, viem_1.createPublicClient)({
chain,
transport: (0, viem_1.http)(rpcUrl),
});
try {
const decimals = await client.readContract({
address: tokenContract,
abi: viem_1.erc20Abi,
functionName: 'decimals',
});
return Number(decimals);
}
catch (error) {
// Default to 18 decimals if we can't get the actual decimals
return 18;
}
}
/**
* Format token amount with proper decimals
*/
function formatTokenAmount(amount, decimals) {
if (decimals === 18) {
// For 18 decimals, we can use formatEther
return (0, viem_1.formatEther)(amount);
}
// For other decimals, we need to format manually
const divisor = BigInt(10 ** decimals);
const wholePart = amount / divisor;
const fractionalPart = amount % divisor;
if (fractionalPart === 0n) {
return wholePart.toString();
}
// Convert fractional part to string and pad with leading zeros
let fractionalStr = fractionalPart.toString().padStart(decimals, '0');
// Remove trailing zeros
fractionalStr = fractionalStr.replace(/0+$/, '');
if (fractionalStr === '') {
return wholePart.toString();
}
return `${wholePart}.${fractionalStr}`;
}
/**
* Parse token amount with proper decimals
*/
function parseTokenAmount(amount, decimals) {
if (decimals === 18) {
// For 18 decimals, we can use parseEther
return (0, viem_1.parseEther)(amount);
}
// For other decimals, we need to parse manually
const parts = amount.split('.');
const wholePart = parts[0] || '0';
const fractionalPart = parts[1] || '';
// Convert whole part
let result = BigInt(wholePart) * BigInt(10 ** decimals);
// Add fractional part
if (fractionalPart) {
const fractionalValue = BigInt(fractionalPart.padEnd(decimals, '0').slice(0, decimals));
result += fractionalValue;
}
return result;
}
//# sourceMappingURL=chain-utils.js.map