chaingate
Version:
Multi-chain cryptocurrency SDK for TypeScript — unified API for Bitcoin, Ethereum, Litecoin, Dogecoin, Bitcoin Cash, Polygon, Arbitrum, and any EVM-compatible chain. Create wallets, query balances, send transactions, and manage tokens and NFTs across UTXO
53 lines (52 loc) • 1.61 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isHex = isHex;
exports.hexToBytes = hexToBytes;
exports.bytesToHex = bytesToHex;
exports.isBase58 = isBase58;
const errors_1 = require("../errors");
/**
* Checks whether a string is valid hexadecimal. Supports optional `0x` prefix.
*
* @param s - The string to validate.
* @returns `true` if valid hex.
*/
function isHex(s) {
const clean = s.startsWith('0x') ? s.substring(2) : s;
return clean.length > 0 && clean.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(clean);
}
/**
* Converts a hex string to bytes. Supports optional `0x` prefix.
*
* @param hex - The hex string to decode.
* @throws {@link InvalidHexError} If the string is not valid hex.
*/
function hexToBytes(hex) {
const clean = hex.startsWith('0x') ? hex.substring(2) : hex;
if (clean.length % 2 !== 0)
throw new errors_1.InvalidHexError('Invalid hex: odd length');
const bytes = new Uint8Array(clean.length / 2);
for (let i = 0; i < clean.length; i += 2) {
bytes[i / 2] = parseInt(clean.substring(i, i + 2), 16);
}
return bytes;
}
/**
* Converts bytes to a lowercase hex string (without `0x` prefix).
*
* @param bytes - The byte array to encode.
*/
function bytesToHex(bytes) {
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* Checks whether a string contains only valid Base58 characters.
*
* @param s - The string to validate.
* @returns `true` if valid Base58.
*/
function isBase58(s) {
return /^[A-HJ-NP-Za-km-z1-9]+$/.test(s);
}