Compare commits

..

1 Commits

Author SHA1 Message Date
defiQUG
74b175c2ce Fix address detail loading states 2026-04-16 14:11:18 -07:00
10 changed files with 161 additions and 221 deletions

View File

@@ -2,102 +2,71 @@ name: CI
on:
push:
branches: [ master, main, develop ]
branches: [ main, develop ]
pull_request:
branches: [ master, main, develop ]
# Cancel in-flight runs on the same ref to save CI minutes.
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
GO_VERSION: '1.23.4'
NODE_VERSION: '20'
branches: [ main, develop ]
jobs:
test-backend:
name: Backend (go 1.23.x)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: backend/go.sum
- name: go vet
working-directory: backend
run: go vet ./...
- name: go build
working-directory: backend
run: go build ./...
- name: go test
working-directory: backend
run: go test ./...
scan-backend:
name: Backend security scanners
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: backend/go.sum
- name: Install staticcheck
run: go install honnef.co/go/tools/cmd/staticcheck@v0.5.1
- name: Install govulncheck
run: go install golang.org/x/vuln/cmd/govulncheck@latest
- name: staticcheck
working-directory: backend
run: staticcheck ./...
- name: govulncheck
working-directory: backend
run: govulncheck ./...
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: actions/setup-go@v4
with:
go-version: '1.22'
- name: Run tests
run: |
cd backend
go test ./...
- name: Build
run: |
cd backend
go build ./...
test-frontend:
name: Frontend (node 20)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci
- name: Lint (eslint)
working-directory: frontend
run: npm run lint
- name: Type-check (tsc)
working-directory: frontend
run: npm run type-check
- name: Build
working-directory: frontend
run: npm run build
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: actions/setup-node@v3
with:
node-version: '20'
- name: Install dependencies
run: |
cd frontend
npm ci
- name: Run tests
run: |
cd frontend
npm test
- name: Build
run: |
cd frontend
npm run build
gitleaks:
name: gitleaks (secret scan)
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
# Full history so we can also scan past commits, not just the tip.
fetch-depth: 0
- name: Run gitleaks
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Repo-local config lives at .gitleaks.toml.
GITLEAKS_CONFIG: .gitleaks.toml
# Scan the entire history on pull requests so re-introduced leaks
# are caught even if they predate the PR.
GITLEAKS_ENABLE_SUMMARY: 'true'
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: actions/setup-go@v4
with:
go-version: '1.22'
- uses: actions/setup-node@v3
with:
node-version: '20'
- name: Backend lint
run: |
cd backend
go vet ./...
- name: Frontend lint
run: |
cd frontend
npm ci
npm run lint
npm run type-check

View File

@@ -1,24 +0,0 @@
# gitleaks configuration for explorer-monorepo.
#
# Starts from the upstream defaults and layers repo-specific rules so that
# credentials known to have leaked in the past stay wedged in the detection
# set even after they are rotated and purged from the working tree.
#
# See docs/SECURITY.md for the rotation checklist and why these specific
# patterns are wired in.
[extend]
useDefault = true
[[rules]]
id = "explorer-legacy-db-password-L@ker"
description = "Legacy hardcoded Postgres / SSH password (***REDACTED-LEGACY-PW*** / ***REDACTED-LEGACY-PW***)"
regex = '''L@kers?\$?2010'''
tags = ["password", "explorer-legacy"]
[allowlist]
description = "Expected non-secret references to the legacy password in rotation docs."
paths = [
'''^docs/SECURITY\.md$''',
'''^CHANGELOG\.md$''',
]

View File

@@ -42,11 +42,10 @@ type HolderInfo struct {
// GetTokenDistribution gets token distribution for a contract
func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract string, topN int) (*DistributionStats, error) {
// Refresh the materialized view. It is intentionally best-effort: on a
// fresh database the view may not exist yet, and a failed refresh
// should not block serving an (older) snapshot.
if _, err := td.db.Exec(ctx, `REFRESH MATERIALIZED VIEW CONCURRENTLY token_distribution`); err != nil {
_ = err
// 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
@@ -58,7 +57,8 @@ func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract
var holders int
var totalSupply string
if err := td.db.QueryRow(ctx, query, contract, td.chainID).Scan(&holders, &totalSupply); err != nil {
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)
}

View File

@@ -41,11 +41,14 @@ func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
})
}
// compressionMiddleware is a pass-through today; it exists so that the
// routing stack can be composed without conditionals while we evaluate the
// right compression approach (likely gorilla/handlers.CompressHandler in a
// follow-up). Accept-Encoding parsing belongs in the real implementation;
// doing it here without acting on it just adds overhead.
// compressionMiddleware adds gzip compression (simplified - use gorilla/handlers in production)
func (s *Server) compressionMiddleware(next http.Handler) http.Handler {
return next
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if client accepts gzip
if r.Header.Get("Accept-Encoding") != "" {
// In production, use gorilla/handlers.CompressHandler
// For now, just pass through
}
next.ServeHTTP(w, r)
})
}

View File

@@ -475,12 +475,8 @@ func (s *Server) HandleMissionControlBridgeTrace(w http.ResponseWriter, r *http.
body, statusCode, err := fetchBlockscoutTransaction(r.Context(), tx)
if err == nil && statusCode == http.StatusOK {
var txDoc map[string]interface{}
if uerr := json.Unmarshal(body, &txDoc); uerr != nil {
// Fall through to the RPC fallback below. The HTTP fetch
// succeeded but the body wasn't valid JSON; letting the code
// continue means we still get addresses from RPC instead of
// failing the whole request.
_ = uerr
if err := json.Unmarshal(body, &txDoc); err != nil {
err = fmt.Errorf("invalid blockscout JSON")
} else {
fromAddr = extractEthAddress(txDoc["from"])
toAddr = extractEthAddress(txDoc["to"])

View File

@@ -87,12 +87,9 @@ func (t *Tracer) storeTrace(ctx context.Context, txHash common.Hash, blockNumber
) PARTITION BY LIST (chain_id)
`
// Ensure the table exists. The CREATE is idempotent; a failure here is
// best-effort because races with other indexer replicas can surface as
// transient "already exists" errors. The follow-up INSERT will surface
// any real schema problem.
if _, err := t.db.Exec(ctx, query); err != nil {
_ = err
_, err := t.db.Exec(ctx, query)
if err != nil {
// Table might already exist
}
// Insert trace

View File

@@ -86,14 +86,7 @@ func (bi *BlockIndexer) IndexLatestBlocks(ctx context.Context, count int) error
latestBlock := header.Number.Uint64()
// `count` may legitimately reach back farther than latestBlock (e.g.
// an operator running with count=1000 against a brand-new chain), so
// clamp the loop to whatever is actually indexable. The previous
// "latestBlock-uint64(i) >= 0" guard was a no-op on an unsigned type.
for i := 0; i < count; i++ {
if uint64(i) > latestBlock {
break
}
for i := 0; i < count && latestBlock-uint64(i) >= 0; i++ {
blockNum := latestBlock - uint64(i)
if err := bi.IndexBlock(ctx, blockNum); err != nil {
// Log error but continue

View File

@@ -1,17 +0,0 @@
checks = [
"all",
# Style / unused nits. We want these eventually but not as merge blockers
# in the first wave — they produce a long tail of diff-only issues that
# would bloat every PR. Re-enable in a dedicated cleanup PR.
"-ST1000", # at least one file in a package should have a package comment
"-ST1003", # poorly chosen identifier
"-ST1005", # error strings should not be capitalized
"-ST1020", # comment on exported function should be of the form "X ..."
"-ST1021", # comment on exported type should be of the form "X ..."
"-ST1022", # comment on exported var/const should be of the form "X ..."
"-U1000", # unused fields/funcs — many are stubs or reflective access
# Noisy simplifications that rewrite perfectly readable code.
"-S1016", # should use type conversion instead of struct literal
"-S1031", # unnecessary nil check around range — defensive anyway
]

View File

@@ -6,15 +6,6 @@ import (
"time"
)
// ctxKey is an unexported type for tracer context keys so they cannot
// collide with keys installed by any other package (staticcheck SA1029).
type ctxKey string
const (
ctxKeyTraceID ctxKey = "trace_id"
ctxKeySpanID ctxKey = "span_id"
)
// Tracer provides distributed tracing
type Tracer struct {
serviceName string
@@ -57,8 +48,9 @@ func (t *Tracer) StartSpan(ctx context.Context, name string) (*Span, context.Con
Logs: []LogEntry{},
}
ctx = context.WithValue(ctx, ctxKeyTraceID, traceID)
ctx = context.WithValue(ctx, ctxKeySpanID, spanID)
// Add to context
ctx = context.WithValue(ctx, "trace_id", traceID)
ctx = context.WithValue(ctx, "span_id", spanID)
return span, ctx
}

View File

@@ -51,14 +51,17 @@ export default function AddressDetailPage() {
const [watchlistEntries, setWatchlistEntries] = useState<string[]>([])
const [methodResults, setMethodResults] = useState<Record<string, { loading: boolean; value?: string; error?: string }>>({})
const [methodInputs, setMethodInputs] = useState<Record<string, string[]>>({})
const [loading, setLoading] = useState(true)
const [addressInfoLoading, setAddressInfoLoading] = useState(true)
const [activityLoading, setActivityLoading] = useState(true)
const loadAddressInfo = useCallback(async () => {
setAddressInfoLoading(true)
try {
const { ok, data } = await addressesApi.getSafe(chainId, address)
if (!ok) {
setAddressInfo(null)
setContractProfile(null)
setGruProfile(null)
return
}
setAddressInfo(data ?? null)
@@ -82,10 +85,13 @@ export default function AddressDetailPage() {
setAddressInfo(null)
setContractProfile(null)
setGruProfile(null)
} finally {
setAddressInfoLoading(false)
}
}, [chainId, address])
const loadTransactions = useCallback(async () => {
setActivityLoading(true)
try {
const [transactionsResult, balancesResult, transfersResult] = await Promise.all([
addressesApi.getTransactionsSafe(chainId, address, 1, 20),
@@ -102,27 +108,37 @@ export default function AddressDetailPage() {
setTokenBalances([])
setTokenTransfers([])
} finally {
setLoading(false)
setActivityLoading(false)
}
}, [chainId, address])
useEffect(() => {
if (!router.isReady || !address) {
setLoading(router.isReady ? false : true)
setAddressInfoLoading(!router.isReady)
setActivityLoading(!router.isReady)
if (router.isReady && !address) {
setAddressInfo(null)
setTransactions([])
setTokenBalances([])
setTokenTransfers([])
}
return
}
if (!isValidAddressParam) {
setLoading(false)
setAddressInfoLoading(false)
setActivityLoading(false)
setAddressInfo(null)
setTransactions([])
setTokenBalances([])
setTokenTransfers([])
return
}
loadAddressInfo()
loadTransactions()
setAddressInfo(null)
setTransactions([])
setTokenBalances([])
setTokenTransfers([])
void loadAddressInfo()
void loadTransactions()
}, [address, isValidAddressParam, loadAddressInfo, loadTransactions, router.isReady])
useEffect(() => {
@@ -403,6 +419,8 @@ export default function AddressDetailPage() {
const gruTransferCount = tokenTransfers.filter((transfer) =>
Boolean(getGruExplorerMetadata({ address: transfer.token_address, symbol: transfer.token_symbol })),
).length
const showPrimaryLoadingState = !router.isReady || (addressInfoLoading && !addressInfo)
const resolvedAddressInfo = addressInfo as AddressInfo
return (
<div className="container mx-auto px-4 py-6 sm:py-8">
@@ -426,7 +444,7 @@ export default function AddressDetailPage() {
Search this address
</Link>
)}
{watchlistAddress && router.isReady && !loading && (
{watchlistAddress && router.isReady && !addressInfoLoading && (
<button
type="button"
onClick={handleWatchlistToggle}
@@ -437,7 +455,7 @@ export default function AddressDetailPage() {
)}
</div>
{!router.isReady || loading ? (
{showPrimaryLoadingState ? (
<Card className="mb-6">
<p className="text-sm text-gray-600 dark:text-gray-400">Loading address...</p>
</Card>
@@ -453,7 +471,7 @@ export default function AddressDetailPage() {
</Link>
</div>
</Card>
) : !addressInfo ? (
) : !addressInfoLoading && !addressInfo ? (
<Card className="mb-6">
<p className="text-sm text-gray-600 dark:text-gray-400">Address not found.</p>
<div className="mt-4 flex flex-wrap gap-3 text-sm">
@@ -470,68 +488,69 @@ export default function AddressDetailPage() {
<Card title="Address Information" className="mb-6">
<dl className="space-y-4">
<DetailRow label="Address">
<Address address={addressInfo.address} />
<Address address={resolvedAddressInfo.address} />
</DetailRow>
{addressInfo.balance && (
<DetailRow label="Coin Balance">{formatWeiAsEth(addressInfo.balance)}</DetailRow>
{resolvedAddressInfo.balance && (
<DetailRow label="Coin Balance">{formatWeiAsEth(resolvedAddressInfo.balance)}</DetailRow>
)}
<DetailRow label="Watchlist">
{isSavedToWatchlist ? 'Saved for quick access' : 'Not saved yet'}
</DetailRow>
<DetailRow label="Verification">
<div className="flex flex-wrap gap-2">
<EntityBadge label={addressInfo.is_contract ? (addressInfo.is_verified ? 'verified' : 'contract') : 'eoa'} />
<EntityBadge label={resolvedAddressInfo.is_contract ? (resolvedAddressInfo.is_verified ? 'verified' : 'contract') : 'eoa'} />
{contractProfile?.source_verified ? <EntityBadge label="source available" tone="success" /> : null}
{contractProfile?.abi_available ? <EntityBadge label="abi available" tone="info" /> : null}
{addressInfo.token_contract ? <EntityBadge label={addressInfo.token_contract.type || 'token'} tone="info" /> : null}
{resolvedAddressInfo.token_contract ? <EntityBadge label={resolvedAddressInfo.token_contract.type || 'token'} tone="info" /> : null}
</div>
</DetailRow>
{addressInfo.token_contract && (
{resolvedAddressInfo.token_contract && (
<DetailRow label="Token Contract">
<div className="space-y-2">
<div>
{addressInfo.token_contract.symbol || addressInfo.token_contract.name || 'Token contract'} · {addressInfo.token_contract.type || 'Token'}
{resolvedAddressInfo.token_contract.symbol || resolvedAddressInfo.token_contract.name || 'Token contract'} · {resolvedAddressInfo.token_contract.type || 'Token'}
</div>
<Link href={`/tokens/${addressInfo.token_contract.address}`} className="text-primary-600 hover:underline">
<Link href={`/tokens/${resolvedAddressInfo.token_contract.address}`} className="text-primary-600 hover:underline">
Open token detail
</Link>
</div>
</DetailRow>
)}
{addressInfo.tags.length > 0 && (
{resolvedAddressInfo.tags.length > 0 && (
<DetailRow label="Tags" valueClassName="flex flex-wrap gap-2">
{addressInfo.tags.map((tag, i) => (
{resolvedAddressInfo.tags.map((tag, i) => (
<EntityBadge key={i} label={tag} className="px-2 py-1 text-[11px]" />
))}
</DetailRow>
)}
<DetailRow label="Transactions">{addressInfo.transaction_count}</DetailRow>
<DetailRow label="Tokens">{addressInfo.token_count}</DetailRow>
<DetailRow label="Type">{addressInfo.is_contract ? 'Contract' : 'EOA'}</DetailRow>
<DetailRow label="Transactions">{resolvedAddressInfo.transaction_count}</DetailRow>
<DetailRow label="Tokens">{resolvedAddressInfo.token_count}</DetailRow>
<DetailRow label="Type">{resolvedAddressInfo.is_contract ? 'Contract' : 'EOA'}</DetailRow>
<DetailRow label="Recent Activity">
{incomingTransactions} incoming / {outgoingTransactions} outgoing txs
{activityLoading ? 'Loading recent activity...' : `${incomingTransactions} incoming / ${outgoingTransactions} outgoing txs`}
</DetailRow>
{addressInfo.internal_transaction_count != null && (
<DetailRow label="Internal Calls">{addressInfo.internal_transaction_count}</DetailRow>
{resolvedAddressInfo.internal_transaction_count != null && (
<DetailRow label="Internal Calls">{resolvedAddressInfo.internal_transaction_count}</DetailRow>
)}
{addressInfo.logs_count != null && (
<DetailRow label="Indexed Logs">{addressInfo.logs_count}</DetailRow>
{resolvedAddressInfo.logs_count != null && (
<DetailRow label="Indexed Logs">{resolvedAddressInfo.logs_count}</DetailRow>
)}
<DetailRow label="Token Flow">
{incomingTokenTransfers} incoming / {outgoingTokenTransfers} outgoing token transfers
{addressInfo.token_transfer_count != null ? ` · ${addressInfo.token_transfer_count} total indexed` : ''}
{activityLoading
? 'Loading token transfer activity...'
: `${incomingTokenTransfers} incoming / ${outgoingTokenTransfers} outgoing token transfers${resolvedAddressInfo.token_transfer_count != null ? ` · ${resolvedAddressInfo.token_transfer_count} total indexed` : ''}`}
</DetailRow>
{addressInfo.creation_transaction_hash && (
{resolvedAddressInfo.creation_transaction_hash && (
<DetailRow label="Created In">
<Link href={`/transactions/${addressInfo.creation_transaction_hash}`} className="text-primary-600 hover:underline">
<Address address={addressInfo.creation_transaction_hash} truncate showCopy={false} />
<Link href={`/transactions/${resolvedAddressInfo.creation_transaction_hash}`} className="text-primary-600 hover:underline">
<Address address={resolvedAddressInfo.creation_transaction_hash} truncate showCopy={false} />
</Link>
</DetailRow>
)}
</dl>
</Card>
{addressInfo.is_contract && (
{resolvedAddressInfo.is_contract && (
<Card title="Contract Profile" className="mb-6">
<dl className="space-y-4">
<DetailRow label="Interaction Surface">
@@ -771,12 +790,16 @@ export default function AddressDetailPage() {
</Link>
</div>
) : null}
<Table
columns={tokenBalanceColumns}
data={tokenBalances}
emptyMessage="No token balances were indexed for this address."
keyExtractor={(balance) => balance.token_address || `${balance.token_symbol}-${balance.value}`}
/>
{activityLoading ? (
<p className="text-sm text-gray-600 dark:text-gray-400">Loading token balances...</p>
) : (
<Table
columns={tokenBalanceColumns}
data={tokenBalances}
emptyMessage="No token balances were indexed for this address."
keyExtractor={(balance) => balance.token_address || `${balance.token_symbol}-${balance.value}`}
/>
)}
</Card>
<Card title="Recent Token Transfers" className="mb-6">
@@ -791,21 +814,29 @@ export default function AddressDetailPage() {
</Link>
</div>
) : null}
<Table
columns={tokenTransferColumns}
data={tokenTransfers}
emptyMessage="No token transfers were found for this address."
keyExtractor={(transfer) => `${transfer.transaction_hash}-${transfer.token_address}-${transfer.value}`}
/>
{activityLoading ? (
<p className="text-sm text-gray-600 dark:text-gray-400">Loading token transfers...</p>
) : (
<Table
columns={tokenTransferColumns}
data={tokenTransfers}
emptyMessage="No token transfers were found for this address."
keyExtractor={(transfer) => `${transfer.transaction_hash}-${transfer.token_address}-${transfer.value}`}
/>
)}
</Card>
<Card title="Transactions">
<Table
columns={transactionColumns}
data={transactions}
emptyMessage="No recent transactions were found for this address."
keyExtractor={(tx) => tx.hash}
/>
{activityLoading ? (
<p className="text-sm text-gray-600 dark:text-gray-400">Loading recent transactions...</p>
) : (
<Table
columns={transactionColumns}
data={transactions}
emptyMessage="No recent transactions were found for this address."
keyExtractor={(tx) => tx.hash}
/>
)}
</Card>
</>
)}