← Back to Official Package Registry
Tier 4: FinTech, GraphQL, CDP & SSO • Double-Entry Ledger & Stripev1.0.0 • 48 KB • Ed25519 Verified

payments_ledger@1.0.0

Minor-unit multi-currency Money math, penny-exact allocation, transactional SQLite double-entry ledger, and .secret Stripe/LemonSqueezy SDK.

use [payments_ledger]use [payments_ledger/stripe]
veko pkg add payments_ledger@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

payments_ledger

Exact multi-currency minor-unit Money arithmetic, penny-exact largest-remainder allocation, transactional immutable double-entry SQLite ledger, and .secret-aware Stripe and LemonSqueezy SDK helpers.

Overview

payments_ledger eliminates floating-point rounding bugs, unbalanced accounting mutations, duplicate webhook credits, and timing side-channels in financial applications:

  • payments_ledger: Checked i64 minor-unit Money (money, money-add, money-sub, money-mul-bps, Hamilton largest-remainder money-allocate, ISO-4217 format-money) and an ACID append-only double-entry ledger backed by Zero-FFI db/sqlite (open-ledger, close-ledger, create-account, post-transaction, account-balance, trial-balance, reverse-transaction).
  • payments_ledger/stripe: .secret-compatible HMAC-SHA256 webhook signature generators and verifiers for Stripe (Stripe-Signature: t=...,v1=... with replay tolerance window and multi-key rotation) and LemonSqueezy (X-Signature) using constant-time bits/ct-eq?, plus RFC 3986 form-urlencoded request builders for Stripe Checkout Sessions, PaymentIntents, and Refunds and a live net/client transport helper.

Installation

powershell
veko pkg add payments_ledger@1.0.0

Import the ledger and payment provider modules:

rebol
use [
    pay    = payments_ledger
    stripe = payments_ledger/stripe
]

Architecture & Financial Guarantees

  1. Zero Floating-Point Money Math: Every Money amount is stored in integer ISO-4217 minor units (0 decimals for JPY/KRW, 3 for BHD/KWD/OMR, 2 for USD/EUR/GBP), guarded by checked 64-bit arithmetic (math/add-checked, math/sub-checked, math/mul-checked).
  2. Penny-Exact Hamilton Allocation: money-allocate distributes integer quotients first and assigns leftover pennies in descending order of exact fractional remainders, guaranteeing $\sum \text{parts} = \text{total}$ ($10.00 -> $3.34, $3.33, $3.33).
  3. Immutable Double-Entry Invariants: post-transaction executes inside a SQLite BEGIN ... COMMIT B-tree transaction, verifying sum(debits) == sum(credits) > 0, uniform currency across all legs and accounts, idempotency_key replay deduplication, and bounded-account overdraft protection (allow_overdraft == false). Corrections never mutate or delete historical rows; reverse-transaction appends a compensating entry that flips .debit and .credit legs.
  4. .secret & Constant-Time Webhook Hygiene: verify-stripe-webhook and verify-lemonsqueezy-webhook accept .secret-tainted keys (bytes/with-secret or os/getenv/secret) without exposing key material to serialization sinks, validate timestamp skew before JSON decoding, and compare 32-byte HMAC-SHA256 digests with bits/ct-eq?.

Complete API Reference

payments_ledger

Type / SignatureDescription
Money = struct { amount i64, currency str }Exact minor-unit monetary value with 3-letter ISO-4217 currency.
Account = struct { id str, name str, kind enum, currency str, allow_overdraft bool }Ledger chart-of-accounts definition (.asset, .liability, .equity, .revenue, .expense).
LedgerEntry = struct { account_id str, direction enum, amount i64, currency str }Single .debit or .credit posting leg.
money = fn [amount i64, currency str] MoneyConstructs a validated Money value.
money-add = fn [a Money, b Money] Money / money-sub = fn [a Money, b Money] MoneyChecked same-currency addition and subtraction.
money-mul-bps = fn [val Money, bps i64] MoneyBasis-points fee calculation (290 bps = 2.90%) with half-away-from-zero rounding.
money-allocate = fn [total Money, weights block[i64]] block[Money]Largest-remainder proportional split with zero lost cents.
format-money = fn [val Money] strFormats Money according to ISO-4217 minor-unit precision.
debit = fn [account_id str, val Money] LedgerEntry / credit = fn [account_id str, val Money] LedgerEntryLeg constructors for post-transaction.
open-ledger = fn [db_path str] Ledger / close-ledger = fn [mut ledger Ledger] enumOpens and closes a :memory: or file-backed SQLite ledger.
create-account = fn [mut ledger Ledger, id str, name str, kind enum, currency str /bounded bounded bool = false] AccountCreates an account (/bounded true forbids negative normal balances).
post-transaction = fn [mut ledger Ledger, tx_id str, description str, entries block /idempotency_key idem_key str = '' /timestamp ts_unix i64 = 0] mapAtomically posts a balanced multi-leg transaction.
account-balance = fn [ledger Ledger, account_id str] MoneyComputes the exact normal-side Money balance of account_id.
trial-balance = fn [ledger Ledger /currency filter_ccy str = ''] mapComputes global debit/credit totals and proves total_debits == total_credits.
reverse-transaction = fn [mut ledger Ledger, orig_tx_id str, reversal_tx_id str, reason str /timestamp ts_unix i64 = 0] mapPosts an immutable compensating reversal transaction.

payments_ledger/stripe

Type / SignatureDescription
CheckoutItem = struct { price_id str, name str, unit_amount i64, currency str, quantity i64 }Line item for build-checkout-form.
sign-stripe-webhook = fn [secret_key any, timestamp_sec i64, payload str] strGenerates a t=...,v1=... Stripe-Signature header.
verify-stripe-webhook = fn [payload str, sig_header str, secret_key any, now_unix i64 /tolerance tolerance_sec i64 = 300] mapVerifies Stripe-Signature HMAC-SHA256 + timestamp replay window using bits/ct-eq?.
sign-lemonsqueezy-webhook / verify-lemonsqueezy-webhookGenerates and verifies LemonSqueezy X-Signature HMAC-SHA256 headers.
build-checkout-form / build-payment-intent-form / build-refund-formEncodes nested bracket application/x-www-form-urlencoded Stripe payloads.
stripe-post-form = fn [api_key str, endpoint_path str, form_body str /idempotency_key idem_key str = '' /base_url base_url str = 'https://api.stripe.com'] mapSends an authenticated Stripe API request via net/client.

Example Usage

rebol
use [pay = payments_ledger]

shares = pay/money-allocate (pay/money 1000 'USD') [1 1 1]
// -> ['$3.34', '$3.33', '$3.33']

mut ledger = pay/open-ledger ':memory:'
_ = pay/create-account mut ledger 'asset:cash' 'Operating Cash' .asset 'USD'
_ = pay/create-account mut ledger 'rev:subs' 'Subscriptions' .revenue 'USD'

_ = pay/post-transaction/idempotency_key mut ledger 'tx-1' 'Invoice #42' [
    (pay/debit  'asset:cash' (pay/money 4900 'USD'))
    (pay/credit 'rev:subs'   (pay/money 4900 'USD'))
] 'inv-42'

tb = pay/trial-balance ledger
println `Balanced: {tb.balanced}, Cash: {pay/format-money (pay/account-balance ledger 'asset:cash')}`

Verification

powershell
veko check packages/payments_ledger/src/stripe.vk
veko check packages/payments_ledger/src/mod.vk
veko check packages/payments_ledger/examples/demo.vk
veko run -C all packages/payments_ledger/examples/demo.vk
packages/payments_ledger/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/payments_ledger/examples/demo.vk
// Self-contained runnable verification suite for `payments_ledger` (`1.0.0`):
// Penny-exact 3-way `money-allocate`, basis-point fee math, SQLite double-entry postings,
// unbalanced & overdraft rejections, idempotency replay safety, compensating reversal entry,
// global `trial-balance`, and `.secret`-keyed Stripe & LemonSqueezy webhook verification!

use [
	fs
	pay    = payments_ledger
	stripe = payments_ledger/stripe
]

assert-eq = fn [label str, got any, want any] any [
	if got != want [
		println `[FAIL] {label}: got {mold got}, expected {mold want}`
		return (err `assert-eq failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

assert-true = fn [label str, cond bool] any [
	if not cond [
		println `[FAIL] {label}`
		return (err `assert-true failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

main = fn [] any [
	println '=== payments_ledger 1.0.0 Verification Suite ==='

	// 1. Exact minor-unit `Money` math, basis-points fee, and penny-exact 3-way `money-allocate`
	ten_usd = pay/money 1000 'USD'
	parts = pay/money-allocate ten_usd [1 1 1]
	_ = assert-eq/or '3-way $10.00 split part[0] == $3.34' (pay/format-money parts[0]) '$3.34' [e -> return e]
	_ = assert-eq/or '3-way $10.00 split part[1] == $3.33' (pay/format-money parts[1]) '$3.33' [e -> return e]
	_ = assert-eq/or '3-way $10.00 split part[2] == $3.33' (pay/format-money parts[2]) '$3.33' [e -> return e]

	re_sum = pay/money-add (pay/money-add parts[0] parts[1]) parts[2]
	_ = assert-eq/or 'Allocated parts sum back to exact $10.00 (1000 cents)' re_sum.amount 1000 [e -> return e]

	// Currency mismatch rejected
	ccy_mismatch = pay/money-add/or ten_usd (pay/money 500 'EUR') [ pay/money -1 'USD' ]
	_ = assert-eq/or 'Currency mismatch (USD + EUR) cleanly rejected' ccy_mismatch.amount -1 [e -> return e]

	// Basis-points processing fee: 2.90% (290 bps) on $100.00 -> $2.90
	gross = pay/money 10000 'USD'
	fee = pay/money-mul-bps gross 290
	_ = assert-eq/or '290 bps fee on $100.00 == $2.90 (290 cents)' (pay/format-money fee) '$2.90' [e -> return e]

	// 2. Transactional Immutable Double-Entry SQLite Ledger (with temp file cleanup via `defer`)
	tmp_db = str/join [(os/temp-dir) '/veko_payments_ledger_demo_' (mold (time/unix)) '.sqlite'] ''
	tmp_jnl = str/append tmp_db '-journal'
	defer [
		_ = os/remove/or tmp_db [ .ok ]
		_ = os/remove/or tmp_jnl [ .ok ]
	]

	mut ledger = pay/open-ledger/or tmp_db [e -> return e]
	_ = pay/create-account mut ledger 'asset:stripe_clearing' 'Stripe Clearing' .asset 'USD'
	_ = pay/create-account mut ledger 'expense:stripe_fees' 'Stripe Processing Fees' .expense 'USD'
	_ = pay/create-account mut ledger 'revenue:platform' 'Platform SaaS Fee' .revenue 'USD'
	// Bounded merchant payout wallet (`allow_overdraft = false` via `/bounded true`)
	_ = pay/create-account/bounded mut ledger 'liab:merchant_wallet' 'Merchant Payable Wallet' .liability 'USD' true

	// Post split marketplace charge ($100.00 gross -> $97.10 clearing + $2.90 fee == $10.00 platform rev + $90.00 merchant wallet)
	tx1 = pay/post-transaction/idempotency_key/or mut ledger 'tx-charge-001' 'Order #9001 settled' [
		(pay/debit  'asset:stripe_clearing' (pay/money 9710 'USD'))
		(pay/debit  'expense:stripe_fees'   (pay/money 290 'USD'))
		(pay/credit 'revenue:platform'      (pay/money 1000 'USD'))
		(pay/credit 'liab:merchant_wallet'  (pay/money 9000 'USD'))
	] 'idem-order-9001' [e -> return e]
	_ = assert-eq/or 'tx-charge-001 total == 10000 cents, idempotent_replay == false' tx1.idempotent_replay false [e -> return e]
	_ = assert-eq/or 'Merchant wallet balance == $90.00' (pay/format-money (pay/account-balance ledger 'liab:merchant_wallet')) '$90.00' [e -> return e]

	// Idempotency replay safety: re-posting with identical `idempotency_key` does NOT double-credit!
	tx1_replay = pay/post-transaction/idempotency_key/or mut ledger 'tx-charge-001-retry' 'Order #9001 webhook retry' [
		(pay/debit  'asset:stripe_clearing' (pay/money 9710 'USD'))
		(pay/debit  'expense:stripe_fees'   (pay/money 290 'USD'))
		(pay/credit 'revenue:platform'      (pay/money 1000 'USD'))
		(pay/credit 'liab:merchant_wallet'  (pay/money 9000 'USD'))
	] 'idem-order-9001' [e -> return e]
	_ = assert-eq/or 'Idempotent replay returns original tx-charge-001 without double-posting' tx1_replay.tx_id 'tx-charge-001' [e -> return e]
	_ = assert-eq/or 'Idempotent replay flag == true' tx1_replay.idempotent_replay true [e -> return e]
	_ = assert-eq/or 'Merchant wallet balance remains exact $90.00 after replay' (pay/account-balance ledger 'liab:merchant_wallet').amount 9000 [e -> return e]

	// Unbalanced transaction rejection (`debits=5000 != credits=4999`)
	unbal = pay/post-transaction/or mut ledger 'tx-bad-unbal' 'Broken entry' [
		(pay/debit  'asset:stripe_clearing' (pay/money 5000 'USD'))
		(pay/credit 'revenue:platform'      (pay/money 4999 'USD'))
	] [ { rejected = true } ]
	_ = assert-eq/or 'Unbalanced transaction (5000 vs 4999) rejected atomically' (map/get/or unbal 'rejected' [ false ]) true [e -> return e]

	// Overdraft guard rejection on bounded `liab:merchant_wallet` (trying to debit $95.00 when balance is $90.00)
	overdraft = pay/post-transaction/or mut ledger 'tx-bad-overdraft' 'Excess payout' [
		(pay/debit  'liab:merchant_wallet'  (pay/money 9500 'USD'))
		(pay/credit 'asset:stripe_clearing' (pay/money 9500 'USD'))
	] [ { rejected = true } ]
	_ = assert-eq/or 'Bounded account overdraft ($95 payout > $90 balance) rejected & rolled back' (map/get/or overdraft 'rejected' [ false ]) true [e -> return e]

	// Valid partial payout ($40.00) followed by compensating reversal entry (`reverse-transaction`)
	_ = pay/post-transaction/or mut ledger 'tx-payout-001' 'Merchant payout #1' [
		(pay/debit  'liab:merchant_wallet'  (pay/money 4000 'USD'))
		(pay/credit 'asset:stripe_clearing' (pay/money 4000 'USD'))
	] [e -> return e]
	_ = assert-eq/or 'Merchant wallet after $40 payout == $50.00' (pay/account-balance ledger 'liab:merchant_wallet').amount 5000 [e -> return e]

	_ = pay/reverse-transaction/or mut ledger 'tx-payout-001' 'tx-rev-payout-001' 'ACH return R01' [e -> return e]
	_ = assert-eq/or 'Compensating reversal restores merchant wallet to $90.00' (pay/account-balance ledger 'liab:merchant_wallet').amount 9000 [e -> return e]

	// Global `trial-balance` across all postings (`10000 + 4000 + 4000 = 18000` debits == `18000` credits!)
	tb = pay/trial-balance ledger
	_ = assert-eq/or 'Global trial-balance proves total_debits == total_credits' tb.balanced true [e -> return e]
	_ = assert-eq/or 'Global trial-balance cumulative debits == 18000 (immutable reversal preserved)' tb.total_debits 18000 [e -> return e]
	_ = assert-eq/or 'Global trial-balance cumulative credits == 18000' tb.total_credits 18000 [e -> return e]

	_ = pay/close-ledger mut ledger
	_ = assert-true/or 'SQLite ledger database persisted cleanly on disk' (fs/file? tmp_db) [e -> return e]

	// 3. `.secret`-keyed Stripe & LemonSqueezy Webhook Verification + Replay/Tamper Rejection + Form Builders
	raw_key_txt = 'whsec_live_veko_secret_key_2026!'
	mut wh_secret = bytes/with-secret 0
	_ = bytes/push-all mut wh_secret (bytes/from-str raw_key_txt)
	_ = assert-eq/or 'Webhook signing secret is .secret-tainted (<secret> on mold)' (mold wh_secret) '<secret>' [e -> return e]

	now_ts = 1765000000
	wh_body = '{"id":"evt_1Q9x","type":"checkout.session.completed","data":{"amount_total":10000}}'
	// Simulate incoming public HTTP `Stripe-Signature` header arriving from Stripe
	sig_hdr = stripe/sign-stripe-webhook raw_key_txt (now_ts - 15) wh_body

	ver_ok = stripe/verify-stripe-webhook/or wh_body sig_hdr wh_secret now_ts [e -> return e]
	_ = assert-eq/or 'Valid .secret-keyed Stripe webhook verified in constant time' (ver_ok.verified == true) true [e -> return e]
	_ = assert-eq/or 'Decoded Stripe webhook event type' (map/get ver_ok.event 'type') 'checkout.session.completed' [e -> return e]

	// Tampered payload rejected
	tampered_body = '{"id":"evt_1Q9x","type":"checkout.session.completed","data":{"amount_total":999999}}'
	ver_tamper = stripe/verify-stripe-webhook/or tampered_body sig_hdr wh_secret now_ts [ { verified = false } ]
	_ = assert-eq/or 'Tampered Stripe webhook payload rejected' (ver_tamper.verified == true) false [e -> return e]

	// Replay outside tolerance window (`now_ts + 600` > 300s default tolerance) rejected
	ver_replay = stripe/verify-stripe-webhook/or wh_body sig_hdr wh_secret (now_ts + 600) [ { verified = false } ]
	_ = assert-eq/or 'Stale Stripe webhook replay outside 300s window rejected' (ver_replay.verified == true) false [e -> return e]

	// LemonSqueezy `X-Signature` verification against `.secret` key
	ls_sig = stripe/sign-lemonsqueezy-webhook raw_key_txt wh_body
	ls_ok = stripe/verify-lemonsqueezy-webhook/or wh_body ls_sig wh_secret [e -> return e]
	_ = assert-eq/or 'LemonSqueezy X-Signature HMAC-SHA256 verified with .secret key' (ls_ok.verified == true) true [e -> return e]

	// URL-encoded Checkout Session & Refund form builders
	co_form = stripe/build-checkout-form/customer_email/metadata 'payment' 'https://app.veko.dev/ok' 'https://app.veko.dev/cancel' [
		(stripe/CheckoutItem { name = 'Veko Cloud Pro', unit_amount = 4900, currency = 'usd', quantity = 2 })
	] 'billing@veko.dev' { order_id = 'ord_9001' }
	_ = assert-true/or 'Stripe Checkout form encodes nested bracket line_items & metadata' ((str/contains? co_form 'line_items%5B0%5D%5Bprice_data%5D%5Bunit_amount%5D=4900') and (str/contains? co_form 'metadata%5Border_id%5D=ord_9001')) [e -> return e]

	rf_form = pay/build-refund-form/amount/reason 'pi_3Q9xVeko' 2500 'requested_by_customer'
	_ = assert-true/or 'Stripe Refund form encodes payment_intent, partial amount, and reason' ((str/contains? rf_form 'payment_intent=pi_3Q9xVeko') and (str/contains? rf_form 'amount=2500')) [e -> return e]

	println 'ALL payments_ledger 1.0.0 TESTS PASSED'
	.ok
]

res = main
if err? res [
	println (mold res)
	os/exit 1
]
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/payments_ledger/1.0.0.vkp
Archive SHA-256: ca48704f41133090ebf1274ef6d7e936212190149cebc4a7f857a9b522673f7a
Merkle Root: cc6c41e75ebff0be94b4a60f59df11e20f7ae8273052d57de9fd005f93b284ec
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"payments_ledger","version":"1.0.0","tier":4.0,"tier_label":"Tier 4: FinTech, GraphQL, CDP & SSO","category":"Double-Entry Ledger & Stripe","description":"Minor-unit multi-currency Money math, penny-exact allocation, transactional SQLite double-entry ledger, and .secret Stripe/LemonSqueezy SDK.","modules":["payments_ledger","payments_ledger/stripe"],"homepage":"https://veko-lang.org/packages/payments_ledger"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md7 KB55b1414948f65cf7a498b4fc3b553f1550fbdd28b8ded04b4dfbb84aa71fab03
examples/demo.vk9 KB98177a24beb5ca059bb16eeb67fa97fde6e1e91c1f04881f2e0762c23e631752
mod.vk20 KBfcb1ff2f4663f4d8dde57372ff6da2d0efd2352a214dc5e836b6e9d29f8fd231
stripe.vk10 KB08fdd3dd83cf14eb25392fe112af0e167c21c9a6cebb977a858715e1786e3632