Add full monorepo: virtual-banker, backend, frontend, docs, scripts, deployment

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
defiQUG
2026-02-10 11:32:49 -08:00
parent 4d4f8cedad
commit 903c03c65b
815 changed files with 125522 additions and 264 deletions

View File

@@ -0,0 +1,100 @@
package analytics
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
)
// AddressRiskAnalyzer analyzes address risk
type AddressRiskAnalyzer struct {
db *pgxpool.Pool
chainID int
}
// NewAddressRiskAnalyzer creates a new address risk analyzer
func NewAddressRiskAnalyzer(db *pgxpool.Pool, chainID int) *AddressRiskAnalyzer {
return &AddressRiskAnalyzer{
db: db,
chainID: chainID,
}
}
// RiskAnalysis represents address risk analysis
type RiskAnalysis struct {
Address string
RiskScore float64
RiskLevel string
Factors map[string]bool
Flags []string
}
// AnalyzeAddress analyzes risk for an address
func (ara *AddressRiskAnalyzer) AnalyzeAddress(ctx context.Context, address string) (*RiskAnalysis, error) {
// Get address statistics
query := `
SELECT
tx_count_sent,
tx_count_received,
total_sent_wei,
total_received_wei
FROM addresses
WHERE address = $1 AND chain_id = $2
`
var txSent, txReceived int
var totalSent, totalReceived string
err := ara.db.QueryRow(ctx, query, address, ara.chainID).Scan(&txSent, &txReceived, &totalSent, &totalReceived)
if err != nil {
// Address not found, return low risk
return &RiskAnalysis{
Address: address,
RiskScore: 0.0,
RiskLevel: "low",
Factors: make(map[string]bool),
Flags: []string{},
}, nil
}
// Calculate risk score (simplified)
riskScore := 0.0
factors := make(map[string]bool)
flags := []string{}
// High volume = lower risk
if txSent+txReceived > 100 {
factors["high_volume"] = true
riskScore -= 0.1
}
// Check for suspicious patterns (simplified)
if txSent > 1000 && txReceived == 0 {
factors["suspicious_activity"] = true
riskScore += 0.3
flags = append(flags, "high_outbound_only")
}
// Normalize risk score
if riskScore < 0 {
riskScore = 0
}
if riskScore > 1 {
riskScore = 1
}
riskLevel := "low"
if riskScore > 0.7 {
riskLevel = "high"
} else if riskScore > 0.4 {
riskLevel = "medium"
}
return &RiskAnalysis{
Address: address,
RiskScore: riskScore,
RiskLevel: riskLevel,
Factors: factors,
Flags: flags,
}, nil
}

View File

@@ -0,0 +1,127 @@
package analytics
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// BridgeAnalytics provides bridge analytics
type BridgeAnalytics struct {
db *pgxpool.Pool
}
// NewBridgeAnalytics creates a new bridge analytics instance
func NewBridgeAnalytics(db *pgxpool.Pool) *BridgeAnalytics {
return &BridgeAnalytics{db: db}
}
// BridgeStats represents bridge statistics
type BridgeStats struct {
Transfers24h int
Volume24h string
Chains map[int]ChainStats
TopTokens []TokenStats
}
// ChainStats represents chain statistics
type ChainStats struct {
Outbound int
Inbound int
VolumeOut string
VolumeIn string
}
// TokenStats represents token statistics
type TokenStats struct {
Token string
Symbol string
Transfers int
Volume string
}
// GetBridgeStats gets bridge statistics
func (ba *BridgeAnalytics) GetBridgeStats(ctx context.Context, chainFrom, chainTo *int, startDate, endDate *time.Time) (*BridgeStats, error) {
query := `
SELECT
COUNT(*) as transfers_24h,
SUM(amount) as volume_24h
FROM analytics_bridge_history
WHERE timestamp >= NOW() - INTERVAL '24 hours'
`
args := []interface{}{}
argIndex := 1
if chainFrom != nil {
query += fmt.Sprintf(" AND chain_from = $%d", argIndex)
args = append(args, *chainFrom)
argIndex++
}
if chainTo != nil {
query += fmt.Sprintf(" AND chain_to = $%d", argIndex)
args = append(args, *chainTo)
argIndex++
}
if startDate != nil {
query += fmt.Sprintf(" AND timestamp >= $%d", argIndex)
args = append(args, *startDate)
argIndex++
}
if endDate != nil {
query += fmt.Sprintf(" AND timestamp <= $%d", argIndex)
args = append(args, *endDate)
argIndex++
}
var transfers24h int
var volume24h string
err := ba.db.QueryRow(ctx, query, args...).Scan(&transfers24h, &volume24h)
if err != nil {
return nil, fmt.Errorf("failed to get bridge stats: %w", err)
}
stats := &BridgeStats{
Transfers24h: transfers24h,
Volume24h: volume24h,
Chains: make(map[int]ChainStats),
TopTokens: []TokenStats{},
}
// Get chain stats
chainQuery := `
SELECT
chain_from,
COUNT(*) FILTER (WHERE chain_from = $1) as outbound,
COUNT(*) FILTER (WHERE chain_to = $1) as inbound,
SUM(amount) FILTER (WHERE chain_from = $1) as volume_out,
SUM(amount) FILTER (WHERE chain_to = $1) as volume_in
FROM analytics_bridge_history
WHERE (chain_from = $1 OR chain_to = $1) AND timestamp >= NOW() - INTERVAL '24 hours'
GROUP BY chain_from
`
// Simplified - in production, iterate over all chains
rows, _ := ba.db.Query(ctx, chainQuery, 138)
for rows.Next() {
var chainID, outbound, inbound int
var volumeOut, volumeIn string
if err := rows.Scan(&chainID, &outbound, &inbound, &volumeOut, &volumeIn); err == nil {
stats.Chains[chainID] = ChainStats{
Outbound: outbound,
Inbound: inbound,
VolumeOut: volumeOut,
VolumeIn: volumeIn,
}
}
}
rows.Close()
return stats, nil
}

View File

@@ -0,0 +1,133 @@
package analytics
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
)
// Calculator calculates network analytics
type Calculator struct {
db *pgxpool.Pool
chainID int
}
// NewCalculator creates a new analytics calculator
func NewCalculator(db *pgxpool.Pool, chainID int) *Calculator {
return &Calculator{
db: db,
chainID: chainID,
}
}
// NetworkStats represents network statistics
type NetworkStats struct {
CurrentBlock int64 `json:"current_block"`
TPS float64 `json:"tps"`
GPS float64 `json:"gps"`
AvgGasPrice int64 `json:"avg_gas_price"`
PendingTransactions int `json:"pending_transactions"`
BlockTime float64 `json:"block_time_seconds"`
}
// CalculateNetworkStats calculates current network statistics
func (c *Calculator) CalculateNetworkStats(ctx context.Context) (*NetworkStats, error) {
// Get current block
var currentBlock int64
err := c.db.QueryRow(ctx,
`SELECT MAX(number) FROM blocks WHERE chain_id = $1`,
c.chainID,
).Scan(&currentBlock)
if err != nil {
return nil, fmt.Errorf("failed to get current block: %w", err)
}
// Get transactions in last 10 blocks
var txCount int
var totalGas int64
var blockTimeSum float64
query := `
SELECT
COUNT(*) as tx_count,
SUM(gas_used) as total_gas,
EXTRACT(EPOCH FROM (MAX(timestamp) - MIN(timestamp))) / COUNT(DISTINCT block_number) as avg_block_time
FROM transactions
WHERE chain_id = $1 AND block_number > $2
`
err = c.db.QueryRow(ctx, query, c.chainID, currentBlock-10).Scan(&txCount, &totalGas, &blockTimeSum)
if err != nil {
txCount = 0
totalGas = 0
blockTimeSum = 0
}
// Calculate TPS and GPS
tps := float64(txCount) / (blockTimeSum * 10)
gps := float64(totalGas) / (blockTimeSum * 10)
// Get average gas price
var avgGasPrice int64
c.db.QueryRow(ctx,
`SELECT AVG(gas_price) FROM transactions WHERE chain_id = $1 AND block_number > $2 AND gas_price IS NOT NULL`,
c.chainID, currentBlock-100,
).Scan(&avgGasPrice)
// Get pending transactions
var pendingTx int
c.db.QueryRow(ctx,
`SELECT COUNT(*) FROM mempool_transactions WHERE chain_id = $1 AND status = 'pending'`,
c.chainID,
).Scan(&pendingTx)
return &NetworkStats{
CurrentBlock: currentBlock,
TPS: tps,
GPS: gps,
AvgGasPrice: avgGasPrice,
PendingTransactions: pendingTx,
BlockTime: blockTimeSum,
}, nil
}
// TopContracts gets top contracts by transaction count
func (c *Calculator) TopContracts(ctx context.Context, limit int) ([]ContractStats, error) {
query := `
SELECT
to_address as contract_address,
COUNT(*) as tx_count,
SUM(value) as total_value
FROM transactions
WHERE chain_id = $1 AND to_address IS NOT NULL
GROUP BY to_address
ORDER BY tx_count DESC
LIMIT $2
`
rows, err := c.db.Query(ctx, query, c.chainID, limit)
if err != nil {
return nil, fmt.Errorf("failed to query top contracts: %w", err)
}
defer rows.Close()
var contracts []ContractStats
for rows.Next() {
var contract ContractStats
if err := rows.Scan(&contract.Address, &contract.TransactionCount, &contract.TotalValue); err != nil {
continue
}
contracts = append(contracts, contract)
}
return contracts, nil
}
// ContractStats represents contract statistics
type ContractStats struct {
Address string
TransactionCount int64
TotalValue string
}

View File

@@ -0,0 +1,119 @@
package analytics
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// FlowTracker tracks address-to-address flows
type FlowTracker struct {
db *pgxpool.Pool
chainID int
}
// NewFlowTracker creates a new flow tracker
func NewFlowTracker(db *pgxpool.Pool, chainID int) *FlowTracker {
return &FlowTracker{
db: db,
chainID: chainID,
}
}
// Flow represents a flow between addresses
type Flow struct {
From string
To string
Token string
Amount string
Count int
FirstSeen time.Time
LastSeen time.Time
}
// TrackFlow tracks a flow between addresses
func (ft *FlowTracker) TrackFlow(ctx context.Context, from, to, token string, amount string) error {
query := `
INSERT INTO analytics_flows (
chain_id, from_address, to_address, token_contract,
total_amount, transfer_count, first_seen, last_seen
) VALUES ($1, $2, $3, $4, $5, 1, NOW(), NOW())
ON CONFLICT (chain_id, from_address, to_address, token_contract) DO UPDATE SET
total_amount = analytics_flows.total_amount + $5::numeric,
transfer_count = analytics_flows.transfer_count + 1,
last_seen = NOW(),
updated_at = NOW()
`
_, err := ft.db.Exec(ctx, query, ft.chainID, from, to, token, amount)
if err != nil {
return fmt.Errorf("failed to track flow: %w", err)
}
return nil
}
// GetFlows gets flows matching criteria
func (ft *FlowTracker) GetFlows(ctx context.Context, from, to, token string, startDate, endDate *time.Time, limit int) ([]Flow, error) {
query := `
SELECT from_address, to_address, token_contract, total_amount, transfer_count, first_seen, last_seen
FROM analytics_flows
WHERE chain_id = $1
`
args := []interface{}{ft.chainID}
argIndex := 2
if from != "" {
query += fmt.Sprintf(" AND from_address = $%d", argIndex)
args = append(args, from)
argIndex++
}
if to != "" {
query += fmt.Sprintf(" AND to_address = $%d", argIndex)
args = append(args, to)
argIndex++
}
if token != "" {
query += fmt.Sprintf(" AND token_contract = $%d", argIndex)
args = append(args, token)
argIndex++
}
if startDate != nil {
query += fmt.Sprintf(" AND last_seen >= $%d", argIndex)
args = append(args, *startDate)
argIndex++
}
if endDate != nil {
query += fmt.Sprintf(" AND last_seen <= $%d", argIndex)
args = append(args, *endDate)
argIndex++
}
query += " ORDER BY last_seen DESC LIMIT $" + fmt.Sprintf("%d", argIndex)
args = append(args, limit)
rows, err := ft.db.Query(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("failed to query flows: %w", err)
}
defer rows.Close()
flows := []Flow{}
for rows.Next() {
var f Flow
if err := rows.Scan(&f.From, &f.To, &f.Token, &f.Amount, &f.Count, &f.FirstSeen, &f.LastSeen); err != nil {
continue
}
flows = append(flows, f)
}
return flows, nil
}

View File

@@ -0,0 +1,104 @@
package analytics
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
)
// TokenDistribution provides token distribution analytics
type TokenDistribution struct {
db *pgxpool.Pool
chainID int
}
// NewTokenDistribution creates a new token distribution analyzer
func NewTokenDistribution(db *pgxpool.Pool, chainID int) *TokenDistribution {
return &TokenDistribution{
db: db,
chainID: chainID,
}
}
// DistributionStats represents token distribution statistics
type DistributionStats struct {
Contract string
Symbol string
TotalSupply string
Holders int
Distribution map[string]string
TopHolders []HolderInfo
}
// HolderInfo represents holder information
type HolderInfo struct {
Address string
Balance string
Percentage string
}
// GetTokenDistribution gets token distribution for a contract
func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract string, topN int) (*DistributionStats, error) {
// Refresh materialized view
_, err := td.db.Exec(ctx, `REFRESH MATERIALIZED VIEW CONCURRENTLY token_distribution`)
if err != nil {
// Ignore error if view doesn't exist yet
}
// Get distribution from materialized view
query := `
SELECT holder_count, total_balance
FROM token_distribution
WHERE token_contract = $1 AND chain_id = $2
`
var holders int
var totalSupply string
err = td.db.QueryRow(ctx, query, contract, td.chainID).Scan(&holders, &totalSupply)
if err != nil {
return nil, fmt.Errorf("failed to get distribution: %w", err)
}
// Get top holders
topHoldersQuery := `
SELECT address, balance
FROM token_balances
WHERE token_contract = $1 AND chain_id = $2 AND balance > 0
ORDER BY balance DESC
LIMIT $3
`
rows, err := td.db.Query(ctx, topHoldersQuery, contract, td.chainID, topN)
if err != nil {
return nil, fmt.Errorf("failed to get top holders: %w", err)
}
defer rows.Close()
topHolders := []HolderInfo{}
for rows.Next() {
var holder HolderInfo
if err := rows.Scan(&holder.Address, &holder.Balance); err != nil {
continue
}
// Calculate percentage (simplified)
holder.Percentage = "0.0" // TODO: Calculate from total supply
topHolders = append(topHolders, holder)
}
stats := &DistributionStats{
Contract: contract,
Holders: holders,
TotalSupply: totalSupply,
Distribution: make(map[string]string),
TopHolders: topHolders,
}
// Calculate distribution metrics
stats.Distribution["top_10_percent"] = "0.0" // TODO: Calculate
stats.Distribution["top_1_percent"] = "0.0" // TODO: Calculate
stats.Distribution["gini_coefficient"] = "0.0" // TODO: Calculate
return stats, nil
}