invoices: self-contained payout addresses

Crypto options were limited to a hard-coded asset list, with one
address per coin in a side table. A payout address now carries
everything an invoice needs: ticker, name, QR URI scheme, amount
parameter, CoinGecko id, address and an active flag. Any coin can be
added, several addresses per ticker are fine, and known tickers fill the
QR and rate fields from the built-in templates.

The new-invoice form picks a payout address. The invoice snapshots the
ticker, address, name, scheme and amount parameter, and the PDF and QR
render from that copy, so editing, retiring or deleting a payout entry
never changes an issued invoice. "Fetch live" looks up the rate by the
payout address's CoinGecko id.

Migration 012 keeps the existing rows and backfills both the payout
metadata and the snapshots on existing crypto invoices.

Assisted-by: Claude:opus-5
This commit is contained in:
Sergei Poljanski 2026-10-10 09:17:09 +04:00
commit 33ba7650c3
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
19 changed files with 420 additions and 176 deletions

View file

@ -1,8 +1,10 @@
require 'json'
# Registry of crypto payment assets — one asset (coin, or token+chain for
# stablecoins) per invoice. Adding an asset is one entry here plus, optionally,
# a default payout address in the CRYPTO_ADDRESSES env (JSON, code => address).
# Built-in crypto templates. Payout addresses (payout_addresses table) carry
# their own ticker, name, QR scheme, amount parameter and CoinGecko id; these
# entries only prefill those fields for a known ticker, back-fill rows from
# before that, and name legacy invoices. Nothing here limits which coins can
# be used.
#
# QR encoding is driven by scheme/amount_param:
# scheme + amount_param => scheme:<addr>?<param>=<amt> (wallet prefills amount)
@ -12,7 +14,7 @@ require 'json'
# coingecko is the id for the simple/price endpoint; chain variants of a
# stablecoin share the token's id.
module CryptoAsset
ASSETS = {
DEFAULTS = {
'BTC' => { name: 'Bitcoin', coingecko: 'bitcoin', scheme: 'bitcoin', amount_param: 'amount' },
'LTC' => { name: 'Litecoin', coingecko: 'litecoin', scheme: 'litecoin', amount_param: 'amount' },
'ETH' => { name: 'Ethereum', coingecko: 'ethereum', scheme: 'ethereum', amount_param: nil },
@ -29,7 +31,15 @@ module CryptoAsset
'USDC-ALGO' => { name: 'USD Coin (Algorand)', coingecko: 'usd-coin', scheme: nil, amount_param: nil }
}.freeze
CODES = ASSETS.keys.freeze
ASSETS = DEFAULTS # older name
CODES = DEFAULTS.keys.freeze
TICKER_RE = /\A[A-Z0-9][A-Z0-9-]{1,19}\z/
SCHEME_RE = /\A[a-z][a-z0-9+.-]{1,31}\z/
AMOUNT_PARAMS = %w[amount tx_amount].freeze
# Suggestions for the admin form; wallets only honour real URI schemes.
KNOWN_SCHEMES = (DEFAULTS.values.filter_map { |a| a[:scheme] } +
%w[dogecoin bitcoincash dash zcash tron ton]).uniq.freeze
module_function

View file

@ -2,25 +2,24 @@ require 'rqrcode'
require_relative 'crypto_asset'
# Renders a crypto payment QR as PNG bytes for embedding in the PDF.
# The encoded payload depends on the asset (see CryptoAsset): a payment URI
# with amount, a bare scheme URI, or just the address.
# The payload follows the payout entry's scheme/amount parameter: a payment
# URI with amount, a bare scheme URI, or just the address.
module CryptoQr
module_function
# `amount` is a BigDecimal or nil (address-only QR).
def uri(coin, address, amount)
asset = CryptoAsset[coin] or return address
return address unless asset[:scheme]
base = "#{asset[:scheme]}:#{address}"
return base if amount.nil? || asset[:amount_param].nil?
def uri(scheme:, amount_param:, address:, amount:)
return address unless scheme
base = "#{scheme}:#{address}"
return base if amount.nil? || amount_param.nil?
# Trim trailing zeros so the wallet shows a clean amount; keep up to 8 dp.
amt = amount.round(8).to_s('F').sub(/\.?0+$/, '')
"#{base}?#{asset[:amount_param]}=#{amt}"
"#{base}?#{amount_param}=#{amt}"
end
# Returns PNG bytes (binary string), sized for a crisp ~120pt PDF placement.
def png(coin, address, amount, size: 480)
qr = RQRCode::QRCode.new(uri(coin, address, amount), level: :m)
def png(size: 480, **payload)
qr = RQRCode::QRCode.new(uri(**payload), level: :m)
qr.as_png(
bit_depth: 1,
border_modules: 2,

View file

@ -2,7 +2,6 @@ require 'net/http'
require 'json'
require 'uri'
require 'bigdecimal'
require_relative 'crypto_asset'
# Fetches the current price of a CryptoAsset from CoinGecko (free, no API key).
#
@ -17,11 +16,11 @@ module CryptoRate
module_function
# Returns a BigDecimal: the price of 1 unit of `coin` in `currency`.
# Returns a BigDecimal: the price of 1 unit of the CoinGecko asset `id`
# (a payout address's coingecko field) in `currency`.
# `gel_rate` (USD->GEL) is required only when currency == 'GEL'.
def fetch(coin, currency, gel_rate: nil)
asset = CryptoAsset[coin] or raise Error, "Unknown coin: #{coin}"
id = asset[:coingecko]
def fetch(id, currency, gel_rate: nil)
raise Error, 'No CoinGecko id set for this payout address; enter the rate by hand.' if id.to_s.empty?
currency = currency.to_s.upcase
if currency == 'GEL'

View file

@ -103,7 +103,10 @@ class Invoice < Sequel::Model(:invoices)
private
# Crypto is opt-in: only populated when an address is given. Rate and
# Crypto is opt-in: only populated when an address is given (the route
# fills these from the chosen PayoutAddress#snapshot). Name/scheme/amount
# param are copied so later payout edits don't change this invoice; a
# known ticker without them falls back to the built-in template. Rate and
# amount are both optional; if amount is blank but rate is present,
# derive it.
def apply_crypto(invoice, params, subtotal)
@ -111,10 +114,15 @@ class Invoice < Sequel::Model(:invoices)
return if address.empty?
coin = params[:crypto_coin].to_s.upcase
CryptoAsset.valid?(coin) or raise ArgumentError, "Unknown coin: #{coin}"
coin.match?(CryptoAsset::TICKER_RE) or raise ArgumentError, "Bad ticker: #{coin}"
tmpl = CryptoAsset::DEFAULTS[coin] || {}
pick = ->(k, t) { params.key?(k) ? params[k].to_s.strip.then { |v| v.empty? ? nil : v } : tmpl[t] }
invoice.crypto_coin = coin
invoice.crypto_address = address
invoice.crypto_name = pick.(:crypto_name, :name) || coin
invoice.crypto_scheme = pick.(:crypto_scheme, :scheme)
invoice.crypto_amount_param = pick.(:crypto_amount_param, :amount_param)
rate = decimal_or_nil(params[:crypto_rate])
invoice.crypto_rate = rate

View file

@ -289,20 +289,21 @@ class InvoicePdf
def draw_crypto(pdf)
coin = @invoice.crypto_coin
asset = CryptoAsset[coin] || {}
name = @invoice.crypto_name || CryptoAsset.name(coin) # snapshot; legacy fallback
amount = @invoice.crypto_amount_due
qr_size = 78
pdf.move_down 12
pdf.fill_color COLOR_MUTED
pdf.font_size(8) { pdf.text "PAY IN #{CryptoAsset.name(coin).upcase} (#{coin})", character_spacing: 1.5 }
pdf.font_size(8) { pdf.text "PAY IN #{name.upcase} (#{coin})", character_spacing: 1.5 }
pdf.fill_color COLOR_TEXT
pdf.move_down 4
# Fixed-height row: QR on the right (drawn with float so it doesn't advance
# the cursor), text column on the left. The outer bounding_box of height
# qr_size leaves the cursor exactly below the row when it ends.
qr_bytes = CryptoQr.png(coin, @invoice.crypto_address, amount)
qr_bytes = CryptoQr.png(scheme: @invoice.crypto_scheme, amount_param: @invoice.crypto_amount_param,
address: @invoice.crypto_address, amount: amount)
pdf.bounding_box([0, pdf.cursor], width: pdf.bounds.width, height: qr_size) do
pdf.float do
pdf.bounding_box([pdf.bounds.right - qr_size, pdf.bounds.top], width: qr_size, height: qr_size) do
@ -325,8 +326,8 @@ class InvoicePdf
pdf.font_size(8) { pdf.text @invoice.crypto_address }
pdf.move_down 3
pdf.fill_color COLOR_MUTED
hint = if asset[:amount_param]
"Scan the QR with any #{CryptoAsset.name(coin)} wallet to prefill the payment."
hint = if @invoice.crypto_scheme && @invoice.crypto_amount_param
"Scan the QR with any #{name} wallet to prefill the payment."
else
"QR encodes the address. Send #{coin} only. Verify the network before sending."
end

View file

@ -61,7 +61,9 @@ class InvoiceStats
live.group_by(&:client_name).map { |c, l| [c, l.size, gel(l)] }.sort_by { |_, _, g| -g }.first(n)
end
# [[ticker, name, invoices]] — name from the invoices' own snapshot.
def crypto_usage
live.select(&:crypto?).group_by(&:crypto_coin).map { |c, l| [c, l.size] }.sort_by { |_, n| -n }
live.select(&:crypto?).group_by(&:crypto_coin)
.map { |c, l| [c, l.filter_map(&:crypto_name).last || c, l.size] }.sort_by { |_, _, n| -n }
end
end

View file

@ -1,36 +1,71 @@
require 'sequel'
require_relative 'crypto_asset'
# Default payout address per coin (see migration 010).
# A crypto payout option, self-contained: ticker (`coin`, printed on the
# PDF), display name, QR URI scheme + amount parameter, CoinGecko id for the
# live rate, and the address. Several per ticker are fine (e.g. Ledger and
# exchange). The new-invoice form picks one; the invoice copies its fields
# (#snapshot), so editing or retiring an entry never changes issued invoices.
class PayoutAddress < Sequel::Model(:payout_addresses)
unrestrict_primary_key
ADDRESS_RE = /\A[a-zA-Z0-9]{10,128}\z/ # same loose shape check as invoices
ADDRESS_RE = /\A[a-zA-Z0-9]{10,128}\z/ # loose shape check, same as invoices
FIELDS = %i[name coin scheme amount_param coingecko address].freeze
def self.map
to_hash(:coin, :address).slice(*CryptoAsset::CODES)
def self.listing
order(Sequel.desc(:active), :coin, :name, :id).all
end
# First boot after the move: take over what the env/Forgejo secrets held.
def self.active_list
where(active: true).order(:coin, :name, :id).all
end
# First boot after moving off env: import CRYPTO_ADDRESSES / LTC_ADDRESS.
def self.seed_from_env!
return if count.positive?
CryptoAsset.env_addresses.each do |coin, address|
next unless address.match?(ADDRESS_RE)
create(coin: coin, address: address, updated_by: 'env import', updated_at: Time.now.utc)
create(**template(coin), coin: coin, address: address, updated_by: 'env import', updated_at: Time.now.utc)
end
end
# Upsert or (blank address) delete. Returns an error string or nil.
def self.set!(coin, address, by:)
coin = coin.to_s.upcase
return 'unknown coin' unless CryptoAsset.valid?(coin)
address = address.to_s.strip
if address.empty?
where(coin: coin).delete
return nil
# Known ticker → its usual name/scheme/amount param/CoinGecko id.
def self.template(coin)
a = CryptoAsset::DEFAULTS[coin.to_s.upcase] or return {}
{ name: a[:name], scheme: a[:scheme], amount_param: a[:amount_param], coingecko: a[:coingecko] }
end
# Cleans form input: blanks → nil, scheme lowercased without a trailing
# colon, ticker uppercased; empty optional fields are taken from the
# template when the ticker is a known one.
def self.clean(raw, fill_from_template: false)
v = FIELDS.to_h { |f| [f, raw[f.to_s].to_s.strip.then { |x| x.empty? ? nil : x }] }
v[:coin] = v[:coin]&.upcase
v[:scheme] = v[:scheme]&.downcase&.delete_suffix(':')
v[:coingecko] = v[:coingecko]&.downcase
if fill_from_template
template(v[:coin]).each { |k, t| v[k] ||= t }
end
return "#{coin}: address looks invalid" unless address.match?(ADDRESS_RE)
row = self[coin] || new(coin: coin)
row.set(address: address, updated_by: by, updated_at: Time.now.utc).save
v[:name] ||= v[:coin]
v
end
def self.error_for(v)
label = v[:coin] || 'new entry'
return "#{label}: ticker must be A–Z, 0–9 and -, 2–20 characters" unless v[:coin].to_s.match?(CryptoAsset::TICKER_RE)
return "#{label}: address looks invalid" unless v[:address].to_s.match?(ADDRESS_RE)
return "#{label}: scheme must look like 'litecoin' (full coin name, lowercase)" if v[:scheme] && !v[:scheme].match?(CryptoAsset::SCHEME_RE)
return "#{label}: unknown amount parameter" if v[:amount_param] && !CryptoAsset::AMOUNT_PARAMS.include?(v[:amount_param])
return "#{label}: amount in QR needs a scheme" if v[:amount_param] && !v[:scheme]
return "#{label}: CoinGecko id looks invalid" if v[:coingecko] && !v[:coingecko].match?(/\A[a-z0-9-]{2,64}\z/)
nil
end
# What an invoice copies at issue (Invoice.build reads these params).
def snapshot
{ crypto_coin: coin, crypto_address: address, crypto_name: name,
crypto_scheme: scheme, crypto_amount_param: amount_param }
end
def option_label
"#{name} · #{coin} · #{address[0, 10]}…"
end
end