Help us shape the future of Go! Take the 2026 Go Developer Survey

tbdb

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: MIT Imports: 20 Imported by: 0

README

tbdb

A wrapper for TigerBeetle database client Go with enhanced interfaces for currency handling, ledger management, and financial operations. Can be used standalone or as a Qore dependency.

Go Report Card

Features

  • Interface-based Architecture: Flexible Ledger and Amount interfaces for custom implementations
  • Built-in Currency Support: Pre-configured support for major currencies (USD, EUR, etc.) and cryptocurrencies (BTC, ETH, USDT)
  • High Performance: Optimized with sync.Pool, pre-computed scaling factors, and efficient Uint128 operations
  • Account Management: Simplified account creation with categories (Control, Balance, Income, Liabilities, Testing)
  • Transaction Support: Standard transfers, pending transfers, and resolution mechanisms
  • Statement Generation: Historical balances, transfer records, and account statements with custom enrichment
  • Batch Operations: Leverage TigerBeetle's high throughput with batch processing (up to 8,189 items)

Installation

Requirements:

  • Go 1.21+
  • TigerBeetle Cluster Release v0.16.57
go get github.com/qoinlyid/tbdb

Quick Start

Standalone Usage
package main

import (
  "log"
  "github.com/qoinlyid/tbdb"
)

func main() {
  // Create instance.
  instance := tbdb.New()

  // Open connection (new session).
  if err := instance.Open(); err != nil {
    log.Fatal(err)
  }
  defer func() { _ = instance.Close() }()

  // Create accounts with built-in category.
  result, err := instance.CreateAccountsWithCategory(
    tbdb.AccountCategoryBalance,
    tbdb.CreateAccount{
      Ledger: tbdb.USD,
      UserData128: tbdb.Uint128FromUint64(12345),
    },
  )
  if err != nil {
    log.Fatal(err)
  }

  // Create transfer.
  debitAccountID, err := tbdb.Uint128FromHex("198c8caa0ed1b230d56b39be8add93b")
  if err != nil {
    log.Fatal(err)
  }
  creditAccountID, err := tbdb.Uint128FromHex("198c8cbea858163e614bda026cc5848")
  if err != nil {
    log.Fatal(err)
  }
  transferResult, err := instance.CreateTransfers([]tbdb.TransferData{{
    DebitAccountID: debitAccountID,
    CreditAccountID: creditAccountID,
    Amount: tbdb.USD.NewAmountFromFloat64(150.00),
    Ledger: USD,
  }})
  // And much more...
}
As Qore Dependency
import "github.com/qoinlyid/tbdb"

type Module struct {
  Tbdb *tbdb.Instance
}

func InitModule() *Module {
  m := &Module{
    Tbdb: tbdb.New(),
  }
  // Another stuff...
  return m
}

// Open/Close handled automatically by Qore

Configuration

Configuration Reference
Key Description Default
TBDB_DEPENDENCY_PRIORITY Dependency priority for open/close order 10
TBDB_CLUSTER_ID TigerBeetle cluster ID 0
TBDB_ADDRESSES TigerBeetle node addresses (comma-separated for multi node replica) ""
Configuration Files

You can use OS environment variables, dotenv file .env, .json file, .toml file or .yaml file. Example file:

JSON Example (.json):

{
  "TBDB_CLUSTER_ID": 1,
  "TBDB_ADDRESSES": "127.0.0.1:3000"
}

YAML Example (.yaml):

TBDB_CLUSTER_ID: 1
TBDB_ADDRESSES: "127.0.0.1:3000"

Environment file (.env):

TBDB_CLUSTER_ID=1
TBDB_ADDRESSES=127.0.0.1:3000

To use a specific config file (Standalone mode):

os.Setenv("QORE_CONFIG_USED", "./.env.json")
cache := cache.New()

API Reference

Currencies

Built-in currencies with proper decimal handling:

// Fiat currencies
tbdb.USD  // 2 decimals
tbdb.SGD  // 2 decimals
tbdb.IDR  // 2 decimals

// Cryptocurrencies  
tbdb.BTC  // 8 decimals
tbdb.ETH  // 18 decimals
tbdb.USDT // 6 decimals

// Custom currency
cur, err := tbdb.NewCurrency("DOGE", 8)
Amount Operations
// Create amount
amount := tbdb.USD.NewAmountFromFloat64(1000.50)

// Operations
sum, err := amount.Add(otherAmount)
diff, err := amount.Sub(otherAmount) 
scaled, err := amount.Mul(1.5)
portion, err := amount.Percentage(10) // 10% = 100.05

// Comparisons
if amount.GreaterThan(minimum) {
  // Process payment
}

// Formatting
fmt.Println(amount.Uint128ToString()) // "USD 1,000.50"
Account Categories

Pre-defined categories with appropriate flags:

  • AccountCategoryControl: System account to used as controll account for source/destination accounts (History flag)
  • AccountCategoryBalance: Asset accounts (History + DebitsMustNotExceedCredits)
  • AccountCategoryIncome: Revenue accounts (History + DebitsMustNotExceedCredits)
  • AccountCategoryLiabilities: Liability accounts (History flag)
  • AccountCategoryTesting: Test accounts (no flags)
Transfers
// Standard transfer
instance.CreateTransfers([]tbdb.TransferData
  DebitAccountID:  fromAccount
  CreditAccountID: toAccount
  Amount:         amount
  Ledger:         tbdb.USD,
}})

// Pending transfer (2-phase commit)
code := 1
linked := true
instance.CreatePendingTransfers(transfers, linked, code)

// Resolve pending
instance.ResolvePendingTransfers([]tbdb.PendingTransfer{{
  PendingID: pendingID,
  Amount:    finalAmount,
  State:     tbdb.ResolvePendingStatePost, // or StateVoid
}})
Querying
// Account lookup
accounts, err := instance.LookupAccounts([]tbdb.AccountLookup{{
  ID:       accountID,
  Monetary: tbdb.USD.NewMonetary(),
}})

// Historical data
filter := tbdb.AccountTransferFilter{
  AccountID: accountID,
  TimeMin:   startTime,
  TimeMax:   endTime,
  Monetary:  tbdb.USD.NewMonetary(),
  Limit:     100,
}

balances, err := instance.GetHistoricalBalances(filter)
transfers, err := instance.GetAccountTransfers(filter)
statements, err := instance.GetAccountStatements(filter, enrichmentFunc)

Custom Implementations

Custom Ledger
type CustomLedger struct {
  category string
  version  uint8
}

func (l *CustomLedger) EncodeLedger() tbdb.LedgerCode {
  // Your encoding logic...
  return tbdb.LedgerCode(encoded)
}

func (l *CustomLedger) DecodeLedger() string {
  return fmt.Sprintf("category=%s, version=%d", l.category, l.version)
}
Custom Amount
type TokenAmount struct {
  decimals uint8
  symbol   string
}

func (t *TokenAmount) Float64ToUint128() (tbdb.Uint128, error) {
  // Custom conversion logic...
}

func (t *TokenAmount) Uint128ToString() string {
  // Custom formatting...
}

// Implement remaining Amount interface methods...

Performance Optimizations

  • Object Pooling: Reuses big.Int, big.Float, and strings.Buildere instances
  • Pre-computed Scales: O(1) lookup for decimal scaling factors
  • Fast Paths: Optimized paths for uint64-sized values
  • Batch Processing: Process up to 8,189 items in a single operation
  • Efficient Uint128: Custom implementation avoiding unnecessary heap allocations.

Error Handling

The package provides detailed error types:

var
  ErrClientNil                  // TigerBeetle client not
  ErrMonetaryMustNotBeNil       // Missing monetary
  ErrExceedsMaxTigerBeetleBatch // Batch size > 8,
  ErrNegativeOrNilBigInt        // Invalid amount value
  // ... more specific errors
)

Documentation

Overview

Package tbdb is TigerBeetle DB client wrapper with enchanced methods. This package can be as standalone usage or as a Qore dependency.

Qore dependency usage

Instance should embed on Qore module:

type Module struct {
	Tbdb *tbdb.Instance
}

func InitModule() *Module {
	m := &Module{
		Tbdb: tbdb.New()
	}

	return m
}

Then, Open & Close instance & connection will be handled automatically by Qore.

Standalone

You can use this package as a standalone Go package to suit your needs. You can place the Instance pointer as a singleton anywhere you like.

instance := tbdb.New()
if err := instance.Open(); err != nil {
	log.Fatal(err)
}
defer func() { _ = instance.Close() }()

The only thing that you must be aware is, the Open-Close should be in that order.

Package tbdb Code generated by github.com/qoinlyid/qore; DO NOT EDIT. Code generated by github.com/qoinlyid/qore; DO NOT EDIT. Code generated by github.com/qoinlyid/qore; DO NOT EDIT.

Index

Constants

View Source
const TigerBeetleMaxBatch uint16 = 8189

Variables

View Source
var (
	ErrOpenTBConnection    = errors.New("failed to open TigerBeetle connection")
	ErrClientNil           = errors.New("client TigeBeetle is nil")
	ErrInvalidLength       = errors.New("invalid length")
	ErrHexTooLong          = errors.New("hex too long")
	ErrNegativeOrNilBigInt = errors.New("negative or nil big.Int")
	ErrBigIntOverflow      = errors.New("big.Int overflows")

	// Operations.
	ErrMonetaryMustNotBeNil       = errors.New("account monetary must not be nil")
	ErrUnknownCategory            = errors.New("unknown account category")
	ErrCurrencyAmountMismatch     = errors.New("currency mismatch")
	ErrExceedsMaxTigerBeetleBatch = fmt.Errorf("exceeds maximum batch size %d", TigerBeetleMaxBatch)
	ErrAccountIDMustNotBeZero     = errors.New("account id must not be zero")
	ErrAccountIDMustNotBeIntMax   = errors.New("account id must not be 2^128 - 1")
	ErrTimeMinMustNotBeZero       = errors.New("account transfer filter time min must not be zero")
	ErrTimeMaxMustNotBeZero       = errors.New("account transfer filter time max must not be zero")
)
View Source
var (
	// Vietnamese Dong (no decimals).
	VND *currency = newCurrency("VND", 0)
	// Indonesian Rupiah.
	IDR *currency = newCurrency("IDR", 2)
	// Malaysian Ringgit.
	MYR *currency = newCurrency("MYR", 2)
	// Singapore Dollar.
	SGD *currency = newCurrency("SGD", 2)
	// Thai Baht.
	THB *currency = newCurrency("THB", 2)
	// Philippine Peso.
	PHP *currency = newCurrency("PHP", 2)
	// US Dollar.
	USD *currency = newCurrency("USD", 2)
	// Euro.
	EUR *currency = newCurrency("EUR", 2)

	// Tether (6 decimals).
	USDT *currency = newCurrency("USDT", 6)
	// Bitcoin (8 decimals).
	BTC *currency = newCurrency("BTC", 8)
	// Binance Coin (12 decimals).
	BNB *currency = newCurrency("BNB", 12)
	// Ethereum (18 decimals).
	ETH *currency = newCurrency("ETH", 18)
)

Built-in currencies with their decimal precision.

Functions

func NewCurrency

func NewCurrency(code string, decimal uint8) (*currency, error)

NewCurrency creates a new currency with validation. Returns error if code length or decimal precision is invalid.

cur, err := tbdb.NewCurrency("DOGE", 8)
if err != nil {
	log.Println(err)
}

Types

type Account

type Account struct {
	// ID is unique account identifier.
	ID Uint128
	// DebitsPending.
	DebitsPending Amount
	// DebitsPosted.
	DebitsPosted Amount
	// CreditsPending.
	CreditsPending Amount
	// CreditsPosted.
	CreditsPosted Amount
	// UserData128 is 128-bit user-defined data.
	UserData128 Uint128
	// UserData64 is 64-bit user-defined data.
	UserData64 uint64
	// UserData32 is 32-bit user-defined data.
	UserData32 uint32
	// Reserved may be used for additional data in the future.
	Reserved uint32
	// Ledger this account belongs to.
	Ledger uint32
	// Code is account type code.
	Code uint16
	// Flags is account behavior flags.
	Flags AccountFlags
	// Timestamp is account creation timestamp.
	Timestamp uint64
}

Account defines TigerBeetle's account.

type AccountBalance

type AccountBalance struct {
	// This is the time the account balance was updated, as nanoseconds since UNIX epoch.
	// The timestamp refers to the same Transfer.timestamp which changed the Account.
	Timestamp uint64
	// Amount of pending debits.
	DebitsPending Amount
	// Amount of posted debits.
	DebitsPosted Amount
	// Amount of pending credits.
	CreditsPending Amount
	// Amount of posted credits.
	CreditsPosted Amount
}

AccountBalance defines account's balance record.

type AccountCategory

type AccountCategory uint16

AccountCategory defines account category that underlying the TigerBeetle's account code.

const (
	// Account category used for account that is source and/or destination.
	AccountCategoryControl AccountCategory = 1000
	// Account category used for account that is asset account & respected 'DebitsMustNotExceedCredits' flags.
	AccountCategoryBalance AccountCategory = 1001
	// Account category used for account that is income account & respected 'DebitsMustNotExceedCredits' flags.
	AccountCategoryIncome AccountCategory = 1002
	// Account category used for account that is liabilities account.
	AccountCategoryLiabilities AccountCategory = 1003
	// Account category used for account that is testing account.
	AccountCategoryTesting AccountCategory = 9999
)

Enum of account category.

type AccountEventResult

type AccountEventResult struct {
	// Index of the account in the original request.
	Index uint32
	// ID is unique account identifier (auto-generated if zero).
	ID Uint128
	// Result is creation result status.
	Result CreateAccountResult
	// Err is error creation.
	Err error
}

AccountEventResult defines result data for create single account event.

type AccountEventResults

type AccountEventResults struct {
	// Create account success & failed count.
	SuccessCount, FailedCount int
	// Silce of each result.
	Results []AccountEventResult
}

AccountEventResults defines result data for create many account event.

type AccountFilterFlags

type AccountFilterFlags struct {
	Debits   bool
	Credits  bool
	Reversed bool
}

func (AccountFilterFlags) ToUint32

func (f AccountFilterFlags) ToUint32() uint32

type AccountFlags

type AccountFlags struct {
	Linked                     bool
	DebitsMustNotExceedCredits bool
	CreditsMustNotExceedDebits bool
	History                    bool
	Imported                   bool
	Closed                     bool
}

func (AccountFlags) String

func (f AccountFlags) String() string

func (AccountFlags) ToUint16

func (f AccountFlags) ToUint16() uint16

type AccountLookup

type AccountLookup struct {
	// ID is unique account identifier.
	ID Uint128
	// Monetary represent account monetary type.
	Monetary Amount
}

AccountLookup defines lookup account parameters.

type AccountStatement

type AccountStatement struct {
	// ID is unique account identifier.
	ID Uint128
	// DebitAccountID is debit account id.
	DebitAccountID Uint128
	// CreditAccountID is credit account id.
	CreditAccountID Uint128
	// Debit is the monetary amount for debit transfer.
	Debit Amount
	// Credit is the monetary amount for credit transfer.
	Credit Amount
	// BalanceBefore is the monetary of balance before.
	BalanceBefore Amount
	// BalanceAfter is the monetary of balance after.
	BalanceAfter Amount
	// UserData128 is 128-bit user-defined data.
	UserData128 Uint128
	// UserData64 is 64-bit user-defined data.
	UserData64 uint64
	// Timestamp is the time transfer was created; in nanoseconds since UNIX epoch.
	Timestamp uint64
	// UserData32 is 32-bit user-defined data.
	UserData32 uint32
	// Ledger this account belongs to.
	Ledger uint32
	// This is a user-defined enum denoting the reason for (or category of) the transfer.
	Code uint16
	// Flags defines the behavior of transfer.
	Flags TransferFlags
	// Additional is user-defined data that be writen by given closure.
	Additional any
}

AccountStatement defines account's statement record.

type AccountTransfer

type AccountTransfer struct {
	// ID is unique account identifier.
	ID Uint128
	// DebitAccountID is debit account id.
	DebitAccountID Uint128
	// CreditAccountID is credit account id.
	CreditAccountID Uint128
	// PendingID reference to pending transfer id.
	PendingID Uint128
	// Amount is the monetary amount.
	Amount Amount
	// UserData128 is 128-bit user-defined data.
	UserData128 Uint128
	// UserData64 is 64-bit user-defined data.
	UserData64 uint64
	// Timestamp is the time transfer was created; in nanoseconds since UNIX epoch.
	Timestamp uint64
	// UserData32 is 32-bit user-defined data.
	UserData32 uint32
	// Timeout is the interval of pending transfer; in seconds
	Timeout uint32
	// Ledger this account belongs to.
	Ledger uint32
	// This is a user-defined enum denoting the reason for (or category of) the transfer.
	Code uint16
	// Flags defines the behavior of transfer.
	Flags TransferFlags
}

AccountTransfer defines account's transfer record.

type AccountTransferFilter

type AccountTransferFilter struct {
	// The minimum transfer time from which results will be returned, inclusive range; required.
	TimeMin time.Time
	// The maximum transfer time from which results will be returned, inclusive range. Required
	TimeMax time.Time
	// AccountID is unique identifier of account. Required or must not be zero.
	AccountID Uint128
	// Filter the results by 128-bit user-defined data on transfer event.
	// Optional; set to zero to disable the filter
	UserData128 Uint128
	// Filter the results by 64-bit user-defined data on transfer event.
	// Optional; set to zero to disable the filter
	UserData64 uint64
	// Filter the results by 32-bit user-defined data on transfer event.
	// Optional; set to zero to disable the filter
	UserData32 uint32
	// The maximum number of results that can be returned by this query.
	Limit uint32
	// Filter the results by Transfer.code.
	// Optional; set to zero to disable the filter
	Code uint16
	// Monetary represent account monetary type; required.
	Monetary Amount
	// To specifies querying behavior.
	Flags AccountFilterFlags
}

AccountTransferFilter defines filter account transfer parameters.

type Amount

type Amount interface {
	// SetUint128Value sets Uint128 value to the monetary.
	SetUint128Value(val Uint128) Amount

	// SetFloat64Value sets float64 value to the monetary.
	SetFloat64Value(val float64) Amount

	// Float64ToUint128 converts a human-readable float64 to TigerBeetle's Uint128 format.
	// Implementation should handle scaling and precision according to the specific
	// monetary unit's requirements (e.g., decimal places, rounding rules).
	Float64ToUint128() (Uint128, error)

	// ToUint128FromValue returns Uint128 valu type depends on value that has been set.
	ToUint128FromValue() Uint128

	// Uint128ToFloat64 converts TigerBeetle's Uint128 back to human-readable float64.
	// Implementation should reverse the scaling applied in Float64ToUint128.
	Uint128ToFloat64() float64

	// Uint128ToString formats a Uint128 amount as a human-readable string.
	// Implementation can define custom formatting rules (currency symbols,
	// thousand separators, decimal precision, etc.).
	Uint128ToString() string

	// Add safely adds two Uint128 amounts.
	// Returns error if the operation would cause overflow or violates
	// implementation-specific constraints.
	Add(b Uint128) (Uint128, error)

	// Sub safely subtracts b from a.
	// Returns error if the result would be invalid according to
	// implementation rules (e.g., negative amounts not allowed).
	Sub(b Uint128) (Uint128, error)

	// Mul multiplies an amount by a floating-point multiplier.
	// Implementation should handle precision and rounding according to
	// the monetary unit's requirements.
	Mul(multiplier float64) (Uint128, error)

	// Div divides an amount by a floating-point divisor.
	// Implementation should handle division precision and edge cases
	// (zero divisor, infinity, NaN) according to its requirements.
	Div(divisor float64) (Uint128, error)

	// Percentage calculates a percentage of the given amount.
	// Implementation should define how percentage calculation and rounding
	// are handled for the specific monetary unit.
	Percentage(percent float64) (Uint128, error)

	// Compare compares two Uint128 amounts according to implementation rules.
	// Returns:
	//	- -1 if a < b
	//	- 0 if a == b
	//	- 1 if a > b
	Compare(b Uint128) int

	// IsZero checks if the amount represents zero value according to
	// implementation-defined zero semantics.
	IsZero() bool

	// Equal checks if two amounts are considered equal by the implementation.
	Equal(b Uint128) bool

	// GreaterThan checks if a > b according to implementation comparison rules.
	GreaterThan(b Uint128) bool

	// GreaterThanOrEqual checks if a >= b according to implementation comparison rules.
	GreaterThanOrEqual(b Uint128) bool

	// LessThan checks if a < b according to implementation comparison rules.
	LessThan(b Uint128) bool

	// LessThanOrEqual checks if a <= b according to implementation comparison rules.
	LessThanOrEqual(b Uint128) bool

	// Min returns the smaller of two amounts according to implementation comparison rules.
	Min(b Uint128) Uint128

	// Max returns the larger of two amounts according to implementation comparison rules.
	Max(b Uint128) Uint128
}

Amount defines the interface for monetary amount operations and conversions. Implementers can define custom scaling, precision, and formatting rules while maintaining compatibility with TigerBeetle's Uint128 amount type. This allows for different currency systems, token standards, or custom monetary units.

type Config

type Config struct {
	// DependencyPriority defines priority of cache dependency.
	DependencyPriority int `json:"TBDB_DEPENDENCY_PRIORITY" mapstructure:"CACHE_DEPENDENCY_PRIORITY"`

	// ClusterID defines TigerBeetle cluster id.
	ClusterID uint64 `json:"TBDB_CLUSTER_ID" mapstructure:"TBDB_CLUSTER_ID"`

	// Addresses defines TigerBeetle nodes address. Use comma separated to set multi nodes.
	Addresses string `json:"TBDB_ADDRESSES" mapstructure:"TBDB_ADDRESSES"`
	// contains filtered or unexported fields
}

Config defines Cache config.

type CreateAccount

type CreateAccount struct {
	// ID is unique account identifier (auto-generated if zero).
	ID Uint128
	// UserData128 is 128-bit user-defined data.
	UserData128 Uint128
	// UserData64 is 64-bit user-defined data.
	UserData64 uint64
	// UserData32 is 32-bit user-defined data.
	UserData32 uint32
	// Ledger this account belongs to.
	Ledger Ledger
}

CreateAccount defines account argument for create single account event.

type CreateAccountResult

type CreateAccountResult = types.CreateAccountResult

CreateAccountResult represents the result of account creation operations.

type CreateAccounts

type CreateAccounts struct {
	CreateAccount

	// Code is account type code.
	Code uint16
	// Flags is account behavior flags.
	Flags AccountFlags
	// Timestamp is account creation timestamp.
	Timestamp uint64
}

CreateAccounts defines account argument for create many account event.

type CreateTransferResult

type CreateTransferResult = types.CreateTransferResult

CreateTransferResult represents the result of transfer creation operations.

type Instance

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

Instance defines TigerBeetle DB dependency singleton.

func New

func New() *Instance

New creates singleton dependency instance.

func (*Instance) Client

func (i *Instance) Client() (tb.Client, error)

Client returns TigerBeetle client interface.

func (*Instance) Close

func (i *Instance) Close() error

Close an backend connection or destruct the dependency.

func (*Instance) CreateAccount

func (i *Instance) CreateAccount(account CreateAccount, code uint16, flags AccountFlags) (AccountEventResult, error)

CreateAccount creates single TigerBeetle's account. This is simple method to just create a single account. Use 'CreateAccountBatch' to take advantage for high throughput instead.

func (*Instance) CreateAccountBatch

func (i *Instance) CreateAccountBatch(accounts []CreateAccounts) (AccountEventResults, error)

CreateAccountBatch wraps TigerBeetle's CreateAccounts method to create one or many account(s).

func (*Instance) CreateAccountsWithCategory

func (i *Instance) CreateAccountsWithCategory(category AccountCategory, accounts ...CreateAccount) (AccountEventResults, error)

CreateAccountsWithCategory creates TigerBeetle's account with built-in category from this tbdb package. It will return 'ErrUnknownCategory' if given category is unknown. Some built-in category have their respected account flags, as shown on the list bellow:

  • AccountCategoryControl: History
  • AccountCategoryBalance: History, DebitsMustNotExceedCredits
  • AccountCategoryIncome: History, DebitsMustNotExceedCredits
  • AccountCategoryTesting: None

func (*Instance) CreatePendingTransfers

func (i *Instance) CreatePendingTransfers(
	transfers []TransferData,
	linked bool,
	code uint16,
) (TransferEventResults, error)

CreatePendingTransfers .

func (*Instance) CreateTransfers

func (i *Instance) CreateTransfers(transfers []TransferData) (TransferEventResults, error)

CreateTransfers .

func (*Instance) GetAccountStatements

func (i *Instance) GetAccountStatements(
	filter AccountTransferFilter,
	closureFn ...StatementClosureFn,
) ([]AccountStatement, error)

GetAccountStatements fetchs the account statements record involving a given account The max size of AccountStatement array result is equal to TigerBeetleMaxBatch, even the filter.Limit set to > TigerBeetleMaxBatch.

func (*Instance) GetAccountTransfers

func (i *Instance) GetAccountTransfers(filter AccountTransferFilter) ([]AccountTransfer, error)

GetAccountTransfers fetchs the transfers record involving a given account. The max size of AccountTransfer array result is equal to TigerBeetleMaxBatch, even the filter.Limit set to > TigerBeetleMaxBatch.

func (*Instance) GetHisotricalBalances

func (i *Instance) GetHisotricalBalances(filter AccountTransferFilter) ([]AccountBalance, error)

GetHisotricalBalances fetchs the historical account balances. The max size of AccountBalance array result is equal to TigerBeetleMaxBatch, even the filter.Limit set to > TigerBeetleMaxBatch.

func (*Instance) HealthCheck

func (i *Instance) HealthCheck(ctx context.Context) *qore.DependencyStats

HealthCheck returns statistics for dependency health check.

func (*Instance) LookupAccounts

func (i *Instance) LookupAccounts(lookups []AccountLookup) ([]Account, error)

LookupAccounts fetchs one or more accounts by their ids alongside the monetary.

func (*Instance) Name

func (i *Instance) Name() string

Code generated by github.com/qoinlyid/qore; DO NOT EDIT. Name returns dependency name.

func (*Instance) Open

func (i *Instance) Open() error

Open an backend connection or construct the dependency.

func (*Instance) Priority

func (i *Instance) Priority() int

Code generated by github.com/qoinlyid/qore; DO NOT EDIT. Priority returns dependency open-close priority.

func (*Instance) ResolvePendingTransfers

func (i *Instance) ResolvePendingTransfers(pendings []PendingTransfer) (TransferEventResults, error)

ResolvePendingTransfers resolves pending transfers based on given state, either its posted or voided.

type Ledger

type Ledger interface {
	// EncodeLedger generates a unique LedgerCode for TigerBeetle.
	// The code combines currency properties into a deterministic identifier.
	EncodeLedger() LedgerCode

	// DecodeLedger converts the LedgerCode back to human-readable format.
	// Returns a formatted string describing the currency and its properties.
	DecodeLedger() string
}

Ledger defines the interface for encoding and decoding ledger codes. Used to generate unique identifiers for TigerBeetle ledgers based on currency properties.

type LedgerCode

type LedgerCode uint32

type PendingTransfer

type PendingTransfer struct {
	// ID is unique account identifier (auto-generated if zero).
	ID Uint128
	// Pending transfer id that must reference to transfer id with pending state & required.
	PendingID Uint128
	// Amount that want to resolved from pending transfer.
	//
	// For post-pending state:
	//	- Amount less than actual pending transfer amount, then only this amount is posted & the remainder
	//	is restored to its original account.
	//	- Amount equal to actual pending transfer amount, then full pending amount will be posted
	//	- Amount greater than actual pending transfer amount, then will be failed.
	//
	// For void-pending state: Amount can be zero value.
	Amount Amount
	// UserData32 is 32-bit user-defined data.
	UserData32 uint32
	// State is type of resolve, either will posted or voided.
	State ResolvePendingState
}

PendingTransfer defines pending transfer data that want to resolved by TigerBeetle's transfer event.

type ResolvePendingState

type ResolvePendingState uint8
const (
	ResolvePendingStatePost ResolvePendingState = 1
	ResolvePendingStateVoid ResolvePendingState = 2
)

type StatementClosureFn

type StatementClosureFn func(
	id, userData128 Uint128,
	userData64 uint64,
	userData32 uint32,
	code uint16,
	flags TransferFlags,
	timestamp uint64,
) any

StatementClosureFn is closure function of statement.

type Transfer

type Transfer = types.Transfer

type TransferData

type TransferData struct {
	// ID is unique account identifier (auto-generated if zero).
	ID Uint128
	// DebitAccountID is debit account id, required.
	DebitAccountID Uint128
	// CreditAccountID is credit account id, required.
	CreditAccountID Uint128
	// Amount must be greater than 0.
	Amount Amount
	// UserData128 is 128-bit user-defined data.
	UserData128 Uint128
	// UserData64 is 64-bit user-defined data.
	UserData64 uint64
	// UserData32 is 32-bit user-defined data.
	UserData32 uint32
	// Ledger this account belongs to.
	Ledger Ledger
	// contains filtered or unexported fields
}

TransferData defines transfer argument for create TigerBeetle's transfer event.

type TransferEventResult

type TransferEventResult struct {
	// Index of the transfer in the original request.
	Index uint32
	// ID is unique transfer identifier (auto-generated if zero).
	ID Uint128
	// Result is creation result status.
	Result CreateTransferResult
	// Err is error creation.
	Err error
}

TransferEventResult defines result data for create transfer event.

type TransferEventResults

type TransferEventResults struct {
	// Create transfer success & failed count.
	SuccessCount, FailedCount int
	// Silce of each result.
	Results []TransferEventResult
}

TransferEventResults defines result data for create transfer batch event.

type TransferFlags

type TransferFlags struct {
	Linked              bool
	Pending             bool
	PostPendingTransfer bool
	VoidPendingTransfer bool
	BalancingDebit      bool
	BalancingCredit     bool
	ClosingDebit        bool
	ClosingCredit       bool
	Imported            bool
}

func (TransferFlags) String

func (f TransferFlags) String() string

func (TransferFlags) ToUint16

func (f TransferFlags) ToUint16() uint16

type Uint128

type Uint128 struct {
	Hi uint64
	Lo uint64
}

Uint128 represents a 128-bit number with two 64-bit parts.

func NewID

func NewID() Uint128

NewID generates a unique ID from the TigerBeetle binding.

func SafeNewID

func SafeNewID() (id Uint128, err error)

SafeNewID calls NewID but wrapped up with panic recover.

func Uint128FromBigInt

func Uint128FromBigInt(b *big.Int) (Uint128, error)

Uint128FromBigInt converts a non-negative big.Int < 2^128 to Uint128.

func Uint128FromBytesLE

func Uint128FromBytesLE(b []byte) (Uint128, error)

Uint128FromBytesLE constructs Uint128 from 16-byte little-endian slice.

func Uint128FromHex

func Uint128FromHex(s string) (Uint128, error)

Uint128FromHex decodes a hex string (big-endian, up to 32 chars) into Uint128.

func Uint128FromParts

func Uint128FromParts(hi, lo uint64) Uint128

Uint128FromParts constructs Uint128 from hi and lo parts.

func Uint128FromUint64

func Uint128FromUint64(v uint64) Uint128

Uint128FromUint64 constructs Uint128 from a uint64 value.

func (Uint128) AppendHex

func (u Uint128) AppendHex(dst []byte) []byte

AppendHex appends Uint128 hex string to dst.

func (Uint128) BigInt

func (u Uint128) BigInt() *big.Int

BigInt returns a big.Int representation (heap allocation).

func (Uint128) BytesLE

func (u Uint128) BytesLE() [16]byte

BytesLE returns 16-byte little-endian representation.

func (Uint128) Compare

func (u Uint128) Compare(v Uint128) int

Compare compares two Uint128 values: -1 if u<v, 0 if u==v, 1 if u>v.

func (Uint128) Hex

func (u Uint128) Hex() string

Hex returns big-endian hex string without leading zeros.

func (Uint128) IsZero

func (u Uint128) IsZero() bool

IsZero returns true if Uint128 is zero.

func (Uint128) MarshalJSON

func (u Uint128) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler as string to avoid precision issues.

func (Uint128) MarshalText

func (u Uint128) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Uint128) String

func (u Uint128) String() string

String implements fmt.Stringer by delegating to Hex.

func (*Uint128) UnmarshalJSON

func (u *Uint128) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Uint128) UnmarshalText

func (u *Uint128) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

Jump to

Keyboard shortcuts

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