npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kokosro/ledger

v0.3.0

Published

Server-side ledger execution, state management, and RPC server

Readme

@kokosro/ledger

⚠️ Experimental: This package is in active development and the API may change.

Server-side ledger execution, state management, and JSON-RPC server for the TypeScript blockchain.

Installation

npm install @kokosro/ledger viem

Description

This package provides the core blockchain execution engine, including:

  • Transaction processing and validation
  • Contract execution system
  • State management with Merkle Patricia Trie
  • Block production and validation
  • JSON-RPC server for remote access
  • Persistence with LevelDB
  • Mempool and fee market

Designed for private blockchain applications, API cost tracking systems, and permissioned execution environments.

Quick Start

Embedded Mode (Simple)

import {
  createLedger,
  registerContractFunction,
  getEmptyAccount,
  TxKinds,
} from "@kokosro/ledger";
import { privateKeyToAccount } from "viem/accounts";

// Register contract functions
registerContractFunction(
  "myContract",
  async ({ caller, address, state, value, data }) => {
    // Your contract logic here
    const count = state.readStorage("count") || "0";
    await state.writeStorage("count", String(parseInt(count) + 1));

    return {
      success: true,
      computationCost: 5000n,
      returnData: "0x",
    };
  }
);

// Create blockchain
const rootAccount = privateKeyToAccount("0x...");
const validatorAccount = privateKeyToAccount("0x...");

const ledger = await createLedger({
  chainParams: {
    chainId: 1337n,
    root: rootAccount.address,
    targetMempoolSize: 100,
    feeBase: 1000n,
    feeSlope: 10n,
    blockSpeedTarget: 5000,
  },
  validators: [validatorAccount.address],
  genesis: [
    {
      ...getEmptyAccount(rootAccount.address),
      balance: 1_000_000n,
    },
  ],
});

// Submit transaction
await ledger.submitTransaction(signedTx);

// Propose block (validator only)
await ledger.proposeBlock(validatorAccount.address);

JSON-RPC Server Mode (Production)

import { createLedger, startJsonRpcServer } from "@kokosro/ledger";

const ledger = await createLedger({
  chainParams: {
    /* ... */
  },
  validators: [validatorAddress],
  genesis: [
    /* ... */
  ],
  persistence: {
    enabled: true,
    dbPath: "./data/ledger",
  },
});

// Start RPC server
const server = await startJsonRpcServer(ledger, {
  port: 37847,
  host: "0.0.0.0",
  cors: true,
});

console.log("JSON-RPC server running at http://localhost:37847");

Key APIs

Ledger Creation

const ledger = await createLedger(config: LedgerConfig): Promise<Ledger>

Contract System

// Register contract function
registerContractFunction(
  name: string,
  handler: ContractHandler
): void

// Declare contract with metadata
declareContract(definition: HumanReadableContract): void

// Example contracts provided
import {
  counterContractDefinition,
  erc20ContractDefinition,
  storageContractDefinition,
  greeterContract,
} from '@kokosro/ledger';

Transaction Utilities

validateTransaction(tx: TxSigned, state: State): Promise<void>
executeTransaction(tx: TxSigned, state: State, context: BlockContext): Promise<TxExecutionResult>
calculateTxFee(tx: TxSigned, baseFee: bigint): bigint
computeContractAddress(deployer: Address, nonce: bigint): Address

Ledger Methods

interface Ledger {
  submitTransaction(tx: TxSigned): Promise<void>;
  proposeBlock(proposer: Address): Promise<Block>;
  getAccount(address: Address): Promise<Account>;
  getBlock(height: bigint): Promise<Block | null>;
  getLatestBlock(): Promise<Block>;
  getChainHeight(): Promise<bigint>;
  getCurrentValidator(): Address;
  getBaseFee(): bigint;
  getTotalSupply(): Promise<bigint>;
  getPendingTransactions(): TxSigned[];
  getMempoolSize(): number;
}

JSON-RPC Server

// Start server
startJsonRpcServer(ledger: Ledger, config?: ServerConfig): Promise<Server>

// Stop server
stopJsonRpcServer(server: Server): Promise<void>

// Handle individual requests
handleJsonRpcRequest(request: JsonRpcRequest, methods: RpcMethodHandler): Promise<JsonRpcResponse>

State Management

const state = await createState(params: CreateStateParams): Promise<State>
const emptyAccount = getEmptyAccount(address: Address): Account

Block & Validator Utilities

createBlock(params): Block
createGenesisBlock(params): Block
validateBlock(block: Block, state: State): Promise<void>
getValidatorForHeight(height: bigint, validators: Address[]): Address
canProposeBlock(proposer: Address, validators: Address[], blockTime: number): boolean

Production Features

Persistence

import { createLedger, createLevelDB } from "@kokosro/ledger";

const ledger = await createLedger({
  // ... config
  persistence: {
    enabled: true,
    dbPath: "./data/ledger",
  },
});

Recovery

import { ChainRecovery } from "@kokosro/ledger";

const recovery = new ChainRecovery(db);
const result = await recovery.loadChain();

if (!result.isNewChain) {
  console.log(`Resumed chain at height ${result.chainHeight}`);
}

Metrics & Monitoring

import { Metrics } from "@kokosro/ledger";

const metrics = new Metrics();
metrics.recordTx(txHash, success);
metrics.recordBlock(blockTime);

const stats = metrics.getStats();
console.log(`TPS: ${stats.tps}, Avg Block Time: ${stats.avgBlockTime}ms`);

Snapshots

import { SnapshotManager } from "@kokosro/ledger";

const snapshots = new SnapshotManager(db, { interval: 1000, keep: 10 });
await snapshots.createSnapshot(height, stateRoot);
const snapshot = await snapshots.getLatestSnapshot();

Transaction Types

  • MINT: Create new tokens (root account only)
  • DEPLOY: Deploy a contract
  • CALL: Execute contract or transfer value
  • BURN: Burn tokens
  • CHANGE_ROOT: Change root account
  • ADD_VALIDATOR: Add validator
  • REMOVE_VALIDATOR: Remove validator

Fee Model

Total Fee = Computation Cost + Congestion Fee
Congestion Fee = feeBase + (feeSlope × mempoolSize)

Fees are burned (destroyed), reducing total supply.

Related Packages

License

ISC © 2025 kokosro