feat: explorer API, wallet, CCIP scripts, and config refresh
- Backend REST/gateway/track routes, analytics, Blockscout proxy paths. - Frontend wallet and liquidity surfaces; MetaMask token list alignment. - Deployment docs, verification scripts, address inventory updates. Check: go build ./... under backend/ (pass). Made-with: Cursor
This commit is contained in:
@@ -3,6 +3,7 @@ package analytics
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -28,60 +29,64 @@ type BridgeStats struct {
|
||||
|
||||
// ChainStats represents chain statistics
|
||||
type ChainStats struct {
|
||||
Outbound int
|
||||
Inbound int
|
||||
VolumeOut string
|
||||
VolumeIn string
|
||||
Outbound int
|
||||
Inbound int
|
||||
VolumeOut string
|
||||
VolumeIn string
|
||||
}
|
||||
|
||||
// TokenStats represents token statistics
|
||||
type TokenStats struct {
|
||||
Token string
|
||||
Symbol string
|
||||
Transfers int
|
||||
Volume string
|
||||
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'
|
||||
`
|
||||
|
||||
clauses := []string{"timestamp >= NOW() - INTERVAL '24 hours'"}
|
||||
args := []interface{}{}
|
||||
argIndex := 1
|
||||
|
||||
if chainFrom != nil {
|
||||
query += fmt.Sprintf(" AND chain_from = $%d", argIndex)
|
||||
clauses = append(clauses, fmt.Sprintf("chain_from = $%d", argIndex))
|
||||
args = append(args, *chainFrom)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
if chainTo != nil {
|
||||
query += fmt.Sprintf(" AND chain_to = $%d", argIndex)
|
||||
clauses = append(clauses, fmt.Sprintf("chain_to = $%d", argIndex))
|
||||
args = append(args, *chainTo)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
if startDate != nil {
|
||||
query += fmt.Sprintf(" AND timestamp >= $%d", argIndex)
|
||||
clauses = append(clauses, fmt.Sprintf("timestamp >= $%d", argIndex))
|
||||
args = append(args, *startDate)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
if endDate != nil {
|
||||
query += fmt.Sprintf(" AND timestamp <= $%d", argIndex)
|
||||
clauses = append(clauses, fmt.Sprintf("timestamp <= $%d", argIndex))
|
||||
args = append(args, *endDate)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
filteredCTE := fmt.Sprintf(`
|
||||
WITH filtered AS (
|
||||
SELECT chain_from, chain_to, token_contract, amount
|
||||
FROM analytics_bridge_history
|
||||
WHERE %s
|
||||
)
|
||||
`, strings.Join(clauses, " AND "))
|
||||
|
||||
var transfers24h int
|
||||
var volume24h string
|
||||
err := ba.db.QueryRow(ctx, query, args...).Scan(&transfers24h, &volume24h)
|
||||
err := ba.db.QueryRow(ctx, filteredCTE+`
|
||||
SELECT COUNT(*) as transfers_24h, COALESCE(SUM(amount)::text, '0') as volume_24h
|
||||
FROM filtered
|
||||
`, args...).Scan(&transfers24h, &volume24h)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get bridge stats: %w", err)
|
||||
}
|
||||
@@ -93,21 +98,28 @@ func (ba *BridgeAnalytics) GetBridgeStats(ctx context.Context, chainFrom, chainT
|
||||
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
|
||||
`
|
||||
rows, err := ba.db.Query(ctx, filteredCTE+`
|
||||
SELECT
|
||||
chain_id,
|
||||
SUM(outbound) as outbound,
|
||||
SUM(inbound) as inbound,
|
||||
COALESCE(SUM(volume_out)::text, '0') as volume_out,
|
||||
COALESCE(SUM(volume_in)::text, '0') as volume_in
|
||||
FROM (
|
||||
SELECT chain_from AS chain_id, 1 AS outbound, 0 AS inbound, amount AS volume_out, 0::numeric AS volume_in
|
||||
FROM filtered
|
||||
UNION ALL
|
||||
SELECT chain_to AS chain_id, 0 AS outbound, 1 AS inbound, 0::numeric AS volume_out, amount AS volume_in
|
||||
FROM filtered
|
||||
) chain_rollup
|
||||
GROUP BY chain_id
|
||||
ORDER BY chain_id
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get chain breakdown: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// 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
|
||||
@@ -120,8 +132,30 @@ func (ba *BridgeAnalytics) GetBridgeStats(ctx context.Context, chainFrom, chainT
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
tokenRows, err := ba.db.Query(ctx, filteredCTE+`
|
||||
SELECT
|
||||
token_contract,
|
||||
COUNT(*) as transfers,
|
||||
COALESCE(SUM(amount)::text, '0') as volume
|
||||
FROM filtered
|
||||
WHERE token_contract IS NOT NULL AND token_contract <> ''
|
||||
GROUP BY token_contract
|
||||
ORDER BY transfers DESC, volume DESC
|
||||
LIMIT 10
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get top bridge tokens: %w", err)
|
||||
}
|
||||
defer tokenRows.Close()
|
||||
|
||||
for tokenRows.Next() {
|
||||
var token TokenStats
|
||||
if err := tokenRows.Scan(&token.Token, &token.Transfers, &token.Volume); err != nil {
|
||||
continue
|
||||
}
|
||||
stats.TopTokens = append(stats.TopTokens, token)
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,13 +3,15 @@ package analytics
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// TokenDistribution provides token distribution analytics
|
||||
type TokenDistribution struct {
|
||||
db *pgxpool.Pool
|
||||
db *pgxpool.Pool
|
||||
chainID int
|
||||
}
|
||||
|
||||
@@ -23,12 +25,12 @@ func NewTokenDistribution(db *pgxpool.Pool, chainID int) *TokenDistribution {
|
||||
|
||||
// DistributionStats represents token distribution statistics
|
||||
type DistributionStats struct {
|
||||
Contract string
|
||||
Symbol string
|
||||
TotalSupply string
|
||||
Holders int
|
||||
Distribution map[string]string
|
||||
TopHolders []HolderInfo
|
||||
Contract string
|
||||
Symbol string
|
||||
TotalSupply string
|
||||
Holders int
|
||||
Distribution map[string]string
|
||||
TopHolders []HolderInfo
|
||||
}
|
||||
|
||||
// HolderInfo represents holder information
|
||||
@@ -76,13 +78,16 @@ func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract
|
||||
defer rows.Close()
|
||||
|
||||
topHolders := []HolderInfo{}
|
||||
totalSupplyRat, ok := parseNumericString(totalSupply)
|
||||
if !ok || totalSupplyRat.Sign() <= 0 {
|
||||
totalSupplyRat = big.NewRat(0, 1)
|
||||
}
|
||||
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
|
||||
holder.Percentage = formatPercentage(holder.Balance, totalSupplyRat, 4)
|
||||
topHolders = append(topHolders, holder)
|
||||
}
|
||||
|
||||
@@ -94,11 +99,132 @@ func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract
|
||||
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
|
||||
balances, err := td.loadHolderBalances(ctx, contract)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to compute holder metrics: %w", err)
|
||||
}
|
||||
|
||||
stats.Distribution["top_10_percent"] = concentrationPercent(balances, totalSupplyRat, 0.10)
|
||||
stats.Distribution["top_1_percent"] = concentrationPercent(balances, totalSupplyRat, 0.01)
|
||||
stats.Distribution["gini_coefficient"] = giniCoefficient(balances)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (td *TokenDistribution) loadHolderBalances(ctx context.Context, contract string) ([]*big.Rat, error) {
|
||||
rows, err := td.db.Query(ctx, `
|
||||
SELECT balance
|
||||
FROM token_balances
|
||||
WHERE token_contract = $1 AND chain_id = $2 AND balance > 0
|
||||
ORDER BY balance DESC
|
||||
`, contract, td.chainID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
balances := make([]*big.Rat, 0)
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
continue
|
||||
}
|
||||
if balance, ok := parseNumericString(raw); ok && balance.Sign() > 0 {
|
||||
balances = append(balances, balance)
|
||||
}
|
||||
}
|
||||
|
||||
return balances, nil
|
||||
}
|
||||
|
||||
func parseNumericString(raw string) (*big.Rat, bool) {
|
||||
value, ok := new(big.Rat).SetString(raw)
|
||||
return value, ok
|
||||
}
|
||||
|
||||
func formatPercentage(raw string, total *big.Rat, decimals int) string {
|
||||
value, ok := parseNumericString(raw)
|
||||
if !ok {
|
||||
return "0"
|
||||
}
|
||||
return formatRatioAsPercent(value, total, decimals)
|
||||
}
|
||||
|
||||
func concentrationPercent(balances []*big.Rat, total *big.Rat, percentile float64) string {
|
||||
if len(balances) == 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
count := int(math.Ceil(float64(len(balances)) * percentile))
|
||||
if count < 1 {
|
||||
count = 1
|
||||
}
|
||||
if count > len(balances) {
|
||||
count = len(balances)
|
||||
}
|
||||
|
||||
sum := new(big.Rat)
|
||||
for i := 0; i < count; i++ {
|
||||
sum.Add(sum, balances[i])
|
||||
}
|
||||
|
||||
return formatRatioAsPercent(sum, total, 4)
|
||||
}
|
||||
|
||||
func formatRatioAsPercent(value, total *big.Rat, decimals int) string {
|
||||
if value == nil || total == nil || total.Sign() <= 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
percent := new(big.Rat).Quo(value, total)
|
||||
percent.Mul(percent, big.NewRat(100, 1))
|
||||
return formatRat(percent, decimals)
|
||||
}
|
||||
|
||||
func giniCoefficient(balances []*big.Rat) string {
|
||||
if len(balances) == 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
total := new(big.Rat)
|
||||
for _, balance := range balances {
|
||||
total.Add(total, balance)
|
||||
}
|
||||
if total.Sign() <= 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
weightedSum := new(big.Rat)
|
||||
n := len(balances)
|
||||
for i := range balances {
|
||||
index := n - i
|
||||
weighted := new(big.Rat).Mul(balances[i], big.NewRat(int64(index), 1))
|
||||
weightedSum.Add(weightedSum, weighted)
|
||||
}
|
||||
|
||||
nRat := big.NewRat(int64(n), 1)
|
||||
numerator := new(big.Rat).Mul(weightedSum, big.NewRat(2, 1))
|
||||
denominator := new(big.Rat).Mul(nRat, total)
|
||||
gini := new(big.Rat).Quo(numerator, denominator)
|
||||
gini.Sub(gini, new(big.Rat).Quo(big.NewRat(int64(n+1), 1), nRat))
|
||||
|
||||
if gini.Sign() < 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
return formatRat(gini, 6)
|
||||
}
|
||||
|
||||
func formatRat(value *big.Rat, decimals int) string {
|
||||
if value == nil {
|
||||
return "0"
|
||||
}
|
||||
text := new(big.Float).SetPrec(256).SetRat(value).Text('f', decimals)
|
||||
for len(text) > 1 && text[len(text)-1] == '0' {
|
||||
text = text[:len(text)-1]
|
||||
}
|
||||
if len(text) > 1 && text[len(text)-1] == '.' {
|
||||
text = text[:len(text)-1]
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user