balance

package
v1.25.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const UsdQuarksPerUnit = 1_000_000

UsdQuarksPerUnit is the scale of UsdCostBasis: 1 unit is $0.000001. It is deliberately equal to the core mint's quarks per unit, so a core mint account's USD cost basis is exactly its quark balance.

Variables

View Source
var (
	ErrRecordNotFound = errors.New("balance record not found")
	ErrRecordExists   = errors.New("balance record already exists")

	// ErrInsufficientBalance is returned when a debit exceeds the balance.
	ErrInsufficientBalance = errors.New("insufficient balance")

	// ErrBalanceChanged is returned when a drain or close expected a different
	// balance than the one on record.
	ErrBalanceChanged = errors.New("balance is not the expected value")

	ErrAccountClosed = errors.New("account open state is stale")

	// ErrAccountUnlocked is returned when a delta other than a credit targets
	// an account whose timelock vault has unlocked. The ledger stops
	// maintaining the record at unlock, so nothing may leave it. Credits are
	// still applied, since an unlocked record is excluded from every read and
	// turning one away only blocks the flow recording it.
	ErrAccountUnlocked = errors.New("account is unlocked")

	ErrCheckpointNotFound = errors.New("checkpoint not found")
	ErrStaleCheckpoint    = errors.New("checkpoint is stale")
)

Functions

func SortDeltas added in v1.25.0

func SortDeltas(deltas []*Delta)

SortDeltas orders deltas by token account, then by kind, so every store implementation acquires row locks in the same order and cannot deadlock against another transaction applying deltas to the same accounts.

func UsdCostBasisFromFloat added in v1.25.0

func UsdCostBasisFromFloat(usd float64) int64

UsdCostBasisFromFloat converts a USD value into UsdQuarksPerUnit, rounding to the nearest unit. This is the single conversion point, so every caller rounds identically.

func UsdCostBasisToFloat added in v1.25.0

func UsdCostBasisToFloat(usdCostBasis int64) float64

UsdCostBasisToFloat converts a value in UsdQuarksPerUnit back into USD. Use it only at the edge, e.g. when populating a client-facing response.

Types

type Delta added in v1.25.0

type Delta struct {
	TokenAccount string
	Kind         DeltaKind

	// Quarks is the amount credited, debited or drained. Ignored for
	// DeltaClose, and must be zero for DeltaAdjustUsdCostBasis.
	Quarks uint64

	// UsdCostBasis is added on credit and subtracted on debit. It is signed
	// so that a credit can also carry a downward reconciliation. Ignored for
	// DeltaDrain and DeltaClose, where the basis is zeroed along with the
	// balance. For DeltaAdjustUsdCostBasis it is the signed correction, added
	// as is.
	UsdCostBasis int64
}

Delta is a single balance change to apply to a token account.

func MergeDeltas added in v1.25.0

func MergeDeltas(deltas []*Delta) []*Delta

MergeDeltas returns a copy of deltas in SortDeltas order with consecutive credits, debits and cost basis adjustments to the same account combined into one. Applying one combined delta is equivalent to applying the parts in sequence, since those kinds are additive and their predicates are monotonic in the amount, but it touches the row once. Drains and closes are never merged, since an account can only legitimately be drained or closed once.

func (*Delta) Validate added in v1.25.0

func (d *Delta) Validate() error

type DeltaKind added in v1.25.0

type DeltaKind uint8

DeltaKind selects the predicate a Delta is applied under.

const (
	// DeltaCredit adds funds to an open account.
	DeltaCredit DeltaKind = iota + 1

	// DeltaDebit removes funds from an account with sufficient balance.
	DeltaDebit

	// DeltaDrain removes exactly the account's full balance and closes it.
	DeltaDrain

	// DeltaClose closes an account with a zero balance.
	DeltaClose

	// DeltaAdjustUsdCostBasis adds a signed correction to an account's USD
	// cost basis without moving quarks. It carries no predicate: every
	// predicate on the other kinds protects a quark invariant, and none of
	// them apply when no quarks move. A correction is only ever issued for a
	// period the ledger was already tracking, so refusing one would leave the
	// basis wrong rather than protect anything.
	DeltaAdjustUsdCostBasis
)

func (DeltaKind) String added in v1.25.0

func (k DeltaKind) String() string

type ExternalCheckpointRecord

type ExternalCheckpointRecord struct {
	Id uint64

	TokenAccount   string
	Quarks         uint64
	SlotCheckpoint uint64

	LastUpdatedAt time.Time
}

func (*ExternalCheckpointRecord) Clone

func (*ExternalCheckpointRecord) CopyTo

func (*ExternalCheckpointRecord) Validate

func (r *ExternalCheckpointRecord) Validate() error

type Record added in v1.25.0

type Record struct {
	Id uint64

	TokenAccount string
	OwnerAccount string
	MintAccount  string

	Quarks uint64

	// UsdCostBasis is the account's USD cost basis, in UsdQuarksPerUnit.
	// A cost basis may legitimately be negative.
	UsdCostBasis int64

	IsOpen bool

	// IsLocked indicates the timelock vault is still locked, so the account
	// is managed by OCP and every balance change flows through the ledger.
	// Once a vault unlocks, funds can move on chain without an intent, so the
	// record's values must not be trusted or aggregated: nothing may leave
	// the account through the ledger, while credits keep being recorded
	// against a balance that no longer reflects the chain. Unlocking is
	// one-way.
	IsLocked bool

	UpdatedAt time.Time
}

Record is the materialized balance of a token account managed by Code.

func (*Record) Clone added in v1.25.0

func (r *Record) Clone() Record

func (*Record) CopyTo added in v1.25.0

func (r *Record) CopyTo(dst *Record)

func (*Record) Validate added in v1.25.0

func (r *Record) Validate() error

type Store

type Store interface {
	// Create creates a new balance record.
	//
	// ErrRecordExists is returned if the token account already has a record.
	Create(ctx context.Context, record *Record) error

	// Get gets the balance record for a token account.
	//
	// ErrRecordNotFound is returned if no record exists.
	Get(ctx context.Context, tokenAccount string) (*Record, error)

	// GetBatch gets balance records for a set of token accounts. Accounts
	// without a record are omitted from the result.
	GetBatch(ctx context.Context, tokenAccounts ...string) (map[string]*Record, error)

	// GetAllByOwner gets all balance records for an owner.
	//
	// ErrRecordNotFound is returned if no records exist.
	GetAllByOwner(ctx context.Context, owner string) ([]*Record, error)

	// GetAllByOwnerAndMint gets all balance records for an owner and mint.
	//
	// ErrRecordNotFound is returned if no records exist.
	GetAllByOwnerAndMint(ctx context.Context, owner, mint string) ([]*Record, error)

	// GetAllLockedByMint gets locked balance records for a mint with at
	// least minQuarks, paged by record ID. Unlocked records are excluded,
	// since funds can move on chain without an intent once a vault unlocks,
	// making their balances stale.
	//
	// ErrRecordNotFound is returned if no records exist.
	GetAllLockedByMint(ctx context.Context, mint string, minQuarks uint64, cursor query.Cursor, limit uint64, direction query.Ordering) ([]*Record, error)

	// CountLockedByMint counts locked records for a mint with at least
	// minQuarks. Unlocked records are excluded, since their balances are
	// stale.
	CountLockedByMint(ctx context.Context, mint string, minQuarks uint64) (uint64, error)

	// ApplyDeltas atomically applies a set of deltas. Either every delta is
	// applied or none are. Deltas are applied in SortDeltas order.
	//
	// Every delta must target an account with a record, otherwise
	// ErrRecordNotFound is returned and nothing is applied. Callers are
	// responsible for not producing deltas for accounts the ledger doesn't
	// track, like external wallets.
	//
	// ErrInsufficientBalance is returned when a debit exceeds the balance.
	// ErrBalanceChanged is returned when a drain or close doesn't match the
	// balance. ErrAccountClosed is returned when a credit, debit, drain or
	// close targets a closed account, which is frozen. ErrAccountUnlocked is
	// returned when a delta other than a credit targets an unlocked account,
	// whose record is no longer maintained. DeltaAdjustUsdCostBasis carries
	// no predicate: it moves no quarks, so it applies to closed and unlocked
	// accounts alike and only fails when the record is missing.
	ApplyDeltas(ctx context.Context, deltas ...*Delta) error

	// MarkAsUnlocked marks an account's timelock vault as unlocked, which is
	// one-way and idempotent. It is called in the same transaction that
	// commits the timelock record's transition out of the locked state, so
	// the flag cannot disagree with the timelock record it mirrors.
	//
	// ErrRecordNotFound is returned if no record exists.
	MarkAsUnlocked(ctx context.Context, tokenAccount string) error

	// SaveExternalCheckpoint saves an external balance at a checkpoint.
	//
	// ErrStaleCheckpoint is returned if the checkpoint is outdated
	SaveExternalCheckpoint(ctx context.Context, record *ExternalCheckpointRecord) error

	// GetExternalCheckpoint gets an exeternal balance checkpoint for a
	// given account.
	//
	// ErrCheckpointNotFound is returend if no DB record exists.
	GetExternalCheckpoint(ctx context.Context, account string) (*ExternalCheckpointRecord, error)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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