commerce

package
v1.799.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2026 License: Apache-2.0, MIT Imports: 55 Imported by: 0

README

commerce

commerce

Checkout, billing, pricing, invoicing — the light commerce router for the Hanzo platform. NOT in PCI-DSS scope (PAN data lives in hanzoai/vault).

Status License

Quick start

docker run -p 8001:8001 ghcr.io/hanzoai/commerce:latest

What this is

commerce handles orders, products, subscriptions, invoices, and customer records for every Hanzo deployment. It is CDE-connected, not CDE-in-scope: card data is tokenized at hanzoai/vault and commerce only ever sees the token. The service is production multi-tenant (37+ X-Org-Id call sites), IAM-integrated, and already exposes func Mount(*zip.App, cloud.Deps) error — it is one of the three reference implementations of the HIP-0106 Mount contract.

Specs

Implements:

  • HIP-0037 AI Cloud Platform (billing surface)
  • HIP-0106 Unified Cloud Binary (commerce subsystem — already exposes Mount())

Architecture

   client  ->  gateway  ->  commerce (zip.App)
                              |
                     orders / products / subscriptions / invoices
                              |
                  +-----------+-----------+
                  |                       |
              hanzoai/vault          billing provider
              (CDE — tokenizes PAN)   (Stripe etc., webhook in)
                              |
                  per-tenant data via base (HIP-0302)

Hanzo Build status

Hanzo is a scalable DX platform designed to power next-gen internet companies.

Development

Getting started

You can use make to setup your development enviroment. Running:

$ make deps

...will download the Go App Engine SDK and unzip it into sdk/. When hacking on things you'll want to ensure $GOROOT and $GOPATH point to their respective directories inside sdk/.

You can source the provided .env file to set these variables, or use autoenv to set them automatically whenever you cd into the project directory.

Installing Go tools

You can install the common Go command line tools and configure gocode to work with App Engine by running:

$ make tools
Development server

You can then use make serve to run the local development server and make test to run tests.

You can create a local config.json file containing configuration variables to customize settings locally (for instance to disable the auto fixture loading).

This Makefile is used to build, test, and deploy a Go application running on Google App Engine, with dependencies managed through a combination of Go tools, Python SDK scripts, and Node.js for asset compilation. Here's a detailed breakdown of how it works and the general flow of operations:

Key Concepts
  • Google App Engine: This is the platform used for deploying and managing the application.
  • Go SDK and App Engine SDK: Go is the language used, and the App Engine SDK is required for running the app locally and deploying it to the cloud.
  • Node.js Assets: JavaScript and CSS assets are handled using tools like requisite, uglifyjs, and stylus.
  • Staging and Production Environments: Different configurations are used for deploying to development, staging, and production environments.
How the Makefile Works
1. System Variables
  • os: Detects the operating system (linux or darwin) and converts it to lowercase for uniformity.
  • pwd: Stores the current directory path.
  • platform: Constructs the platform string based on the OS and architecture.
  • sdk: Defines the specific App Engine SDK version to be used.
  • sdk_path, goroot, gopath: Defines paths where the Go SDK and Go environment will be installed.
2. SDK Installation

The SDK is downloaded if it doesn’t exist. The following steps are performed:

  • .sdk target: Downloads the App Engine SDK as a zip file and unzips it into a .sdk folder.

    • It also performs extra setup (e.g., downloading mtime_file_watcher.py to monitor file changes).
  • .sdk/go: Creates a wrapper script to use the goapp command from the SDK.

  • .sdk/gpm: Downloads gpm, a Go dependency manager, to the .sdk directory.

3. Dependency Management
  • deps target: Ensures all Go and JS/CSS dependencies are installed.
    • deps-assets: Runs npm update to update JS/CSS dependencies.
    • deps-go: Installs Go dependencies using gpm from the Godeps file.
4. Environment Configuration
  • The gae_development, gae_staging, gae_production, and gae_sandbox variables hold different configurations (YAML files) for deploying the app to various environments.

  • project_env, project_id, gae_config: Select the appropriate environment based on Makefile options (production, sandbox, etc.).

5. Building the Project
  • build target: Builds the Go modules listed under modules using goapp from the App Engine SDK.

  • install target: Installs the Go application and all dependencies.

6. Asset Compilation
  • JavaScript: Files are compiled and minified using requisite, coffee, and uglifyjs.

    • compile-js: Compiles CoffeeScript files and aggregates JavaScript with requisite.
    • compile-js-min: Minifies the compiled JavaScript files.
  • CSS: Files are compiled and autoprefixed using stylus and autoprefixer.

    • compile-css: Compiles Stylus files into CSS.
    • compile-css-min: Minifies CSS and applies prefixes for cross-browser compatibility.
7. Testing and Linting
  • test target: Runs unit tests using ginkgo, with options for verbose and focused tests.

  • bench target: Runs benchmark tests.

  • test-watch: Watches the files and runs the tests on changes.

8. Running the Development Server
  • serve target: Starts the App Engine development server using the dev_appserver.py command from the SDK.
    • serve-clear-datastore: Clears the local datastore before starting the server.
    • serve-public: Starts the server with a public-facing IP (0.0.0.0).
9. Deployment
  • deploy target: Deploys the app to the selected environment (staging, production, etc.).

    • rollback target: Rolls back the deployment if needed.
  • deploy-app target: Updates the environment configuration and deploys each module using appcfg.py (App Engine deployment tool).

  • datastore-export, datastore-import: Commands for exporting and importing Google Cloud Datastore data.

Local Setup Steps
  1. Download Dependencies: Run make deps to install all Go, JS, and CSS dependencies.
  2. Build the Project: Use make build to build the Go application.
  3. Run Development Server: Use make serve to start the local App Engine server.
Staging and Production Setup
  1. Staging: Run make deploy to deploy the app to the staging environment.

    • Make sure the environment variables are set to the correct staging project ID (project_id).
  2. Production: Set the production=1 flag when calling make deploy to deploy to the production environment.

  3. Rolling Back: Use make rollback to revert to a previous version if needed.

Tools

Various Go tools are included in the tools target to assist with development (linting, formatting, etc.). These tools are installed using the goapp get and goapp install commands.

Documentation

Overview

client.go is the in-process inter-subsystem commerce client — the REAL implementation of cloud's types.CommerceClient, absorbed here from the retired in-process stub that used to fail closed on entitlement. It answers cloud's licensing/entitlements tier with DIRECT Go calls into the embedded commerce datastore (subscriptions) plus the @hanzo/plans vocabulary (plan → license features) — no HTTP hop, no network.

MONEY-SAFETY. CheckEntitlement NEVER fabricates a grant. It returns Active:true ONLY when a real active, unexpired subscription in the org's own datastore namespace holds a plan tier whose @hanzo/plans license-features actually name the product. Any machinery it cannot resolve (commerce not co-resident, org not resolvable, subscription query error, plans vocabulary unavailable) returns an ERROR — the entitlements gate treats an erroring client as "cannot verify ⇒ 503", the specified secure default, so an unverifiable product is never enabled. A clean "resolved, but no plan licenses this product" is a real Active:false answer (the gate turns it into a 402 upgrade prompt), never an error and never a grant.

Package commerce provides the main application framework for Hanzo Commerce.

Commerce is a multi-tenant e-commerce platform that runs as a standalone binary with embedded SQLite for per-user/org data and optional analytics via datastore.

Architecture:

┌─────────────────────────────────────────────────────────────┐
│                     Commerce App                            │
├─────────────────────────────────────────────────────────────┤
│  HTTP Server (Gin)  │  Hooks System  │  Background Tasks    │
├─────────────────────────────────────────────────────────────┤
│  User SQLite        │  Org SQLite    │  Analytics (CH)      │
│  + sqlite-vec       │  + sqlite-vec  │  (parallel queries)  │
└─────────────────────────────────────────────────────────────┘

Package commerce (pkg/commerce) is the embedded Commerce server. One backend, one HTTP handler. Mirrors pkg/tasks/embed.go shape:

cfg := commerce.EmbedConfig{DataDir: "/var/lib/commerce", HTTPAddr: ":8090"}
srv, err := commerce.Embed(ctx, cfg)
defer srv.Stop(ctx)

The legacy App in commerce.go is the bootstrap — server.go wires it into commerced/main.go cleanly. The /v1/commerce/* surface stays behind hanzoai/gateway and is gated by COMMERCED_REQUIRE_IDENTITY.

mount.go folds the embedded commerce app into the unified Hanzo Cloud binary (HIP-0106): cloud serves the /v1/commerce/* + /_/commerce/* checkout / tenant / billing surface ITSELF instead of proxying a remote commerce pod. It absorbs the former thin -svc mount wrapper — ONE package now owns the commerce library, its in-process cloud.CommerceClient (client.go), AND this cloud-subsystem registration, exactly as clients/kms owns the KMS library + its /v1/kms subsystem (the "drop the -svc wrapper" pattern, cf. #241 gatewaysvc → gateway). cloud never imports this package back: init() registers the mount + the client factory via cloud's inversion hooks (cloud.Register / cloud.RegisterCommerceClientFactory), so there is no cloud⇄commerce import cycle.

WRAP, DON'T REWRITE. commerce.Embed runs the ENTIRE gin runtime (DB, per-org SQLite, KMS, hooks, cron) in-process, binds NO listener, and returns an http.Handler; Mount attaches THAT handler verbatim at every prefix commerce owns, so commerce's behaviour is preserved byte-for-byte.

PCI SCOPE. Commerce is a LIGHT ROUTER, NOT in PCI-DSS scope: tokens + intent IDs only, NEVER a PAN. PAN-touching paths call the out-of-process Payments / Vault (ZAP-RPC); when those clients are absent the payment handlers fail closed while tenant config + admin stay served — mountFromDeps warns loudly at startup.

FAIL-SOFT. A broken Embed does NOT crash the binary: commerce degrades to a 503 on its own prefixes (mountFailClosed) while every co-resident subsystem stays up — the blast-radius isolation the consolidation exists for.

ACTIVATION is the enable-list gate: the operator adds "commerce" to --enable only when the cloud pod should host commerce; until then commerce is served by the standalone pod and cloud reaches it over the CLOUD_COMMERCE_HTTP_URL / CLOUD_COMMERCE_ZAP_ADDR seam (pickCommerceClient — the network path is preserved; this fold does NOT force the cutover).

Index

Constants

This section is empty.

Variables

View Source
var (
	Version   = "1.46.39"
	GitCommit = "dev"
	BuildTime = "unknown"
)

Version, GitCommit, and BuildTime are set via -ldflags at build time. Version's default is the source-of-record release; CI overrides it with the immutable image tag (-X github.com/hanzoai/cloud/clients/commerce.Version=<tag>) so the running binary's /healthz version always equals its deployed tag.

Functions

func BalanceCents added in v1.799.2

func BalanceCents(ctx context.Context, org, subject, currency string, test bool) (int64, error)

BalanceCents returns subject's available prepaid balance (USD cents) in org, read DIRECTLY from the co-resident embedded commerce ledger — no HTTP hop. It is the native twin of the /v1/billing/balance read (billing.zapGetBalance): resolve the org's own datastore namespace, tally the subject's iam-user transactions in the currency, and return Balance - Holds clamped at zero. It reuses the SAME currentEmbedded seam the in-process entitlement client resolves through.

This is the read the money cutover (admin/finance backfill) and the admin cockpit's credit panels use when commerce runs in the SAME binary: the admin commerce HTTP client dials an unroutable in-proc address and reads $0, which would silently migrate/report nothing. When commerce is NOT co-resident this returns an ERROR (never 0), so a caller can tell "not wired" from a real zero balance and fail loud rather than move money on a phantom figure. Subject is lowercased + trimmed; an empty currency defaults to usd.

func MountFromDeps

func MountFromDeps(app *zip.App, deps cloud.Deps) error

mountFromDeps adapts the registry's cloud.Deps to Mount's decomplected MountConfig — the ONE place the whole-Deps bag is narrowed to the values commerce uses. It also carries the PCI scope-guard warnings (Payments / Vault presence) that belong with Deps, keeping Mount itself off the wide dependency surface.

func PublishEmbedded

func PublishEmbedded(e *Embedded)

PublishEmbedded records the mounted Embedded as the in-process entitlement source. Mount calls it once; nil un-publishes (tests).

Types

type App

type App struct {

	// Root command
	RootCmd *cobra.Command

	// Database manager
	DB *db.Manager

	// Infrastructure manager
	Infra *infra.Manager

	// Hook system
	Hooks *hooks.Registry

	// Events client (sends to analytics-collector via HTTP)
	Events *events.Client

	// Publisher sends commerce events to NATS/JetStream
	Publisher *events.Publisher

	// KMS client for secret management
	KMS *kms.CachedClient

	// ZAP node for inter-service vector operations
	ZAP *infra.ZAPNode

	// HTTP router
	Router *gin.Engine

	// CheckoutResolver maps hostnames (pay.example.com, …) to Tenant
	// configs for the embedded checkout SPA. Mutable at runtime so the
	// admin can add/remove hostnames and toggle providers without a
	// restart. Legacy resolver — new code reads CommerceStore.Tenants.
	CheckoutResolver *checkout.StaticResolver

	// CommerceStore is the hanzo/base-backed persistence seam. When set it
	// provides the authoritative tenants + hostname-claims collections;
	// handlers that have migrated off the legacy resolver use this directly.
	// Initialized in Bootstrap from COMMERCE_DATA_DIR / COMMERCE_BASE_URL.
	CommerceStore *commercestore.Store
	// contains filtered or unexported fields
}

App is the main Commerce application

func New

func New() *App

New creates a new Commerce application with default configuration

func NewWithConfig

func NewWithConfig(config *Config) *App

NewWithConfig creates a new Commerce application with the given configuration

func (*App) Bootstrap

func (app *App) Bootstrap() error

Bootstrap initializes the application

func (*App) Config

func (app *App) Config() *Config

Config returns the current configuration

func (*App) DataPath

func (app *App) DataPath(subpath string) string

DataPath returns the full path within the data directory

func (*App) IsDev

func (app *App) IsDev() bool

IsDev returns true if running in development mode

func (*App) Serve

func (app *App) Serve() error

Serve starts the HTTP server

func (*App) Shutdown

func (app *App) Shutdown() error

Shutdown gracefully shuts down the application

func (*App) Start

func (app *App) Start() error

Start runs the application

type Client

type Client = types.CommerceClient

Client is the in-process inter-subsystem seam cloud's licensing/entitlements tier calls. It IS cloud's types.CommerceClient — one narrow interface (GetOrgConfig + the real CheckEntitlement), not a second copy — kept as an alias so a value satisfies both names with no adapter. Add methods here only when a consumer needs them; keep it narrow.

func InProcessClient

func InProcessClient(brand string) Client

InProcessClient returns the process-wide, lazily-resolved client cloud's pickCommerceClient wires as deps.Commerce. BuildDeps runs before MountAll, so it resolves the published Embedded per call rather than capturing one; brand answers OrgConfig even before Mount publishes.

type Config

type Config struct {
	// DataDir is the base directory for all data
	DataDir string

	// Dev enables development mode
	Dev bool

	// RequireIdentity makes the identity boundary (auth.Gin) reject any
	// request that arrives without X-Org-Id/X-User-Id. Sourced from
	// COMMERCED_REQUIRE_IDENTITY. It is OFF by default and MUST stay off
	// wherever the cloud-api -> commerce per-org billing path runs: that
	// path authenticates with a Bearer service token + X-Org-Id and
	// carries NO X-Org-Id, so a require-identity gate would 401 the money
	// path. The anti-spoofing boundary is EdgeAuth (always mounted), not
	// this gate.
	RequireIdentity bool

	// Secret for encryption and sessions
	Secret string

	// HTTP server address
	HTTPAddr string

	// HTTPS server address (optional)
	HTTPSAddr string

	// TLS certificate paths
	TLSCert string
	TLSKey  string

	// CORS allowed origins
	AllowedOrigins []string

	// Database configuration
	Database db.Config

	// Analytics collector endpoint (optional)
	AnalyticsEndpoint string

	// Analytics DSN (optional, for direct datastore queries)
	DatastoreDSN string

	// Infrastructure configuration
	Infra infra.Config

	// Query timeout
	QueryTimeout time.Duration

	// KMS configuration for secret management
	KMS kms.Config

	// IAM configuration for hanzo.id JWT validation
	IAM struct {
		Enabled           bool     `json:"enabled"`
		Issuer            string   `json:"issuer"`
		ClientID          string   `json:"clientId"`
		ClientSecret      string   `json:"clientSecret"`
		AcceptedAudiences []string `json:"acceptedAudiences"`
		AcceptedIssuers   []string `json:"acceptedIssuers"`
		JwksURI           string   `json:"jwksUri"`
	} `json:"iam"`
}

Config holds application configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration

type EmbedConfig

type EmbedConfig struct {
	DataDir         string       // "" → COMMERCE_DIR or ./commerce_data
	HTTPAddr        string       // "" → COMMERCE_HTTP or 127.0.0.1:8090
	Dev             bool         // dev mode — gin.DebugMode + reload-friendly logging
	RequireIdentity bool         // gateway trust: refuse requests without X-Org-Id/X-User-Id
	Logger          *slog.Logger // nil → slog.Default()
	AllowedOrigins  []string     // CORS — usually ["*"] behind gateway
}

EmbedConfig configures the in-process Commerce server. Empty values fall through to commerce.DefaultConfig (env-based) so commerced binds the same env contract the legacy commerce binary did.

type Embedded

type Embedded struct {
	// contains filtered or unexported fields
}

Embedded is the handle to a running in-process Commerce server. The underlying *App owns the heavy lifting (DB, infra, KMS, hooks, cron) — Embedded wraps it for clean Stop/HTTPHandler/HTTPAddr access from commerced.

func Embed

func Embed(ctx context.Context, cfg EmbedConfig) (*Embedded, error)

Embed bootstraps the Commerce app and returns a handle. Call Stop before the process exits.

func Mount

func Mount(app *zip.App, cfg MountConfig, log luxlog.Logger) (*Embedded, error)

Mount boots the in-process commerce app and attaches its http.Handler to app at every commerce prefix. It also publishes the handler for in-process S2S billing dispatch (commerceinproc) and the Embedded as the source for the in-process entitlement client (client.go). It returns the live *Embedded (nil on a fail-soft degrade). Called once when "commerce" is enabled.

func (*Embedded) App

func (e *Embedded) App() *App

App exposes the underlying App for tests and hook registration.

func (*Embedded) Client

func (e *Embedded) Client() Client

Client returns the in-process commerce.Client bound to THIS Embedded — it reads this embed's datastore directly. Used by tests and any caller holding the Embedded; the process-wide pick-time seam cloud wires is InProcessClient.

func (*Embedded) HTTPAddr

func (e *Embedded) HTTPAddr() string

HTTPAddr returns the configured listen address.

func (*Embedded) HTTPHandler

func (e *Embedded) HTTPHandler() http.Handler

HTTPHandler returns the gin router as a plain http.Handler. commerced wraps this with healthz + the embedded SPA at /_/commerce/.

func (*Embedded) Stop

func (e *Embedded) Stop(ctx context.Context) error

Stop shuts the server down. Idempotent.

type MountConfig

type MountConfig struct {
	Brand   string
	Env     string
	DataDir string
	Domain  string
}

MountConfig is the decomplected commerce-relevant slice of cloud.Deps — the VALUES Mount uses (brand/env/data-dir/domain), grouped, instead of the whole Deps bag. Accept a value, return the concrete *Embedded.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the per-request, org-scoped data layer. Each request lands on its own *db.DB shard keyed by the gateway-supplied X-Org-Id, so two orgs can never see each other's rows even if a handler bug forgets to scope its query.

func NewStore

func NewStore(mgr *db.Manager) *Store

NewStore wraps a db.Manager. The returned Store has no org binding — call WithOrg to land on a specific shard.

func (*Store) DB

func (s *Store) DB() (db.DB, error)

DB returns the per-org *db.DB shard. It opens the shard lazily; the underlying db.Manager memoizes them so two requests on the same org share the same SQLite handle (with its own connection pool).

func (*Store) FromContext

func (s *Store) FromContext(ctx context.Context) *Store

FromContext returns a Store bound to the org id attached by pkg/auth.Gin (or pkg/auth.RequireIdentity). Empty org → unscoped "system" shard, which is the legacy default for unauthenticated dev requests. A request that asks for tenant data without an org must have failed the gateway-trust gate already.

func (*Store) Org

func (s *Store) Org() string

Org returns the bound org id ("" before WithOrg).

func (*Store) WithOrg

func (s *Store) WithOrg(org string) *Store

WithOrg binds the store to a per-org SQLite shard. Empty org falls back to the "system" shard so unauthenticated probes still land somewhere predictable.

Directories

Path Synopsis
Package ai provides AI-powered product recommendations and embeddings via Hanzo Cloud-Backend (Rust inference API) and Hanzo Cloud (Go API).
Package ai provides AI-powered product recommendations and embeddings via Hanzo Cloud-Backend (Rust inference API) and Hanzo Cloud (Go API).
api
account
Package account — login deprecated.
Package account — login deprecated.
b2b
Package b2b wires the B2B commerce HTTP surface: companies, employees (with their spending headroom), quotes (accept/reject + message thread), and spend-approvals.
Package b2b wires the B2B commerce HTTP surface: companies, employees (with their spending headroom), quotes (accept/reject + message thread), and spend-approvals.
catalog
Package catalog is the HTTP surface for the platform product catalog — the CMS source-of-truth for a brand's OWN products (Models, Vector, KMS, …) that docs.<brand>, the console sidebar, and pricing derive from.
Package catalog is the HTTP surface for the platform product catalog — the CMS source-of-truth for a brand's OWN products (Models, Vector, KMS, …) that docs.<brand>, the console sidebar, and pricing derive from.
cdn
costs
Package costs is commerce's vendor-cost / COGS surface — the mirror of the revenue/usage billing package.
Package costs is commerce's vendor-cost / COGS surface — the mirror of the revenue/usage billing package.
dashv2
Package dashv2 — login deprecated.
Package dashv2 — login deprecated.
exchange
Package exchange wires the order-exchange HTTP surface: CRUD on exchanges plus confirm/cancel transitions.
Package exchange wires the order-exchange HTTP surface: CRUD on exchanges plus confirm/cancel transitions.
giftcard
Package giftcard is the HTTP surface for gift cards: base CRUD via rest plus money actions (redeem / balance / void).
Package giftcard is the HTTP surface for gift cards: base CRUD via rest plus money actions (redeem / balance / void).
producttaxonomy
Package producttaxonomy is the HTTP surface for the product-builder taxonomy: options (+values), categories (hierarchical), tags, types, and the return/refund reason lookups.
Package producttaxonomy is the HTTP surface for the product-builder taxonomy: options (+values), categories (hierarchical), tags, types, and the return/refund reason lookups.
tax
xd
Package auth provides authentication utilities including IAM OAuth2/OIDC integration.
Package auth provides authentication utilities including IAM OAuth2/OIDC integration.
Package billing embeds the Next.js-built billing admin SPA into the commerce binary.
Package billing embeds the Next.js-built billing admin SPA into the commerce binary.
allotment
Package allotment grants a plan's recurring monthly included-usage credit to a tenant's prepaid balance.
Package allotment grants a plan's recurring monthly included-usage credit to a tenant's prepaid balance.
bucket
Package bucket is the ONE place that classifies commerce ledger transactions into the three money buckets the console + GPU policy read, and derives the per-bucket balances from the REAL tagged ledger — never a fabricated split.
Package bucket is the ONE place that classifies commerce ledger transactions into the three money buckets the console + GPU policy read, and derives the per-bucket balances from the REAL tagged ledger — never a fabricated split.
credit
Package credit provides reusable starter credit logic.
Package credit provides reusable starter credit logic.
engine
Package engine provides core billing business logic: usage aggregation, payment collection, and subscription lifecycle management.
Package engine provides core billing business logic: usage aggregation, payment collection, and subscription lifecycle management.
grant
Package grant implements manual subscription grants — used for gifting Pro subscriptions, comp'ing beta users, and admin overrides.
Package grant implements manual subscription grants — used for gifting Pro subscriptions, comp'ing beta users, and admin overrides.
husdindex
Package husdindex is Step 3 of the chain-backed credit ledger: it makes the on-chain HUSD balance the source of truth and the commerce DB a cache.
Package husdindex is Step 3 of the chain-backed credit ledger: it makes the on-chain HUSD balance the source of truth and the commerce DB a cache.
husdledger
Package husdledger wires the chain-backed credit ledger (treasury mint service + husdindex projector, Steps 2-3) to commerce's production per-org SQLite stores, and exposes the ONE mint entrypoint (Service.MintCredit) the billing handlers call in place of a direct DB credit write (Step 4).
Package husdledger wires the chain-backed credit ledger (treasury mint service + husdindex projector, Steps 2-3) to commerce's production per-org SQLite stores, and exposes the ONE mint entrypoint (Service.MintCredit) the billing handlers call in place of a direct DB credit write (Step 4).
ledger
Package ledger implements a double-entry accounting ledger for the billing engine.
Package ledger implements a double-entry accounting ledger for the billing engine.
tier
Package tier defines the tiered credit system for Hanzo billing.
Package tier defines the tiered credit system for Hanzo billing.
trial
Package trial implements the new-signup on-ramp: a trialing subscription of the $20/mo entry plan funded with a single unified trial credit.
Package trial implements the new-signup on-ramp: a trialing subscription of the $20/mo entry plan funded with a single unified trial credit.
workflows
Package workflows provides Temporal workflow definitions for automated recurring billing, subscription lifecycle management, and dunning retry logic.
Package workflows provides Temporal workflow definitions for automated recurring billing, subscription lifecycle management, and dunning retry logic.
Package checkout: admin API scaffolding for /_/commerce/*.
Package checkout: admin API scaffolding for /_/commerce/*.
cmd
commerce command
commerce-encrypt-dbs command
Command commerce-encrypt-dbs converts commerce's PLAINTEXT per-tenant SQLite stores (users/<id>/data.db, orgs/<id>/data.db) to the ENVELOPED, SQLCipher- encrypted layout the daemon opens under COMMERCE_KMS_MASTER_KEY.
Command commerce-encrypt-dbs converts commerce's PLAINTEXT per-tenant SQLite stores (users/<id>/data.db, orgs/<id>/data.db) to the ENVELOPED, SQLCipher- encrypted layout the daemon opens under COMMERCE_KMS_MASTER_KEY.
commerced command
OTel telemetry bootstrap — installs the global tracer provider that ships this service's spans to the shared o11y backend (SigNoz) over OTLP.
OTel telemetry bootstrap — installs the global tracer provider that ships this service's spans to the shared o11y backend (SigNoz) over OTLP.
grant command
Package main implements commerce-grant — a CLI for manually granting subscriptions to users (e.g.
Package main implements commerce-grant — a CLI for manually granting subscriptions to users (e.g.
sbom-scan command
Command sbom-scan clones Hanzo GitHub repos, runs git blame analysis, and produces SBOMEntry + Contributor records for OSS revenue sharing payouts.
Command sbom-scan clones Hanzo GitHub repos, runs git blame analysis, and produces SBOMEntry + Contributor records for OSS revenue sharing payouts.
development command
production command
sandbox command
staging command
test command
cron
payout/contributor
Package contributor executes the OSS contributor revenue sharing payouts.
Package contributor executes the OSS contributor revenue sharing payouts.
key
Package db provides a multi-layer database abstraction supporting: - User-level SQLite with sqlite-vec for personal data and vector search - Organization-level SQLite for shared tenant data - Hanzo Datastore (DATASTORE_URL) for deep analytics and parallel queries
Package db provides a multi-layer database abstraction supporting: - User-level SQLite with sqlite-vec for personal data and vector search - Organization-level SQLite for shared tenant data - Hanzo Datastore (DATASTORE_URL) for deep analytics and parallel queries
Package delay provides a task queue abstraction for background job execution.
Package delay provides a task queue abstraction for background job execution.
demo
Package events provides a thin HTTP client for the analytics collector.
Package events provides a thin HTTP client for the analytics collector.
Package hooks provides event types for the hook system.
Package hooks provides event types for the hook system.
Package infra provides unified infrastructure clients for Commerce.
Package infra provides unified infrastructure clients for Commerce.
log
Package metering is the ONE way every Hanzo product meters usage to commerce — the single billing source of truth — so that every product (not only the LLM/cloud path) can be paid for.
Package metering is the ONE way every Hanzo product meters usage to commerce — the single billing source of truth — so that every product (not only the LLM/cloud path) can be paid for.
Package middleware provides HTTP middleware for the Commerce API.
Package middleware provides HTTP middleware for the Commerce API.
iammiddleware
Package iammiddleware is the gateway-trust shim for legacy call sites.
Package iammiddleware is the gateway-trust shim for legacy call sites.
svcorg
Package svcorg resolves — and memoizes — the organization a verified service token acts on behalf of (cloud-api → commerce per-org billing).
Package svcorg resolves — and memoizes — the organization a verified service token acts on behalf of (cloud-api → commerce per-org billing).
Package mintauth is the ONE structural money-mint invariant for the commerce ledger: a write that MINTS spendable balance (credits the gateway-honored IAM-user wallet without a funded source) is refused unless its persistence context is authorized to mint.
Package mintauth is the ONE structural money-mint invariant for the commerce ledger: a write that MINTS spendable balance (credits the gateway-honored IAM-user wallet without a funded source) is refused unless its persistence context is authorized to mint.
models
app
approval
Package approval is the B2B spend-approval domain: before a company's (models/company) cart converts to an order, it can require sign-off from an admin or sales manager.
Package approval is the B2B spend-approval domain: before a company's (models/company) cart converts to an order, it can require sign-off from an admin or sales manager.
catalogentry
Package catalogentry is the CMS source-of-truth for the platform product catalog — the single list docs.<brand>, the console sidebar, and pricing all derive from.
Package catalogentry is the CMS source-of-truth for the platform product catalog — the single list docs.<brand>, the console sidebar, and pricing all derive from.
company
Package company is the B2B company domain: a customer organization that buys through the store.
Package company is the B2B company domain: a customer organization that buys through the store.
employee
Package employee is the B2B buyer domain: a person who purchases on behalf of a company (models/company).
Package employee is the B2B buyer domain: a person who purchases on behalf of a company (models/company).
exchange
Package exchange is the order-exchange domain (Medusa v2 core parity): an exchange pairs a return of inbound items on an order with outbound replacement items.
Package exchange is the order-exchange domain (Medusa v2 core parity): an exchange pairs a return of inbound items on an order with outbound replacement items.
fee
giftcard
Package giftcard is the gift-card domain: a prepaid, code-addressable balance an org issues and a customer redeems against orders.
Package giftcard is the gift-card domain: a prepaid, code-addressable balance an org issues and a customer redeems against orders.
giftcardredemption
Package giftcardredemption is the append-only debit ledger for gift cards.
Package giftcardredemption is the append-only debit ledger for gift cards.
husdcursor
Package husdcursor persists the HUSD indexer's scan position: the last block fully projected into the ledger, per chain.
Package husdcursor persists the HUSD indexer's scan position: the last block fully projected into the ledger, per chain.
husdissuance
Package husdissuance is the durable, idempotent record of ONE treasury HUSD mint in the chain-backed credit ledger.
Package husdissuance is the durable, idempotent record of ONE treasury HUSD mint in the chain-backed credit ledger.
husdsettlement
Package husdsettlement is the audit record of ONE org→treasury HUSD settlement: the on-chain sweep that reconciles an org's on-chain balance back down to its off-chain ledger balance after metered usage (and reclaimed/expired grants) drew it down.
Package husdsettlement is the audit record of ONE org→treasury HUSD settlement: the on-chain sweep that reconciles an org's on-chain balance back down to its off-chain ledger balance after metered usage (and reclaimed/expired grants) drew it down.
idempotencykey
Package idempotencykey is a reusable idempotency guard for money-moving HTTP requests (refunds, captures, payouts).
Package idempotencykey is a reusable idempotency guard for money-moving HTTP requests (refunds, captures, payouts).
order
Package order provides the Order model with support for the new db.DB interface.
Package order provides the Order model with support for the new db.DB interface.
ossaccrual
Package ossaccrual is the payout-accrual ledger for the SBOM-driven OSS developer payout system.
Package ossaccrual is the payout-accrual ledger for the SBOM-driven OSS developer payout system.
product
Package product provides model initialization and query helpers for the v2 Product model.
Package product provides model initialization and query helpers for the v2 Product model.
productcategory
Package productcategory is the hierarchical product category tree (Medusa v2 parity: product-category).
Package productcategory is the hierarchical product category tree (Medusa v2 parity: product-category).
productoption
Package productoption is a product's option axis (e.g.
Package productoption is a product's option axis (e.g.
productoptionvalue
Package productoptionvalue is one value of a product option (e.g.
Package productoptionvalue is one value of a product option (e.g.
producttag
Package producttag is a free-form product tag (Medusa v2 parity: product-tag).
Package producttag is a free-form product tag (Medusa v2 parity: product-tag).
producttype
Package producttype is a product type classification (Medusa v2 parity: product-type).
Package producttype is a product type classification (Medusa v2 parity: product-type).
quote
Package quote is the B2B request-for-quote domain: a company (models/company) negotiates the price of a draft order with the merchant.
Package quote is the B2B request-for-quote domain: a company (models/company) negotiates the price of a draft order with the merchant.
refundreason
Package refundreason is the refund-reason lookup (Medusa v2 parity: refund-reason) — the categorized reason a payment was refunded.
Package refundreason is the refund-reason lookup (Medusa v2 parity: refund-reason) — the categorized reason a payment was refunded.
returnreason
Package returnreason is the return-reason lookup (Medusa v2 parity: return-reason) — the categorized reason a customer returns an item.
Package returnreason is the return-reason lookup (Medusa v2 parity: return-reason) — the categorized reason a customer returns an item.
sbomrecord
Package sbomrecord stores the Software Bill of Materials emitted for a deployed image.
Package sbomrecord stores the Software Bill of Materials emitted for a deployed image.
user/v2
Package user provides the User model using the new db.DB interface.
Package user provides the User model using the new db.DB interface.
Package ossattr is the pure, deterministic attribution core of the SBOM-driven OSS-developer payout system.
Package ossattr is the pure, deterministic attribution core of the SBOM-driven OSS-developer payout system.
Package ossfunding resolves an OSS package (by PURL) to a payout target — where the money for that package should go.
Package ossfunding resolves an OSS package (by PURL) to a payout target — where the money for that package should go.
Package payment provides per-org payment processor configuration.
Package payment provides per-org payment processor configuration.
providers
Package providers is a convenience package that imports all payment provider packages, ensuring they are available for the processor registry.
Package providers is a convenience package that imports all payment provider packages, ensuring they are available for the processor registry.
providers/bitpay
Package bitpay implements the BitPay payment processor for Commerce.
Package bitpay implements the BitPay payment processor for Commerce.
providers/circle
Package circle implements the Circle Payments API processor for Commerce.
Package circle implements the Circle Payments API processor for Commerce.
providers/coinbase_commerce
Package coinbase_commerce implements the Coinbase Commerce payment processor for Commerce.
Package coinbase_commerce implements the Coinbase Commerce payment processor for Commerce.
providers/moonpay
Package moonpay implements the MoonPay on-ramp processor for Commerce.
Package moonpay implements the MoonPay on-ramp processor for Commerce.
providers/opennode
Package opennode implements the OpenNode (Lightning) payment processor for Commerce.
Package opennode implements the OpenNode (Lightning) payment processor for Commerce.
providers/solanapay
Package solanapay implements the Solana Pay payment processor for Commerce.
Package solanapay implements the Solana Pay payment processor for Commerce.
providers/square
Package square is the unified Square payment provider.
Package square is the unified Square payment provider.
providers/stripe
Package stripe — catalog (Products and Prices) helpers used by the plan seeder.
Package stripe — catalog (Products and Prices) helpers used by the plan seeder.
router
Package router provides an intelligent multi-processor payment routing layer.
Package router provides an intelligent multi-processor payment routing layer.
x402
Package x402 implements the x402 Payment Protocol (LP-3028) for HTTP-native crypto payments using the 402 Payment Required status code.
Package x402 implements the x402 Payment Protocol (LP-3028) for HTTP-native crypto payments using the 402 Payment Required status code.
pkg
auth
Package auth wires gateway-supplied identity headers (X-Org-Id, X-User-Id, X-User-Email) into request context.
Package auth wires gateway-supplied identity headers (X-Org-Id, X-User-Id, X-User-Email) into request context.
org
Package org provides KV-cached org resolution from gateway-supplied X-Org-Id headers.
Package org provides KV-cached org resolution from gateway-supplied X-Org-Id headers.
husd-treasury-addr command
Command husd-treasury-addr prints the EVM address of the HUSD treasury key (env HUSD_TREASURY_KEY).
Command husd-treasury-addr prints the EVM address of the HUSD treasury key (env HUSD_TREASURY_KEY).
Package seed wires @hanzo/plans entries to payment-processor catalogs.
Package seed wires @hanzo/plans entries to payment-processor catalogs.
Package store — hanzo/base seam entry point.
Package store — hanzo/base seam entry point.
migrations
Package migrations — commerce-owned base migrations.
Package migrations — commerce-owned base migrations.
seed
Package seed — one-shot seed helpers for local dev.
Package seed — one-shot seed helpers for local dev.
test
test-integration
thirdparty
cloudflare
Package cloudflare provides a Cloudflare API v4 client for Commerce.
Package cloudflare provides a Cloudflare API v4 client for Commerce.
kms
Package kms provides a thin HTTP client for Hanzo KMS secret management.
Package kms provides a thin HTTP client for Hanzo KMS secret management.
mercury
Package mercury provides types and utilities for integrating with the Mercury bank API and webhook events.
Package mercury provides types and utilities for integrating with the Mercury bank API and webhook events.
mpc
paypal/ipn
Reference: https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
Reference: https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
Package treasury is the chain-backed credit ledger's mint authority boundary.
Package treasury is the chain-backed credit ledger's mint authority boundary.
datastorestore
Package datastorestore is the production treasury.IssuanceStore: it persists HUSD mint issuances to the per-org SQLite ledger via models/husdissuance.
Package datastorestore is the production treasury.IssuanceStore: it persists HUSD mint issuances to the per-org SQLite ledger via models/husdissuance.
Package ui exposes the built admin-commerce (Hanzo GUI v7) bundle as an embedded filesystem.
Package ui exposes the built admin-commerce (Hanzo GUI v7) bundle as an embedded filesystem.
util
bit
cache
Package cache (memcache.go) provides a caching abstraction layer that can work with different backends (in-memory, Redis, etc.) to replace appengine/memcache.
Package cache (memcache.go) provides a caching abstraction layer that can work with different backends (in-memory, Redis, etc.) to replace appengine/memcache.
csv
fs
gob
husd
Package husd is the ONE place that configures on-chain HUSD (Hanzo USD stablecoin, ERC-20 on the Hanzo EVM) operations and converts USD cents to and from the token's base units.
Package husd is the ONE place that configures on-chain HUSD (Hanzo USD stablecoin, ERC-20 on the Hanzo EVM) operations and converts USD cents to and from the token's base units.
jwt
nscontext
Package nscontext provides namespace context functionality that replaces google.golang.org/appengine.Namespace.
Package nscontext provides namespace context functionality that replaces google.golang.org/appengine.Namespace.
search
Package search provides a search abstraction layer with pluggable backends.
Package search provides a search abstraction layer with pluggable backends.
slug
Package slug transforms strings into a normalized form well suited for use in URLs.
Package slug transforms strings into a normalized form well suited for use in URLs.
val

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL