ledger

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package ledger tracks agent balances on the platform.

Flow:

  1. Agent deposits USDC to platform address
  2. Platform credits agent's balance
  3. Agent spends via session keys (debits balance)
  4. Agent withdraws (platform sends USDC)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInsufficientBalance = errors.New("insufficient balance")
	ErrAgentNotFound       = errors.New("agent not found")
	ErrInvalidAmount       = errors.New("invalid amount")
	ErrDuplicateDeposit    = errors.New("deposit already processed")
)

Functions

This section is empty.

Types

type Balance

type Balance struct {
	AgentAddr   string    `json:"agentAddr"`
	Available   string    `json:"available"`   // Can be spent
	Pending     string    `json:"pending"`     // Deposits awaiting confirmation
	Escrowed    string    `json:"escrowed"`    // Locked in escrow awaiting service delivery
	CreditLimit string    `json:"creditLimit"` // Maximum credit available
	CreditUsed  string    `json:"creditUsed"`  // Current credit drawn
	TotalIn     string    `json:"totalIn"`     // Lifetime deposits
	TotalOut    string    `json:"totalOut"`    // Lifetime withdrawals + spending
	UpdatedAt   time.Time `json:"updatedAt"`
}

Balance represents an agent's balance

type DepositRequest

type DepositRequest struct {
	AgentAddress string `json:"agentAddress" binding:"required"`
	Amount       string `json:"amount" binding:"required"`
	TxHash       string `json:"txHash" binding:"required"`
}

DepositRequest for manual deposit recording (admin use)

type Entry

type Entry struct {
	ID          string    `json:"id"`
	AgentAddr   string    `json:"agentAddr"`
	Type        string    `json:"type"` // deposit, withdrawal, spend, refund
	Amount      string    `json:"amount"`
	TxHash      string    `json:"txHash,omitempty"`
	Reference   string    `json:"reference,omitempty"` // session key ID, service ID, etc.
	Description string    `json:"description,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

Entry represents a ledger entry

type Handler

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

Handler provides HTTP endpoints for ledger operations

func NewHandler

func NewHandler(ledger *Ledger) *Handler

NewHandler creates a new ledger handler

func NewHandlerWithWithdrawals

func NewHandlerWithWithdrawals(ledger *Ledger, executor WithdrawalExecutor) *Handler

NewHandlerWithWithdrawals creates a handler that can execute withdrawals

func (*Handler) GetBalance

func (h *Handler) GetBalance(c *gin.Context)

GetBalance handles GET /agents/:address/balance

func (*Handler) GetHistory

func (h *Handler) GetHistory(c *gin.Context)

GetHistory handles GET /agents/:address/ledger

func (*Handler) RecordDeposit

func (h *Handler) RecordDeposit(c *gin.Context)

RecordDeposit handles POST /admin/deposits (for manual/webhook deposit recording)

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(r *gin.RouterGroup)

RegisterRoutes sets up ledger routes

func (*Handler) RequestWithdrawal

func (h *Handler) RequestWithdrawal(c *gin.Context)

RequestWithdrawal handles POST /agents/:address/withdraw

type Ledger

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

Ledger manages agent balances

func New

func New(store Store) *Ledger

New creates a new ledger

func (*Ledger) CanSpend

func (l *Ledger) CanSpend(ctx context.Context, agentAddr, amount string) (bool, error)

CanSpend checks if an agent has sufficient balance (including credit)

func (*Ledger) ConfirmHold

func (l *Ledger) ConfirmHold(ctx context.Context, agentAddr, amount, reference string) error

ConfirmHold finalizes a held amount after on-chain confirmation. Moves funds from pending → total_out.

func (*Ledger) Deposit

func (l *Ledger) Deposit(ctx context.Context, agentAddr, amount, txHash string) error

Deposit credits an agent's balance (called when deposit detected on-chain)

func (*Ledger) EscrowLock

func (l *Ledger) EscrowLock(ctx context.Context, agentAddr, amount, reference string) error

EscrowLock locks funds in escrow before service delivery. Moves funds from available → escrowed.

func (*Ledger) GetBalance

func (l *Ledger) GetBalance(ctx context.Context, agentAddr string) (*Balance, error)

GetBalance returns an agent's current balance

func (*Ledger) GetCreditInfo

func (l *Ledger) GetCreditInfo(ctx context.Context, agentAddr string) (creditLimit, creditUsed string, err error)

GetCreditInfo returns the current credit limit and usage

func (*Ledger) GetHistory

func (l *Ledger) GetHistory(ctx context.Context, agentAddr string, limit int) ([]*Entry, error)

GetHistory returns ledger entries for an agent

func (*Ledger) Hold

func (l *Ledger) Hold(ctx context.Context, agentAddr, amount, reference string) error

Hold places a hold on funds before an on-chain transfer. Moves funds from available → pending so they can't be double-spent.

func (*Ledger) Refund

func (l *Ledger) Refund(ctx context.Context, agentAddr, amount, reference string) error

Refund credits back an agent's balance (used when a transfer fails after debit)

func (*Ledger) RefundEscrow

func (l *Ledger) RefundEscrow(ctx context.Context, agentAddr, amount, reference string) error

RefundEscrow returns escrowed funds to the buyer after a dispute. Moves from escrowed → available.

func (*Ledger) ReleaseEscrow

func (l *Ledger) ReleaseEscrow(ctx context.Context, buyerAddr, sellerAddr, amount, reference string) error

ReleaseEscrow releases escrowed funds to the seller after confirmation. Moves from buyer's escrowed → seller's available.

func (*Ledger) ReleaseHold

func (l *Ledger) ReleaseHold(ctx context.Context, agentAddr, amount, reference string) error

ReleaseHold returns held funds to available when a transfer fails. Moves funds from pending → available.

func (*Ledger) RepayCredit

func (l *Ledger) RepayCredit(ctx context.Context, agentAddr, amount string) error

RepayCredit reduces outstanding credit usage

func (*Ledger) SetCreditLimit

func (l *Ledger) SetCreditLimit(ctx context.Context, agentAddr, limit string) error

SetCreditLimit sets the maximum credit for an agent

func (*Ledger) Spend

func (l *Ledger) Spend(ctx context.Context, agentAddr, amount, sessionKeyID string) error

Spend debits an agent's balance (called by session key transactions)

func (*Ledger) Withdraw

func (l *Ledger) Withdraw(ctx context.Context, agentAddr, amount, txHash string) error

Withdraw processes a withdrawal request

type MemoryStore

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

MemoryStore is an in-memory ledger store for demo/development mode.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory ledger store.

func (*MemoryStore) ConfirmHold

func (m *MemoryStore) ConfirmHold(ctx context.Context, agentAddr, amount, reference string) error

func (*MemoryStore) Credit

func (m *MemoryStore) Credit(ctx context.Context, agentAddr, amount, txHash, description string) error

func (*MemoryStore) Debit

func (m *MemoryStore) Debit(ctx context.Context, agentAddr, amount, reference, description string) error

func (*MemoryStore) EscrowLock

func (m *MemoryStore) EscrowLock(ctx context.Context, agentAddr, amount, reference string) error

func (*MemoryStore) GetBalance

func (m *MemoryStore) GetBalance(ctx context.Context, agentAddr string) (*Balance, error)

func (*MemoryStore) GetCreditInfo

func (m *MemoryStore) GetCreditInfo(ctx context.Context, agentAddr string) (string, string, error)

func (*MemoryStore) GetHistory

func (m *MemoryStore) GetHistory(ctx context.Context, agentAddr string, limit int) ([]*Entry, error)

func (*MemoryStore) HasDeposit

func (m *MemoryStore) HasDeposit(ctx context.Context, txHash string) (bool, error)

func (*MemoryStore) Hold

func (m *MemoryStore) Hold(ctx context.Context, agentAddr, amount, reference string) error

func (*MemoryStore) Refund

func (m *MemoryStore) Refund(ctx context.Context, agentAddr, amount, reference, description string) error

func (*MemoryStore) RefundEscrow

func (m *MemoryStore) RefundEscrow(ctx context.Context, agentAddr, amount, reference string) error

func (*MemoryStore) ReleaseEscrow

func (m *MemoryStore) ReleaseEscrow(ctx context.Context, buyerAddr, sellerAddr, amount, reference string) error

func (*MemoryStore) ReleaseHold

func (m *MemoryStore) ReleaseHold(ctx context.Context, agentAddr, amount, reference string) error

func (*MemoryStore) RepayCredit

func (m *MemoryStore) RepayCredit(ctx context.Context, agentAddr, amount string) error

func (*MemoryStore) SetCreditLimit

func (m *MemoryStore) SetCreditLimit(ctx context.Context, agentAddr, limit string) error

func (*MemoryStore) UseCredit

func (m *MemoryStore) UseCredit(ctx context.Context, agentAddr, amount string) error

func (*MemoryStore) Withdraw

func (m *MemoryStore) Withdraw(ctx context.Context, agentAddr, amount, txHash string) error

type PostgresStore

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

PostgresStore implements Store with PostgreSQL

func NewPostgresStore

func NewPostgresStore(db *sql.DB) *PostgresStore

NewPostgresStore creates a new PostgreSQL-backed ledger store

func (*PostgresStore) ConfirmHold

func (p *PostgresStore) ConfirmHold(ctx context.Context, agentAddr, amount, reference string) error

ConfirmHold finalizes a held amount (moves from pending to total_out). Called after on-chain transfer is confirmed.

func (*PostgresStore) Credit

func (p *PostgresStore) Credit(ctx context.Context, agentAddr, amount, txHash, description string) error

Credit adds funds to an agent's balance, auto-repaying credit first

func (*PostgresStore) Debit

func (p *PostgresStore) Debit(ctx context.Context, agentAddr, amount, reference, description string) error

Debit removes funds from an agent's balance with credit support. Uses available balance first, then draws from credit for any shortfall.

func (*PostgresStore) EscrowLock

func (p *PostgresStore) EscrowLock(ctx context.Context, agentAddr, amount, reference string) error

EscrowLock moves funds from available to escrowed.

func (*PostgresStore) GetBalance

func (p *PostgresStore) GetBalance(ctx context.Context, agentAddr string) (*Balance, error)

GetBalance retrieves an agent's balance

func (*PostgresStore) GetCreditInfo

func (p *PostgresStore) GetCreditInfo(ctx context.Context, agentAddr string) (string, string, error)

GetCreditInfo returns the current credit limit and usage

func (*PostgresStore) GetHistory

func (p *PostgresStore) GetHistory(ctx context.Context, agentAddr string, limit int) ([]*Entry, error)

GetHistory retrieves ledger entries for an agent

func (*PostgresStore) HasDeposit

func (p *PostgresStore) HasDeposit(ctx context.Context, txHash string) (bool, error)

HasDeposit checks if a deposit tx has already been processed

func (*PostgresStore) Hold

func (p *PostgresStore) Hold(ctx context.Context, agentAddr, amount, reference string) error

Hold places a hold on funds (moves from available to pending) with credit support. If available < amount, draws the shortfall from credit line.

func (*PostgresStore) Migrate

func (p *PostgresStore) Migrate(ctx context.Context) error

Migrate creates the ledger tables with NUMERIC columns

func (*PostgresStore) Refund

func (p *PostgresStore) Refund(ctx context.Context, agentAddr, amount, reference, description string) error

Refund credits back funds to an agent's balance (reverses a failed debit)

func (*PostgresStore) RefundEscrow

func (p *PostgresStore) RefundEscrow(ctx context.Context, agentAddr, amount, reference string) error

RefundEscrow returns escrowed funds to available (dispute refund).

func (*PostgresStore) ReleaseEscrow

func (p *PostgresStore) ReleaseEscrow(ctx context.Context, buyerAddr, sellerAddr, amount, reference string) error

ReleaseEscrow moves funds from buyer's escrowed to seller's available.

func (*PostgresStore) ReleaseHold

func (p *PostgresStore) ReleaseHold(ctx context.Context, agentAddr, amount, reference string) error

ReleaseHold returns held funds to available (transfer failed/timed out).

func (*PostgresStore) RepayCredit

func (p *PostgresStore) RepayCredit(ctx context.Context, agentAddr, amount string) error

RepayCredit reduces outstanding credit usage

func (*PostgresStore) SetCreditLimit

func (p *PostgresStore) SetCreditLimit(ctx context.Context, agentAddr, limit string) error

SetCreditLimit sets the maximum credit for an agent

func (*PostgresStore) UseCredit

func (p *PostgresStore) UseCredit(ctx context.Context, agentAddr, amount string) error

UseCredit draws from the agent's credit line

func (*PostgresStore) Withdraw

func (p *PostgresStore) Withdraw(ctx context.Context, agentAddr, amount, txHash string) error

Withdraw processes a withdrawal with row-level locking.

type Store

type Store interface {
	GetBalance(ctx context.Context, agentAddr string) (*Balance, error)
	Credit(ctx context.Context, agentAddr, amount, txHash, description string) error
	Debit(ctx context.Context, agentAddr, amount, reference, description string) error
	Refund(ctx context.Context, agentAddr, amount, reference, description string) error
	Withdraw(ctx context.Context, agentAddr, amount, txHash string) error
	GetHistory(ctx context.Context, agentAddr string, limit int) ([]*Entry, error)
	HasDeposit(ctx context.Context, txHash string) (bool, error)

	// Two-phase hold operations for safe transaction execution.
	// Hold moves funds from available → pending before on-chain transfer.
	// ConfirmHold moves from pending → total_out after confirmation.
	// ReleaseHold moves from pending → available if transfer fails.
	Hold(ctx context.Context, agentAddr, amount, reference string) error
	ConfirmHold(ctx context.Context, agentAddr, amount, reference string) error
	ReleaseHold(ctx context.Context, agentAddr, amount, reference string) error

	// Escrow operations for buyer-protection payments.
	// EscrowLock moves funds from available → escrowed.
	// ReleaseEscrow moves from buyer's escrowed → seller's available.
	// RefundEscrow moves from escrowed → available (dispute refund).
	EscrowLock(ctx context.Context, agentAddr, amount, reference string) error
	ReleaseEscrow(ctx context.Context, buyerAddr, sellerAddr, amount, reference string) error
	RefundEscrow(ctx context.Context, agentAddr, amount, reference string) error

	// Credit line operations.
	// SetCreditLimit sets the maximum credit for an agent.
	// UseCredit draws from the agent's credit line.
	// RepayCredit reduces outstanding credit usage.
	// GetCreditInfo returns the current credit limit and usage.
	SetCreditLimit(ctx context.Context, agentAddr, limit string) error
	UseCredit(ctx context.Context, agentAddr, amount string) error
	RepayCredit(ctx context.Context, agentAddr, amount string) error
	GetCreditInfo(ctx context.Context, agentAddr string) (creditLimit, creditUsed string, err error)
}

Store persists ledger data

type WithdrawRequest

type WithdrawRequest struct {
	Amount string `json:"amount" binding:"required"`
}

WithdrawRequest for withdrawal

type WithdrawalExecutor

type WithdrawalExecutor interface {
	Transfer(ctx context.Context, to common.Address, amount *big.Int) (txHash string, err error)
}

WithdrawalExecutor executes on-chain withdrawals

Jump to

Keyboard shortcuts

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