{"modulePath":"github.com/devaccuracy/ledgerforge","version":"v1.0.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package model\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2026 LedgerForge Contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nCopyright 2024 Blnk Finance Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n## Constants\n\n```go\nconst (\n\tOutboxStatusPending    = \"pending\"\n\tOutboxStatusProcessing = \"processing\"\n\tOutboxStatusCompleted  = \"completed\"\n\tOutboxStatusFailed     = \"failed\"\n)\n```\nOutbox status constants\n\n```go\nconst (\n\tLineageTypeCredit       = \"credit\"\n\tLineageTypeDebit        = \"debit\"\n\tLineageTypeBoth         = \"both\"\n\tLineageTypeShadowCommit = \"shadow_commit\"\n\tLineageTypeShadowVoid   = \"shadow_void\"\n)\n```\nLineage type constants\n\n```go\nconst (\n\tPreviewRoleSource      = \"source\"\n\tPreviewRoleDestination = \"destination\"\n)\n```\nBalance roles reported by a projection.\n\n```go\nconst ChainGenesisHash = \"0000000000000000000000000000000000000000000000000000000000000000\"\n```\nChainGenesisHash is the starting head of the transaction hash chain — 64 zeros. ledgerforge.chain\\_state.head\\_hash begins here.\n\n```go\nconst RefundReferenceSuffix = \"_refund\"\n```\nRefundReferenceSuffix is appended to the original transaction id to form the refund transaction's reference (see ledgerforge.io/docs/reference/refund-transaction).\n\n## Functions\n\n```go\nfunc ApplyPrecision(transaction *Transaction) *big.Int\n```\nApplyPrecision handles both operations involving precision: 1. If PreciseAmount exists: converts it to a decimal Amount 2. If Amount exists: converts it to a PreciseAmount This function is now a wrapper that sets default precision if needed and calls applyPrecisionLogic.\n\n```go\nfunc ApplyPrecisionChecked(transaction *Transaction) (*big.Int, error)\n```\nApplyPrecisionChecked validates monetary inputs before changing them.\n\n```go\nfunc ApplyPrecisionWithDBLookup(transaction *Transaction, db *sql.DB) *big.Int\n```\nApplyPrecisionWithDBLookup is retained for compatibility. Lookup failures return nil; callers needing the cause should use the checked variant.\n\n```go\nfunc ApplyPrecisionWithDBLookupChecked(transaction *Transaction, db *sql.DB) (*big.Int, error)\n```\nApplyPrecisionWithDBLookupChecked resolves precision authoritatively without process-global state. API callers use their injected datasource instead.\n\n```go\nfunc ApplyRate(preciseAmount *big.Int, rate float64) *big.Int\n```\nApplyRate applies the exchange rate to the precise amount and returns a \\*big.Int. The rate is applied after precision to maintain accuracy.\n\n```go\nfunc CalculateDistributionsPrecise(ctx context.Context, totalPreciseAmount *big.Int, distributions []Distribution, precision int64) (map[string]*big.Int, error)\n```\nCalculateDistributionsPrecise parses components exactly, truncates fractional minor units, then assigns the remainder to the largest allocation. Equal allocations are ordered lexicographically by identifier. This preserves the existing allocation policy while making every split conserve its total.\n\n```go\nfunc CanonicalChainV2(prevHash string, r ChainRow) []byte\n```\nCanonicalChainV2 is a domain-separated, length-delimited encoding. Each length is an unsigned big-endian uint64 byte count. Numeric text retains its exact stored representation; timestamps denote UTC instants. Mutable metadata is intentionally excluded from the financial commitment.\n\n```go\nfunc CanonicalChainV3(prevHash string, r ChainRow) []byte\n```\nCanonicalChainV3 retains the exact v2 payload and adds immutable execution evidence under a new domain version. V1 and v2 remain byte-for-byte stable.\n\n```go\nfunc ComputeChainHash(prevHash string, r ChainRow) string\n```\nComputeChainHash is the v1 encoding, retained for older-format verification. New seals use ComputeChainHashVersion with canonical version 3.\n\n```go\nfunc ComputeChainHashVersion(version int, prevHash string, r ChainRow) (string, error)\n```\nComputeChainHashVersion verifies explicitly supplied v1/v2 records and v3 seals.\n\n```go\nfunc DecodeTransactionMetadata(data []byte, t *Transaction) error\n```\nDecodeTransactionMetadata consumes the private SQL projection of immutable controls. The marker is removed before metadata leaves the database layer.\n\n```go\nfunc GenerateKey() (string, error)\n```\nGenerateKey creates a new secure API key\n\n```go\nfunc GenerateUUIDWithSuffix(module string) string\n```\nGenerateUUIDWithSuffix generates a UUID with a given module name as a suffix. This is useful for creating unique identifiers with context-specific prefixes.\n\n```go\nfunc Int64ToBigInt(value int64) *big.Int\n```\nInt64ToBigInt converts an int64 value to a \\*big.Int. This is useful for handling large numbers in computations such as financial transactions.\n\n```go\nfunc ParseAmount(amount string, precision float64) (*big.Int, error)\n```\nParseAmount parses a major-unit decimal exactly and rounds to the nearest minor unit, with halves away from zero. Positive amounts rounding to zero are rejected. Use precise\\_amount for integer amounts beyond float64 accuracy.\n\n```go\nfunc PrecisionBankersRound(num float64, precision float64) float64\n```\nPrecisionBankersRound applies banker's rounding (round half to even) at the given precision scale factor.\n\n```go\nfunc RefundReference(originalTransactionID string) string\n```\nRefundReference returns the canonical reference for a refund of originalTransactionID.\n\n```go\nfunc UpdateBalances(transaction *Transaction, source, destination *Balance) error\n```\nUpdateBalances updates the balances for both the source and destination based on the transaction details. It ensures precision is applied and checks for overdraft before updating.\n\n```go\nfunc ValidateCustomerTransactionMetadata(metadata map[string]interface{}) error\n```\nValidateCustomerTransactionMetadata protects execution, lineage and internal recovery/policy bookkeeping while leaving arbitrary customer keys mutable.\n\n```go\nfunc ValidatePrecision(precision float64) error\n```\nValidatePrecision accepts a finite positive integer scale. Zero means the existing default scale of one; stored precisions must be positive.\n\n## Types\n\n```go\ntype APIKey struct {\n\tAPIKeyID   string     `json:\"api_key_id\" db:\"api_key_id\"`\n\tKey        string     `json:\"key\" db:\"key\"`\n\tName       string     `json:\"name\" db:\"name\"`\n\tOwnerID    string     `json:\"owner_id\" db:\"owner_id\"`\n\tScopes     []string   `json:\"scopes\" db:\"scopes\"`\n\tExpiresAt  time.Time  `json:\"expires_at\" db:\"expires_at\"`\n\tCreatedAt  time.Time  `json:\"created_at\" db:\"created_at\"`\n\tLastUsedAt time.Time  `json:\"last_used_at\" db:\"last_used_at\"`\n\tIsRevoked  bool       `json:\"is_revoked\" db:\"is_revoked\"`\n\tRevokedAt  *time.Time `json:\"revoked_at,omitempty\" db:\"revoked_at\"`\n\n\tParentAPIKeyID string `json:\"parent_api_key_id,omitempty\" db:\"parent_api_key_id\"`\n}\n```\n\n```go\nfunc NewAPIKey(name, ownerID string, scopes []string, expiresAt time.Time) (*APIKey, error)\n```\nNewAPIKey creates a new API key instance\n\n```go\nfunc (k *APIKey) HasScope(scope string) bool\n```\nHasScope checks if the API key has the required scope\n\n```go\nfunc (k *APIKey) IsValid() bool\n```\nIsValid checks if the API key is valid\n\n```go\ntype Account struct {\n\tAccountID  string                 `json:\"account_id\"`\n\tName       string                 `json:\"name\" form:\"name\"`\n\tNumber     string                 `json:\"number\" form:\"number\"`\n\tBankName   string                 `json:\"bank_name\"`\n\tCurrency   string                 `json:\"currency\"`\n\tBalanceID  string                 `json:\"balance_id\" `\n\tIdentityID string                 `json:\"identity_id\" form:\"identity_id\"`\n\tLedgerID   string                 `json:\"ledger_id\"`\n\tLedger     *Ledger                `json:\"ledger\"`\n\tBalance    *Balance               `json:\"balance\"`\n\tIdentity   *Identity              `json:\"identity\"`\n\tCreatedAt  time.Time              `json:\"created_at\"`\n\tMetaData   map[string]interface{} `json:\"meta_data\"`\n}\n```\nAccount represents a financial account linked to a balance, identity, and ledger.\n\n```go\ntype AlertCondition struct {\n\tValue        float64  `json:\"value\"`\n\tPrecision    float64  `json:\"precision\"`\n\tPreciseValue *big.Int `json:\"precise_value\"`\n\tField        string   `json:\"field\"`\n\tOperator     string   `json:\"operator\"`\n}\n```\nAlertCondition specifies the field, operator, value, and precision for a balance monitor alert threshold.\n\n```go\ntype Balance struct {\n\t// CurrencyMultiplier is retained for client compatibility; ledger arithmetic does not use it.\n\tCurrencyMultiplier    float64                `json:\"currency_multiplier\"`\n\tID                    int64                  `json:\"-\"`\n\tBalance               *big.Int               `json:\"balance\"`\n\tVersion               int64                  `json:\"version\"`\n\tInflightBalance       *big.Int               `json:\"inflight_balance\"`\n\tCreditBalance         *big.Int               `json:\"credit_balance\"`\n\tInflightCreditBalance *big.Int               `json:\"inflight_credit_balance\"`\n\tDebitBalance          *big.Int               `json:\"debit_balance\"`\n\tInflightDebitBalance  *big.Int               `json:\"inflight_debit_balance\"`\n\tQueuedDebitBalance    *big.Int               `json:\"queued_debit_balance,omitempty\"`\n\tQueuedCreditBalance   *big.Int               `json:\"queued_credit_balance,omitempty\"`\n\tLedgerID              string                 `json:\"ledger_id\"`\n\tIdentityID            string                 `json:\"identity_id\"`\n\tBalanceID             string                 `json:\"balance_id\"`\n\tIndicator             string                 `json:\"indicator,omitempty\"`\n\tCurrency              string                 `json:\"currency\"`\n\tIdentity              *Identity              `json:\"identity,omitempty\"`\n\tLedger                *Ledger                `json:\"ledger,omitempty\"`\n\tCreatedAt             time.Time              `json:\"created_at\"`\n\tInflightExpiresAt     time.Time              `json:\"inflight_expires_at\"`\n\tMetaData              map[string]interface{} `json:\"meta_data\"`\n\tTrackFundLineage      bool                   `json:\"track_fund_lineage\"`\n\tAllocationStrategy    string                 `json:\"allocation_strategy,omitempty\"`\n}\n```\nBalance represents a financial balance with credit, debit, inflight, and queued sub-balances.\n\n```go\nfunc (balance *Balance) Clone() *Balance\n```\nClone returns a deep copy of the balance that a transaction can be applied to without affecting the original.\n\nEvery \\*big.Int field is copied by value. This is what makes the copy meaningful: big.Int's Add and Sub mutate their receiver, so a plain struct copy would share the underlying integers with the original, and applying a transaction to the copy would silently rewrite the original's balances too.\n\nUsed by the dry-run projection to hold a \"before\" snapshot alongside the balances the transaction is applied to.\n\n```go\nfunc (balance *Balance) CommitInflightCredit(transaction *Transaction) error\n```\nCommitInflightCredit commits a credit from the inflight balance and adds it to the credit balance.\n\n```go\nfunc (balance *Balance) CommitInflightDebit(transaction *Transaction) error\n```\nCommitInflightDebit commits a debit from the inflight balance and adds it to the debit balance, returning an error if the inflight hold cannot cover the amount.\n\n```go\nfunc (balance *Balance) InitializeBalanceFields()\n```\nInitializeBalanceFields initializes all the fields of the Balance struct that might be nil. This ensures that all balance-related fields have valid \\*big.Int values for further operations.\n\n```go\nfunc (balance *Balance) RollbackInflightCredit(amount *big.Int) error\n```\nRollbackInflightCredit rolls back (decreases) the inflight credit balance by the specified amount.\n\n```go\nfunc (balance *Balance) RollbackInflightDebit(amount *big.Int) error\n```\nRollbackInflightDebit rolls back (decreases) the inflight debit balance by the specified amount.\n\n```go\ntype BalanceFilter struct {\n\tID                 int64     `json:\"id\"`\n\tBalanceRange       string    `json:\"balance_range\"`\n\tCreditBalanceRange string    `json:\"credit_balance_range\"`\n\tDebitBalanceRange  string    `json:\"debit_balance_range\"`\n\tCurrency           string    `json:\"currency\"`\n\tLedgerID           string    `json:\"ledger_id\"`\n\tFrom               time.Time `json:\"from\"`\n\tTo                 time.Time `json:\"to\"`\n}\n```\nBalanceFilter defines filter criteria for querying balances by range, currency, ledger, and time period.\n\n```go\ntype BalanceMonitor struct {\n\tMonitorID   string         `json:\"monitor_id\"`\n\tBalanceID   string         `json:\"balance_id\"`\n\tDescription string         `json:\"description,omitempty\"`\n\tCallBackURL string         `json:\"-\"`\n\tCreatedAt   time.Time      `json:\"created_at\"`\n\tCondition   AlertCondition `json:\"condition\"`\n}\n```\nBalanceMonitor defines a condition-based alert that triggers a callback when a balance meets the specified criteria.\n\n```go\nfunc (bm *BalanceMonitor) CheckCondition(b *Balance) bool\n```\nCheckCondition checks if a balance meets the condition specified by a BalanceMonitor. It compares various balance fields (e.g., debit balance, credit balance) against the precise value.\n\n```go\ntype BalanceProjection struct {\n\tBalanceID string `json:\"balance_id\"`\n\tRole      string `json:\"role\"`\n\tCurrency  string `json:\"currency\"`\n\n\t// Virtual marks a balance that does not exist yet — an @indicator that a\n\t// real post would create on demand. It is projected against zero and is\n\t// not created by the preview.\n\tVirtual bool `json:\"virtual,omitempty\"`\n\n\tCurrentBalance               string `json:\"current_balance\"`\n\tCurrentAvailable             string `json:\"current_available\"`\n\tCurrentCreditBalance         string `json:\"current_credit_balance\"`\n\tCurrentDebitBalance          string `json:\"current_debit_balance\"`\n\tCurrentInflightDebitBalance  string `json:\"current_inflight_debit_balance\"`\n\tCurrentInflightCreditBalance string `json:\"current_inflight_credit_balance\"`\n\n\tResultingBalance               string `json:\"resulting_balance\"`\n\tResultingAvailable             string `json:\"resulting_available\"`\n\tResultingCreditBalance         string `json:\"resulting_credit_balance\"`\n\tResultingDebitBalance          string `json:\"resulting_debit_balance\"`\n\tResultingInflightDebitBalance  string `json:\"resulting_inflight_debit_balance\"`\n\tResultingInflightCreditBalance string `json:\"resulting_inflight_credit_balance\"`\n}\n```\nBalanceProjection is one balance's state before and after the projected transaction. Current\\* is the snapshot the projection started from; Resulting\\* is that snapshot with the transaction applied in memory.\n\n```go\ntype BalanceTracker struct {\n\tBalances    map[string]*Balance\n\tFrequencies map[string]int\n\tMutex       sync.Mutex\n}\n```\nBalanceTracker tracks in-memory balance state and access frequency for hot-path optimization.\n\n```go\ntype BulkTransactionPreview struct {\n\tDryRun bool `json:\"dry_run\"`\n\n\t// WouldApply is false when any item in the batch would be rejected.\n\tWouldApply bool `json:\"would_apply\"`\n\n\t// Cumulative reports whether items were projected against each other's\n\t// effects. That mirrors how the batch would really run: items are applied\n\t// one after another only when skip_queue is set, and are otherwise\n\t// dispatched concurrently with no guaranteed order.\n\tCumulative bool `json:\"cumulative\"`\n\tAtomic     bool `json:\"atomic\"`\n\n\tResults []TransactionPreview `json:\"results\"`\n\n\t// Balances is the batch's combined effect per balance, and is reported only\n\t// in cumulative mode — without a guaranteed order there is no single\n\t// combined outcome to state.\n\tBalances []BalanceProjection `json:\"balances,omitempty\"`\n\n\tNotes []string `json:\"notes,omitempty\"`\n}\n```\nBulkTransactionPreview is the projected effect of a batch that was evaluated but never applied.\n\n```go\nfunc (preview *BulkTransactionPreview) AddNote(note string)\n```\nAddNote appends an advisory note to the batch projection.\n\n```go\nfunc (preview *BulkTransactionPreview) Finalize()\n```\nFinalize applies the same reconciliation to a batch and to each of its items, so a rejected item does not report a status either.\n\n```go\ntype BulkTransactionRequest struct {\n\tTransactions []*Transaction `json:\"transactions\"`\n\tInflight     bool           `json:\"inflight\"`\n\tAtomic       bool           `json:\"atomic\"`\n\tRunAsync     bool           `json:\"run_async\"`\n\tSkipQueue    bool           `json:\"skip_queue\"`\n}\n```\nBulkTransactionRequest encapsulates the data needed for a bulk transaction request.\n\n```go\ntype BulkTransactionResult struct {\n\tBatchID          string `json:\"batch_id\"`\n\tStatus           string `json:\"status\"` // e.g., \"processing\", \"applied\", \"inflight\", \"failed\"\n\tTransactionCount int    `json:\"transaction_count,omitempty\"`\n\tError            string `json:\"error,omitempty\"`\n}\n```\nBulkTransactionResult represents the outcome of a bulk transaction operation.\n\n```go\ntype ChainCheckpoint struct {\n\tSequence  int64     `json:\"sequence\"`\n\tCount     int64     `json:\"count\"`\n\tHeadHash  string    `json:\"head_hash\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n}\n```\nChainCheckpoint is an exportable root. External signatures or anchors can attest to it independently of the database that holds the chain.\n\n```go\ntype ChainIssue struct {\n\tSequence      int64  `json:\"sequence,omitempty\"`\n\tTransactionID string `json:\"transaction_id,omitempty\"`\n\tReason        string `json:\"reason\"`\n}\n```\n\n```go\ntype ChainRow struct {\n\tHistoricalRate    string\n\tOverdraftLimit    string\n\tQueueAction       string\n\tExecutionControls string\n\tScheduledFor      *time.Time\n\n\tID                string\n\tPrecision         string\n\tRate              string\n\tParentTransaction string\n\tEffectiveDate     *time.Time\n\tTransactionID     string\n\tSource            string\n\tDestination       string\n\tAmount            string // NUMERIC rendered as text\n\tPreciseAmount     string // NUMERIC rendered as text (the authoritative ledger amount)\n\tCurrency          string\n\tStatus            string\n\tReference         string\n\tCreatedAt         time.Time\n}\n```\nChainRow carries the canonical, immutable fields of a transaction that the hash chain seals. The chainer and the verifier both build it from the same DB columns so a recomputed hash is reproducible. Numeric values are read as exact PostgreSQL text, never converted through floating point.\n\n```go\ntype ChainState struct {\n\tChainKey    string\n\tLastSeq     int64\n\tHeadHash    string\n\tGenesisHash string\n\tGenesisAt   time.Time\n\tUpdatedAt   time.Time\n}\n```\nChainState mirrors the ledgerforge.chain\\_state bookmark row.\n\n```go\ntype ChainVerifyResult struct {\n\tVerified    bool         `json:\"verified\"`\n\tLastSeq     int64        `json:\"last_sequence\"`\n\tHeadHash    string       `json:\"head_hash\"`\n\tBrokenSeq   int64        `json:\"broken_sequence,omitempty\"`\n\tBrokenTxnID string       `json:\"broken_transaction_id,omitempty\"`\n\tReason      string       `json:\"reason,omitempty\"`\n\tPending     int64        `json:\"pending\"`\n\tTampering   []ChainIssue `json:\"tampering\"`\n}\n```\nChainVerifyResult distinguishes broken commitments from asynchronous coverage.\n\n```go\ntype ChainedTransaction struct {\n\tCanonicalVersion int\n\tRow              ChainRow\n\tChainSeq         int64\n\tChainPrevHash    string\n\tChainHash        string\n}\n```\nChainedTransaction is a transaction read back in chain order for verification: its canonical fields plus the stored chain linkage.\n\n```go\ntype Distribution struct {\n\tIdentifier          string `json:\"identifier\"`\n\tDistribution        string `json:\"distribution\"`                   // Can be a percentage (e.g., \"10%\"), a fixed amount (e.g., \"100\"), or \"left\"\n\tPreciseDistribution string `json:\"precise_distribution,omitempty\"` // Fixed amount in minor units (e.g., \"1006\" for 1006 cents)\n\tTransactionID       string `json:\"transaction_id\"`\n}\n```\nDistribution defines how a transaction amount is allocated to a specific source or destination.\n\n```go\ntype ExecutionControls struct {\n\tReservedMetadata   map[string]interface{} `json:\"reserved_metadata\"`\n\tEconomicVersion    int                    `json:\"economic_version\"`\n\tAllowOverdraft     bool                   `json:\"allow_overdraft\"`\n\tInflight           bool                   `json:\"inflight\"`\n\tAtomic             bool                   `json:\"atomic\"`\n\tSkipQueue          bool                   `json:\"skip_queue\"`\n\tSkipBalanceUpdate  bool                   `json:\"skip_balance_update\"`\n\tParentKind         string                 `json:\"parent_kind\"`\n\tQueuedParent       string                 `json:\"queued_parent\"`\n\tQueueLane          string                 `json:\"queue_lane\"`\n\tShadowFor          string                 `json:\"shadow_for\"`\n\tGroupIDs           []string               `json:\"group_ids\"`\n\tSources            []Distribution         `json:\"sources\"`\n\tDestinations       []Distribution         `json:\"destinations\"`\n\tInflightExpiryDate time.Time              `json:\"inflight_expiry_date\"`\n\tInflightCommitDate time.Time              `json:\"inflight_commit_date\"`\n}\n```\nExecutionControls is stored in an immutable JSONB column. It is independent of customer metadata, including for recovery and queued execution.\n\n```go\nfunc DecodeExecutionControls(data []byte) (ExecutionControls, error)\n```\nDecodeExecutionControls applies the historical type checks only to schema 0. It never normalizes the original evidence used by the hash chain.\n\n```go\nfunc (c ExecutionControls) Apply(t *Transaction)\n```\n\n```go\ntype ExternalTransaction struct {\n\tID          string    `json:\"id\"`\n\tAmount      float64   `json:\"amount\"`\n\tReference   string    `json:\"reference\"`\n\tCurrency    string    `json:\"currency\"`\n\tDescription string    `json:\"description\"`\n\tDate        time.Time `json:\"date\"`\n\tSource      string    `json:\"source\"`\n}\n```\n\n```go\nfunc (et *ExternalTransaction) ToInternalTransaction() *Transaction\n```\nToInternalTransaction converts an ExternalTransaction to an InternalTransaction. This is useful when reconciling external transactions with internal records.\n\n```go\ntype Identity struct {\n\tIdentityID       string                 `json:\"identity_id\" form:\"identity_id\"`\n\tIdentityType     string                 `json:\"identity_type\" form:\"identity_type\"`\n\tOrganizationName string                 `json:\"organization_name\" form:\"organization_name\"`\n\tCategory         string                 `json:\"category\" form:\"category\"`\n\tFirstName        string                 `json:\"first_name\" form:\"first_name\"`\n\tLastName         string                 `json:\"last_name\" form:\"last_name\"`\n\tOtherNames       string                 `json:\"other_names\" form:\"other_names\"`\n\tGender           string                 `json:\"gender\" form:\"gender\"`\n\tEmailAddress     string                 `json:\"email_address\" form:\"email_address\"`\n\tPhoneNumber      string                 `json:\"phone_number\" form:\"phone_number\"`\n\tNationality      string                 `json:\"nationality\" form:\"nationality\"`\n\tStreet           string                 `json:\"street\" form:\"street\"`\n\tCountry          string                 `json:\"country\" form:\"country\"`\n\tState            string                 `json:\"state\" form:\"state\"`\n\tPostCode         string                 `json:\"post_code\" form:\"postCode\"`\n\tCity             string                 `json:\"city\" form:\"city\"`\n\tDOB              time.Time              `json:\"dob\" form:\"dob\"`\n\tCreatedAt        time.Time              `json:\"created_at\" form:\"createdAt\"`\n\tMetaData         map[string]interface{} `json:\"meta_data\" form:\"metaData\"`\n}\n```\n\n```go\nfunc (i *Identity) IsFieldTokenized(fieldName string) bool\n```\n\n```go\nfunc (i *Identity) MarkFieldAsTokenized(fieldName string)\n```\n\n```go\ntype KeyPolicy struct {\n\tDenyAll       bool           `json:\"deny_all,omitempty\"`\n\tInheritedFrom []string       `json:\"inherited_from,omitempty\"`\n\tAPIKeyID      string         `json:\"api_key_id\"`\n\tVersion       int64          `json:\"version\"`\n\tRules         []SpendingRule `json:\"rules\"`\n\tLedgerIDs     []string       `json:\"ledger_ids,omitempty\"`\n\tBalanceIDs    []string       `json:\"balance_ids,omitempty\"`\n}\n```\n\n```go\ntype Ledger struct {\n\tID        int64                  `json:\"-\"`\n\tLedgerID  string                 `json:\"ledger_id\"`\n\tName      string                 `json:\"name\"`\n\tCreatedAt time.Time              `json:\"created_at\"`\n\tMetaData  map[string]interface{} `json:\"meta_data\"`\n}\n```\n\n```go\ntype LedgerFilter struct {\n\tID   int64     `json:\"id\"`\n\tFrom time.Time `json:\"from\"`\n\tTo   time.Time `json:\"to\"`\n}\n```\n\n```go\ntype LegProjection struct {\n\tIdentifier    string  `json:\"identifier\"`\n\tRole          string  `json:\"role\"`\n\tPreciseAmount string  `json:\"precise_amount\"`\n\tAmount        float64 `json:\"amount\"`\n}\n```\nLegProjection is one split of a multi-source/destination transaction.\n\n```go\ntype LineageMapping struct {\n\tID                 int64     `json:\"id\"`\n\tBalanceID          string    `json:\"balance_id\"`\n\tProvider           string    `json:\"provider\"`\n\tShadowBalanceID    string    `json:\"shadow_balance_id\"`\n\tAggregateBalanceID string    `json:\"aggregate_balance_id\"`\n\tIdentityID         string    `json:\"identity_id\"`\n\tCreatedAt          time.Time `json:\"created_at\"`\n}\n```\nLineageMapping tracks the relationship between a balance, its fund provider, and associated shadow/aggregate balances.\n\n```go\ntype LineageOutbox struct {\n\tID                   int64           `json:\"id\"`\n\tTransactionID        string          `json:\"transaction_id\"`\n\tSourceBalanceID      string          `json:\"source_balance_id,omitempty\"`\n\tDestinationBalanceID string          `json:\"destination_balance_id,omitempty\"`\n\tProvider             string          `json:\"provider,omitempty\"`\n\tLineageType          string          `json:\"lineage_type\"` // \"credit\", \"debit\", \"both\"\n\tPayload              json.RawMessage `json:\"payload\"`\n\tStatus               string          `json:\"status\"`\n\tAttempts             int             `json:\"attempts\"`\n\tMaxAttempts          int             `json:\"max_attempts\"`\n\tLastError            string          `json:\"last_error,omitempty\"`\n\tCreatedAt            time.Time       `json:\"created_at\"`\n\tProcessedAt          *time.Time      `json:\"processed_at,omitempty\"`\n\tLockedUntil          *time.Time      `json:\"locked_until,omitempty\"`\n\tInflight             bool            `json:\"inflight\"`\n}\n```\nLineageOutbox represents a pending lineage processing task. It is inserted atomically with the main transaction to ensure no lineage work is lost.\n\n```go\ntype Match struct {\n\tExternalTransactionID string\n\tInternalTransactionID string\n\tReconciliationID      string\n\tAmount                float64\n\tDate                  time.Time\n}\n```\n\n```go\ntype MatchingCriteria struct {\n\tField          string  `json:\"field\"`\n\tOperator       string  `json:\"operator\"`\n\tValue          string  `json:\"value\"`\n\tPattern        string  `json:\"pattern\"`\n\tAllowableDrift float64 `json:\"allowable_drift\"`\n}\n```\n\n```go\ntype MatchingRule struct {\n\tID          int64              `json:\"-\"`\n\tRuleID      string             `json:\"rule_id\"`\n\tCreatedAt   time.Time          `json:\"created_at\"`\n\tUpdatedAt   time.Time          `json:\"updated_at\"`\n\tName        string             `json:\"name\"`\n\tDescription string             `json:\"description\"`\n\tCriteria    []MatchingCriteria `json:\"criteria\"`\n}\n```\n\n```go\ntype PolicyAdmission struct {\n\tID        string      `json:\"admission_id\"`\n\tAPIKeyID  string      `json:\"api_key_id\"`\n\tIdentity  string      `json:\"identity\"`\n\tVersion   int64       `json:\"policy_version\"`\n\tDay       time.Time   `json:\"day\"`\n\tDecision  string      `json:\"decision\"`\n\tDecidedBy string      `json:\"decided_by,omitempty\"`\n\tLegs      []PolicyLeg `json:\"legs\"`\n}\n```\n\n```go\ntype PolicyBudgetCapacity struct {\n\tAPIKeyID string `json:\"api_key_id\"`\n\tUsed     string `json:\"used_minor\"`\n\tLimit    string `json:\"daily_limit,omitempty\"`\n}\n```\n\n```go\ntype PolicyCapacity struct {\n\tBudgets   []PolicyBudgetCapacity `json:\"budgets,omitempty\"`\n\tCurrency  string                 `json:\"currency\"`\n\tPrecision float64                `json:\"precision\"`\n\tDay       time.Time              `json:\"day\"`\n\tUsed      string                 `json:\"used_minor\"`\n\tRemaining *string                `json:\"remaining_minor,omitempty\"`\n}\n```\nUsed reports the narrowest declared daily budget. Remaining is the minimum available capacity across all charged budgets, whose usage is shown in Budgets.\n\n```go\ntype PolicyLeg struct {\n\tTransactionID     string  `json:\"transaction_id\"`\n\tReference         string  `json:\"reference\"`\n\tSource            string  `json:\"source\"`\n\tDestination       string  `json:\"destination\"`\n\tSourceLedger      string  `json:\"source_ledger\"`\n\tDestinationLedger string  `json:\"destination_ledger\"`\n\tCurrency          string  `json:\"currency\"`\n\tPrecision         float64 `json:\"precision\"`\n\tAmount            string  `json:\"amount\"`\n}\n```\n\n```go\ntype PreviewRejection struct {\n\tCode    string `json:\"code\"`\n\tReason  string `json:\"reason\"`\n\tMessage string `json:\"message\"`\n}\n```\nPreviewRejection describes why a projected transaction would not apply.\n\nCode is the same error code a real post would return, so existing client-side handling for e.g. TXN\\_INSUFFICIENT\\_FUNDS works against a preview unchanged.\n\n```go\ntype Reconciliation struct {\n\tID                    int64      `json:\"-\"`\n\tReconciliationID      string     `json:\"reconciliation_id\"`\n\tUploadID              string     `json:\"upload_id\"`\n\tStatus                string     `json:\"status\"`\n\tMatchedTransactions   int        `json:\"matched_transactions\"`\n\tUnmatchedTransactions int        `json:\"unmatched_transactions\"`\n\tIsDryRun              bool       `json:\"is_dry_run\"`\n\tStartedAt             time.Time  `json:\"started_at\"`\n\tCompletedAt           *time.Time `json:\"completed_at\"`\n}\n```\n\n```go\ntype ReconciliationProgress struct {\n\tLastProcessedExternalTxnID string `json:\"last_processed_external_txn_id\"`\n\tProcessedCount             int    `json:\"processed_count\"`\n}\n```\n\n```go\ntype ReconciliationResults struct {\n\tReconciliationID      string     `json:\"reconciliation_id\"`\n\tStatus                string     `json:\"status\"`\n\tStartedAt             time.Time  `json:\"started_at\"`\n\tCompletedAt           *time.Time `json:\"completed_at,omitempty\"`\n\tMatchedTransactions   []Match    `json:\"matched_transactions\"`\n\tUnmatchedTransactions []string   `json:\"unmatched_transactions\"`\n}\n```\n\n```go\ntype SpendingRule struct {\n\tCurrency       string  `json:\"currency\"`\n\tPrecision      float64 `json:\"precision\"`\n\tMaxTransaction string  `json:\"max_transaction,omitempty\"`\n\tDailyLimit     string  `json:\"daily_limit,omitempty\"`\n\tApprovalAbove  string  `json:\"approval_above,omitempty\"`\n}\n```\nPolicy amounts are exact integer minor units encoded as decimal strings. A currency is authorised only at the specified minor-unit multiplier.\n\n```go\ntype Transaction struct {\n\tParentKind       string                 `json:\"-\"`\n\tQueuedParent     string                 `json:\"queued_parent,omitempty\"`\n\tQueueLane        string                 `json:\"queue_lane,omitempty\"`\n\tShadowFor        string                 `json:\"-\"`\n\tReservedMetadata map[string]interface{} `json:\"-\"`\n\n\t// Rate is retained for client compatibility; ledger arithmetic does not use it.\n\tRate               float64                `json:\"rate\"`\n\tID                 int64                  `json:\"-\"`\n\tPreciseAmount      *big.Int               `json:\"precise_amount,omitempty\"`\n\tAmount             float64                `json:\"amount\"`\n\tAmountString       string                 `json:\"amount_string,omitempty\"`\n\tPrecision          float64                `json:\"precision\"`\n\tOverdraftLimit     float64                `json:\"overdraft_limit\"`\n\tTransactionID      string                 `json:\"transaction_id\"`\n\tParentTransaction  string                 `json:\"parent_transaction\"`\n\tSource             string                 `json:\"source,omitempty\"`\n\tDestination        string                 `json:\"destination,omitempty\"`\n\tReference          string                 `json:\"reference\"`\n\tCurrency           string                 `json:\"currency\"`\n\tDescription        string                 `json:\"description,omitempty\"`\n\tStatus             string                 `json:\"status\"`\n\tQueueAction        string                 `json:\"queue_action,omitempty\"`\n\tHash               string                 `json:\"hash\"`\n\tAllowOverdraft     bool                   `json:\"allow_overdraft\"`\n\tInflight           bool                   `json:\"inflight\"`\n\tSkipBalanceUpdate  bool                   `json:\"-\"`\n\tSkipQueue          bool                   `json:\"skip_queue\"`\n\tAtomic             bool                   `json:\"atomic\"`\n\tGroupIds           []string               `json:\"-\"`\n\tSources            []Distribution         `json:\"sources,omitempty\"`\n\tDestinations       []Distribution         `json:\"destinations,omitempty\"`\n\tCreatedAt          time.Time              `json:\"created_at\"`\n\tEffectiveDate      *time.Time             `json:\"effective_date,omitempty\"`\n\tScheduledFor       time.Time              `json:\"scheduled_for,omitempty\"`\n\tInflightExpiryDate time.Time              `json:\"inflight_expiry_date,omitempty\"`\n\tInflightCommitDate time.Time              `json:\"inflight_commit_date,omitempty\"`\n\tMetaData           map[string]interface{} `json:\"meta_data,omitempty\"`\n}\n```\nTransaction represents a financial transaction between source and destination balances.\n\n```go\nfunc (transaction *Transaction) Clone() *Transaction\n```\nClone returns a deep copy of the transaction, safe to mutate without affecting the original.\n\nThe balance-applying path mutates the transaction it is given — UpdateBalances sets PreciseAmount, and the inflight helpers rewrite Amount — so a caller that wants to keep its own transaction intact (notably the dry-run projection, which must not disturb a transaction it was only asked to evaluate) applies the arithmetic to a clone.\n\n```go\nfunc (t *Transaction) ExecutionControls() ExecutionControls\n```\n\n```go\nfunc (t *Transaction) ExecutionMetadata() map[string]interface{}\n```\nExecutionMetadata returns immutable internal lineage decisions after a DB read, and creation-time metadata for a transaction that has not been accepted.\n\n```go\nfunc (t *Transaction) GetEffectiveDate() time.Time\n```\nGetEffectiveDate returns the transaction's effective date, falling back to CreatedAt if not explicitly set.\n\n```go\nfunc (transaction *Transaction) HashTxn() string\n```\nHashTxn generates a SHA-256 hash of a transaction's relevant fields. This ensures the integrity of the transaction by creating a unique hash from its details.\n\n```go\nfunc (transaction *Transaction) SplitTransactionPrecise(ctx context.Context) ([]*Transaction, error)\n```\nFunction to integrate the new CalculateDistributionsPrecise into SplitTransaction\n\n```go\nfunc (transaction *Transaction) ToJSON() ([]byte, error)\n```\nToJSON serializes the transaction to JSON bytes.\n\n```go\nfunc (transaction *Transaction) ValidateAmount() error\n```\nValidateAmount is the exported ingest check used by QueueTransaction so zero/empty amounts never land on the queue.\n\n```go\ntype TransactionPreview struct {\n\tDryRun bool `json:\"dry_run\"`\n\n\t// WouldApply reports whether a real post of this transaction would be\n\t// accepted against the balances as they currently stand. When false,\n\t// Rejection carries the reason.\n\tWouldApply bool              `json:\"would_apply\"`\n\tRejection  *PreviewRejection `json:\"rejection,omitempty\"`\n\n\t// Operation names the settlement being projected on the inflight endpoint:\n\t// \"commit\" or \"void\". Empty for ordinary transaction projections.\n\tOperation string `json:\"operation,omitempty\"`\n\n\t// Status is the status the transaction would carry once applied. It is\n\t// omitted when WouldApply is false: a rejected projection has no resulting\n\t// status, because the real endpoint returns an error and writes no\n\t// transaction at all. See Finalize.\n\tStatus        string              `json:\"status,omitempty\"`\n\tReference     string              `json:\"reference,omitempty\"`\n\tCurrency      string              `json:\"currency\"`\n\tAmount        float64             `json:\"amount\"`\n\tPreciseAmount string              `json:\"precise_amount\"`\n\tPrecision     float64             `json:\"precision\"`\n\tBalances      []BalanceProjection `json:\"balances\"`\n\n\t// Legs is populated for multi-source/destination transactions: one entry\n\t// per split, using the same distribution math a real post would use.\n\tLegs []LegProjection `json:\"legs,omitempty\"`\n\n\t// Notes carry advisory information that is not a rejection — an ignored\n\t// field, or a condition worth surfacing before the caller posts for real.\n\tNotes []string `json:\"notes,omitempty\"`\n}\n```\nTransactionPreview is the projected effect of a transaction that was evaluated but never applied.\n\nMonetary values are strings in minor units, matching precise\\_amount, so no precision is lost in transit.\n\n```go\nfunc (preview *TransactionPreview) AddNote(note string)\n```\nAddNote appends an advisory note to the projection.\n\n```go\nfunc (preview *TransactionPreview) Finalize()\n```\nFinalize reconciles fields that only describe a transaction that would actually apply.\n\nStatus is set early, from the status the transaction would carry once applied, and the projection only later discovers it would be rejected -- an insufficient balance, a failing leg, a validation failure downstream. Left alone, the response then asserts two things that cannot both be true:\n\n\t\"would_apply\": false,\n\t\"rejection\":   { \"code\": \"TXN_INSUFFICIENT_FUNDS\", ... },\n\t\"status\":      \"APPLIED\"\n\nA rejected projection has no resulting status. The real endpoint returns an error and writes no transaction, so there is no status to report; clearing it lets the omitempty tag drop the field rather than name an outcome that cannot happen. Callers read would\\_apply and rejection for that answer.\n\n","path":"github.com/devaccuracy/ledgerforge/model","name":"model","synopsis":"","isRedistributable":true}
