Contents

API reference

Every public export, by entry point: the main package plus the ports, adapters, engines, netting, and testing subpaths.

A complete list of everything the library exports, grouped by the import path you reach it through.

Source package.jsonsrc/index.ts

The library ships a curated, faceted exports map: the main package re-exports everything, and each subpath is a focused entry point. Install it, then import from whichever one you need.

npm install @pwngh/economy-lab
import { createEconomy, topUp, toAmount } from '@pwngh/economy-lab';
import type { Store } from '@pwngh/economy-lab/ports';

Entry points

ImportWhat it holds
@pwngh/economy-labEverything: construction, operations, money, the ledger, the worker, and every type.
@pwngh/economy-lab/portsThe port interfaces you implement to plug in your own infrastructure.
@pwngh/economy-lab/adaptersThe bundled in-memory and HTTP adapters, plus the runtime services.
@pwngh/economy-lab/adapters/redisThe Redis-backed Cache (carries the ioredis driver).
@pwngh/economy-lab/adapters/sqsThe SQS-backed Dispatcher (carries the AWS SDK).
@pwngh/economy-lab/engines/postgresThe Postgres Store (carries pg).
@pwngh/economy-lab/engines/mysqlThe MySQL Store and schema helpers (carries mysql2).
@pwngh/economy-lab/nettingThe in-instance netting session.
@pwngh/economy-lab/store-kitThe primitives a custom Store implementation computes with.
@pwngh/economy-lab/testingThe conformance harness for testing your own adapters.

Every section below links to the source it comes from.

@pwngh/economy-lab

The main entry point. It re-exports the whole surface, so you can import any symbol here — construction, operations, money, the ledger, errors, the worker, and every type. The focused subpaths further down are curated subsets of this one.

Construction

Stand up an Economy in one call, or assemble one from a Capabilities bundle you built yourself.

src/index.ts
ExportWhat it is
createEconomyThe one call to stand up an Economy; batteries-included in-memory with env-driven config and overridable ports.
EconomyOptionsEverything createEconomy accepts, all optional; wins over env-derived config when passed explicitly.
economyFromCapabilitiesThe low-level assembler: an Economy from a fully-built Capabilities bundle; escape hatch for sharing a store.
EconomyThe request-processing and read interface: submit operations, query state, prove integrity, and close the store.

Composition and environment

Wire an economy or worker from environment variables, or resolve the store, ports, and adapter selection yourself.

src/index.ts
ExportWhat it is
composeWires an Economy whose store, cache, and dispatcher come from env; thin over capabilitiesFromEnv.
composeWorkerWires a background Worker for deferred, time-driven work over the same env-selected store and dispatcher.
ComposedWorkerWhat composeWorker returns: the worker plus the handles its host must manage—the store to close and dispatcher.
capabilitiesFromEnvAssembles the full Capabilities bundle from env: store, cache, dispatcher, external ports, and runtime services.
workerCtxFromDerives a worker context from a capability bundle: runtime services minus request-path-only pieces.
externalsFromEnvResolves the four external ports from env; dev defaults, production requires real values and fails fast.
ExternalsThe four external services: signer (signing key), processor (payout provider), rates (CREDIT-to-USD), pricing (fee split).
ExternalPortsExternal services with no built-in stand-in: pricing, processor, signer, and rates.
RuntimeDefaultsRuntime services capabilitiesFromEnv fills in; pass any to override, e.g. a fixed clock for reproducible tests.
describeSelectionReads the adapter selection from env: DATABASE_URL picks store, REDIS_URL adds cache, SQS_QUEUE_URL or DISPATCHER_URL picks dispatcher.
SelectionWhich concrete adapter each env knob picks, before any driver loads; one reading of the selection.
checkEnvValidates env without constructing: returns every deployment startup problem or empty array when complete.
EnvMapA read-only view of the environment variables the library reads.

Configuration

Load the tunable Config and fill in its defaults.

src/config.ts
ExportWhat it is
loadConfigBuild Config from env vars, defaulting any value that is unset or invalid.
defaultConfigThe default Config without an environment: the exact values loadConfig derives from an empty env, with any knobs in overrides applied on top.
ConfigAll tunable settings in one object.

Operation constructors

One typed builder per operation kind: each sets kind and returns a ready Operation to submit.

src/operation.ts
ExportWhat it is
topUpAdd funds to a user’s spendable wallet.
spendDebit a buyer’s wallet and grant them an SKU or item.
refundReverse a spend operation, returning money to the buyer.
clawbackRemove funds from a user’s wallet without a linked order.
requestPayoutMove earned credits from a seller’s wallet to the payout reserve.
subscribeCreate a recurring subscription charging a buyer each period.
cancelSubscriptionEnd an active subscription.
grantEntitlementGive a user an item, feature, or entitlement with optional attributes.
revokeEntitlementRemove an entitlement from a user.
grantPromoGive a user expiring promotional credits.
adjustManual correction an operator posts by hand to balance the books.
reverseManual undo an operator runs by hand to cancel a prior transaction.
reversePayoutUndo a not-yet-paid payout and return reserved credits to seller.
settlePayoutMove settled payout funds from reserve to revenue.

Operations and actors

The Operation union, the Principal that authorizes it, and the factories that build each actor kind.

src/actor.ts
ExportWhat it is
OperationUnion of all request types a caller can submit to the economy.
PrincipalWho is making a request, and what they are allowed to do.
RecipientOne party who gets a cut of a sale; the price splits across all recipients.
EntitlementAttrsOptional details carried on an entitlement grant.
userActorAn end user; may act only on their own accounts.
systemActorA trusted internal service acting on the platform’s behalf.
operatorActorA human operator running a manual, fully-audited action.

Money

The Amount value type and the exact-integer arithmetic, conversion, and wire encoding around it.

src/money.ts
ExportWhat it is
AmountA money value: currency plus amount in minor units (cents for dollars), branded to enforce construction via toAmount or decodeAmount.
CurrencyThe currencies the system handles: in-app CREDIT and real-world USD.
toAmountBuilds an Amount from currency and minor-unit count, throwing AMOUNT_OVERFLOW if outside 64-bit range.
decodeAmountParses a decimal string (e.g. ‘12.34’) into an Amount, throwing INVALID_AMOUNT for bad format or out-of-range values.
encodeAmountEncodes an amount as text (e.g. ‘CREDIT:12.34’) with fixed two decimals for JSON, events, and tamper-evident hashing.
decodeAmountWireParses a wire amount string (e.g. ‘CREDIT:12.34’) back into an Amount, the inverse of encodeAmount.
isAmountType guard to check if a value is a branded Amount.
addAdds two amounts of the same currency, throwing CURRENCY_MISMATCH or AMOUNT_OVERFLOW.
negReturns the negation of an amount, checking it stays in 64-bit range.
compareCompares two amounts of the same currency, throwing CURRENCY_MISMATCH.
zeroCreates a zero amount for the given currency.
isZeroChecks if an amount is zero.
isNegativeChecks if an amount is negative.
convertFloorConverts an amount to another currency at a rate, rounding down for safe outward payments.
convertCeilConverts an amount to another currency at a rate, rounding up to under-cover risk like USD trust.
SCALEMinor units per whole unit (100 cents = $1), shared for consistent rounding.

Accounts and ledger

Reference an account, name the platform system accounts, and post balanced ledger legs.

src/accounts.ts
ExportWhat it is
spendableA user’s spendable account: money they topped up and can spend, backed by real USD held in trust.
earnedA user’s earned account: revenue owed to them as a seller, which the platform must pay out.
promoA user’s promo account: a marketing grant that expires.
currencyReturns the denomination of an account (CREDIT except for USD accounts).
SYSTEMThe platform’s own (‘house’) accounts; every id starts with ‘platform:’ and classifies as debit-normal (up on debit) or credit-normal (up on credit).
ownerOfExtracts the user id from a wallet account (part before the ‘:kind’ suffix), returning empty string for malformed ids.
isWalletAccountChecks if a reference is a user wallet account rather than a platform house account.
AccountRefA branded account identifier string, enforcing well-formed ids from constructor functions and SYSTEM accounts.
creditBuilds a credit leg for one account; raises credit-normal accounts and lowers debit-normal ones.
debitBuilds a debit leg for one account; lowers credit-normal accounts and raises debit-normal ones.
LegA debit or credit entry for one account in a posting, with debit-positive amount and currency matching the account.

Outcomes and errors

What a submit resolves to, and the typed error surface a thrown fault carries.

src/errors.ts
ExportWhat it is
OutcomeThe result of submitting an operation: committed, duplicate, or rejected.
RejectionDetailStructured context on a rejection, with fields depending on the reason (account, required, available, minimum, etc.).
TransactionA committed posting: the record of money that actually moved.
EconomyErrorThe thrown-error type for every fault, carrying one stable error code and retry decision.
ERROR_CODESStable, namespaced error codes for thrown faults (e.g., LEDGER.OVERDRAFT).
ErrorCodeThe union of every ERROR_CODES value for autocompletion and exhaustiveness checking.
RejectionCodeReasons a well-formed request is declined on a healthy system (expected ‘no’ answers).
normalizeErrorTurns anything caught in a catch into an EconomyError, wrapping raw exceptions as retryable STORE.FAILURE.
statusForErrorMaps an EconomyError to its HTTP status: 401 for auth, 400 for caller-fixable requests, 503 for retryable, 500 otherwise.

HTTP server and webhooks

Run the economy as a Fetch HTTP service and apply verified provider callbacks.

src/server.ts
ExportWhat it is
createServerAn HTTP entry point for an Economy: takes a Fetch Request, returns a Response.
handleWebhookMaps a verified provider callback to its operation and persists it to the inbox.
PurchaseEventA verified inbound purchase event from a billing provider.

Background worker

Drive the deferred, time-based work: the per-cycle sweeps, the outbox relay, the inbox, and the full prover.

src/worker/index.ts
ExportWhat it is
createWorkerBuild the worker from the store and context; always has runOnce, with scheduler also gets start(intervalMs).
WorkerHandle the host program uses to drive background jobs: runOnce runs every job once, start runs them on a timer.
WorkerCtxCapabilities for the background worker (clock, ids, digest, signer, processor, rates, logger, meter, config).
drainInboxApplies a batch of pending inbox events (verified provider callbacks) to the ledger.
relayOutboxDelivers a batch of pending outbox events, each written in the posting transaction.
proveEconomyThe thorough read-only prover: recomputes the whole hash chain to catch any altered entry.
SweepNameNames of the background jobs run each cycle: payouts, subscriptions, treasury, feeSweep, floatCoverage, etc.
SweepInputArguments for every background job in one object; limit caps each due-item pass, options may carry AbortSignal.
SweepResultOne job’s outcome: its summary, or its caught error as data with code and retry flag.
SweepBatchOne entry per job, keyed by name; a failing job never hides the others.
SweepRunrunOnce’s result: the batch plus the txn id of every posting the run minted.

In-memory adapters

Zero-infrastructure Store, Cache, and Processor implementations for tests and local runs.

src/adapters/memory.ts
ExportWhat it is
memoryStoreBuild an in-memory Store with working transaction rollback for tests and development.
memoryCacheBuilds an in-process Cache backed by a Map; reference implementation and single-process cache when no Redis.
memoryProcessorBuild an in-memory Processor for demos and tests that accepts every payout with deterministic providerRef.

Rates, pricing, and entitlements

Configure the CREDIT-to-USD rates and the fee split, and cache entitlement lookups.

src/adapters/rates.ts
ExportWhat it is
configuredRatesBuild the production CREDIT-to-USD rate source from a deployment’s configured rates.
flatFeeBuilt-in constructor for the required external port: the fee split policy.
FeePolicySplits a sale’s price across recipients and the platform into debit/credit legs with no rounding loss.
cachedEntitlementsWrap a store so entitlements.owns is served from a bitset when warm, for fast ownership checks.
BitsetOptionsTuning knobs for the entitlement bitset cache (TTL, resident user cap).

Runtime services

The concrete clock, ids, digest, signer, logger, and meter a production host wires in.

src/runtime.ts
ExportWhat it is
jsonlLoggerStructured logger for production hosts, writing one JSON object per line.
noopLoggerA Logger that discards every line: the silent default for a host that wants no log output.
noopMeterA Meter that discards every count and observation: the default when a host collects no metrics.
systemDigestProduction hasher returning the shared SHA-256 Digest.
systemSignerProduction signer using Ed25519 so an auditor can confirm a checkpoint wasn’t rewritten.
signingPublicKeyHexHex-encoded raw 32-byte Ed25519 public key derived from signingKey for external verification.

Read model

The shapes read returns: statements, postings, sagas, rates, checkpoints, and the solvency proof.

src/contract.ts
ExportWhat it is
StatementOne page of an account’s entries, walked via a cursor.
RangeA statement query’s half-open time range, in epoch milliseconds.
PostingA balanced double-entry posting: legs sum to zero in each currency.
SagaThe stored state of one in-flight payout, tracking reserve, rate, state, attempts, and settlement.
CheckpointA signed snapshot of the whole ledger: every account’s head hash reduced to one Merkle root and signed.
StoredLinkOne posting as lineage returns it, carrying the two hashes that tie it into the account’s tamper-evident chain.
RateAn exchange rate as exact integers: the multiplier is rate / 10^scale.
EconomyEventThe fixed shape of every event the system emits, with type, version, subject, and audience.
EconomyStatusThe economy’s pause state at a moment in time, derived from maintenance window and clock.
ProveReportThe integrity check result: one flag per property the ledger must hold.

Focused entry points

Each subpath re-exports a slice of the surface. The ports, adapters, and netting symbols below are also available from the main package; the driver-carrying adapters and the engines are not — they load a database or cloud driver, so they live behind their own subpath and are imported only where that driver is installed.

@pwngh/economy-lab/ports

The port interfaces — the contracts you implement to plug your own infrastructure into the economy. Types only; import them to type an adapter you are writing.

src/ports.ts
ExportWhat it is
StoreThe full set of stores the system reads and writes.
SignerSigns bytes and checks signatures, used to vouch for ledger checkpoints.
ProcessorExternal payment provider: all money leaving the platform goes through this.
RatesSupplies fixed CREDIT-to-USD rates from an audited source, never from config or caller input.
ClockProvides milliseconds since the Unix epoch.
IdsMints prefixed unique identifiers, one namespace per entity kind.
DigestThe SHA-256 hash of the input.
DispatcherHands an outgoing event off for delivery (e.g. SQS or HTTP); the core doesn’t know which.
LoggerLogs events at specified levels with structured fields.
MeterRecords metrics via count and observe methods.
CacheOptional read-through cache for hot reads such as balances; best-effort, so any error degrades to a direct ledger read.
SchedulerRuns a task every N milliseconds; the returned function stops the loop.
PayeeDirectoryVerifies payee status; checks if a user is cleared, pending, blocked, or has no verification.
CapabilitiesEvery external capability economyFromCapabilities(...) needs, gathered into one object.
OptionsPer-transaction options for the store, such as an AbortSignal.

@pwngh/economy-lab/adapters

The bundled adapter factories: in-memory and HTTP implementations of the ports, plus the runtime services (clock, ids, digest, signer). The driver-backed Redis and SQS adapters live in their own subpaths below.

src/adapters/index.ts
ExportWhat it is
memoryStoreBuild an in-memory Store with working transaction rollback for tests and development.
memoryCacheBuilds an in-process Cache backed by a Map; reference implementation and single-process cache when no Redis.
httpDispatcherBuild the Dispatcher that POSTs one economy event to a remote endpoint over HTTP with at-least-once delivery.
memoryProcessorBuild an in-memory Processor for demos and tests that accepts every payout with deterministic providerRef.
httpProcessorBuild a Processor that pays sellers via an external provider over HTTP.
configuredRatesBuild the production CREDIT-to-USD rate source from a deployment’s configured rates.
flatFeeBuilt-in constructor for the required external port: the fee split policy.
cachedEntitlementsWrap a store so entitlements.owns is served from a bitset when warm, for fast ownership checks.
systemClockProduction clock reading wall-clock time.
fixedClockFake clock for tests, frozen at start (epoch ms); only advance(ms) moves it forward.
randomIdsProduction id generator using random UUIDs with a prefix (e.g. txn_3f2a…).
sequentialIdsPredictable id generator for tests that counts up from seed for repeatable test outcomes.
systemDigestProduction hasher returning the shared SHA-256 Digest.
systemSignerProduction signer using Ed25519 so an auditor can confirm a checkpoint wasn’t rewritten.
signingPublicKeyHexHex-encoded raw 32-byte Ed25519 public key derived from signingKey for external verification.
systemCapabilitiesBundles the four capabilities (clock, id generator, hasher, signer) for a production host.
jsonlLoggerStructured logger for production hosts, writing one JSON object per line.
noopLoggerA Logger that discards every line: the silent default for a host that wants no log output.
noopMeterA Meter that discards every count and observation: the default when a host collects no metrics.

@pwngh/economy-lab/adapters/redis

The Redis-backed Cache. Carries the ioredis driver, so it is imported only when Redis is configured.

src/adapters/redis.ts
ExportWhat it is
redisCacheFromAdapt an already-connected ioredis client into the Cache the core expects.

@pwngh/economy-lab/adapters/sqs

The SQS-backed Dispatcher for the outbox relay. Carries the AWS SDK, so it is imported only when SQS is configured.

src/adapters/sqs.ts
ExportWhat it is
sqsDispatcherBuild the dispatcher that publishes events to SQS as JSON messages with automatic deduplication.
SqsDispatcherConfigConfiguration for the SQS dispatcher including queue URL and client.
SqsClientStructural shape of the SQS client method the adapter calls.
SqsCommandStructural shape of one SQS client method this adapter calls.

@pwngh/economy-lab/engines/postgres

The Postgres Store. Carries the pg driver.

src/engines/postgres.ts
ExportWhat it is
postgresStoreBuild a Store backed by Postgres using real database transactions with proper isolation and chain-based ledger verification.
PostgresStoreOptionsConfiguration for postgresStore including URL, schema isolation, digest, clock, velocity window, pool sizing, and connection timeouts.

@pwngh/economy-lab/engines/mysql

The MySQL Store and its schema helpers. Carries the mysql2 driver.

src/engines/mysql.ts
ExportWhat it is
mysqlStoreBuild a full MySQL-backed store on a mysql2 connection pool, with transactional consistency and named-lock-based synchronization.
MysqlPoolThe mysql2/promise pool interface, exported for type compatibility with stores built on MySQL.
createMysqlPoolCreate a mysql2 connection pool from a connection URL, with configurable connection limit and proper bigint/collation handling.
readSchemaVersionRead the database’s stamped schema version from schema_meta, or null when absent (un-migrated or pre-versioning database).
applyMysqlSchemaCreate all tables and stored routines from db/mysql-schema.sql; drops and recreates tables so running this resets to a clean schema.

@pwngh/economy-lab/netting

The in-instance netting session: reserve, move, and settle many balances in memory, then post one net transaction. Used for high-frequency in-world economies.

src/netting.ts
ExportWhat it is
instanceSessionOpen a netting session that accepts movements (idempotent per key, guarded by reservation registry) and settles the net in clearing chunks.
recoverSessionRebuild a session from its journal (crash-recovery path); outcomes and running net re-derive from journal rows for consistency.
createReservationsCreate a cross-session reservation registry that tracks pending per-user-account totals to prevent overdraft races across sessions.
ReservationsThe cross-session registry tracking pending per-account totals to prevent overdraft races across the process.
MovementRequestOne movement offered to the session: an idempotency key and a balanced set of CREDIT legs.
MovementOutcomeThe result of offering one movement: either accepted with sequence number or rejected with a reason code.
SettleReportThe outcome of settling a session: mode (netted or replayed), postings committed, rejected movements, journal head, and count of netted movements.
SessionOptionsOptional session configuration: max movements per journal batch, max accounts per settlement chunk, and shared reservation registry.
InstanceSessionA durable journal session that accepts movements, batches them, and settles the net posting in chunks with idempotency and chain verification.
SessionDepsThe store, digest, and clock dependencies a session needs to manage movements and settlement.

@pwngh/economy-lab/store-kit

The store implementer’s toolkit. The conformance suite is the public invitation to bring your own Store; these are the primitives a conforming implementation needs to compute the same chain hashes, balance deltas, orderings, and wire encodings the built-in engines compute.

src/store-kit.ts
ExportWhat it is
chainHashThe per-account chain hash over a posting: previous head, txn id, account, legs, and meta, in the canonical byte layout.
balanceDeltaOne leg’s signed effect on its account’s balance, from the leg’s side and the account’s normal side.
GENESISThe 32-byte zero hash an account’s chain starts from.
GENESIS_HEXThe genesis hash as lowercase hex, for stores that keep heads as text.
baseOfStrips a platform shard suffix, so identity checks see the base account.
walletKindOfThe wallet kind encoded in a user account id, or null for platform accounts.
byCodeUnitThe canonical string ordering every engine sorts by, so results match across backends.
fromHexHex to bytes, for stores that keep hashes as text.
toHexBytes to lowercase hex, the inverse.
metaStringReads one string field out of posting meta, or null.
metaNumberReads one number field out of posting meta, or null.
encodeAmountsDeep-encodes every Amount in a value into wire strings, for storing meta or events.
decodeAmountsThe inverse: revives wire strings back into Amounts.
VELOCITY_CURRENCYThe currency the trust store’s velocity window counts in.
AccountKindThe wallet kinds walletKindOf can return.

@pwngh/economy-lab/testing

The conformance harness. Run the same suite against any Store, Cache, Dispatcher, or Processor implementation to prove it upholds the contract.

test/conformance/index.ts
ExportWhat it is
runStoreConformanceRun the adapter conformance suite for Store implementations to verify they meet the ledger invariants.
runCacheConformanceRun the adapter conformance suite for Cache implementations to verify they match the built-in contract.
runDispatcherConformanceRun the adapter conformance suite for Dispatcher implementations with harness support for custom test setups.
runProcessorConformanceRun the adapter conformance suite for Processor implementations with harness support for custom test setups.
DispatcherHarnessTest harness interface for running dispatcher conformance suites.
ProcessorHarnessTest harness interface for running processor conformance suites.

See also