export { ContractType } from '@klever/connect-encoding'; /** * Brand type helper for creating nominal types * @internal */ type Brand = K & { __brand: T; }; /** * A branded type representing a valid Klever address * Must start with 'klv1' and be exactly 62 characters long * * @example * ```typescript * const address: KleverAddress = createKleverAddress('klv1...') * ``` */ type KleverAddress = Brand; /** * A branded type representing a valid transaction hash * Must be exactly 64 hexadecimal characters * * @example * ```typescript * const hash: TransactionHash = createTransactionHash('0123456789abcdef...') * ``` */ type TransactionHash = Brand; /** * A branded type representing a asset amount in smallest units * * @example * ```typescript * const amount: AssetAmount = createAssetAmount(1000000n) // 1 KLV * ``` */ type AssetAmount = Brand; type AssetID = Brand; type BlockHeight = Brand; type BlockHash = Brand; type Nonce = Brand; type PublicKey = Brand; type PrivateKey = Brand; type Signature = Brand; type HexString = Brand; type Base58String = Brand; /** * Type guard to check if a string is a valid Klever address * * @param value - The string to check * @returns True if the string is a valid Klever address * * @example * ```typescript * if (isKleverAddress(input)) { * // input is now typed as KleverAddress * } * ``` */ declare function isKleverAddress(value: string): value is KleverAddress; /** * Validates a Klever address using bech32 decoding * * This function performs full bech32 validation by decoding the address * and verifying both the prefix and data length. It's more thorough than * the regex-based `isKleverAddress()` function. * * @param address - The address string to validate * @returns True if the address is valid (correct prefix and data length) * * @example * ```typescript * if (isValidAddress('klv1qqqqqqqqqqqqqpgqxwklx...')) { * console.log('Valid Klever address') * } * ``` * * @see {@link isKleverAddress} for a faster regex-based validation */ declare function isValidAddress(address: string): boolean; /** * Validates if an address is a smart contract address. * * Mirrors klever-go core.IsSmartContractAddress: * - a valid all-zero Klever address is accepted * - otherwise bytes 0..7 must be zero * - bytes 8..9 must match the Wasm VM type (05 00) * * @param address - The address string to validate * @returns True if the address is a valid smart contract address * * @example * ```typescript * if (isValidContractAddress('klv1qqqqqqqqqqqqqpgqxwklx...')) { * console.log('Valid smart contract address') * } * ``` * * @see {@link isValidAddress} for general address validation */ declare function isValidContractAddress(address: string): boolean; /** * Type guard to check if a string is a valid transaction hash * * @param value - The string to check * @returns True if the string is a valid transaction hash * * @example * ```typescript * if (isTransactionHash(input)) { * // input is now typed as TransactionHash * } * ``` */ declare function isTransactionHash(value: string): value is TransactionHash; /** * Creates a KleverAddress from a string with validation * * @param value - The address string to validate and convert * @returns A validated KleverAddress * @throws {Error} If the address is invalid * * @example * ```typescript * const address = createKleverAddress('klv1qqqqqqqqqqqqqpgqxwklx...') * ``` */ declare function createKleverAddress(value: string): KleverAddress; /** * Creates a TransactionHash from a string with validation * * @param value - The hash string to validate and convert * @returns A validated TransactionHash * @throws {Error} If the hash is invalid * * @example * ```typescript * const hash = createTransactionHash('1234567890abcdef...') * ``` */ declare function createTransactionHash(value: string): TransactionHash; /** * Type guard to check if a string is a valid block hash * * @param value - The string to check * @returns True if the string is a valid block hash * * @example * ```typescript * if (isBlockHash(input)) { * // input is now typed as BlockHash * } * ``` */ declare function isBlockHash(value: string): value is BlockHash; /** * Creates a BlockHash from a string with validation * * @param value - The hash string to validate and convert * @returns A validated BlockHash * @throws {Error} If the hash is invalid * * @example * ```typescript * const hash = createBlockHash('1234567890abcdef...') * ``` */ declare function createBlockHash(value: string): BlockHash; /** * Creates a AssetAmount from various numeric types * * @param value - The amount as bigint, string, or number * @param _decimals - The number of decimals (currently unused) * @returns A validated AssetAmount * @throws {Error} If the amount is negative * * @example * ```typescript * const amount1 = createAssetAmount(1000000n) // From bigint * const amount2 = createAssetAmount('1000000') // From string * const amount3 = createAssetAmount(1000000) // From number * ``` */ declare function createAssetAmount(value: bigint | string | number, _decimals?: number): AssetAmount; /** * Formats a AssetAmount to a human-readable string * * @param amount - The asset amount in smallest units * @param decimals - The number of decimal places (default: 6 for KLV) * @returns A formatted string representation * * @example * ```typescript * formatAssetAmount(createAssetAmount(1000000n)) // '1' * formatAssetAmount(createAssetAmount(1500000n)) // '1.5' * formatAssetAmount(createAssetAmount(1234567n)) // '1.234567' * ``` */ declare function formatAssetAmount(amount: AssetAmount, decimals?: number): string; /** * Parses a human-readable string to a AssetAmount * * @param value - The string to parse (e.g., '1.5') * @param decimals - The number of decimal places (default: 6 for KLV) * @returns A AssetAmount in smallest units * * @example * ```typescript * parseAssetAmount('1') // 1000000n (1 KLV) * parseAssetAmount('1.5') // 1500000n (1.5 KLV) * parseAssetAmount('0.000001') // 1n (0.000001 KLV) * ``` */ declare function parseAssetAmount(value: string, decimals?: number): AssetAmount; interface IProposalMapItem { message: string; precision: number; unit: string; } interface IProposalsMap { FeePerDataByte: IProposalMapItem; KAppFeeCreateValidator: IProposalMapItem; KAppFeeCreateAsset: IProposalMapItem; MaxEpochsUnclaimed: IProposalMapItem; MinSelfDelegatedAmount: IProposalMapItem; MinTotalDelegatedAmount: IProposalMapItem; BlockRewards: IProposalMapItem; StakingRewards: IProposalMapItem; KAppFeeTransfer: IProposalMapItem; KAppFeeAssetTrigger: IProposalMapItem; KAppFeeValidatorConfig: IProposalMapItem; KAppFeeFreeze: IProposalMapItem; KAppFeeUnfreeze: IProposalMapItem; KAppFeeDelegate: IProposalMapItem; KAppFeeUndelegate: IProposalMapItem; KAppFeeWithdraw: IProposalMapItem; KAppFeeClaim: IProposalMapItem; KAppFeeUnjail: IProposalMapItem; KAppFeeSetAccountName: IProposalMapItem; KAppFeeProposal: IProposalMapItem; KAppFeeVote: IProposalMapItem; KAppFeeConfigITO: IProposalMapItem; KAppFeeSetITOPrices: IProposalMapItem; KAppFeeBuy: IProposalMapItem; KAppFeeSell: IProposalMapItem; KAppFeeCancelMarketOrder: IProposalMapItem; KAppFeeCreateMarketplace: IProposalMapItem; KAppFeeConfigMarketplace: IProposalMapItem; KAppFeeUpdateAccountPermission: IProposalMapItem; MaxNFTMintBatch: IProposalMapItem; MinKFIStakedToEnableProposals: IProposalMapItem; MinKLVBucketAmount: IProposalMapItem; MaxBucketSize: IProposalMapItem; LeaderValidatorRewardsPercentage: IProposalMapItem; ProposalMaxEpochsDuration: IProposalMapItem; KAppFeeDeposit: IProposalMapItem; KAppFeeITOTrigger: IProposalMapItem; KAppFeeSmartContract: IProposalMapItem; } interface IParsedNetworkParam { number: number; currentValue: string; parameterLabel: string; } declare enum NetworkParamsIndexer { FeePerDataByte = 0, KAppFeeCreateValidator = 1, KAppFeeCreateAsset = 2, MaxEpochsUnclaimed = 3, MinSelfDelegatedAmount = 4, MinTotalDelegatedAmount = 5, BlockRewards = 6, StakingRewards = 7, KAppFeeTransfer = 8, KAppFeeAssetTrigger = 9, KAppFeeValidatorConfig = 10, KAppFeeFreeze = 11, KAppFeeUnfreeze = 12, KAppFeeDelegate = 13, KAppFeeUndelegate = 14, KAppFeeWithdraw = 15, KAppFeeClaim = 16, KAppFeeUnjail = 17, KAppFeeSetAccountName = 18, KAppFeeProposal = 19, KAppFeeVote = 20, KAppFeeConfigITO = 21, KAppFeeSetITOPrices = 22, KAppFeeBuy = 23, KAppFeeSell = 24, KAppFeeCancelMarketOrder = 25, KAppFeeCreateMarketplace = 26, KAppFeeConfigMarketplace = 27, KAppFeeUpdateAccountPermission = 28, MaxNFTMintBatch = 29, MinKFIStakedToEnableProposals = 30, MinKLVBucketAmount = 31, MaxBucketSize = 32, LeaderValidatorRewardsPercentage = 33, ProposalMaxEpochsDuration = 34, KAppFeeITOTrigger = 35, KAppFeeDeposit = 36, KAppFeeSmartContract = 37 } declare const ParamContractMap: Record; /** * Transaction type constants for Klever blockchain operations * * This object provides developer-friendly shortcuts to transaction types * while maintaining compatibility with the underlying proto enum values. * Each transaction type represents a specific operation that can be performed on the blockchain. * * @example * ```typescript * import { TXType } from '@klever/connect-core' * * // Create a transfer transaction * const transferType = TXType.Transfer * * // Create a delegation transaction * const delegateType = TXType.Delegate * ``` */ declare const TXType: { /** * Transfer assets between accounts * Used for sending KLV, KFI, or any other fungible tokens */ readonly Transfer: number; /** * Create a new asset (token) on the blockchain * Allows creation of fungible tokens, NFTs, and other asset types */ readonly CreateAsset: number; /** * Create a new validator node * Requires minimum self-delegation and validator configuration */ readonly CreateValidator: number; /** * Update validator configuration * Modify validator settings like commission rate, rewards destination, etc. */ readonly ValidatorConfig: number; /** * Freeze assets for staking or other purposes * Locks tokens to participate in bucket-based staking */ readonly Freeze: number; /** * Unfreeze previously frozen assets * Initiates the unbonding period for frozen tokens */ readonly Unfreeze: number; /** * Delegate tokens to a validator * Stake tokens with a validator to earn rewards */ readonly Delegate: number; /** * Undelegate tokens from a validator * Remove delegation and start the unbonding period (21 days) */ readonly Undelegate: number; /** * Withdraw unbonded tokens * Claim tokens after the unbonding period has completed */ readonly Withdraw: number; /** * Claim staking rewards * Collect accumulated rewards from delegation or validation */ readonly Claim: number; /** * Unjail a validator * Restore a jailed validator to active status */ readonly Unjail: number; /** * Trigger asset-related operations * Perform actions like minting, burning, pausing, or wiping assets */ readonly AssetTrigger: number; /** * Set or update account name * Assign a human-readable name to an account address */ readonly SetAccountName: number; /** * Create a governance proposal * Submit a proposal for community voting */ readonly Proposal: number; /** * Vote on a governance proposal * Cast a vote in favor or against a proposal */ readonly Vote: number; /** * Configure an Initial Token Offering (ITO) * Set up parameters for a token sale */ readonly ConfigITO: number; /** * Set ITO pricing information * Define price tiers and sale conditions for an ITO */ readonly SetITOPrices: number; /** * Buy assets from an ITO or marketplace * Purchase tokens or NFTs from available offers */ readonly Buy: number; /** * Sell assets on marketplace * Create a sell order for assets */ readonly Sell: number; /** * Cancel a marketplace order * Remove an active buy or sell order */ readonly CancelMarketOrder: number; /** * Create a new marketplace * Initialize a marketplace for trading assets */ readonly CreateMarketplace: number; /** * Configure marketplace settings * Update marketplace parameters and rules */ readonly ConfigMarketplace: number; /** * Update account permissions * Modify account access control and multi-signature settings */ readonly UpdateAccountPermission: number; /** * Deposit assets * Deposit tokens into a contract or liquidity pool */ readonly Deposit: number; /** * Trigger ITO-related operations * Perform actions like starting, pausing, or finalizing an ITO */ readonly ITOTrigger: number; /** * Smart contract interaction * Deploy or invoke smart contract functions */ readonly SmartContract: number; }; /** * Type representing any valid transaction type value * Extracted from the TXType constant object */ type TXTypeValue = (typeof TXType)[keyof typeof TXType]; /** * Smart contract specific transaction types * Distinguishes between contract deployment and invocation * * @example * ```typescript * // Deploy a new contract * const deployType = SCTXType.SCDeploy * * // Invoke an existing contract * const invokeType = SCTXType.SCInvoke * ``` */ declare enum SCTXType { /** * Invoke a function on an existing smart contract * Calls a method on a deployed contract */ SCInvoke = 0, /** * Deploy a new smart contract * Upload and initialize contract code on the blockchain */ SCDeploy = 1 } /** * Network configuration types for Klever blockchain */ /** * Predefined network names supported by Klever * * @example * ```typescript * const network: NetworkName = 'mainnet' * const testNetwork: NetworkName = 'testnet' * ``` */ type NetworkName = 'mainnet' | 'testnet' | 'devnet' | 'local' | 'custom'; /** * Network endpoint URIs for connecting to Klever blockchain * * Provides different types of endpoints for various use cases: * - `api`: Fast, cached data from indexer (recommended for most queries) * - `node`: Direct node access for latest state * - `ws`: Real-time updates via WebSocket * - `explorer`: Block explorer for viewing blockchain data * * @example * ```typescript * const uris: NetworkURI = { * api: 'https://api.mainnet.klever.finance', * node: 'https://node.mainnet.klever.finance', * ws: 'wss://ws.mainnet.klever.finance', * explorer: 'https://kleverscan.org' * } * ``` */ interface NetworkURI { /** Indexer/Proxy API endpoint - provides indexed and parsed blockchain data (faster, cached) */ api?: string; /** Direct node API endpoint - raw blockchain node access (slower, but always up-to-date) */ node?: string; /** WebSocket endpoint for real-time updates and subscriptions */ ws?: string; /** Block explorer URL for viewing transactions and addresses */ explorer?: string; } /** * Complete network configuration with metadata * * Includes all information needed to connect to and interact with a Klever network. * * @example * ```typescript * const mainnet: Network = { * name: 'mainnet', * chainId: 'klever-mainnet', * config: { * api: 'https://api.mainnet.klever.finance', * node: 'https://node.mainnet.klever.finance' * }, * isTestnet: false, * nativeCurrency: { * name: 'Klever', * symbol: 'KLV', * decimals: 6 * } * } * ``` */ interface Network { /** Network name identifier */ name: NetworkName; /** Chain ID for this network */ chainId: string; /** Network endpoint configuration */ config: NetworkURI; /** Whether this is a test network */ isTestnet: boolean; /** Native currency information */ nativeCurrency: { /** Full name of the currency */ name: string; /** Currency symbol/ticker */ symbol: string; /** Number of decimal places */ decimals: number; }; } /** * Flexible network configuration for KleverProvider * * Accepts multiple formats for convenience: * - String name for predefined networks: `'mainnet'`, `'testnet'`, etc. * - NetworkURI object for custom endpoint configuration * - Full Network object for complete custom network setup * * @example * ```typescript * // Using predefined network name * const config1: NetworkConfig = 'mainnet' * * // Using custom URIs * const config2: NetworkConfig = { * api: 'https://my-custom-api.com' * } * * // Using full network configuration * const config3: NetworkConfig = { * name: 'custom', * chainId: 'my-chain', * config: { api: 'https://api.mychain.com' }, * isTestnet: true, * nativeCurrency: { name: 'MyToken', symbol: 'MTK', decimals: 6 } * } * ``` */ type NetworkConfig = NetworkName | NetworkURI | Network; /** * Core type definitions for Klever Connect SDK * Inspired by ethers.js, CosmJS, and @solana/web3.js */ type Environment = 'browser' | 'node' | 'react-native' | 'unknown'; /** * Base error class for all Klever SDK errors * * All custom errors in the SDK extend from this class, providing * a consistent interface with error codes and optional details. * * @example * ```typescript * try { * // Some operation * } catch (error) { * if (error instanceof KleverError) { * console.error(`Error [${error.code}]: ${error.message}`) * console.error('Details:', error.details) * } * } * ``` */ declare class KleverError extends Error { /** Error code for categorizing the error */ readonly code: string; /** Additional error details (can be any type) */ readonly details?: unknown; /** * Creates a new KleverError instance * * @param message - Human-readable error description * @param code - Error code identifier * @param details - Optional additional error information */ constructor(message: string, code: string, details?: unknown); } /** * Error thrown when input validation fails * * Used for invalid addresses, amounts, transaction parameters, etc. * * @example * ```typescript * if (!isValidAddress(address)) { * throw new ValidationError('Invalid Klever address', { address }) * } * ``` */ declare class ValidationError extends KleverError { /** * Creates a new ValidationError * * @param message - Description of what validation failed * @param details - Optional details about the invalid input */ constructor(message: string, details?: unknown); } /** * Error thrown when network/RPC operations fail * * Used for connection failures, timeout errors, API errors, etc. * * @example * ```typescript * try { * await provider.getBalance(address) * } catch (error) { * if (error instanceof NetworkError) { * console.error('Network request failed:', error.message) * } * } * ``` */ declare class NetworkError extends KleverError { /** * Creates a new NetworkError * * @param message - Description of the network failure * @param details - Optional details (status code, response data, etc.) */ constructor(message: string, details?: unknown); } /** * Error thrown when transaction operations fail * * Used for transaction building, signing, broadcasting, or execution failures. * * @example * ```typescript * try { * await signer.sendTransaction(txRequest) * } catch (error) { * if (error instanceof TransactionError) { * console.error('Transaction failed:', error.message) * console.error('Details:', error.details) * } * } * ``` */ declare class TransactionError extends KleverError { /** * Creates a new TransactionError * * @param message - Description of the transaction failure * @param details - Optional details (transaction data, blockchain response, etc.) */ constructor(message: string, details?: unknown); } /** * Error thrown when smart contract operations fail * * Used for contract deployment, invocation, or ABI-related errors. * * @example * ```typescript * try { * await contract.invoke('transfer', [recipient, amount]) * } catch (error) { * if (error instanceof ContractError) { * console.error('Contract call failed:', error.message) * } * } * ``` */ declare class ContractError extends KleverError { /** * Creates a new ContractError * * @param message - Description of the contract operation failure * @param details - Optional details (method name, parameters, contract response, etc.) */ constructor(message: string, details?: unknown); } /** * Error thrown when wallet operations fail * * Used for key management, signing, or wallet-related errors. * * @example * ```typescript * try { * const wallet = new Wallet(privateKey) * } catch (error) { * if (error instanceof WalletError) { * console.error('Wallet initialization failed:', error.message) * } * } * ``` */ declare class WalletError extends KleverError { /** * Creates a new WalletError * * @param message - Description of the wallet operation failure * @param details - Optional details about the failure */ constructor(message: string, details?: unknown); } /** * Error thrown when encoding/decoding operations fail * * Used for proto encoding/decoding, bech32, hex, or other format conversions. * * @example * ```typescript * try { * const decoded = bech32Decode(address) * } catch (error) { * if (error instanceof EncodingError) { * console.error('Failed to decode address:', error.message) * } * } * ``` */ declare class EncodingError extends KleverError { /** * Creates a new EncodingError * * @param message - Description of the encoding/decoding failure * @param details - Optional details (input data, expected format, etc.) */ constructor(message: string, details?: unknown); } /** * Error thrown when cryptographic operations fail * * Used for signing, verification, hashing, or other crypto operations. * * @example * ```typescript * try { * const signature = await wallet.signMessage(message) * } catch (error) { * if (error instanceof CryptoError) { * console.error('Signing failed:', error.message) * } * } * ``` */ declare class CryptoError extends KleverError { /** * Creates a new CryptoError * * @param message - Description of the cryptographic operation failure * @param details - Optional details about the failure */ constructor(message: string, details?: unknown); } /** * Core constants for Klever Connect SDK */ /** * Asset ID for Klever's native token (KLV) * Used as the identifier for KLV in all transactions and balances * @example 'KLV' */ declare const KLV_ASSET_ID = "KLV"; /** * Asset ID for Klever Finance token (KFI) * Used as the identifier for KFI in all transactions and balances * @example 'KFI' */ declare const KFI_ASSET_ID = "KFI"; /** * Number of decimal places for KLV token * KLV uses 6 decimals, so 1 KLV = 1,000,000 smallest units * @example 6 * @see {@link KLV_MULTIPLIER} for the multiplier value */ declare const KLV_PRECISION = 6; /** * Number of decimal places for KFI token * KFI uses 6 decimals, so 1 KFI = 1,000,000 smallest units * @example 6 * @see {@link KFI_MULTIPLIER} for the multiplier value */ declare const KFI_PRECISION = 6; /** * Multiplier to convert KLV to smallest units * Equals 1,000,000 (10^6) since KLV has 6 decimal places * @example 1000000 * @see {@link KLV_PRECISION} */ declare const KLV_MULTIPLIER: number; /** * Multiplier to convert KFI to smallest units * Equals 1,000,000 (10^6) since KFI has 6 decimal places * @example 1000000 * @see {@link KFI_PRECISION} */ declare const KFI_MULTIPLIER: number; /** * Display name for Klever token * @example 'Klever' */ declare const KLV_NAME = "Klever"; /** * Display name for Klever Finance token * @example 'Klever Finance' */ declare const KFI_NAME = "Klever Finance"; /** * Base transaction size in bytes used for fee estimation * Represents the approximate minimum size of a transaction * @example 250 */ declare const BASE_TX_SIZE = 250; /** * Common assets configuration on Klever blockchain * Provides metadata for the main native tokens (KLV and KFI) * * @example * ```typescript * const klvInfo = COMMON_ASSETS.KLV * console.log(klvInfo.id) // 'KLV' * console.log(klvInfo.precision) // 6 * console.log(klvInfo.name) // 'Klever' * ``` */ declare const COMMON_ASSETS: { KLV: { id: string; precision: number; name: string; }; KFI: { id: string; precision: number; name: string; }; }; /** * Bech32 prefix for Klever addresses * All Klever addresses start with 'klv1' * @example 'klv' * @see {@link ADDRESS_LENGTH} for the full address length */ declare const ADDRESS_PREFIX = "klv"; /** * Total length of a Klever address in characters * Klever addresses are exactly 62 characters long (including 'klv1' prefix) * Format: klv1 (4 chars) + 58 bech32 encoded chars = 62 total * @example 62 * @see {@link ADDRESS_PREFIX} */ declare const ADDRESS_LENGTH = 62; /** * Maximum size for transaction message/data field in bytes * Equals 100 KB (102,400 bytes) * @example 102400 */ declare const MAX_MESSAGE_SIZE: number; /** * Length of transaction signatures in bytes * Klever uses 64-byte signatures * @example 64 */ declare const SIGNATURE_LENGTH = 64; /** * Minimum self-delegation required to create a validator * Equals 1,000,000 KLV (1,000,000,000,000 in smallest units) * @example 1000000000000n */ declare const MIN_SELF_DELEGATION = 1000000000000n; /** * Time period in seconds for unbonding delegated tokens * Equals 21 days (1,814,400 seconds) * After undelegating, tokens are locked for this period before being available * @example 1814400 */ declare const UNBONDING_TIME: number; /** * Maximum number of delegators that can delegate to a single validator * @example 10000 */ declare const MAX_DELEGATORS_PER_VALIDATOR = 10000; /** * Average block time in seconds * Klever blockchain produces a new block approximately every 4 seconds * @example 4 * @see {@link BLOCKS_PER_EPOCH} */ declare const BLOCK_TIME = 4; /** * Number of blocks in one epoch * Equals 5,400 blocks (approximately 6 hours at 4 seconds per block) * @example 5400 * @see {@link BLOCK_TIME}, {@link EPOCH_DURATION} */ declare const BLOCKS_PER_EPOCH = 5400; /** * Number of blocks produced in one year * Used for APY calculations and reward estimations * @example 7884000 */ declare const BLOCKS_PER_YEAR = 7884000; /** * Maximum transaction size in bytes * Equals 32 KB (32,768 bytes) * Transactions exceeding this size will be rejected * @example 32768 */ declare const MAX_TX_SIZE = 32768; /** * Maximum length for asset names * Asset names cannot exceed 32 characters * @example 32 * @see {@link MAX_TICKER_LENGTH} */ declare const MAX_ASSET_NAME_LENGTH = 32; /** * Maximum length for asset ticker symbols * Ticker symbols cannot exceed 8 characters * @example 8 * @see {@link MAX_ASSET_NAME_LENGTH} */ declare const MAX_TICKER_LENGTH = 8; /** * Duration of one epoch in seconds * Equals 6 hours (21,600 seconds) * @example 21600 * @see {@link BLOCKS_PER_EPOCH} */ declare const EPOCH_DURATION = 21600; /** * Number of milliseconds in one second * Utility constant for time conversions * @example 1000 */ declare const MILLISECONDS_PER_SECOND = 1000; /** * Default number of items per page in paginated API responses * @example 100 * @see {@link MAX_PAGE_SIZE} */ declare const DEFAULT_PAGE_SIZE = 100; /** * Maximum number of items per page in paginated API responses * @example 1000 * @see {@link DEFAULT_PAGE_SIZE} */ declare const MAX_PAGE_SIZE = 1000; /** * Default timeout for API requests in milliseconds * Equals 30 seconds (30,000 milliseconds) * @example 30000 */ declare const DEFAULT_TIMEOUT = 30000; /** * Default number of block confirmations to wait for transaction finality * @example 1 */ declare const DEFAULT_CONFIRMATIONS = 1; /** * Delay in milliseconds before attempting to reconnect after WebSocket disconnect * @example 1000 * @see {@link WS_MAX_RECONNECT_ATTEMPTS} */ declare const WS_RECONNECT_DELAY = 1000; /** * Maximum number of reconnection attempts for WebSocket connections * After this many failed attempts, the connection will be abandoned * @example 5 * @see {@link WS_RECONNECT_DELAY} */ declare const WS_MAX_RECONNECT_ATTEMPTS = 5; /** * Interval in milliseconds between WebSocket ping messages * Used to keep the connection alive and detect disconnections * Equals 30 seconds (30,000 milliseconds) * @example 30000 */ declare const WS_PING_INTERVAL = 30000; /** * Formatting utilities for Klever amounts * Similar to ethers.js formatUnits/parseUnits * * These utilities help convert between human-readable amounts (like "1.5 KLV") * and the smallest units used internally (like 1500000). */ /** * Format a value from its smallest unit to a human-readable string * * Converts amounts from blockchain smallest units to decimal representation. * Trailing zeros are automatically removed from the fractional part. * * @param value - The value in smallest units (e.g., 1000000 = 1 KLV) * @param decimals - The number of decimals (default: 6 for KLV/KFI) * @returns Formatted string representation * * @example * ```typescript * formatUnits(1000000n) // '1' * formatUnits(1500000n) // '1.5' * formatUnits(1234567n) // '1.234567' * formatUnits(500n) // '0.0005' * formatUnits('2000000', 6) // '2' * formatUnits(1000, 3) // '1' (with 3 decimals) * ``` * * @see {@link parseUnits} for the reverse operation * @see {@link formatKLV} for KLV-specific formatting */ declare function formatUnits(value: bigint | string | number, decimals?: number): string; /** * Parse a human-readable string to its smallest unit * * Converts decimal amounts to blockchain smallest units. * Throws an error if too many decimal places are provided. * * @param value - The string or number value (e.g., "1.5" or 1.5) * @param decimals - The number of decimals (default: 6 for KLV/KFI) * @returns Value in smallest units as bigint * @throws {Error} If the value has invalid decimal format or too many decimal places * * @example * ```typescript * parseUnits('1') // 1000000n * parseUnits('1.5') // 1500000n * parseUnits('0.000001') // 1n * parseUnits(2.5) // 2500000n * parseUnits('100', 3) // 100000n (with 3 decimals) * * // Throws error - too many decimals * parseUnits('1.1234567', 6) // Error: Too many decimal places (max 6) * * // Throws error - invalid format * parseUnits('1.2.3') // Error: Invalid decimal value * ``` * * @see {@link formatUnits} for the reverse operation * @see {@link parseKLV} for KLV-specific parsing */ declare function parseUnits(value: string | number, decimals?: number): bigint; /** * Format KLV amount from smallest units to human-readable string * * Convenience function that calls `formatUnits` with 6 decimals (KLV precision). * * @param amount - Amount in smallest units * @returns Formatted KLV string * * @example * ```typescript * formatKLV(1000000n) // '1' * formatKLV(1500000n) // '1.5' * formatKLV('2000000') // '2' * ``` * * @see {@link formatUnits} for the underlying implementation * @see {@link parseKLV} for the reverse operation */ declare function formatKLV(amount: bigint | string | number): string; /** * Parse KLV amount from human-readable string to smallest units * * Convenience function that calls `parseUnits` with 6 decimals (KLV precision). * * @param amount - Human-readable KLV amount * @returns Amount in smallest units as bigint * @throws {Error} If the amount has invalid format or too many decimals * * @example * ```typescript * parseKLV('1') // 1000000n (1 KLV) * parseKLV('1.5') // 1500000n (1.5 KLV) * parseKLV(2) // 2000000n (2 KLV) * parseKLV('0.000001') // 1n (smallest KLV unit) * ``` * * @see {@link parseUnits} for the underlying implementation * @see {@link formatKLV} for the reverse operation */ declare function parseKLV(amount: string | number): bigint; /** * Detects the current JavaScript runtime environment * * Performs comprehensive checks to identify whether the code is running in: * - React Native (mobile app) * - Browser (web app) * - Node.js (server/CLI) * - Unknown environment * * This is useful for conditional behavior based on platform capabilities. * * @returns The detected environment type * * @example * ```typescript * const env = detectEnvironment() * if (env === 'browser') { * // Use browser-specific APIs * } else if (env === 'node') { * // Use Node.js-specific APIs * } * ``` * * @see {@link isBrowser}, {@link isNode}, {@link isReactNative} for specific checks */ declare function detectEnvironment(): Environment; /** * Checks if the code is running in a browser environment * * @returns `true` if running in a browser, `false` otherwise * * @example * ```typescript * if (isBrowser()) { * // Use localStorage, fetch, etc. * window.localStorage.setItem('key', 'value') * } * ``` * * @see {@link detectEnvironment} for full environment detection */ declare function isBrowser(): boolean; /** * Checks if the code is running in Node.js environment * * @returns `true` if running in Node.js, `false` otherwise * * @example * ```typescript * if (isNode()) { * // Use Node.js-specific modules * const fs = require('fs') * } * ``` * * @see {@link detectEnvironment} for full environment detection */ declare function isNode(): boolean; /** * Checks if the code is running in React Native environment * * @returns `true` if running in React Native, `false` otherwise * * @example * ```typescript * if (isReactNative()) { * // Use React Native-specific modules * import { AsyncStorage } from 'react-native' * } * ``` * * @see {@link detectEnvironment} for full environment detection */ declare function isReactNative(): boolean; /** * Lightweight logging system with multiple levels and customizable output * * @example * ```typescript * import { createLogger } from '@klever/connect-core' * * const logger = createLogger('MyModule', { * level: 'debug', * prefix: true, * timestamp: true * }) * * logger.debug('Starting operation', { data: 123 }) * logger.info('Operation complete') * logger.warn('Low balance detected') * logger.error('Failed to send transaction', error) * ``` */ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'; interface LoggerOptions { /** Minimum log level to output */ level?: LogLevel; /** Include timestamp in logs */ timestamp?: boolean; /** Include module prefix in logs */ prefix?: boolean; /** Custom log handler */ handler?: LogHandler; /** Enable color output (Node.js only) */ colors?: boolean; } interface LogHandler { debug(module: string, message: string, ...args: unknown[]): void; info(module: string, message: string, ...args: unknown[]): void; warn(module: string, message: string, ...args: unknown[]): void; error(module: string, message: string, ...args: unknown[]): void; } interface Logger { debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; child(module: string): Logger; setLevel(level: LogLevel): void; } /** * Creates a logger instance for a specific module * * Logger instances provide debug, info, warn, and error logging methods * with configurable levels, formatting, and output handling. * * @param module - The module name to prefix log messages with * @param options - Optional logger configuration * @returns A configured Logger instance * * @example * ```typescript * const logger = createLogger('MyModule', { * level: 'debug', * timestamp: true, * colors: true * }) * * logger.debug('Detailed debug info') * logger.info('Operation started') * logger.warn('Low memory warning') * logger.error('Operation failed', error) * * // Create child logger with nested module name * const childLogger = logger.child('SubModule') * childLogger.info('Message from MyModule:SubModule') * ``` */ declare function createLogger(module: string, options?: LoggerOptions): Logger; /** * Sets global logger options that apply to all loggers created via `getGlobalLogger()` * * This allows you to configure logging behavior across the entire SDK from a single point. * Changes affect all future logger instances created with `getGlobalLogger()`. * * @param options - Partial logger options to merge with current global settings * * @example * ```typescript * // Set global log level to debug * setGlobalLoggerOptions({ level: 'debug' }) * * // Disable timestamps and colors * setGlobalLoggerOptions({ * timestamp: false, * colors: false * }) * * // Use custom log handler * setGlobalLoggerOptions({ * handler: myCustomHandler * }) * ``` * * @see {@link getGlobalLogger} * @see {@link initBrowserLogger} */ declare function setGlobalLoggerOptions(options: Partial): void; /** * Initialize logger configuration from browser environment * Call this in your app initialization to set up logging * * @example * ```typescript * // In your browser app initialization * initBrowserLogger({ * level: 'debug', * timestamp: false, * colors: false * }) * * // Or load from window.__env__ * window.__env__ = { KLEVER_LOG_LEVEL: 'debug' } * initBrowserLogger() * ``` */ declare function initBrowserLogger(options?: Partial): void; /** * Creates a logger instance using global configuration * * This is the recommended way to create loggers in the SDK, as it ensures * consistent configuration across all modules. The global options can be * set via `setGlobalLoggerOptions()` or `initBrowserLogger()`. * * @param module - The module name for the logger * @returns A Logger instance configured with global options * * @example * ```typescript * // In your module * const logger = getGlobalLogger('MyModule') * * logger.info('Module initialized') * logger.debug('Processing data', { count: 10 }) * ``` * * @see {@link setGlobalLoggerOptions} to configure global options * @see {@link createLogger} for creating loggers with custom options */ declare function getGlobalLogger(module: string): Logger; /** * Pre-configured logger for core SDK operations * @example * ```typescript * coreLogger.info('SDK initialized') * ``` */ declare const coreLogger: Logger; /** * Pre-configured logger for provider/network operations * @example * ```typescript * providerLogger.debug('Fetching account balance') * ``` */ declare const providerLogger: Logger; /** * Pre-configured logger for wallet operations * @example * ```typescript * walletLogger.info('Signing transaction') * ``` */ declare const walletLogger: Logger; /** * Pre-configured logger for transaction operations * @example * ```typescript * transactionLogger.debug('Building transfer transaction') * ``` */ declare const transactionLogger: Logger; /** * Pre-configured logger for smart contract operations * @example * ```typescript * contractLogger.info('Invoking contract method', { method: 'transfer' }) * ``` */ declare const contractLogger: Logger; export { ADDRESS_LENGTH, ADDRESS_PREFIX, type AssetAmount, type AssetID, BASE_TX_SIZE, BLOCKS_PER_EPOCH, BLOCKS_PER_YEAR, BLOCK_TIME, type Base58String, type BlockHash, type BlockHeight, COMMON_ASSETS, ContractError, CryptoError, DEFAULT_CONFIRMATIONS, DEFAULT_PAGE_SIZE, DEFAULT_TIMEOUT, EPOCH_DURATION, EncodingError, type Environment, type HexString, type IParsedNetworkParam, type IProposalMapItem, type IProposalsMap, KFI_ASSET_ID, KFI_MULTIPLIER, KFI_NAME, KFI_PRECISION, KLV_ASSET_ID, KLV_MULTIPLIER, KLV_NAME, KLV_PRECISION, type KleverAddress, KleverError, type LogHandler, type LogLevel, type Logger, type LoggerOptions, MAX_ASSET_NAME_LENGTH, MAX_DELEGATORS_PER_VALIDATOR, MAX_MESSAGE_SIZE, MAX_PAGE_SIZE, MAX_TICKER_LENGTH, MAX_TX_SIZE, MILLISECONDS_PER_SECOND, MIN_SELF_DELEGATION, type Network, type NetworkConfig, NetworkError, type NetworkName, NetworkParamsIndexer, type NetworkURI, type Nonce, ParamContractMap, type PrivateKey, type PublicKey, SCTXType, SIGNATURE_LENGTH, type Signature, TXType, type TXTypeValue, TransactionError, type TransactionHash, UNBONDING_TIME, ValidationError, WS_MAX_RECONNECT_ATTEMPTS, WS_PING_INTERVAL, WS_RECONNECT_DELAY, WalletError, contractLogger, coreLogger, createAssetAmount, createBlockHash, createKleverAddress, createLogger, createTransactionHash, detectEnvironment, formatAssetAmount, formatKLV, formatUnits, getGlobalLogger, initBrowserLogger, isBlockHash, isBrowser, isKleverAddress, isNode, isReactNative, isTransactionHash, isValidAddress, isValidContractAddress, parseAssetAmount, parseKLV, parseUnits, providerLogger, setGlobalLoggerOptions, transactionLogger, walletLogger };