import { TransactionHash, KleverAddress, BlockHash, AssetID } from '@klever/connect-core'; import * as N from '@klever/connect-core/src/types/network'; import { NetworkName as NetworkName$1, Network as Network$1 } from '@klever/connect-core/src/types/network'; interface CacheOptions { /** Time to live in milliseconds (default: 15000ms = 15 seconds) */ ttl?: number; /** Maximum number of cached items (default: 100) */ maxSize?: number; /** Cache key prefix */ prefix?: string; } interface RetryOptions { /** Maximum number of retries */ maxRetries?: number; /** Initial retry delay in milliseconds */ retryDelay?: number; /** Backoff strategy */ backoff?: 'linear' | 'exponential'; /** Custom retry condition */ retryIf?: (error: Error) => boolean; } /** * Custom network configuration shorthand * Use when you want to connect to a custom Klever node */ interface CustomNetworkConfig { /** Custom node URL (required for custom networks) */ url: string; /** Chain ID of the custom network */ chainId: string; /** WebSocket URL for subscriptions (optional) */ ws?: string; /** Explorer URL (optional) */ explorer?: string; /** Whether this is a testnet (default: true for custom networks) */ isTestnet?: boolean; } /** * Full provider configuration object */ interface ProviderConfigObject { /** * Network configuration * Can be: * - A network name: 'mainnet', 'testnet', 'devnet', 'local' * - A Network object: NETWORKS.mainnet, NETWORKS.testnet, or createCustomNetwork() */ network?: NetworkName$1 | Network$1; /** Custom network configuration shorthand (alternative to network) */ url?: string; /** Chain ID when using custom URL */ chainId?: string; /** Request timeout in milliseconds (default: 30000) */ timeout?: number; /** Number of retries for failed requests (deprecated, use retry.maxRetries) */ retries?: number; /** Custom headers for requests */ headers?: Record; /** Cache configuration (default: enabled with 15s TTL) */ cache?: CacheOptions | false; /** Retry configuration (default: 3 retries with exponential backoff) */ retry?: RetryOptions | false; /** WebSocket URL for subscriptions (optional, overrides network.ws) */ ws?: string; /** Enable debug logging (default: false) */ debug?: boolean; } /** * Provider configuration - can be: * - undefined: Uses mainnet * - A network name string: 'mainnet', 'testnet', 'devnet', 'local' * - A configuration object with network or custom URL */ type ProviderConfig = NetworkName$1 | ProviderConfigObject; interface IAccount { address: string; balance: bigint; nonce: number; assets?: IAssetBalance[]; } /** Asset type enum matching KDAData_EnumAssetType from blockchain */ declare enum AssetType { Fungible = 0, NonFungible = 1, SemiFungible = 2 } /** Staking interest type enum matching StakingData_EnumInterestType */ declare enum StakingInterestType { APRI = 0,// Annual Percentage Rate Interest FPRI = 1 } /** User's last claim information for a KDA */ interface UserKDALastClaim { timestamp: number; epoch: number; } /** User's bucket information for staking */ interface UserKDABucket { id: string; stakedAt: number; stakedEpoch: number; unstakedEpoch: number; balance: bigint; delegation: string; validatorName: string; } /** * Complete asset balance information from blockchain * Matches AccountKDA structure from Go backend */ interface IAssetBalance { /** Address of the account holding this asset */ address: string; /** Asset ID (KDA ID) */ assetId: string; /** Collection ID for NFTs */ collection?: string | undefined; /** NFT nonce for specific NFT instances */ nftNonce?: number | undefined; /** Human-readable asset name */ assetName: string; /** Asset type (Fungible, NonFungible, SemiFungible) */ assetType: AssetType; /** Total balance in smallest units */ balance: bigint; /** Number of decimal places for display */ precision: number; /** Frozen balance (staked) in smallest units */ frozenBalance: bigint; /** Unfrozen balance (available after unstaking cooldown) */ unfrozenBalance: bigint; /** Last claim information for rewards */ lastClaim: UserKDALastClaim; /** Staking buckets for this asset */ buckets: UserKDABucket[]; /** NFT metadata */ metadata?: string | undefined; /** MIME type for NFT content */ mime?: string | undefined; /** Marketplace ID if listed for sale */ marketplaceId?: string | undefined; /** Order ID if active order exists */ orderId?: string | undefined; /** Staking interest type (APR or FPR) */ stakingType: StakingInterestType; } interface IBalance { address: string; token: string; amount: bigint; decimals: number; } interface IBroadcastResult { hash: string; code?: string; message?: string; } interface IBulkBroadcastResult { hashes: string[]; code?: string; message?: string; } interface IContractQueryParams { ScAddress: string; FuncName: string; Arguments?: string[]; } interface IContractQueryResult { data?: { returnData?: string[]; returnCode?: string; returnMessage?: string; gasRemaining?: bigint; gasRefund?: bigint; }; error?: string; code?: string; } interface IFaucetResult { txHash: string; status: string; } /** * Contract data from API responses (e.g., getTransaction) * Represents contracts in mined/historical transactions returned by the Klever API. * * Note: This is for READ operations (API → Client). * For WRITE operations (building new transactions), use ContractRequestData instead. * * @property type - Contract type number (0=Transfer, 4=Freeze, etc.) * @property typeString - Human-readable type name, added by the indexer (e.g., "Transfer") * @property parameter - Contract-specific data (untyped for historical transactions) */ interface IContractData { type: number; typeString?: string; parameter: Record | ISCData; } interface ICallValueData { assetId: string; amount: bigint; } interface ISCData { address: string; scType: number; callValue?: ICallValueData[]; input?: string; } declare enum TransactionStatus { Pending = "pending", Success = "success", Failed = "failed", Invalid = "invalid" } interface ITransactionLog { address: string; contractId?: number; timestamp?: number; events: ILogEvent[]; } interface ILogEvent { address: string; identifier: string; topics: string[]; data: string[]; } interface IFees { KAppFee: number; BandwidthFee: number; TotalFee: number; } interface IFeesResponse { kAppFee: number; bandwidthFee: number; gasEstimated: number; safetyMargin: number; gasMultiplier: number; returnMessage: string; kdaFee: { kda?: Uint8Array; amount?: number; }; } interface IReceipt { type?: number; typeString?: string; cID?: number; [key: string]: unknown; } /** * Transaction response from the API/Indexer * This represents a transaction that has been processed and indexed * Contains parsed data with human-readable addresses and contract info */ interface ITransactionResponse { hash: string; blockNum: number; sender: string; nonce: number; timestamp: number; kAppFee: number; bandwidthFee: number; totalFee: number; status: TransactionStatus; resultCode?: string; version: number; chainID: string; signature: string[]; contract?: IContractData[]; data?: string[]; receipts?: IReceipt[]; logs?: ITransactionLog; hasLogs?: boolean; hasOperations?: boolean; } /** * Result returned when submitting a transaction * Contains the transaction hash and optionally the full transaction data */ interface TransactionSubmitResult { /** Transaction hash */ hash: TransactionHash; /** Transaction status */ status: 'pending' | 'success' | 'failed'; /** Raw transaction data that was submitted (proto Transaction format from @klever/connect-transactions) */ transaction?: unknown; /** Wait for transaction to be mined/confirmed */ wait?: () => Promise; } /** * Klever API Response Types */ interface ApiResponse { data: T; pagination?: Pagination; error: string; code: string; } interface Pagination { self: number; next: number; previous: number; perPage: number; totalPages: number; totalRecords: number; } interface AddressResponse { account: { address: string; nonce: number; rootHash?: string; balance: number; frozenBalance: number; unfrozenBalance: number; allowance: number; permissions: string[]; timestamp: number; codeHash?: string; codeMetadata: string; assets: Record; }; } /** * Asset balance as returned by the API * Matches AccountKDA structure from Go backend */ interface ApiAssetBalance { address: string; assetId: string; collection?: string; nftNonce?: number; assetName: string; assetType: number; balance: number; precision: number; frozenBalance: number; unfrozenBalance: number; lastClaim: { timestamp: number; epoch: number; }; buckets: Array<{ id: string; stakeAt: number; stakedEpoch: number; unstakedEpoch: number; balance: number; delegation: string; validatorName: string; }>; metadata?: string; mime?: string; marketplaceId?: string; orderId?: string; stakingType: number; } interface ITransactionListResponse { transactions: ITransactionResponse[]; } interface ITransactionApiResponse { transaction: ITransactionResponse; } interface IBroadcastResponse { data?: { txHash?: string; txsHashes?: string[]; count?: number; }; error?: string; code?: string; message?: string; } interface IBlockResponse { hash: string; nonce: number; parentHash: string; timestamp: number; slot: number; epoch: number; isEpochStart: boolean; prevEpochStartSlot: number; size: number; sizeTxs: number; virtualBlockSize: number; txRootHash: string; trieRoot: string; validatorsTrieRoot: string; kappsTrieRoot: string; producerSignature: string; signature: string; prevRandSeed: string; randSeed: string; txCount: number; blockRewards: number; stakingRewards: number; txHashes: string[]; validators: string[]; softwareVersion: string; chainID: string; reserved: string; producerBLS: string; transactions: ITransactionResponse[] | null; producerName: string; producerOwnerAddress: string; producerLogo: string; } interface IAssetResponse { assetId: string; assetName: string; assetType: string; ownerAddress: string; logo?: string; uris?: Record; precision: number; circulatingSupply: string; maxSupply: string; marketCap?: string; verified?: boolean; hidden?: boolean; attributes?: Record; } interface INetworkResponse { nodeVersion: string; apiVersion: string; chainID: string; currentBlockHeight: number; currentBlockHash: string; genesisBlockHash: string; protocolVersion: string; } interface IStakingResponse { frozenBalance: number; unfrozenBalance: number; claimableBalance: number; delegate?: { to: string; amount: number; }; } interface IValidatorResponse { address: string; name?: string; rating: number; jailed: boolean; totalStake: string; selfStake: string; delegatedStake: string; commission: number; maxDelegation: string; website?: string; logo?: string; details?: string; } interface IContractQueryResponse { data?: { returnData?: string[]; returnCode?: string; returnMessage?: string; gasRemaining?: number; gasRefund?: number; }; error?: string; code?: string; } interface IFaucetResponse { data?: { txHash: string; status: string; }; error?: string; code?: string; } interface IMarketResponse { marketId: string; baseAsset: string; quoteAsset: string; lastPrice: string; priceChange24h: string; volume24h: string; high24h: string; low24h: string; } interface ITypedValue { type: string; value: string; } /** * Contract request types for Klever blockchain transactions * These types represent the contract parameters sent to the Klever API for building transactions * * Each contract type (Transfer, Freeze, etc.) has a corresponding Request interface * that defines the parameters needed for that specific operation. */ /** * Amount in smallest units (raw value) * - bigint: Native JavaScript bigint (recommended) * - number: JavaScript number (limited to safe integer range) * - string: String representation of raw value (e.g., "10000000" for 10 KLV) * * Note: All values are treated as raw (smallest units). No automatic conversion. * For human-readable values, use parseKLV() to convert before passing to SDK. * * @example * ```typescript * // All these are 10 KLV (raw value = 10000000): * amount: 10000000n // bigint (recommended) * amount: 10000000 // number * amount: "10000000" // string * * // Convert human-readable to raw: * import { parseKLV } from '@klever/connect-core' * amount: parseKLV("10") // Returns 10000000n (10 KLV) * amount: parseKLV("10.5") // Returns 10500000n (10.5 KLV) * ``` */ type AmountLike = number | bigint | string; interface TransferRequest { receiver: string; amount: AmountLike; kda?: string; kdaRoyalties?: AmountLike; klvRoyalties?: AmountLike; } interface RoyaltyData { amount: AmountLike; percentage: number; } interface RoyaltySplitInfo { percentTransferPercentage?: number; percentTransferFixed?: number; percentMarketPercentage?: number; percentMarketFixed?: number; percentITOPercentage?: number; percentITOFixed?: number; } interface RoyaltiesInfo { address: string; transferPercentage?: RoyaltyData[]; transferFixed?: AmountLike; marketPercentage?: number; marketFixed?: AmountLike; itoPercentage?: number; itoFixed?: AmountLike; splitRoyalties?: Record; } interface PropertiesInfo { canFreeze?: boolean; canWipe?: boolean; canPause?: boolean; canMint?: boolean; canBurn?: boolean; canChangeOwner?: boolean; canAddRoles?: boolean; limitTransfer?: boolean; } interface AttributesInfo { isPaused?: boolean; isNFTMintStopped?: boolean; isRoyaltiesChangeStopped?: boolean; isNFTMetadataChangeStopped?: boolean; } interface StakingInfo { interestType: number; apr: number; minEpochsToClaim: number; minEpochsToUnstake: number; minEpochsToWithdraw: number; } interface RolesInfo { address: string; hasRoleMint?: boolean; hasRoleSetITOPrices?: boolean; hasRoleDeposit?: boolean; hasRoleTransfer?: boolean; } interface CreateAssetRequest { type: number; name: string; ticker: string; ownerAddress: string; adminAddress?: string; logo?: string; uris?: Record; precision: number; initialSupply?: AmountLike; maxSupply: AmountLike; royalties?: RoyaltiesInfo; properties?: PropertiesInfo; attributes?: AttributesInfo; staking?: StakingInfo; roles?: RolesInfo[]; } interface KDAPoolInfo { active: boolean; adminAddress: string; fRatioKLV: AmountLike; fRatioKDA: AmountLike; } interface AssetTriggerRequest { triggerType: number; assetId: string; receiver?: string; amount?: AmountLike; mime?: string; logo?: string; value?: AmountLike; uris?: Record; role?: RolesInfo; staking?: StakingInfo; royalties?: RoyaltiesInfo; kdaPool?: KDAPoolInfo; } interface CreateValidatorRequest { blsPublicKey: string; ownerAddress: string; rewardAddress?: string; canDelegate?: boolean; commission: number; maxDelegationAmount?: AmountLike; logo?: string; uris?: Record; name?: string; } interface ValidatorConfigRequest { blsPublicKey: string; rewardAddress?: string; canDelegate?: boolean; commission?: number; maxDelegationAmount?: AmountLike; logo?: string; uris?: Record; name?: string; } interface FreezeRequest { amount: AmountLike; kda?: string; } interface UnfreezeRequest { kda: string; bucketId?: string; } interface DelegateRequest { receiver: string; bucketId?: string; } interface UndelegateRequest { bucketId: string; } interface WithdrawRequest { kda?: string; withdrawType: number; amount?: AmountLike; currencyID?: string; } interface ClaimRequest { claimType: number; id?: string; } interface UnjailRequest { } interface ProposalRequest { parameters: Record; description?: string; epochsDuration?: number; } interface VoteRequest { type: number; proposalId: number; amount?: AmountLike; } interface PackItem { amount: AmountLike; price: AmountLike; } interface PackInfo { packs: PackItem[]; } interface WhitelistInfo { limit: AmountLike; } interface ConfigITORequest { kda: string; receiverAddress?: string; status?: number; maxAmount?: AmountLike; packInfo?: Record; defaultLimitPerAddress?: AmountLike; whitelistStatus?: number; whitelistInfo?: Record; whitelistStartTime?: AmountLike; whitelistEndTime?: AmountLike; startTime?: AmountLike; endTime?: AmountLike; } interface ITOTriggerRequest { triggerType: number; kda: string; receiverAddress?: string; status?: number; maxAmount?: AmountLike; packInfo?: Record; defaultLimitPerAddress?: AmountLike; whitelistStatus?: number; whitelistInfo?: Record; whitelistStartTime?: AmountLike; whitelistEndTime?: AmountLike; startTime?: AmountLike; endTime?: AmountLike; } interface SetITOPricesRequest { kda: string; packInfo: Record; } interface BuyRequest { buyType: number; id: string; currencyId?: string; amount?: AmountLike; currencyAmount?: AmountLike; } interface SellRequest { marketType: number; marketplaceId: string; assetId: string; currencyId?: string; price: AmountLike; reservePrice?: AmountLike; endTime?: AmountLike; } interface CancelMarketOrderRequest { orderId: string; } interface CreateMarketplaceRequest { name: string; referralAddress?: string; referralPercentage?: number; } interface ConfigMarketplaceRequest { marketplaceId: string; name?: string; referralAddress?: string; referralPercentage?: number; } interface SetAccountNameRequest { name: string; } interface SignerRequest { address: string; weight: AmountLike; } interface PermissionRequest { type: number; permissionName: string; threshold: AmountLike; operations: string; signers: SignerRequest[]; } interface UpdateAccountPermissionRequest { permissions: PermissionRequest[]; } interface DepositRequest { depositType: number; kda?: string; currencyId?: string; amount: AmountLike; } /** * Shared fields for smart contract transaction requests. * * `callValue` sends KLV or KDA amounts along with the smart contract operation. * Keys are asset identifiers such as `KLV`; values are raw amounts in the asset's * smallest unit. */ interface SmartContractBaseRequest { callValue?: Record; } /** * Smart contract transaction request. * * Discriminated by `scType`: * - `0` invokes an existing contract and requires a branded `KleverAddress`. * - `1` deploys a new contract and must not include an address. * - `2` upgrades an existing contract and requires a branded `KleverAddress`. * * Use `createKleverAddress()` from `@klever/connect-core` or another validating * path to create the branded address value before building invoke/upgrade calls. */ type SmartContractRequest = (SmartContractBaseRequest & { scType: 0; address: KleverAddress; }) | (SmartContractBaseRequest & { scType: 1; address?: never; }) | (SmartContractBaseRequest & { scType: 2; address: KleverAddress; }); /** * Contract request data - represents a single contract/operation to be sent in a transaction * Matches the Go API structure: { type: number, parameter: } * A transaction can contain multiple contract requests (e.g., transfer + freeze) */ type ContractRequestData = ({ contractType: 0; } & TransferRequest) | ({ contractType: 1; } & CreateAssetRequest) | ({ contractType: 2; } & CreateValidatorRequest) | ({ contractType: 3; } & ValidatorConfigRequest) | ({ contractType: 4; } & FreezeRequest) | ({ contractType: 5; } & UnfreezeRequest) | ({ contractType: 6; } & DelegateRequest) | ({ contractType: 7; } & UndelegateRequest) | ({ contractType: 8; } & WithdrawRequest) | ({ contractType: 9; } & ClaimRequest) | ({ contractType: 10; } & UnjailRequest) | ({ contractType: 11; } & AssetTriggerRequest) | ({ contractType: 12; } & SetAccountNameRequest) | ({ contractType: 13; } & ProposalRequest) | ({ contractType: 14; } & VoteRequest) | ({ contractType: 15; } & ConfigITORequest) | ({ contractType: 16; } & SetITOPricesRequest) | ({ contractType: 17; } & BuyRequest) | ({ contractType: 18; } & SellRequest) | ({ contractType: 19; } & CancelMarketOrderRequest) | ({ contractType: 20; } & CreateMarketplaceRequest) | ({ contractType: 21; } & ConfigMarketplaceRequest) | ({ contractType: 22; } & UpdateAccountPermissionRequest) | ({ contractType: 23; } & DepositRequest) | ({ contractType: 24; } & ITOTriggerRequest) | ({ contractType: 63; } & SmartContractRequest); interface TransactionReceipt { hash: TransactionHash; status: string; blockNumber: number; timestamp: number; } interface BlockEventData { blockNumber: number; hash?: string; timestamp?: number; } interface PendingEventData { hash: string; from: string; } interface ProviderError { code: string; message: string; originalError?: Error | undefined; } interface ProviderEventMap { block: BlockEventData; pending: PendingEventData; error: ProviderError; connect: void; disconnect: void; } type ProviderEvent = keyof ProviderEventMap; interface WsEventMessage { type: string; address: string; hash: string; data?: unknown; } type BlockIdentifier = BlockHash | number | 'latest'; /** * Transaction build request for node endpoint * Used for building transactions server-side with the node handling nonce, fees, and encoding */ interface BuildTransactionRequest { sender?: string; nonce?: number; contracts: ContractRequestData[]; kdaFee?: string; permissionId?: number; data?: string[]; } /** * Transaction build response from node endpoint * Contains the proto transaction object and transaction hash */ interface BuildTransactionResponse { result: unknown; txHash: string; } interface IProvider { readonly network: Network$1; getNetwork(): Network$1; getBlockNumber(): Promise; getBlock(blockHashOrNumber: BlockIdentifier): Promise; getTransaction(hash: TransactionHash | string, options?: { skipCache?: boolean; }): Promise; getTransactionReceipt(hash: TransactionHash | string): Promise; getTransactionUrl(hash: TransactionHash | string): string; getBalance(address: KleverAddress, assetId?: AssetID): Promise; getAccount(address: KleverAddress): Promise; getNonce(address: KleverAddress): Promise; estimateFee(_tx: unknown): Promise; queryContract(params: IContractQueryParams): Promise; sendRawTransaction(signedTx: string | Uint8Array | unknown): Promise; sendRawTransactions(signedTxs: (string | Uint8Array | unknown)[]): Promise; waitForTransaction(hash: TransactionHash | string, confirmations?: number, onProgress?: (status: 'pending' | 'confirming' | 'failed' | 'timeout', data: { attempts: number; maxAttempts: number; confirmations?: number; required?: number; transaction?: ITransactionResponse; }) => void): Promise; on(event: K, listener: (data: ProviderEventMap[K]) => void): void; off(event: K, listener: (data: ProviderEventMap[K]) => void): void; once(event: K, listener: (data: ProviderEventMap[K]) => void): void; removeAllListeners(event?: K): void; connect?(): void; disconnect?(): void; call(endpoint: string, params?: Record): Promise; buildTransaction(request: BuildTransactionRequest): Promise; } type Network = N.Network; type NetworkName = N.NetworkName; type NetworkConfig = N.NetworkConfig; type NetworkURI = N.NetworkURI; /** * Configuration options for HttpClient */ interface HttpClientConfig { /** Base URL for all HTTP requests */ baseUrl: string; /** Request timeout in milliseconds (default: 30000) */ timeout?: number; /** Default headers to include in all requests */ headers?: Record; /** Number of retry attempts for failed requests (default: 3) */ retries?: number; } /** * Options for individual HTTP requests */ interface RequestOptions { /** HTTP method to use (default: GET) */ method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; /** Headers to include in this specific request */ headers?: Record; /** Request body (will be JSON stringified) */ body?: unknown; /** Request timeout in milliseconds */ timeout?: number; } /** * HTTP client with built-in retry logic and timeout handling * * Features: * - Automatic retries with exponential backoff * - Configurable timeout per request * - Default JSON content type * - Proper error handling for HTTP status codes * - Does not retry client errors (4xx) * * @example * ```typescript * const client = new HttpClient({ * baseUrl: 'https://api.example.com', * timeout: 10000, * retries: 3 * }) * * // GET request * const data = await client.get('/users/123') * * // POST request * const result = await client.post('/users', { * name: 'John', * email: 'john@example.com' * }) * ``` */ declare class HttpClient { private baseUrl; private timeout; private headers; private retries; /** * Creates a new HttpClient instance * * @param config - Client configuration */ constructor(config: HttpClientConfig); /** * Makes an HTTP request with automatic retries and timeout handling * * Implements exponential backoff for retries: * - 1st retry: wait 1 second * - 2nd retry: wait 2 seconds * - 3rd retry: wait 4 seconds * * Client errors (4xx) are not retried. * * @param path - API path to request (will be appended to baseUrl) * @param options - Request options (method, headers, body, timeout) * @returns Promise resolving to the parsed JSON response * @throws {Error} If all retry attempts fail or response is not ok * * @example * ```typescript * const response = await client.request('/users/123', { * method: 'GET', * headers: { 'Authorization': 'Bearer token' } * }) * ``` */ request(path: string, options?: RequestOptions): Promise; /** * Makes a GET request * * @param path - API path to request * @param options - Optional request options * @returns Promise resolving to the parsed JSON response * * @example * ```typescript * const user = await client.get('/users/123') * const users = await client.get('/users', { * headers: { 'X-Custom-Header': 'value' } * }) * ``` */ get(path: string, options?: RequestOptions): Promise; /** * Makes a POST request * * @param path - API path to request * @param body - Request body (will be JSON stringified) * @param options - Optional request options * @returns Promise resolving to the parsed JSON response * * @example * ```typescript * const result = await client.post('/users', { * name: 'John', * email: 'john@example.com' * }) * * const response = await client.post('/api/action', payload, { * timeout: 5000 * }) * ``` */ post(path: string, body?: unknown, options?: RequestOptions): Promise; private sleep; } /** * Simple in-memory cache with TTL (time-to-live) and LRU (least-recently-used) eviction * * Features: * - Automatic expiration based on TTL * - LRU eviction when cache is full * - Configurable max size * - Generic type support * * @internal * * @example * ```typescript * const cache = new SimpleCache({ * ttl: 15000, // 15 seconds * maxSize: 100 // Max 100 entries * }) * * cache.set('user:123', userData) * const user = cache.get('user:123') // Returns userData * * // After 15 seconds * const expired = cache.get('user:123') // Returns undefined * ``` */ declare class SimpleCache { private cache; private readonly ttl; private readonly maxSize; /** * Creates a new SimpleCache instance * * @param options - Cache configuration options * @param options.ttl - Time to live in milliseconds (default: 15000) * @param options.maxSize - Maximum number of entries (default: 100) */ constructor(options: CacheOptions); /** * Retrieves a value from the cache * * Returns undefined if: * - Key doesn't exist * - Entry has expired (also removes it) * * @param key - Cache key * @returns Cached value or undefined * * @example * ```typescript * const user = cache.get('user:123') * if (user) { * console.log('Cache hit:', user) * } else { * console.log('Cache miss or expired') * } * ``` */ get(key: string): T | undefined; /** * Stores a value in the cache with automatic expiration * * If cache is full and key doesn't exist, removes oldest entry (LRU eviction). * Updates expiration time if key already exists. * * @param key - Cache key * @param value - Value to cache * * @example * ```typescript * cache.set('user:123', { name: 'John', age: 30 }) * cache.set('account:abc', accountData) * ``` */ set(key: string, value: T): void; /** * Removes all entries from the cache * * @example * ```typescript * cache.clear() * console.log('Cache cleared') * ``` */ clear(): void; /** * Removes a specific entry from the cache * * @param key - Cache key to remove * @returns true if entry was found and removed, false otherwise * * @example * ```typescript * const wasDeleted = cache.delete('user:123') * if (wasDeleted) { * console.log('Entry removed') * } * ``` */ delete(key: string): boolean; } /** * Klever blockchain provider with built-in caching and retry capabilities * * @example * ```typescript * // Default mainnet * const provider = new KleverProvider() * * // Named network (simple) * const provider = new KleverProvider('testnet') * const provider = new KleverProvider('mainnet') * * // Named network (config object) * const provider = new KleverProvider({ network: 'testnet' }) * * // Custom network (shorthand) * const provider = new KleverProvider({ * url: 'https://custom-node.com', * chainId: '100' * }) * * // Custom network (full) * const provider = new KleverProvider({ * network: createCustomNetwork({ * api: 'https://api.custom.com', * node: 'https://node.custom.com', * chainId: '100' * }) * }) * * // Advanced usage with caching and retry * const provider = new KleverProvider({ * network: 'mainnet', * cache: { ttl: 15000, maxSize: 100 }, * retry: { maxRetries: 3, backoff: 'exponential' }, * debug: true * }) * ``` */ declare class KleverProvider implements IProvider { readonly network: Network; protected apiClient: HttpClient; protected nodeClient: HttpClient; protected cache?: SimpleCache; protected readonly debug: boolean; /** Internal typed event emitter shared across the provider */ private readonly _emitter; /** WebSocket / polling manager (created lazily on first connect()) call) */ private _eventManager; /** * Creates a new KleverProvider instance * * @param config - Provider configuration options * Can be: * - undefined: Uses mainnet * - A network name: 'mainnet', 'testnet', 'devnet', 'local' * - A config object with network or custom URL */ constructor(config?: ProviderConfig); /** * Normalize config input to ProviderConfigObject */ private normalizeConfig; /** * Resolve network from config */ private resolveNetwork; /** * Retrieves account information from the blockchain * * @param address - The Klever address to query * @param options - Additional options * @returns Account information including balance and assets * @throws {Error} If the address is invalid * * @example * ```typescript * const account = await provider.getAccount('klv1...') * console.log('Balance:', account.balance) * console.log('Assets:', account.assets) * ``` */ getAccount(address: KleverAddress, options?: { skipCache?: boolean; }): Promise; /** * Get the current nonce for an address * Convenience method that extracts nonce from getAccount * * @param address - Klever address * @returns Current nonce value * * @example * ```typescript * const nonce = await provider.getNonce('klv1...') * console.log('Current nonce:', nonce) * ``` */ getNonce(address: KleverAddress): Promise; /** * Get balance for a specific token * * @param address - Klever address * @param token - Token identifier (e.g., 'KLV', 'KDA-ABC123') * @returns Balance as bigint * * @example * ```typescript * const balance = await provider.getBalance('klv1...', 'KLV') * console.log(`Balance: ${balance}`) * ``` */ getBalance(address: KleverAddress, token?: string): Promise; /** * Retrieves transaction information by hash * * @param hash - The transaction hash (as TransactionHash branded type or string) * @param options - Additional options * @returns Transaction details including receipts, or null if not found * @throws {NetworkError} If there's a network error * * @example * ```typescript * const tx = await provider.getTransaction('0x123...') * if (tx) { * console.log('Status:', tx.status) * console.log('Block:', tx.blockNum) * console.log('From:', tx.sender) * console.log('Receipts:', tx.receipts) * } * ``` */ getTransaction(hash: TransactionHash | string, options?: { skipCache?: boolean; }): Promise; /** * Retrieves transaction receipt(s) by hash * * Receipts contain detailed information about what happened during transaction execution, * including transfers, freezes, claims, and other operations. * * @param hash - The transaction hash (as TransactionHash branded type or string) * @returns Array of receipts or null if transaction not found * * @example * ```typescript * // Get receipts after transaction is mined * const receipts = await provider.getTransactionReceipt(txHash) * if (receipts) { * console.log(`Transaction has ${receipts.length} receipt(s)`) * receipts.forEach(receipt => { * console.log(`Type: ${receipt.typeString}, Asset: ${receipt.assetId}`) * }) * } * * // Parse receipts with type-safe parsers * import { parseReceipt } from '@klever/connect-provider' * const tx = await provider.getTransaction(txHash) * if (tx) { * const freezeData = parseReceipt.freeze(tx) * console.log(`Bucket ID: ${freezeData.bucketId}`) * } * ``` */ getTransactionReceipt(hash: TransactionHash | string): Promise; /** * Broadcasts a single signed transaction to the network * * @param tx - The signed transaction data * @returns Broadcast result with transaction hash * * @example * ```typescript * const result = await provider.broadcastTransaction(signedTx) * console.log(result.hash) // Transaction hash * ``` */ broadcastTransaction(tx: unknown): Promise; /** * Broadcasts multiple signed transactions to the network in a single batch * * @param txs - Array of signed transaction data * @returns Broadcast result with array of transaction hashes * * @example * ```typescript * const result = await provider.broadcastTransactions([tx1, tx2, tx3]) * console.log(result.hashes) // ['hash1', 'hash2', 'hash3'] * ``` */ broadcastTransactions(txs: unknown[]): Promise; /** * Queries a smart contract (read-only, no gas cost) * * Contract queries are free and don't require signing or broadcasting. * Use this to read contract state or call view functions. * * @param params - Contract query parameters * @returns Query result with return data and status * * @example * ```typescript * // Query contract balance * const result = await provider.queryContract({ * scAddress: 'klv1contract...', * funcName: 'getBalance', * args: ['klv1user...'] * }) * * if (result.error) { * console.error('Query failed:', result.error) * } else { * console.log('Return data:', result.data?.returnData) * console.log('Gas remaining:', result.data?.gasRemaining) * } * ``` */ queryContract(params: IContractQueryParams): Promise; /** * Requests test KLV from faucet (testnet/devnet only) * * @param address - The address to send test KLV to * @param amount - Optional amount to request (in smallest unit) * @returns Faucet result with transaction hash and status * @throws {ValidationError} If address is invalid or network is mainnet * * @example * ```typescript * // Request test KLV on testnet * const provider = new KleverProvider('testnet') * const result = await provider.requestTestKLV('klv1...') * console.log('Faucet TX:', result.txHash) * console.log('Status:', result.status) * * // Wait for confirmation * await provider.waitForTransaction(result.txHash) * const balance = await provider.getBalance('klv1...') * console.log('New balance:', balance) * ``` */ requestTestKLV(address: KleverAddress, amount?: bigint): Promise; /** * Clear all cached data */ clearCache(): void; /** * Get the full URL for viewing a transaction in the explorer * @param txHash - The transaction hash (as TransactionHash branded type or string) * @returns The full URL to view the transaction * * @example * ```typescript * const txUrl = provider.getTransactionUrl('0x123...') * console.log(txUrl) // https://kleverscan.org/transaction/0x123... * ``` */ getTransactionUrl(txHash: TransactionHash | string): string; /** * Get the network name */ getNetworkName(): NetworkName; /** * Get the network object */ getNetwork(): Network; /** * Get the current block number (nonce) from the blockchain * @returns Current block nonce */ getBlockNumber(): Promise; /** * Get block by nonce, hash, or "latest" * @param blockHashOrNumber - Block nonce (number), hash (string), or "latest" * @returns Block information */ getBlock(blockHashOrNumber: BlockIdentifier): Promise; /** * Estimates the fee for a transaction * * TODO: Implementation pending - currently returns zero fees * * This method will calculate the expected fees for a transaction including: * - kAppFee: Application-specific fee * - bandwidthFee: Network bandwidth cost * - gasEstimated: Estimated gas for smart contract execution * * @param _tx - The transaction request to estimate fees for * @returns The estimated fee breakdown * * @example * ```typescript * // Future usage (not yet implemented) * const fees = await provider.estimateFee({ * sender: 'klv1...', * contracts: [{ * type: TXType.Transfer, * parameter: { receiver: 'klv1...', amount: 1000000n } * }] * }) * console.log('Estimated kAppFee:', fees.kAppFee) * console.log('Estimated bandwidthFee:', fees.bandwidthFee) * ``` */ estimateFee(_tx: unknown): Promise; /** * Parse raw transaction data to a format suitable for broadcasting * Supports hex strings, JSON strings, Uint8Arrays, and transaction objects * @private * @throws {Error} If the transaction data is invalid */ private parseRawTransaction; /** * Sends a single raw transaction to the network * @param signedTx - Signed transaction data (hex string, JSON string, Uint8Array, or Transaction object) * @returns The transaction hash * @throws {Error} If the transaction data is invalid, broadcast fails, or no hash is returned * * @example * ```typescript * try { * const hash = await provider.sendRawTransaction(signedTxHex) * console.log(hash) // '0x123...' * } catch (error) { * console.error('Broadcast failed:', error.message) * } * ``` */ sendRawTransaction(signedTx: string | Uint8Array | unknown): Promise; /** * Sends multiple raw transactions to the network in a single batch * @param signedTxs - Array of signed transaction data (hex strings, JSON strings, Uint8Arrays, or Transaction objects) * @returns Array of transaction hashes * @throws {Error} If any transaction data is invalid, broadcast fails, or no hashes are returned * * @example * ```typescript * try { * const hashes = await provider.sendRawTransactions([tx1Hex, tx2Hex, tx3Hex]) * console.log(hashes) // ['0x123...', '0x456...', '0x789...'] * } catch (error) { * console.error('Broadcast failed:', error.message) * } * ``` */ sendRawTransactions(signedTxs: (string | Uint8Array | unknown)[]): Promise; /** * Waits for a transaction to be mined and confirmed * @param hash - The transaction hash (as TransactionHash branded type or string) * @param confirmations - Number of confirmations to wait for (default: 1) * @param onProgress - Optional callback for progress updates * @returns The transaction or null if not found/timeout * * @example * ```typescript * // Basic usage * const tx = await provider.waitForTransaction(hash) * * // With progress callback for UI updates * const tx = await provider.waitForTransaction(hash, 3, (status, data) => { * if (status === 'pending') { * console.log(`Attempt ${data.attempts}/${data.maxAttempts}`) * } else if (status === 'confirming') { * console.log(`Confirmations: ${data.confirmations}/${data.required}`) * } * }) * ``` */ waitForTransaction(hash: TransactionHash | string, confirmations?: number, onProgress?: (status: 'pending' | 'confirming' | 'failed' | 'timeout', data: { attempts: number; maxAttempts: number; confirmations?: number; required?: number; transaction?: ITransactionResponse; }) => void): Promise; private isPendingTransactionLookupError; /** * Subscribe to provider events * * Opens a WebSocket connection to the network's `ws` URL. If WebSocket is unavailable in the * current runtime, or if the network has no `ws` URL configured, the * provider automatically falls back to polling the REST API for new blocks * every 3 seconds. * * Safe to call multiple times — subsequent calls while already connected are * no-ops. To reconnect, call `disconnect()` first. * * @example * ```typescript * const provider = new KleverProvider('mainnet') * provider.on('block', ({ blockNumber }) => console.log('New block:', blockNumber)) * provider.connect() * ``` */ connect(): void; /** * Stop real-time event subscription and release all associated resources * (WebSocket, polling timers). * * After calling `disconnect()` you can call `connect()` again to re-establish * the connection. * * @example * ```typescript * provider.disconnect() * ``` */ disconnect(): void; /** * Register a persistent listener for a provider event. * * The provider emits the following typed events: * - `'block'` — `BlockEventData` — new block produced * - `'pending'` — `PendingEventData` — pending transaction in mempool * - `'error'` — `ProviderError` — connection or polling error * - `'debug'` — `DebugEvent` — internal diagnostic message * - `'network'` — `NetworkChangeEvent` — active network changed * - `'connect'` — `undefined` — WebSocket/polling connection established * - `'disconnect'` — `undefined` — WebSocket/polling connection closed * * Note: You must call `connect()` to start receiving `'block'`, `'pending'`, * `'connect'`, and `'disconnect'` events. `'error'` and `'network'` events * can fire without an active connection. * * @param event - The event name (key of ProviderEventMap) * @param listener - Callback receiving the typed payload * * @example * ```typescript * provider.on('block', ({ blockNumber, hash }) => { * console.log(`New block #${blockNumber}: ${hash}`) * }) * * provider.on('error', ({ code, message }) => { * console.error(`Provider error [${code}]: ${message}`) * }) * * provider.connect() * ``` */ on(event: K, listener: (data: ProviderEventMap[K]) => void): void; /** * Remove a previously registered listener. * * Passing a listener reference that was never registered is a no-op. * * @param event - The event name * @param listener - The exact callback reference that was passed to `on`/`once` * * @example * ```typescript * const handler = ({ blockNumber }: BlockEventData) => console.log(blockNumber) * provider.on('block', handler) * // ... later * provider.off('block', handler) * ``` */ off(event: K, listener: (data: ProviderEventMap[K]) => void): void; /** * Register a one-time listener that is automatically removed after its * first invocation. * * @param event - The event name * @param listener - Callback receiving the typed payload * * @example * ```typescript * // Wait for the first block after connecting * provider.once('block', ({ blockNumber }) => { * console.log('First block received:', blockNumber) * }) * provider.connect() * ``` */ once(event: K, listener: (data: ProviderEventMap[K]) => void): void; /** * Remove all listeners for a specific event, or every listener across all * events when called without arguments. * * @param event - Optional event name. Omit to clear all events. * * @example * ```typescript * // Remove all 'block' listeners * provider.removeAllListeners('block') * * // Remove every listener on the provider * provider.removeAllListeners() * ``` */ removeAllListeners(event?: K): void; /** * Calls a contract method (generic API call) * * TODO: Implementation pending - generic contract calls not yet supported * * This is a low-level method for making arbitrary contract API calls. * For standard contract queries, use `queryContract()` instead. * * @param _endpoint - The API endpoint for the contract call * @param _params - The parameters for the contract call * @returns The result of the contract call * * @example * ```typescript * // Future usage (not yet implemented) * const result = await provider.call('/contract/endpoint', { * param1: 'value1', * param2: 123 * }) * ``` */ call(_endpoint: string, _params?: Record): Promise; /** * Build transaction using node endpoint * Node will handle nonce fetching (if missing), fee calculation, and proto encoding * * This method provides server-side transaction building where the node does the heavy lifting: * - Fetches nonce if not provided * - Calculates kAppFee and bandwidthFee * - Encodes transaction to proto format * - Returns proto transaction object and transaction hash * * @param request - Transaction build request with contracts and optional sender/nonce * @returns Proto transaction object and transaction hash * * @example * ```typescript * const request = { * sender: 'klv1...', * contracts: [{ * type: TXType.Transfer, * parameter: { receiver: 'klv1...', amount: 1000000n, kda: 'KLV' } * }] * } * const tx = await provider.buildTransaction(request) * // tx.result contains proto transaction object (ITransaction) * // tx.txHash contains the transaction hash * ``` */ buildTransaction(request: BuildTransactionRequest): Promise; /** * Execute multiple requests in parallel * Useful for batching multiple API calls for better performance * * @param requests - Array of request functions to execute * @returns Array of results in the same order as requests * * @example * ```typescript * const [account1, account2, balance] = await provider.batch([ * () => provider.getAccount('klv1...'), * () => provider.getAccount('klv1xxx...'), * () => provider.getBalance('klv1...') * ]) * ``` */ batch(requests: (() => Promise)[]): Promise; /** * Alias for getAccount() - matches Solana web3.js naming convention * @see getAccount */ getAccountInfo(address: KleverAddress, options?: { skipCache?: boolean; }): Promise; /** * Alias for broadcastTransaction() - matches ethers.js and web3.js naming convention * More commonly used in Web3 ecosystems * @see broadcastTransaction */ sendTransaction(tx: unknown): Promise; } type Listener = (data: T) => void; /** * Generic typed event emitter. * * @typeParam TEventMap - A record mapping event name strings to their payload * types. Use `void` for events that carry no data. * * @example * ```typescript * interface MyEvents { * block: { nonce: number; hash: string } * error: Error * connect: void * } * * const emitter = new TypedEventEmitter() * emitter.on('block', ({ nonce }) => console.log('block', nonce)) * emitter.emit('block', { nonce: 1, hash: '0xabc' }) * ``` */ declare class TypedEventEmitter> { private readonly _listeners; /** * Add a persistent listener for `event`. * The listener will be called every time the event is emitted. * * @param event - The event name * @param listener - Callback invoked with the event payload */ on(event: K, listener: Listener): this; /** * Remove a previously registered listener for `event`. * If the listener is not found this is a no-op. * * @param event - The event name * @param listener - The exact callback reference that was passed to `on`/`once` */ off(event: K, listener: Listener): this; /** * Add a one-time listener for `event`. * The listener will be invoked at most once and then automatically removed. * * @param event - The event name * @param listener - Callback invoked with the event payload */ once(event: K, listener: Listener): this; /** * Remove all listeners for a specific event, or every listener across all * events when called without arguments. * * @param event - Optional event name. When omitted all listeners are cleared. */ removeAllListeners(event?: K): this; /** * Return the number of listeners currently registered for `event`. * * @param event - The event name */ getListenerCount(event: K): number; /** * Return all event names that currently have at least one listener. */ eventNames(): Array; /** * Dispatch `event` to all registered listeners. * One-time listeners are removed before invocation so that re-entrant * emissions do not call them twice. * * @param event - The event name * @param data - The payload forwarded to every listener */ emit(event: K, data: TEventMap[K]): void; /** Centralised typed accessor — the single place where the Map cast lives. */ private _getEntries; private _addListener; } /** * Manages the real-time event connection (WebSocket or polling fallback) for * a given Klever network. * * Consumers interact via the {@link TypedEventEmitter} that is passed in at * construction time — this class simply drives it with live data. * * @example * ```typescript * const manager = new KleverEventManager( * network, * emitter, * () => provider.getBlockNumber(), * debug, * ) * manager.connect() * // ... * manager.dispose() * ``` */ declare class KleverEventManager { private readonly _network; private readonly _emitter; private readonly _fetchBlockNumber; private readonly _debug; private _ws; private _wsConnected; private _wsAvailable; private _wsConnectTimer; private _reconnectAttempts; private _reconnectTimer; private _poller; private _disposed; constructor(network: Network, emitter: TypedEventEmitter, fetchBlockNumber: () => Promise, debug?: boolean); /** * Open the connection. If WebSocket is available and the network has a `ws` * URL, a WebSocket subscription is established. Otherwise HTTP polling is * used as a fallback. */ connect(): void; /** * Close the connection and clean up all timers. After calling this the * manager must not be reused — create a fresh instance instead. */ dispose(): void; /** Whether the WebSocket connection is currently open */ get isConnected(): boolean; /** Whether the manager is using polling (as opposed to WebSocket) */ get isPolling(): boolean; private _connectWs; private _handleWsMessage; private _scheduleReconnect; private _startPolling; private _teardown; private _safeEmit; private _log; } declare const NETWORKS: Record; declare const DEFAULT_NETWORK: NetworkName; declare function getNetworkByChainId(chainId: string): Network | undefined; declare function createCustomNetwork(config: { chainId: string; api: string; node: string; ws?: string; explorer?: string; isTestnet?: boolean; }): Network; /** * Helper to resolve network configuration to a Network object */ declare function resolveNetwork(network: NetworkName | Network): Network; /** * Helper to get network name from a Network object */ declare function getNetworkName(network: NetworkName | Network): NetworkName; /** * Helper to get network configuration from a Network object * @param network * @returns */ declare function getNetworkConfig(network: NetworkName | Network): NetworkURI; /** * Helper to get network identifier for storage */ declare function getNetworkIdentifier(network: NetworkName): string; /** * Receipt Parser Utilities * * Type-safe parsers for extracting data from transaction receipts. * Works with all transaction types and provides clean, typed outputs. */ interface FreezeReceiptData { /** Bucket ID created (32-byte hash for KLV, KDA ID for other assets) */ bucketId: string; /** Amount frozen */ amount: bigint; /** Asset ID (KDA) */ kda: string; /** All freeze operations if multiple assets were frozen */ freezes?: Array<{ bucketId: string; amount: bigint; kda: string; }> | undefined; /** Raw receipt for additional data */ raw: ITransactionResponse; } interface UnfreezeReceiptData { /** Bucket ID that was unfrozen */ bucketId: string; /** Asset ID (KDA) */ kda: string; /** Timestamp when withdrawal will be available */ availableAt?: number | undefined; /** Raw receipt for additional data */ raw: ITransactionResponse; } interface ClaimReceiptData { /** Array of claimed rewards */ rewards: Array<{ /** Asset ID */ kda: string; /** Amount claimed */ amount: bigint; }>; /** Total amount claimed (sum of all rewards) */ totalClaimed: bigint; /** Claim type (0 = Staking, 1 = Market, 2 = Allowance, 3 = FPR) */ claimType?: number | undefined; /** Raw receipt for additional data */ raw: ITransactionResponse; } interface WithdrawReceiptData { /** Amount withdrawn */ amount: bigint; /** Asset ID (KDA) */ kda: string; /** Withdraw type */ withdrawType?: number | undefined; /** All withdrawals if multiple */ withdrawals?: Array<{ amount: bigint; kda: string; }> | undefined; /** Raw receipt for additional data */ raw: ITransactionResponse; } interface DelegateReceiptData { /** Validator address delegated to */ validator: string; /** Bucket ID that was delegated */ bucketId: string; /** Raw receipt for additional data */ raw: ITransactionResponse; } interface UndelegateReceiptData { /** Bucket ID that was undelegated */ bucketId: string; /** Timestamp when funds will be available for withdrawal */ availableAt?: number | undefined; /** Raw receipt for additional data */ raw: ITransactionResponse; } interface TransferReceiptData { /** Sender address */ sender: string; /** Recipient address */ receiver: string; /** Amount transferred */ amount: bigint; /** Asset ID (KDA) - defaults to KLV */ kda: string; /** All transfers if multiple assets were transferred */ transfers?: Array<{ sender: string; receiver: string; amount: bigint; kda: string; }> | undefined; /** Raw receipt for additional data */ raw: ITransactionResponse; } declare class ReceiptParseError extends Error { readonly receipt?: ITransactionResponse | undefined; readonly receiptType?: string | undefined; constructor(message: string, receipt?: ITransactionResponse | undefined, receiptType?: string | undefined); } /** * Parse freeze transaction receipt to extract bucket ID and frozen amount * * Freeze receipts contain: * - bucketId: Unique identifier for the frozen bucket (32-byte hash) * - amount: Amount that was frozen * - kda: Asset ID (KDA) that was frozen * * Supports multi-freeze transactions where multiple assets are frozen in one transaction. * * @param receipt - Transaction receipt from a freeze operation * @returns Parsed freeze data with bucket ID, amount, and asset details * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * // Single freeze * const tx = await provider.getTransaction(freezeTxHash) * const { bucketId, amount, kda } = parseReceipt.freeze(tx) * console.log(`Frozen ${amount} ${kda} in bucket ${bucketId}`) * * // Multiple freezes * const { bucketId, amount, kda, freezes } = parseReceipt.freeze(tx) * console.log(`Primary freeze: ${amount} ${kda}`) * if (freezes) { * freezes.forEach(f => console.log(` ${f.amount} ${f.kda} -> ${f.bucketId}`)) * } * ``` */ declare function freeze(receipt: ITransactionResponse): FreezeReceiptData; /** * Parse unfreeze transaction receipt to extract bucket and availability details * * Unfreeze receipts contain: * - bucketId: ID of the bucket that was unfrozen * - kda: Asset ID that was unfrozen * - availableAt: Timestamp when funds can be withdrawn (if applicable) * * @param receipt - Transaction receipt from an unfreeze operation * @returns Parsed unfreeze data with bucket ID and availability info * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * const tx = await provider.getTransaction(unfreezeTxHash) * const { bucketId, kda, availableAt } = parseReceipt.unfreeze(tx) * console.log(`Unfrozen ${kda} from bucket ${bucketId}`) * if (availableAt) { * const date = new Date(availableAt * 1000) * console.log(`Available for withdrawal at: ${date.toISOString()}`) * } * ``` */ declare function unfreeze(receipt: ITransactionResponse): UnfreezeReceiptData; /** * Parse claim transaction receipt to extract reward details * * Claim receipts contain: * - rewards: Array of all claimed rewards by asset * - totalClaimed: Sum of all claimed amounts * - claimType: Type of claim (0=Staking, 1=Market, 2=Allowance, 3=FPR) * * Claims always involve multiple receipts (one per asset claimed). * * @param receipt - Transaction receipt from a claim operation * @returns Parsed claim data with rewards array and totals * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * const tx = await provider.getTransaction(claimTxHash) * const { rewards, totalClaimed, claimType } = parseReceipt.claim(tx) * * console.log(`Claimed ${totalClaimed} total across ${rewards.length} assets`) * rewards.forEach(r => { * console.log(` ${r.amount} ${r.kda}`) * }) * * const claimTypes = ['Staking', 'Market', 'Allowance', 'FPR'] * console.log(`Claim type: ${claimTypes[claimType || 0]}`) * ``` */ declare function claim(receipt: ITransactionResponse): ClaimReceiptData; /** * Parse withdraw transaction receipt to extract withdrawal details * * Withdraw receipts contain: * - amount: Amount withdrawn * - kda: Asset ID that was withdrawn * - withdrawType: Type of withdrawal operation * * Supports multi-withdraw transactions. * * @param receipt - Transaction receipt from a withdraw operation * @returns Parsed withdraw data with amount and asset details * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * const tx = await provider.getTransaction(withdrawTxHash) * const { amount, kda, withdrawType } = parseReceipt.withdraw(tx) * console.log(`Withdrew ${amount} ${kda}`) * * // Multiple withdrawals * const { amount, kda, withdrawals } = parseReceipt.withdraw(tx) * if (withdrawals) { * console.log(`Total withdrawals: ${withdrawals.length}`) * withdrawals.forEach(w => console.log(` ${w.amount} ${w.kda}`)) * } * ``` */ declare function withdraw(receipt: ITransactionResponse): WithdrawReceiptData; /** * Parse delegate transaction receipt to extract delegation details * * Delegate receipts contain: * - validator: Address of the validator that was delegated to * - bucketId: Bucket ID that was delegated * * @param receipt - Transaction receipt from a delegate operation * @returns Parsed delegation data with validator and bucket ID * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * const tx = await provider.getTransaction(delegateTxHash) * const { validator, bucketId } = parseReceipt.delegate(tx) * console.log(`Delegated bucket ${bucketId} to validator ${validator}`) * ``` */ declare function delegate(receipt: ITransactionResponse): DelegateReceiptData; /** * Parse undelegate transaction receipt to extract undelegation details * * Undelegate receipts contain: * - bucketId: Bucket ID that was undelegated * - availableAt: Timestamp when funds can be withdrawn * * Note: Undelegate creates a Delegate receipt (type 7) with empty delegate field * * @param receipt - Transaction receipt from an undelegate operation * @returns Parsed undelegation data with bucket ID and availability info * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * const tx = await provider.getTransaction(undelegateTxHash) * const { bucketId, availableAt } = parseReceipt.undelegate(tx) * console.log(`Undelegated bucket ${bucketId}`) * if (availableAt) { * const date = new Date(availableAt * 1000) * console.log(`Available for withdrawal: ${date.toISOString()}`) * } * ``` */ declare function undelegate(receipt: ITransactionResponse): UndelegateReceiptData; /** * Parse transfer transaction receipt to extract transfer details * * Transfer receipts contain: * - sender: Address that sent the assets * - receiver: Address that received the assets * - amount: Amount transferred * - kda: Asset ID that was transferred (defaults to KLV) * * Supports multi-transfer transactions where multiple transfers occur. * * @param receipt - Transaction receipt from a transfer operation * @returns Parsed transfer data with sender, receiver, and amount * @throws {ReceiptParseError} If receipt is missing or invalid * * @example * ```typescript * // Single transfer * const tx = await provider.getTransaction(transferTxHash) * const { sender, receiver, amount, kda } = parseReceipt.transfer(tx) * console.log(`${sender} sent ${amount} ${kda} to ${receiver}`) * * // Multiple transfers * const { sender, receiver, amount, kda, transfers } = parseReceipt.transfer(tx) * console.log(`Primary: ${sender} -> ${receiver}: ${amount} ${kda}`) * if (transfers) { * console.log(`Total transfers: ${transfers.length}`) * transfers.forEach(t => { * console.log(` ${t.sender} -> ${t.receiver}: ${t.amount} ${t.kda}`) * }) * } * ``` */ declare function transfer(receipt: ITransactionResponse): TransferReceiptData; /** * Receipt parser utilities * * Provides type-safe parsing of transaction receipts with hybrid support: * - Simple API: Primary/first receipt for common single-operation cases * - Array fields: All operations when multiple receipts exist * * @example * ```ts * import { parseReceipt } from '@klever/connect-provider' * * // Single freeze * const result = await freeze(100000, 'KLV') * const receipt = await result.wait() * const { bucketId, amount, kda } = parseReceipt.freeze(receipt) * console.log(`Created bucket ${bucketId} with ${amount} ${kda}`) * * // Multiple transfers in one transaction * const transferResult = await transferMultiple(...) * const transferReceipt = await transferResult.wait() * const { sender, receiver, amount, kda, transfers } = parseReceipt.transfer(transferReceipt) * console.log(`Primary: ${sender} → ${receiver}: ${amount} ${kda}`) * if (transfers) { * console.log(`Total transfers: ${transfers.length}`) * transfers.forEach(t => console.log(` ${t.sender} → ${t.receiver}: ${t.amount} ${t.kda}`)) * } * * // Claim rewards (always multiple) * const claimResult = await claim(0) * const claimReceipt = await claimResult.wait() * const { rewards, totalClaimed } = parseReceipt.claim(claimReceipt) * console.log(`Claimed ${totalClaimed} across ${rewards.length} assets`) * ``` */ declare const parseReceipt: { freeze: typeof freeze; unfreeze: typeof unfreeze; claim: typeof claim; withdraw: typeof withdraw; delegate: typeof delegate; undelegate: typeof undelegate; transfer: typeof transfer; }; export { type AddressResponse, type AmountLike, type ApiAssetBalance, type ApiResponse, type AssetTriggerRequest, AssetType, type AttributesInfo, type BlockEventData, type BlockIdentifier, type BuildTransactionRequest, type BuildTransactionResponse, type BuyRequest, type CacheOptions, type CancelMarketOrderRequest, type ClaimReceiptData, type ClaimRequest, type ConfigITORequest, type ConfigMarketplaceRequest, type ContractRequestData, type CreateAssetRequest, type CreateMarketplaceRequest, type CreateValidatorRequest, type CustomNetworkConfig, DEFAULT_NETWORK, type DelegateReceiptData, type DelegateRequest, type DepositRequest, type FreezeReceiptData, type FreezeRequest, HttpClient, type IAccount, type IAssetBalance, type IAssetResponse, type IBalance, type IBlockResponse, type IBroadcastResponse, type IBroadcastResult, type IBulkBroadcastResult, type ICallValueData, type IContractData, type IContractQueryParams, type IContractQueryResponse, type IContractQueryResult, type IFaucetResponse, type IFaucetResult, type IFees, type IFeesResponse, type ILogEvent, type IMarketResponse, type INetworkResponse, type IProvider, type IReceipt, type ISCData, type IStakingResponse, type ITOTriggerRequest, type ITransactionApiResponse, type ITransactionListResponse, type ITransactionLog, type ITransactionResponse, type ITypedValue, type IValidatorResponse, type KDAPoolInfo, KleverEventManager, KleverProvider, NETWORKS, type Network, type NetworkConfig, type NetworkName, type NetworkURI, type PackInfo, type PackItem, type Pagination, type PendingEventData, type PermissionRequest, type PropertiesInfo, type ProposalRequest, type ProviderConfig, type ProviderConfigObject, type ProviderError, type ProviderEvent, type ProviderEventMap, ReceiptParseError, type RetryOptions, type RolesInfo, type RoyaltiesInfo, type RoyaltyData, type RoyaltySplitInfo, type SellRequest, type SetAccountNameRequest, type SetITOPricesRequest, type SignerRequest, type SmartContractBaseRequest, type SmartContractRequest, type StakingInfo, StakingInterestType, type TransactionReceipt, TransactionStatus, type TransactionSubmitResult, type TransferReceiptData, type TransferRequest, TypedEventEmitter, type UndelegateReceiptData, type UndelegateRequest, type UnfreezeReceiptData, type UnfreezeRequest, type UnjailRequest, type UpdateAccountPermissionRequest, type UserKDABucket, type UserKDALastClaim, type ValidatorConfigRequest, type VoteRequest, type WhitelistInfo, type WithdrawReceiptData, type WithdrawRequest, type WsEventMessage, createCustomNetwork, getNetworkByChainId, getNetworkConfig, getNetworkIdentifier, getNetworkName, parseReceipt, resolveNetwork };