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: 15 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotManagedByCode indicates that an account is not owned by Code.
	// It's up to callers to determine how to handle this situation within
	// the context of a balance.
	ErrNotManagedByCode = errors.New("explicitly not handling account not managed by code")
)
View Source
var ErrUnsupportedBalanceChange = errors.New("unsupported balance change")

ErrUnsupportedBalanceChange is returned when records describe a balance change the ledger has no rule for. It's a bug to commit such records with ledger writes enabled, so callers should fail the transaction.

View Source
var ErrUntrackedAccount = errors.New("account is not tracked by the balance ledger")

ErrUntrackedAccount is returned when funds would leave an account the ledger doesn't track.

Functions

func ApplyDeltasInTx added in v1.25.0

func ApplyDeltasInTx(ctx context.Context, data ocp_data.Provider, deltas ...*balance.Delta) error

ApplyDeltasInTx applies balance deltas to the ledger. It must be called within the DB transaction that commits the records the deltas are derived from, so the ledger can never disagree with them.

The ledger only tracks timelock accounts. Credits to any other account, like an external wallet or the fee collector, are dropped, since delta builders don't know which destinations OCP manages. Outgoing deltas from an account the ledger doesn't track are ErrUntrackedAccount, since funds only ever leave accounts OCP manages. An outgoing delta against a tracked account whose vault has unlocked fails loudly with balance.ErrAccountUnlocked: the record is no longer maintained, and a flow still taking funds out of it is a bug to surface, never to paper over. Credits are still applied, since an unlocked record is excluded from every read and turning one away only blocks the flow recording it.

A timelock account with no ledger record at all is balance.ErrRecordNotFound in either direction, since every one gets a record when it's opened.

Store predicate failures (balance.ErrInsufficientBalance, balance.ErrBalanceChanged, balance.ErrAccountClosed, balance.ErrAccountUnlocked) are returned as is for the caller to map.

func BatchCalculateFromCache added in v1.25.0

func BatchCalculateFromCache(ctx context.Context, data ocp_data.Provider, tokenAccounts ...*common.Account) (map[string]*Balance, error)

BatchCalculateFromCache is the default and recommended batch strategy for reliably estimating a set of token accounts' balances using cached values. Both values for an account come from the same ledger record read, so they are guaranteed consistent with each other.

Accounts the ledger doesn't manage are omitted from the result: those with no record, and those whose vault has unlocked. A caller that requires every account it asked for to be managed compares the result's length against its input.

Note: Use this method when calculating balances for accounts that are managed by Code (ie. Timelock account) and operate within the L2 system.

func BatchCalculateFromCacheByOwner added in v1.25.0

func BatchCalculateFromCacheByOwner(ctx context.Context, data ocp_data.Provider, owner *common.Account) (map[string]*Balance, error)

BatchCalculateFromCacheByOwner is the default and recommended strategy for reliably estimating the balance of every account an owner holds, keyed by token account. Each balance carries the mint its account holds, so a caller aggregating across mints doesn't need the account records to say which is which.

Accounts the ledger doesn't manage are omitted, as are owners it holds nothing for, so an owner outside the L2 system is an empty result rather than an error.

Note: Use this method when calculating balances for accounts that are managed by Code (ie. Timelock account) and operate within the L2 system.

func CalculateFromCache

func CalculateFromCache(ctx context.Context, data ocp_data.Provider, tokenAccount *common.Account) (uint64, error)

CalculateFromCache is the default and recommended strategy for reliably estimating a token account's balance using cached values.

The ledger record is the whole answer: it exists for exactly the accounts Code manages, and carries the lock state that says whether it still does. An account with no record, or one whose vault has unlocked, is ErrNotManagedByCode.

Note: Use this method when calculating balances for accounts that are managed by Code (ie. Timelock account) and operate within the L2 system.

func CreateRecordInTx added in v1.25.0

func CreateRecordInTx(ctx context.Context, data ocp_data.Provider, accountInfoRecord *account.Record) error

CreateRecordInTx creates the ledger record for a newly opened account. It must be called within the DB transaction that creates the account info record, so every timelock account has a record from the moment it exists.

It is a no-op for accounts that aren't timelock accounts, which the ledger doesn't track.

func DeltasForExternalDeposit added in v1.25.0

func DeltasForExternalDeposit(intentRecord *intent.Record) ([]*balance.Delta, error)

DeltasForExternalDeposit returns the ledger deltas for an external deposit intent, which is created by workers once funds are observed on chain. Only confirmed deposits are supported, since that's the only state workers commit; the funds are credited to the destination in full.

func DeltasForGiftCardAutoReturn added in v1.25.0

func DeltasForGiftCardAutoReturn(autoReturnIntent *intent.Record, autoReturnAction *action.Record) ([]*balance.Delta, error)

DeltasForGiftCardAutoReturn returns the ledger deltas for returning a gift card's funds to its issuer. The auto-return action is deferred at issuance and contributes nothing until the worker sets its quantity and commits the synthetic return intent, which is when this applies. The gift card is drained and closed, and the issued value is returned to the issuer.

func DeltasForSubmittedIntent added in v1.25.0

func DeltasForSubmittedIntent(intentRecord *intent.Record, actionRecords []*action.Record, withdrawalFeeQuarks uint64) ([]*balance.Delta, error)

DeltasForSubmittedIntent returns the ledger deltas for an intent and its actions as committed by SubmitIntent. Every account that funds move between gets a delta, and USD cost basis moves with the funds.

Actions without a quantity are deferred (eg. a gift card auto-return) and contribute nothing until the quantity is set, at which point the flow setting it is responsible for the delta.

USD cost basis is attributed per intent: the intent's USD market value is the gross amount leaving the source. A fee action carries the configured fee's USD value and the principal carries the remainder, so an intent may have at most one quantified principal action and at most one fee action. withdrawalFeeQuarks is the configured create-on-send withdrawal fee, in core mint quarks.

func DeltasForSwapSellReconciliation added in v1.25.0

func DeltasForSwapSellReconciliation(previous, updated *intent.Record, actionRecords []*action.Record) ([]*balance.Delta, error)

DeltasForSwapSellReconciliation returns the ledger deltas for reconciling a swap sell's funding payment to the value the sell actually realized. The funding payment was committed with an estimated USD market value that the swap worker later overwrites, so the source's cost basis is adjusted by the difference. No quarks move, and the swap destination isn't tracked by the ledger, so only the source is adjusted.

previous and updated are the funding intent before and after the worker reconciles its value. The actions are those of the funding intent, which identify the source.

func UsdCostBasisForIntent added in v1.25.0

func UsdCostBasisForIntent(intentRecord *intent.Record) (int64, error)

UsdCostBasisForIntent is the gross USD cost basis moved by an intent, in balance.UsdQuarksPerUnit.

Types

type Balance added in v1.25.0

type Balance struct {
	MintAccount  string
	Quarks       uint64
	UsdCostBasis int64
}

Balance is a token account's quark balance and USD cost basis, in balance.UsdQuarksPerUnit, alongside the mint it holds.

type Source

type Source uint8
const (
	UnknownSource Source = iota
	CacheSource
	BlockchainSource
)

func CalculateFromBlockchain

func CalculateFromBlockchain(ctx context.Context, data ocp_data.Provider, tokenAccount *common.Account) (uint64, Source, error)

CalculateFromBlockchain is the default and recommended strategy for reliably estimating a token account's balance from the blockchain. This strategy is resistant to various RPC failure nodes, and may return a cached value. The source of the balance calculation is returned.

Note: Use this method when calculating token account balances that are external and not managed by Code and outside the L2 system.

todo: add a batching variant

func (Source) String

func (s Source) String() string

Jump to

Keyboard shortcuts

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