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

dkey-lib

v7.0.0

Published

DKey library for encrypted file sharing with zero-knowledge proofs

Readme

dkey-lib

A TypeScript library for encrypted file sharing with zero-knowledge proofs on blockchain. Enables secure, decentralized file distribution with cryptographic access control.

Features

  • 🔐 Encrypted File Sharing: Encrypt files using BN254 elliptic curve cryptography
  • 🔑 Zero-Knowledge Proofs: Generate and verify ZK proofs for secure key distribution
  • 📦 Content-addressed storage: Frontend chooses IPFS, Swarm, or another data layer
  • ⛓️ Blockchain Integration: Deploy listings, place bids, and manage DKeys on Ethereum-compatible chains
  • 🔄 Profile Management: Serialize and encrypt user profiles for secure storage
  • 🎯 TypeScript Support: Full TypeScript definitions included

Installation

npm install dkey-lib

Prerequisites

  • A wagmi Config for blockchain interactions — see Static / no-bundler checklist for how to build one
  • Access to a supported network (see Supported Chains)
  • Node.js 18+ if you consume the package from Node or a bundler. For the browser bundle Node is a build-time concern only — the shipped IIFE runs in any modern browser.

Browser bundle

For plain JS/HTML/CSS frontends without a bundler, use the browser build. Load it with a script tag:

<!-- From node_modules (if you npm install dkey-lib) -->
<script src="node_modules/dkey-lib/dist/dkey-lib.browser.js"></script>

The API is exposed on window.dkeyLib:

  • Default export (the dkey object): window.dkeyLib.default or window.dkeyLib.dkey
  • Named exports: window.dkeyLib.DkeyUserProfile, window.dkeyLib.Listing, window.dkeyLib.ListingMetadata, window.dkeyLib.Bid, window.dkeyLib.DKey, window.dkeyLib.RESULTS, window.dkeyLib.BidLite

You must still copy the circuits folder from node_modules/dkey-lib/circuits to your public directory and configure paths:

<script>
  window.dkeyLib.dkey.configureCircuits('/circuits');
</script>

Static / no-bundler checklist

Everything a plain HTML/JS app needs, in one place. Miss any of these and the failure usually arrives late — after a proof, or after an upload you have already paid for.

| # | Step | Payload | |---|------|---------| | 1 | Copy node_modules/dkey-lib/circuits/ to your web root | ~13 MB | | 2 | Call dkey.configureCircuits('/circuits') | — | | 3 | Vendor snarkjs.min.js and point at it with dkey.configureSnarkJS('/snarkjs.min.js') | ~0.7 MB | | 4 | Load the IIFE via <script> before your module code | ~1.1 MB | | 5 | Build a wagmi Config with a connector, and connect() before any write | — |

Step 5 is the one that bites. Reads resolve through the config's transport, but every write goes through wagmi's getConnectorClient, which throws:

BLOCKCHAIN_INTERACTION_FAILED: Connector not connected.

unless the config carries a connector and connect() has been called on it. Authorising the wallet with eth_requestAccounts is not enough — wagmi tracks its own connection state. A config that lists listings perfectly will still fail on createListing.

You do not need your own copy of @wagmi/core: the builders are re-exported from the bundle.

<script src="node_modules/dkey-lib/dist/dkey-lib.browser.js"></script>
<script type="module">
  const { dkey, createConfig, connect, injected, custom, http } = window.dkeyLib;

  dkey.configureCircuits('/circuits');
  dkey.configureSnarkJS('/snarkjs.min.js');

  const config = createConfig({
    chains: [{ id: 8453, name: 'Base', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
               rpcUrls: { default: { http: ['https://mainnet.base.org'] } } }],
    connectors: [injected()],
    transports: { 8453: window.ethereum ? custom(window.ethereum) : http() },
  });

  // REQUIRED before any write. Reads work without it; createListing/makeBid do not.
  await connect(config, { connector: injected() });
</script>

To build the browser bundle locally (e.g. after cloning the repo), run:

npm run build:browser

Quick Start

import dkey, { DkeyUserProfile, ListingMetadata } from 'dkey-lib';
import { createConfig } from '@wagmi/core';

// IMPORTANT: Copy the circuits folder from 'node_modules/dkey-lib/circuits'
// to your public/static directory, then configure the paths:
dkey.configureCircuits('/circuits'); // or './circuits' depending on your setup

// Initialize wagmi config
const config = createConfig({ /* your config */ });

// Create a user profile
const profile = new DkeyUserProfile(
  { fid: 123, fname: 'user' },
  {},
  {},
  {},
  {},
  config
);

// Create a listing. The options form is preferred -- the positional overload still works, but
// it takes nine arguments including two adjacent strings, and transposing them fails silently.
const contentRef = '9f2c5e4a6b8d0f1234567890abcdef1234567890abcdef1234567890abcdef12';
const metadata = new ListingMetadata({
  seller: { fid: 123 },
  fileName: 'example.pdf',              // must include the extension
  fileDescription: 'My file description',
  fileSizeInBytes: 1024,
  suggestedPriceInEth: 0.1,
  coverPhotoRef: '',
  coverPhotoLink: 'https://example.com/cover.jpg',
  chainIds: [8453],                     // Base
  // Current block height at creation time. It bounds how far back consumers look when
  // reconstructing this listing's history: too low only wastes work, too high can miss it.
  listingCreatedAfterBlock: Number(await dkey.getCurrentBlock(config, 8453)),
});

const result = await profile.createListing(
  contentRef,
  metadata,
  fileSecretKey,
  10, // howManyDKeysForSale
  5,  // royaltyPercentage
  address
);

Core Concepts

DkeyUserProfile

The main class for managing user interactions with the DKey protocol. Handles:

  • Creating and managing listings
  • Placing and managing bids
  • Acquiring and managing DKeys
  • Profile serialization/encryption

Listing

Represents a file listing on the blockchain. Contains:

  • content reference of the encrypted file
  • File metadata
  • Encryption keys
  • Sales information

Bid

Represents a user's bid on a listing. Contains:

  • Bid amount
  • Public key for decryption
  • Bid status

DKey

Represents an acquired decryption key. Contains:

  • Encrypted file secret key
  • Decryption methods
  • Ownership information

API Reference

Main Exports

// Default export - utility functions
import dkey from 'dkey-lib';

// Named exports - classes and types
import {
  DkeyUserProfile,
  Listing,
  ListingMetadata,
  Bid,
  DKey,
  BidLite,
  RESULTS
} from 'dkey-lib';

Utility Functions

dkey.createKeyAndEncryptFile(data: ArrayBuffer)

Encrypts a file and generates encryption keys.

const { encryptedData, secretKeyX, secretKeyY } = 
  await dkey.createKeyAndEncryptFile(fileBuffer);

dkey.formatContentRef(reference: string)

Formats a content reference into the representations the protocol needs. Accepts either an IPFS CID or a Swarm reference — the library is agnostic about which storage layer you use.

// Swarm reference (bare, 0x-prefixed, or a bzz:// URL with an optional path)
dkey.formatContentRef('9f2c5e4a6b8d0f1234567890abcdef1234567890abcdef1234567890abcdef12');
// { kind: 'swarm', normalizedRef: '9f2c…ef12', url: 'bzz://9f2c…ef12', … }

// IPFS CID (v0 or v1)
dkey.formatContentRef('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi');
// { kind: 'ipfs', normalizedRef: 'bafy…bzdi', url: 'ipfs://bafy…bzdi', … }

Both return { kind, normalizedRef, url, contentRefBytes, contentRefBytesString, hashedRef0xString, hashedRefString }.

contentRefBytesString is what goes on chain. Those bytes are self-describing — a Swarm reference is 32 bytes, while a CID keeps its version and codec (34 bytes for v0, 36 for v1) — so a reference survives the round trip to the chain and back with no loss.

dkey.parseContentRefBytes(bytes)

The inverse: recovers the canonical reference from the bytes the contract stores. Takes raw bytes or a 0x hex string, and needs no network access.

dkey.parseContentRefBytes('0x01701220c3c4…391a');
// { kind: 'ipfs', ref: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi' }

dkey.fetchListings(chainId, config, startingIndex?, numberOfListingsToFetch?)

Lists the content references registered on a chain, newest first, already decoded to canonical CID / Swarm strings — so you can fetch each one directly instead of probing both storage layers to find out where it lives.

const { listings, nextIndex, totalListings } = await dkey.fetchListings(8453, config, undefined, 10);
// listings: [{ ref: 'bafy…', kind: 'ipfs' }, { ref: '9f2c…', kind: 'swarm' }, …]

One call returns the page, the cursor and the total, so no separate count query is needed. Omit startingIndex to begin at the newest, and omit the page size to take everything from there down. To page, pass the previous nextIndex back in and stop when it comes back 0 — that is the terminator, not a valid starting point:

let cursor: number | undefined;
do {
  const page = await dkey.fetchListings(8453, config, cursor, 10);
  cursor = page.nextIndex;
} while (cursor > 0);

The listing index is append-only, so unlike open bids the indices are stable and paging across several blocks stays consistent.

dkey.fetchListingDetails(contentRef, metadata, config)

Fetches listing details from the blockchain.

const details = await dkey.fetchListingDetails(contentRef, metadata, config);

dkey.configureCircuits(basePath?)

Configures circuit file paths for your environment. Call this once after importing the library.

import dkey from 'dkey-lib';

// Configure circuits to match where you serve them
dkey.configureCircuits('/public/circuits');
// or
dkey.configureCircuits('./circuits');

dkey.configureSnarkJS(path)

Points the snarkjs loader at wherever your app serves the script. Defaults to the relative './snarkjs.min.js', so an app served from a subpath resolves it correctly.

dkey.configureSnarkJS('/vendor/snarkjs.min.js');

dkey.loadSnarkJS()

Loads snarkjs and resolves with it. You rarely need to call this — anything that generates or verifies a proof loads it on demand, memoised. It is exposed for warming the load early (it is ~0.7 MB) so the first createListing is not waiting on a download.

await dkey.loadSnarkJS();   // optional; pre-warms the script

Rejects if the script 404s or fails to define the global, naming the path it tried.

dkey.getColorFromContentRef(contentRef)

A deterministic colour for a content reference — the same reference always yields the same one, which makes it useful as a per-listing visual identity.

dkey.getColorFromContentRef('bafybeigdyrzt…');   // 'hsl(222, 70%, 50%)'

Returns an hsl(...) string. The old name getRGBColorFromContentRef still works but is deprecated — it never returned RGB.

DkeyUserProfile Methods

createListing(...)

Creates a new file listing on the blockchain.

makeBid(...)

Places a bid on a listing.

fillBid(...)

Fills a bid (seller only).

sellDkey(...)

Sells an acquired DKey to another user.

fetchDkey(bid)

The supported way to collect a DKey once your bid has been filled. Reads the DKey straight from the contract, adds it to myDKeys and removes the bid.

const result = await profile.fetchDkey(bid);
// result.success === false with result.result === 'DKEY_NOT_FOUND' until the seller fills it

Not-yet-filled is reported as a normal unsuccessful result, so polling this is fine.

checkIfDKeysReceived(chainId) / dkeyReceived(...) — legacy

checkIfDKeysReceived still works: it batch-reads which of your open bids are filled and flags them. But the flow this README used to describe — check, then pull dKey[4] out of event data, then call dkeyReceivedcannot work against DKeyStoreL2, which emits no events at all. Use fetchDkey(bid) instead; it does the read and the bookkeeping in one step.

checkIfDKeysCanBeSold(chainId)

Checks if DKeys are eligible for resale.

serialize() / deserialize()

Serialize/deserialize profile data.

toEncryptedProfileData(password) / fromEncryptedProfileData(...)

Encrypt/decrypt profile data for storage.

Supported Chains

  • Base (Chain ID: 8453)
  • Gnosis (Chain ID: 100)

This list is not hand-maintained — contracts/index.ts is generated from the deployment records in chain/, and a network only appears there once its deployed contract matches the current contract source. Arbitrum is absent because its deployment predates the security audit; it will return once redeployed.

Circuit Files

The library requires circuit files (.wasm, .zkey) to be accessible. By default, they're expected at:

./circuits/encryptAndHash_js/

When using this library, ensure the circuits/ folder is:

  • Copied to your public/static directory, or
  • Configured in your bundler to copy these assets

Then configure the paths to match your setup:

import dkey from 'dkey-lib';

// Configure circuit paths (call once after import)
dkey.configureCircuits('/public/circuits'); // or wherever you serve them

Development

# Install dependencies
npm install

# Build the library
npm run build

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

TypeScript

Full TypeScript support is included. The library exports type definitions in dist/index.d.ts.

License

MIT

Contributing

Contributions are welcome - shoot Noad an email at [email protected]!

Links