database

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2026 License: MIT Imports: 16 Imported by: 0

README

Database Module

The database module provides Supabase (PostgreSQL) integration for the Service Layer.

Overview

This module handles shared database operations including:

  • Supabase REST API client
  • Core data models (User, APIKey, wallets, gasbank, etc.)
  • Repository pattern for data access
  • GasBank operations

Note: Service-specific database operations have been moved to each service's own supabase/ subdirectory. See Service-Specific Repositories below.

Architecture

infrastructure/database/     # Shared database infrastructure
├── supabase_client.go       # Supabase HTTP client
├── supabase_repository.go   # Base repository implementation
├── repository_interface.go  # Interface definitions
├── supabase_models.go       # Shared model definitions
├── errors.go                # Error definitions
├── supabase_*.go            # Shared operations (wallets, apikeys, gasbank)
└── mock_*.go                # Test mocks

services/*/supabase/         # Service-specific database operations (when needed)
├── repository.go            # Service-specific repository interface
└── models.go                # Service-specific data models

infrastructure/*/supabase/   # Infrastructure-backed repos (shared capabilities)
├── accountpool/supabase/    # Account pool persistence
├── globalsigner/supabase/   # Global signer persistence
└── secrets/supabase/        # User secrets persistence + policy metadata

Components

Supabase Client (supabase_client.go)

Main client for Supabase REST API communication.

client, err := database.NewClient(database.Config{
    URL:        "https://your-project.supabase.co",
    ServiceKey: "***REMOVED***",
})
Repository (supabase_repository.go)

High-level data access layer implementing the repository pattern.

repo := database.NewRepository(client)

// Create a user
user, err := repo.CreateUser(ctx, &database.User{
    Address: "NAddr123...",
})

// Get user by address
user, err := repo.GetUserByAddress(ctx, "NAddr123...")

Data Models (supabase_models.go)

Core Models (Shared)
Model Description
User User account information
UserWallet User wallet addresses
APIKey API key for authentication
Secret Encrypted secrets
GasBankAccount Gas balance tracking
GasBankTransaction Gas transaction history
DepositRequest Deposit request tracking
ServiceRequest Service request tracking
PriceFeed Price feed data

Service-Specific Repositories

Service-specific database operations have been moved to each service's own supabase/ package following the Interface Segregation Principle (ISP).

NeoFlow Service
import neoflowsupabase "github.com/R3E-Network/service_layer/services/automation/supabase"

neoflowRepo := neoflowsupabase.NewRepository(baseRepo)

err := neoflowRepo.CreateTrigger(ctx, &neoflowsupabase.Trigger{...})
triggers, err := neoflowRepo.GetTriggers(ctx, userID)
err := neoflowRepo.CreateExecution(ctx, &neoflowsupabase.Execution{...})
NeoAccounts (AccountPool) Service
import neoaccountssupabase "github.com/R3E-Network/service_layer/infrastructure/accountpool/supabase"

poolRepo := neoaccountssupabase.NewRepository(baseRepo)

err := poolRepo.Create(ctx, &neoaccountssupabase.Account{...})
accounts, err := poolRepo.ListAvailable(ctx, 10)
err := poolRepo.Update(ctx, account)
Secrets (User Secrets + Policies)
import secretssupabase "github.com/R3E-Network/service_layer/infrastructure/secrets/supabase"

	secretsRepo := secretssupabase.NewRepository(baseRepo)

	err := secretsRepo.CreateSecret(ctx, &secretssupabase.Secret{...})
	secrets, err := secretsRepo.GetSecrets(ctx, userID)
	err := secretsRepo.SetAllowedServices(ctx, userID, secretName, []string{"neocompute", "neoflow"})
	```

## Shared Operations

### GasBank (`supabase_gasbank.go`)

```go
// Get or create account
account, err := repo.GetOrCreateGasBankAccount(ctx, userID)

// Update balance
err := repo.UpdateGasBankBalance(ctx, userID, newBalance, reserved)

// Create transaction
err := repo.CreateGasBankTransaction(ctx, &database.GasBankTransaction{...})
Authentication
API Keys (supabase_apikeys.go)
// Create API key
err := repo.CreateAPIKey(ctx, &database.APIKey{...})

// Validate API key
apiKey, err := repo.GetAPIKeyByHash(ctx, keyHash)

// List user's API keys
keys, err := repo.GetAPIKeys(ctx, userID)
Wallets (supabase_wallets.go)
// Add wallet
err := repo.CreateWallet(ctx, &database.UserWallet{...})

// Get user wallets
wallets, err := repo.GetWallets(ctx, userID)

// Set primary wallet
err := repo.SetPrimaryWallet(ctx, userID, walletID)

Testing

go test ./infrastructure/database/... -v
Mock Repository
// Create mock for testing
mockRepo := database.NewMockRepository()

// Inject errors for testing error paths
mockRepo.ErrorOnNextCall = errors.New("database error")

// Reset mock state
mockRepo.Reset()

Environment Variables

Variable Description
SUPABASE_URL Supabase project URL
SUPABASE_SERVICE_KEY Supabase service role key

Migration Guide

If you have code using the old service-specific methods from database.RepositoryInterface, migrate to the new service-specific packages:

Old (Deprecated) New
repo.CreateNeoFlowTrigger() neoflowRepo.CreateTrigger()
repo.GetNeoFlowTriggers() neoflowRepo.GetTriggers()
repo.CreatePoolAccount() poolRepo.Create()
repo.GetPoolAccount() poolRepo.GetByID()
repo.GetSecretPolicies() secretsRepo.GetAllowedServices()
repo.SetSecretPolicies() secretsRepo.SetAllowedServices()

Documentation

Overview

Package database provides Supabase database integration.

Package database provides generic repository helpers for CRUD operations.

Package database provides Supabase database integration.

Package database provides Supabase database integration.

Package database provides Supabase database integration.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a record is not found.
	ErrNotFound = errors.New("record not found")

	// ErrAlreadyExists is returned when trying to create a duplicate record.
	ErrAlreadyExists = errors.New("record already exists")

	// ErrUnauthorized is returned when the user is not authorized.
	ErrUnauthorized = errors.New("unauthorized")

	// ErrInvalidInput is returned when input validation fails.
	ErrInvalidInput = errors.New("invalid input")

	// ErrConflict is returned when there's a conflict (e.g., concurrent modification).
	ErrConflict = errors.New("conflict")

	// ErrDatabaseError is returned for general database errors.
	ErrDatabaseError = errors.New("database error")
)

Functions

func GenericCreate

func GenericCreate[T any](base *Repository, ctx context.Context, table string, model *T, onResult func([]T)) error

GenericCreate inserts a new record and optionally updates the model with returned data. T is the model type (e.g., Account, Trigger, RequestRecord).

func GenericDelete

func GenericDelete(base *Repository, ctx context.Context, table, keyField, keyValue string) error

GenericDelete deletes a record by a key field.

func GenericDeleteWithQuery

func GenericDeleteWithQuery(base *Repository, ctx context.Context, table, query string) error

GenericDeleteWithQuery deletes records matching a custom query string. Useful for composite keys where multiple fields must match.

func GenericGetByField

func GenericGetByField[T any](base *Repository, ctx context.Context, table, field, value string) (*T, error)

GenericGetByField fetches a single record by a field value. Returns NotFoundError if no records match.

func GenericList

func GenericList[T any](base *Repository, ctx context.Context, table string) ([]T, error)

GenericList fetches all records from a table.

func GenericListByField

func GenericListByField[T any](base *Repository, ctx context.Context, table, field, value string) ([]T, error)

GenericListByField fetches records matching a field value.

func GenericListWithQuery

func GenericListWithQuery[T any](base *Repository, ctx context.Context, table, query string) ([]T, error)

GenericListWithQuery fetches records with a custom query string.

func GenericUpdate

func GenericUpdate[T any](base *Repository, ctx context.Context, table, keyField, keyValue string, model *T) error

GenericUpdate updates an existing record by a key field.

func GenericUpdateWithQuery

func GenericUpdateWithQuery[T any](base *Repository, ctx context.Context, table, query string, model *T) error

GenericUpdateWithQuery updates records matching a custom query string. Useful for composite keys where multiple fields must match.

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists checks if an error is an already exists error.

func IsInvalidInput

func IsInvalidInput(err error) bool

IsInvalidInput checks if an error is an invalid input error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if an error is a not found error.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized checks if an error is an unauthorized error.

func NewNotFoundError

func NewNotFoundError(entity, id string) error

NewNotFoundError creates a new NotFoundError.

func SanitizeString

func SanitizeString(s string) string

SanitizeString removes potentially dangerous characters from a string.

func ValidateAddress

func ValidateAddress(address string) error

ValidateAddress validates a Neo N3 address.

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail validates an email address.

func ValidateID

func ValidateID(id string) error

ValidateID validates an ID string (UUID or alphanumeric).

func ValidateLimit

func ValidateLimit(limit, defaultLimit, maxLimit int) int

ValidateLimit validates and normalizes a limit parameter.

func ValidateOffset

func ValidateOffset(offset int) int

ValidateOffset validates an offset parameter.

func ValidateStatus

func ValidateStatus(status string, validStatuses []string) error

ValidateStatus validates a status string.

func ValidateTxHash

func ValidateTxHash(txHash string) error

ValidateTxHash validates a transaction hash.

func ValidateUserID

func ValidateUserID(userID string) error

ValidateUserID validates a user ID.

Types

type APIKey

type APIKey struct {
	ID          string    `json:"id"`
	UserID      string    `json:"user_id"`
	Name        string    `json:"name"`
	KeyHash     string    `json:"key_hash"`
	Prefix      string    `json:"prefix"`
	Scopes      []string  `json:"scopes"`
	Description string    `json:"description,omitempty"`
	ExpiresAt   time.Time `json:"expires_at,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	LastUsed    time.Time `json:"last_used,omitempty"`
}

APIKey represents an API key.

type BaseRepository

type BaseRepository interface {
	UserRepository
	ServiceRequestRepository
	GasBankRepository
}

BaseRepository defines the minimal interface required by the marble framework. Services should use this interface for framework integration, and define their own service-specific repository interfaces for domain operations.

type Client

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

Client wraps the Supabase REST API client.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient creates a new Supabase client.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, table string, query string) ([]byte, error)

Delete removes records from the specified table matching the query.

func (*Client) Insert

func (c *Client) Insert(ctx context.Context, table string, data interface{}) ([]byte, error)

Insert inserts a record into the specified table.

func (*Client) Select

func (c *Client) Select(ctx context.Context, table string, query string) ([]byte, error)

Select retrieves records from the specified table.

func (*Client) Update

func (c *Client) Update(ctx context.Context, table string, data interface{}, query string) ([]byte, error)

Update updates records in the specified table matching the query.

func (*Client) Upsert

func (c *Client) Upsert(ctx context.Context, table string, data interface{}, onConflict string) ([]byte, error)

Upsert inserts or updates a record in the specified table.

type Config

type Config struct {
	URL        string
	ServiceKey string
	RestPrefix string
}

Config holds database configuration.

type DepositRequest

type DepositRequest struct {
	ID                    string    `json:"id"`
	UserID                string    `json:"user_id"`
	AccountID             string    `json:"account_id"`
	Amount                int64     `json:"amount"`
	TxHash                string    `json:"tx_hash,omitempty"`
	FromAddress           string    `json:"from_address"`
	Status                string    `json:"status"`
	Confirmations         int       `json:"confirmations"`
	RequiredConfirmations int       `json:"required_confirmations"`
	Error                 string    `json:"error,omitempty"`
	CreatedAt             time.Time `json:"created_at"`
	ConfirmedAt           time.Time `json:"confirmed_at,omitempty"`
	ExpiresAt             time.Time `json:"expires_at"`
}

DepositRequest represents a deposit request.

type GasBankAccount

type GasBankAccount struct {
	ID        string    `json:"id"`
	UserID    string    `json:"user_id"`
	Balance   int64     `json:"balance"`
	Reserved  int64     `json:"reserved"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

GasBankAccount represents a gas bank account.

type GasBankRepository

type GasBankRepository interface {
	GetGasBankAccount(ctx context.Context, userID string) (*GasBankAccount, error)
	CreateGasBankAccount(ctx context.Context, account *GasBankAccount) error
	GetOrCreateGasBankAccount(ctx context.Context, userID string) (*GasBankAccount, error)
	UpdateGasBankBalance(ctx context.Context, userID string, balance, reserved int64) error
	CreateGasBankTransaction(ctx context.Context, tx *GasBankTransaction) error
	GetGasBankTransactions(ctx context.Context, accountID string, limit int) ([]GasBankTransaction, error)
	// DeductFeeAtomic atomically deducts a fee from a user's balance and records the transaction.
	// This ensures balance update and transaction record are committed together.
	DeductFeeAtomic(ctx context.Context, userID string, amount int64, tx *GasBankTransaction) (newBalance int64, err error)
	CreateDepositRequest(ctx context.Context, deposit *DepositRequest) error
	GetDepositRequests(ctx context.Context, userID string, limit int) ([]DepositRequest, error)
	GetDepositByTxHash(ctx context.Context, txHash string) (*DepositRequest, error)
	UpdateDepositStatus(ctx context.Context, depositID, status string, confirmations int) error
	GetPendingDeposits(ctx context.Context, limit int) ([]DepositRequest, error)
}

GasBankRepository defines gas bank data access methods.

type GasBankTransaction

type GasBankTransaction struct {
	ID           string    `json:"id"`
	AccountID    string    `json:"account_id"`
	TxType       string    `json:"tx_type"`
	Amount       int64     `json:"amount"`
	BalanceAfter int64     `json:"balance_after"`
	ReferenceID  string    `json:"reference_id,omitempty"`
	TxHash       string    `json:"tx_hash,omitempty"`
	FromAddress  string    `json:"from_address,omitempty"`
	ToAddress    string    `json:"to_address,omitempty"`
	Status       string    `json:"status,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
}

GasBankTransaction represents a gas bank transaction.

type GenericOps

type GenericOps struct{}

GenericOps provides common CRUD operations for service-specific repositories. This reduces boilerplate by centralizing common patterns like: - JSON marshaling/unmarshaling - Error wrapping with context - Query construction

Usage:

func (r *Repository) Create(ctx context.Context, model *Model) error {
    return GenericCreate(r.base, ctx, "table_name", model, func(rows []Model) {
        if len(rows) > 0 { *model = rows[0] }
    })
}

type MockRepository

type MockRepository struct {

	// Error injection for testing error paths
	ErrorOnNextCall error
	// contains filtered or unexported fields
}

MockRepository is an in-memory implementation of RepositoryInterface for testing.

func NewMockRepository

func NewMockRepository() *MockRepository

NewMockRepository creates a new mock repository for testing.

func (*MockRepository) CreateDepositRequest

func (m *MockRepository) CreateDepositRequest(ctx context.Context, deposit *DepositRequest) error

func (*MockRepository) CreateGasBankAccount

func (m *MockRepository) CreateGasBankAccount(ctx context.Context, account *GasBankAccount) error

func (*MockRepository) CreateGasBankTransaction

func (m *MockRepository) CreateGasBankTransaction(ctx context.Context, tx *GasBankTransaction) error

func (*MockRepository) CreatePriceFeed

func (m *MockRepository) CreatePriceFeed(ctx context.Context, feed *PriceFeed) error

func (*MockRepository) CreateServiceRequest

func (m *MockRepository) CreateServiceRequest(ctx context.Context, req *ServiceRequest) error

func (*MockRepository) CreateUser

func (m *MockRepository) CreateUser(ctx context.Context, user *User) error

func (*MockRepository) DeductFeeAtomic

func (m *MockRepository) DeductFeeAtomic(ctx context.Context, userID string, amount int64, tx *GasBankTransaction) (int64, error)

func (*MockRepository) GetDepositByTxHash

func (m *MockRepository) GetDepositByTxHash(ctx context.Context, txHash string) (*DepositRequest, error)

func (*MockRepository) GetDepositRequests

func (m *MockRepository) GetDepositRequests(ctx context.Context, userID string, limit int) ([]DepositRequest, error)

func (*MockRepository) GetGasBankAccount

func (m *MockRepository) GetGasBankAccount(ctx context.Context, userID string) (*GasBankAccount, error)

func (*MockRepository) GetGasBankTransactions

func (m *MockRepository) GetGasBankTransactions(ctx context.Context, accountID string, limit int) ([]GasBankTransaction, error)

func (*MockRepository) GetLatestPrice

func (m *MockRepository) GetLatestPrice(ctx context.Context, feedID string) (*PriceFeed, error)

func (*MockRepository) GetOrCreateGasBankAccount

func (m *MockRepository) GetOrCreateGasBankAccount(ctx context.Context, userID string) (*GasBankAccount, error)

func (*MockRepository) GetPendingDeposits

func (m *MockRepository) GetPendingDeposits(ctx context.Context, limit int) ([]DepositRequest, error)

func (*MockRepository) GetServiceRequests

func (m *MockRepository) GetServiceRequests(ctx context.Context, userID string, limit int) ([]ServiceRequest, error)

func (*MockRepository) GetUser

func (m *MockRepository) GetUser(ctx context.Context, id string) (*User, error)

func (*MockRepository) GetUserByAddress

func (m *MockRepository) GetUserByAddress(ctx context.Context, address string) (*User, error)

func (*MockRepository) GetUserByEmail

func (m *MockRepository) GetUserByEmail(ctx context.Context, email string) (*User, error)

func (*MockRepository) HealthCheck

func (m *MockRepository) HealthCheck(ctx context.Context) error

HealthCheck simulates a healthy database connection for tests.

func (*MockRepository) Reset

func (m *MockRepository) Reset()

Reset clears all data in the mock repository.

func (*MockRepository) UpdateDepositStatus

func (m *MockRepository) UpdateDepositStatus(ctx context.Context, depositID, status string, confirmations int) error

func (*MockRepository) UpdateGasBankBalance

func (m *MockRepository) UpdateGasBankBalance(ctx context.Context, userID string, balance, reserved int64) error

func (*MockRepository) UpdateServiceRequest

func (m *MockRepository) UpdateServiceRequest(ctx context.Context, req *ServiceRequest) error

func (*MockRepository) UpdateUserEmail

func (m *MockRepository) UpdateUserEmail(ctx context.Context, userID, email string) error

func (*MockRepository) UpdateUserNonce

func (m *MockRepository) UpdateUserNonce(ctx context.Context, userID, nonce string) error

type NotFoundError

type NotFoundError struct {
	Entity string
	ID     string
}

NotFoundError wraps ErrNotFound with context.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type PaginationParams

type PaginationParams struct {
	Limit  int
	Offset int
}

PaginationParams holds pagination parameters.

func DefaultPagination

func DefaultPagination() PaginationParams

DefaultPagination returns default pagination parameters.

func NewPagination

func NewPagination(limit, offset int) PaginationParams

NewPagination creates validated pagination parameters.

func (PaginationParams) ToQuery

func (p PaginationParams) ToQuery() string

ToQuery converts pagination to query string parameters.

type PriceFeed

type PriceFeed struct {
	ID        string    `json:"id"`
	FeedID    string    `json:"feed_id"`
	Pair      string    `json:"pair"`
	Price     int64     `json:"price"`
	Decimals  int       `json:"decimals"`
	Timestamp time.Time `json:"timestamp"`
	Sources   []string  `json:"sources"`
	Signature []byte    `json:"signature"`
}

PriceFeed represents a price feed entry.

type PriceFeedRepository

type PriceFeedRepository interface {
	GetLatestPrice(ctx context.Context, feedID string) (*PriceFeed, error)
	CreatePriceFeed(ctx context.Context, feed *PriceFeed) error
}

PriceFeedRepository defines price feed data access methods.

type QueryBuilder

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

QueryBuilder helps construct Supabase REST queries.

func NewQuery

func NewQuery() *QueryBuilder

NewQuery creates a new query builder.

func (*QueryBuilder) Build

func (q *QueryBuilder) Build() string

Build constructs the final query string.

func (*QueryBuilder) Eq

func (q *QueryBuilder) Eq(field, value string) *QueryBuilder

Eq adds an equality filter: field=eq.value

func (*QueryBuilder) Gte

func (q *QueryBuilder) Gte(field, value string) *QueryBuilder

Gte adds a greater than or equal filter: field=gte.value

func (*QueryBuilder) In

func (q *QueryBuilder) In(field string, values []string) *QueryBuilder

In adds an IN filter: field=in.(value1,value2,...) This is useful for batch queries to avoid N+1 problems.

func (*QueryBuilder) IsFalse

func (q *QueryBuilder) IsFalse(field string) *QueryBuilder

IsFalse adds a boolean false check: field=eq.false

func (*QueryBuilder) IsNull

func (q *QueryBuilder) IsNull(field string) *QueryBuilder

IsNull adds a null check: field=is.null

func (*QueryBuilder) IsTrue

func (q *QueryBuilder) IsTrue(field string) *QueryBuilder

IsTrue adds a boolean true check: field=eq.true

func (*QueryBuilder) Limit

func (q *QueryBuilder) Limit(n int) *QueryBuilder

Limit sets the result limit.

func (*QueryBuilder) Lte

func (q *QueryBuilder) Lte(field, value string) *QueryBuilder

Lte adds a less than or equal filter: field=lte.value

func (*QueryBuilder) OrderAsc

func (q *QueryBuilder) OrderAsc(field string) *QueryBuilder

OrderAsc adds ascending order: order=field.asc

func (*QueryBuilder) OrderDesc

func (q *QueryBuilder) OrderDesc(field string) *QueryBuilder

OrderDesc adds descending order: order=field.desc

type Repository

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

Repository provides data access methods.

func NewRepository

func NewRepository(client *Client) *Repository

NewRepository creates a new repository.

func (*Repository) CreateAPIKey

func (r *Repository) CreateAPIKey(ctx context.Context, key *APIKey) error

CreateAPIKey creates a new API key.

func (*Repository) CreateDepositRequest

func (r *Repository) CreateDepositRequest(ctx context.Context, deposit *DepositRequest) error

CreateDepositRequest creates a new deposit request.

func (*Repository) CreateGasBankAccount

func (r *Repository) CreateGasBankAccount(ctx context.Context, account *GasBankAccount) error

CreateGasBankAccount creates a new gas bank account.

func (*Repository) CreateGasBankTransaction

func (r *Repository) CreateGasBankTransaction(ctx context.Context, tx *GasBankTransaction) error

CreateGasBankTransaction creates a new gas bank transaction record.

func (*Repository) CreatePriceFeed

func (r *Repository) CreatePriceFeed(ctx context.Context, feed *PriceFeed) error

CreatePriceFeed creates a new price feed entry.

func (*Repository) CreateServiceRequest

func (r *Repository) CreateServiceRequest(ctx context.Context, req *ServiceRequest) error

CreateServiceRequest creates a new service request.

func (*Repository) CreateUser

func (r *Repository) CreateUser(ctx context.Context, user *User) error

CreateUser creates a new user.

func (*Repository) CreateWallet

func (r *Repository) CreateWallet(ctx context.Context, wallet *UserWallet) error

CreateWallet creates a new wallet binding.

func (*Repository) DeductFeeAtomic

func (r *Repository) DeductFeeAtomic(ctx context.Context, userID string, amount int64, tx *GasBankTransaction) (int64, error)

DeductFeeAtomic atomically deducts a fee from a user's balance and records the transaction. Uses optimistic locking with version check to ensure atomicity.

func (*Repository) DeleteWallet

func (r *Repository) DeleteWallet(ctx context.Context, walletID, userID string) error

DeleteWallet deletes a wallet binding.

func (*Repository) GetAPIKeyByHash

func (r *Repository) GetAPIKeyByHash(ctx context.Context, keyHash string) (*APIKey, error)

GetAPIKeyByHash retrieves an API key by its hash.

func (*Repository) GetAPIKeys

func (r *Repository) GetAPIKeys(ctx context.Context, userID string) ([]APIKey, error)

GetAPIKeys retrieves all API keys for a user.

func (*Repository) GetDepositByTxHash

func (r *Repository) GetDepositByTxHash(ctx context.Context, txHash string) (*DepositRequest, error)

GetDepositByTxHash retrieves a deposit by transaction hash.

func (*Repository) GetDepositRequests

func (r *Repository) GetDepositRequests(ctx context.Context, userID string, limit int) ([]DepositRequest, error)

GetDepositRequests retrieves deposit requests for a user.

func (*Repository) GetGasBankAccount

func (r *Repository) GetGasBankAccount(ctx context.Context, userID string) (*GasBankAccount, error)

GetGasBankAccount retrieves a gas bank account.

func (*Repository) GetGasBankTransactions

func (r *Repository) GetGasBankTransactions(ctx context.Context, accountID string, limit int) ([]GasBankTransaction, error)

GetGasBankTransactions retrieves transaction history for an account.

func (*Repository) GetLatestPrice

func (r *Repository) GetLatestPrice(ctx context.Context, feedID string) (*PriceFeed, error)

GetLatestPrice retrieves the latest price for a feed.

func (*Repository) GetOrCreateGasBankAccount

func (r *Repository) GetOrCreateGasBankAccount(ctx context.Context, userID string) (*GasBankAccount, error)

GetOrCreateGasBankAccount gets or creates a gas bank account for a user. Uses upsert pattern to handle race conditions safely.

func (*Repository) GetPendingDeposits

func (r *Repository) GetPendingDeposits(ctx context.Context, limit int) ([]DepositRequest, error)

GetPendingDeposits retrieves pending and confirming deposits that may need verification or cleanup.

func (*Repository) GetServiceRequests

func (r *Repository) GetServiceRequests(ctx context.Context, userID string, limit int) ([]ServiceRequest, error)

GetServiceRequests retrieves service requests for a user.

func (*Repository) GetUser

func (r *Repository) GetUser(ctx context.Context, id string) (*User, error)

GetUser retrieves a user by ID.

func (*Repository) GetUserByAddress

func (r *Repository) GetUserByAddress(ctx context.Context, address string) (*User, error)

GetUserByAddress retrieves a user by wallet address.

func (*Repository) GetUserByEmail

func (r *Repository) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail retrieves a user by email.

func (*Repository) GetUserWallets

func (r *Repository) GetUserWallets(ctx context.Context, userID string) ([]UserWallet, error)

GetUserWallets retrieves all wallets for a user.

func (*Repository) GetWallet

func (r *Repository) GetWallet(ctx context.Context, walletID, userID string) (*UserWallet, error)

GetWallet retrieves a wallet by ID for a specific user.

func (*Repository) GetWalletByAddress

func (r *Repository) GetWalletByAddress(ctx context.Context, address string) (*UserWallet, error)

GetWalletByAddress retrieves a wallet by address.

func (*Repository) HealthCheck

func (r *Repository) HealthCheck(ctx context.Context) error

HealthCheck verifies database connectivity by issuing a lightweight query.

func (*Repository) Request

func (r *Repository) Request(ctx context.Context, method, table string, body interface{}, query string) ([]byte, error)

Request makes an HTTP request to the Supabase REST API. This method is exported to allow service-specific repositories to make database calls.

func (*Repository) RevokeAPIKey

func (r *Repository) RevokeAPIKey(ctx context.Context, keyID, userID string) error

RevokeAPIKey revokes an API key.

func (*Repository) SetPrimaryWallet

func (r *Repository) SetPrimaryWallet(ctx context.Context, userID, walletID string) error

SetPrimaryWallet sets a wallet as primary.

func (*Repository) UpdateAPIKeyLastUsed

func (r *Repository) UpdateAPIKeyLastUsed(ctx context.Context, keyID string) error

UpdateAPIKeyLastUsed updates the last_used timestamp.

func (*Repository) UpdateDepositStatus

func (r *Repository) UpdateDepositStatus(ctx context.Context, depositID, status string, confirmations int) error

UpdateDepositStatus updates a deposit request status.

func (*Repository) UpdateGasBankBalance

func (r *Repository) UpdateGasBankBalance(ctx context.Context, userID string, balance, reserved int64) error

UpdateGasBankBalance updates a gas bank account balance.

func (*Repository) UpdateServiceRequest

func (r *Repository) UpdateServiceRequest(ctx context.Context, req *ServiceRequest) error

UpdateServiceRequest updates a service request.

func (*Repository) UpdateUserEmail

func (r *Repository) UpdateUserEmail(ctx context.Context, userID, email string) error

UpdateUserEmail updates user's email.

func (*Repository) UpdateUserNonce

func (r *Repository) UpdateUserNonce(ctx context.Context, userID, nonce string) error

UpdateUserNonce updates the user's nonce for signature verification.

func (*Repository) VerifyWallet

func (r *Repository) VerifyWallet(ctx context.Context, walletID, signature string) error

VerifyWallet marks a wallet as verified.

type RepositoryInterface

type RepositoryInterface interface {
	BaseRepository
	PriceFeedRepository
	// HealthCheck verifies connectivity with the underlying database.
	HealthCheck(ctx context.Context) error
}

RepositoryInterface defines all data access methods. Service-specific operations have been moved to services/*/supabase packages. This interface now only contains shared operations used by multiple services.

type ServiceRequest

type ServiceRequest struct {
	ID          string          `json:"id"`
	UserID      string          `json:"user_id"`
	ServiceType string          `json:"service_type"`
	Status      string          `json:"status"`
	Payload     json.RawMessage `json:"payload"`
	Result      json.RawMessage `json:"result,omitempty"`
	Error       string          `json:"error,omitempty"`
	GasUsed     int64           `json:"gas_used"`
	CreatedAt   time.Time       `json:"created_at"`
	CompletedAt time.Time       `json:"completed_at,omitempty"`
}

ServiceRequest represents a service request.

type ServiceRequestRepository

type ServiceRequestRepository interface {
	GetServiceRequests(ctx context.Context, userID string, limit int) ([]ServiceRequest, error)
	CreateServiceRequest(ctx context.Context, req *ServiceRequest) error
	UpdateServiceRequest(ctx context.Context, req *ServiceRequest) error
}

ServiceRequestRepository defines service request data access methods.

type User

type User struct {
	ID        string    `json:"id"`
	Address   string    `json:"address,omitempty"`
	Email     string    `json:"email,omitempty"`
	Nonce     string    `json:"nonce,omitempty"` // For signature verification
	CreatedAt time.Time `json:"created_at,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitempty"`
}

User represents a user account.

type UserRepository

type UserRepository interface {
	GetUser(ctx context.Context, id string) (*User, error)
	GetUserByAddress(ctx context.Context, address string) (*User, error)
	GetUserByEmail(ctx context.Context, email string) (*User, error)
	CreateUser(ctx context.Context, user *User) error
	UpdateUserEmail(ctx context.Context, userID, email string) error
	UpdateUserNonce(ctx context.Context, userID, nonce string) error
}

UserRepository defines user-related data access methods.

type UserWallet

type UserWallet struct {
	ID                    string    `json:"id"`
	UserID                string    `json:"user_id"`
	Address               string    `json:"address"`
	Label                 string    `json:"label,omitempty"`
	IsPrimary             bool      `json:"is_primary"`
	Verified              bool      `json:"verified"`
	VerificationMessage   string    `json:"verification_message,omitempty"`
	VerificationSignature string    `json:"verification_signature,omitempty"`
	CreatedAt             time.Time `json:"created_at"`
}

UserWallet represents a user's wallet binding.

Jump to

Keyboard shortcuts

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