Compare commits
40 Commits
devin/1776
...
e397245ec9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e397245ec9 | ||
|
|
8cd8bfa195 | ||
|
|
3b7e24080f | ||
|
|
ba08199051 | ||
|
|
0ba2a70c34 | ||
|
|
ac40184d6b | ||
|
|
7a16ddccf7 | ||
|
|
1f5167aded | ||
|
|
f5eb874210 | ||
|
|
1aa81f454a | ||
|
|
1b5cebf505 | ||
| fe9edd842b | |||
| fdb14dc420 | |||
| 7c018965eb | |||
| 78e1ff5dc8 | |||
| fbe0f3e4aa | |||
| 791184be34 | |||
| 14b04f2730 | |||
| 152e0d7345 | |||
| 16d21345d7 | |||
| 6edaffb57f | |||
| 9d0c4394ec | |||
| 19bafbc53b | |||
| 4887e689d7 | |||
| 12ea869f7e | |||
| e43575ea26 | |||
| 2c8d3d222e | |||
| d4849da50d | |||
| c16a7855d5 | |||
| 08946a1971 | |||
| 174cbfde04 | |||
| 8c7e1c70de | |||
| 29fe704f3c | |||
| 070f935e46 | |||
| 945e637d1d | |||
| f4e235edc6 | |||
| 66f35fa2aa | |||
|
|
def11dd624 | ||
| ad69385beb | |||
| db4b9a4240 |
43
.gitea/workflows/deploy-live.yml
Normal file
43
.gitea/workflows/deploy-live.yml
Normal file
@@ -0,0 +1,43 @@
|
||||
name: Deploy Explorer Live
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, master]
|
||||
paths:
|
||||
- '.gitea/workflows/deploy-live.yml'
|
||||
- 'backend/**'
|
||||
- 'config/**'
|
||||
- 'deployment/**'
|
||||
- 'docs/**'
|
||||
- 'frontend/**'
|
||||
- 'scripts/**'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
- 'Makefile'
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Validate live deploy assets
|
||||
run: |
|
||||
test -f scripts/deploy-explorer-config-to-vmid5000.sh
|
||||
test -f scripts/deploy-explorer-ai-to-vmid5000.sh
|
||||
test -f scripts/deploy-next-frontend-to-vmid5000.sh
|
||||
test -f deployment/LIVE_DEPLOYMENT_MAP.md
|
||||
|
||||
- name: Trigger explorer-live deployment
|
||||
run: |
|
||||
SHA="$(git rev-parse HEAD)"
|
||||
BRANCH="${GITHUB_REF_NAME:-}"
|
||||
if [ -z "$BRANCH" ] || [ "$BRANCH" = "HEAD" ]; then
|
||||
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
|
||||
fi
|
||||
curl -sSf -X POST "${{ secrets.PHOENIX_DEPLOY_URL }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.PHOENIX_DEPLOY_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"repo\":\"${{ gitea.repository }}\",\"sha\":\"${SHA}\",\"branch\":\"${BRANCH}\",\"target\":\"explorer-live\"}"
|
||||
141
.github/workflows/ci.yml
vendored
141
.github/workflows/ci.yml
vendored
@@ -2,71 +2,102 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
branches: [ master, main, develop ]
|
||||
pull_request:
|
||||
branches: [ main, develop ]
|
||||
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'
|
||||
|
||||
jobs:
|
||||
test-backend:
|
||||
name: Backend (go 1.23.x)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- 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 ./...
|
||||
- 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 ./...
|
||||
|
||||
test-frontend:
|
||||
name: Frontend (node 20)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- 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
|
||||
- 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
|
||||
|
||||
lint:
|
||||
gitleaks:
|
||||
name: gitleaks (secret scan)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- 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
|
||||
|
||||
- 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'
|
||||
|
||||
71
.github/workflows/e2e-full.yml
vendored
Normal file
71
.github/workflows/e2e-full.yml
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
name: e2e-full
|
||||
|
||||
# Boots the full explorer stack (docker-compose deps + backend + frontend)
|
||||
# and runs the Playwright full-stack smoke spec against it. Not on every
|
||||
# PR (too expensive) — runs on:
|
||||
#
|
||||
# * workflow_dispatch (manual)
|
||||
# * pull_request when the 'run-e2e-full' label is applied
|
||||
# * nightly at 04:00 UTC
|
||||
#
|
||||
# Screenshots from every route are uploaded as a build artefact so
|
||||
# reviewers can eyeball the render without having to boot the stack.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
types: [labeled, opened, synchronize, reopened]
|
||||
schedule:
|
||||
- cron: '0 4 * * *'
|
||||
|
||||
jobs:
|
||||
e2e-full:
|
||||
if: >
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
github.event_name == 'schedule' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
contains(github.event.pull_request.labels.*.name, 'run-e2e-full'))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.23.x'
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install root Playwright dependency
|
||||
run: npm ci --no-audit --no-fund --prefix .
|
||||
|
||||
- name: Run full-stack e2e
|
||||
env:
|
||||
JWT_SECRET: ${{ secrets.JWT_SECRET || 'ci-ephemeral-jwt-secret-not-for-prod' }}
|
||||
CSP_HEADER: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' http://localhost:8080 ws://localhost:8080"
|
||||
run: make e2e-full
|
||||
|
||||
- name: Upload screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-screenshots
|
||||
path: test-results/screenshots/
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Upload playwright report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: playwright-report
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
if-no-files-found: warn
|
||||
13
.gitignore
vendored
13
.gitignore
vendored
@@ -49,3 +49,16 @@ temp/
|
||||
*.test
|
||||
*.out
|
||||
go.work
|
||||
|
||||
# Compiled Go binaries (built artifacts, not source)
|
||||
backend/bin/
|
||||
backend/api/rest/cmd/api-server
|
||||
backend/cmd
|
||||
|
||||
# Tooling / scratch directories
|
||||
out/
|
||||
cache/
|
||||
test-results/
|
||||
playwright-report/
|
||||
.playwright/
|
||||
coverage/
|
||||
|
||||
24
.gitleaks.toml
Normal file
24
.gitleaks.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
# 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). Matches both the expanded form and the shell-escaped form (backslash-dollar) that appeared in scripts/setup-database.sh."
|
||||
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$''',
|
||||
]
|
||||
@@ -9,14 +9,16 @@ echo " SolaceScan Deployment"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Configuration
|
||||
DB_PASSWORD='***REDACTED-LEGACY-PW***'
|
||||
DB_HOST='localhost'
|
||||
DB_USER='explorer'
|
||||
DB_NAME='explorer'
|
||||
RPC_URL='http://192.168.11.250:8545'
|
||||
CHAIN_ID=138
|
||||
PORT=8080
|
||||
# Configuration. All secrets MUST be provided via environment variables; no
|
||||
# credentials are committed to this repo. See docs/SECURITY.md for the
|
||||
# rotation checklist.
|
||||
: "${DB_PASSWORD:?DB_PASSWORD is required (export it or source your secrets file)}"
|
||||
DB_HOST="${DB_HOST:-localhost}"
|
||||
DB_USER="${DB_USER:-explorer}"
|
||||
DB_NAME="${DB_NAME:-explorer}"
|
||||
RPC_URL="${RPC_URL:?RPC_URL is required}"
|
||||
CHAIN_ID="${CHAIN_ID:-138}"
|
||||
PORT="${PORT:-8080}"
|
||||
|
||||
# Step 1: Test database connection
|
||||
echo "[1/6] Testing database connection..."
|
||||
|
||||
@@ -8,11 +8,13 @@ cd "$(dirname "$0")"
|
||||
echo "=== Complete Deployment Execution ==="
|
||||
echo ""
|
||||
|
||||
# Database credentials
|
||||
export DB_PASSWORD='***REDACTED-LEGACY-PW***'
|
||||
export DB_HOST='localhost'
|
||||
export DB_USER='explorer'
|
||||
export DB_NAME='explorer'
|
||||
# Database credentials. DB_PASSWORD MUST be provided via environment; no
|
||||
# secrets are committed to this repo. See docs/SECURITY.md.
|
||||
: "${DB_PASSWORD:?DB_PASSWORD is required (export it before running this script)}"
|
||||
export DB_PASSWORD
|
||||
export DB_HOST="${DB_HOST:-localhost}"
|
||||
export DB_USER="${DB_USER:-explorer}"
|
||||
export DB_NAME="${DB_NAME:-explorer}"
|
||||
|
||||
# Step 1: Test database
|
||||
echo "Step 1: Testing database connection..."
|
||||
|
||||
6
Makefile
6
Makefile
@@ -1,4 +1,4 @@
|
||||
.PHONY: help install dev build test test-e2e clean migrate
|
||||
.PHONY: help install dev build test test-e2e e2e-full clean migrate
|
||||
|
||||
help:
|
||||
@echo "Available targets:"
|
||||
@@ -7,6 +7,7 @@ help:
|
||||
@echo " build - Build all services"
|
||||
@echo " test - Run backend + frontend tests (go test, lint, type-check)"
|
||||
@echo " test-e2e - Run Playwright E2E tests (default: explorer.d-bis.org)"
|
||||
@echo " e2e-full - Boot full stack locally (docker compose + backend + frontend) and run Playwright"
|
||||
@echo " clean - Clean build artifacts"
|
||||
@echo " migrate - Run database migrations"
|
||||
|
||||
@@ -35,6 +36,9 @@ test:
|
||||
test-e2e:
|
||||
npx playwright test
|
||||
|
||||
e2e-full:
|
||||
./scripts/e2e-full.sh
|
||||
|
||||
clean:
|
||||
cd backend && go clean ./...
|
||||
cd frontend && rm -rf .next node_modules
|
||||
|
||||
137
README.md
137
README.md
@@ -1,88 +1,93 @@
|
||||
# SolaceScan Explorer - Tiered Architecture
|
||||
# SolaceScan Explorer
|
||||
|
||||
## 🚀 Quick Start - Complete Deployment
|
||||
Multi-tier block explorer and access-control plane for **Chain 138**.
|
||||
|
||||
**Execute this single command to complete all deployment steps:**
|
||||
Four access tiers:
|
||||
|
||||
```bash
|
||||
cd ~/projects/proxmox/explorer-monorepo
|
||||
bash EXECUTE_DEPLOYMENT.sh
|
||||
| Track | Who | Auth | Examples |
|
||||
|------|-----|------|---------|
|
||||
| 1 | Public | None | `/blocks`, `/transactions`, `/search` |
|
||||
| 2 | Wallet-verified | SIWE JWT | RPC API keys, subscriptions, usage reports |
|
||||
| 3 | Analytics | SIWE JWT (admin or billed) | Advanced analytics, audit logs |
|
||||
| 4 | Operator | SIWE JWT (`operator.*`) | `run-script`, mission-control, ops |
|
||||
|
||||
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for diagrams of how the
|
||||
tracks, services, and data stores fit together, and [docs/API.md](docs/API.md)
|
||||
for the endpoint reference generated from `backend/api/rest/swagger.yaml`.
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
backend/ Go 1.23 services (api/rest, indexer, auth, analytics, ...)
|
||||
frontend/ Next.js 14 pages-router app
|
||||
deployment/ docker-compose and deploy manifests
|
||||
scripts/ e2e specs, smoke scripts, operator runbooks
|
||||
docs/ Architecture, API, testing, security, runbook
|
||||
```
|
||||
|
||||
## What This Does
|
||||
## Quickstart (local)
|
||||
|
||||
1. ✅ Tests database connection
|
||||
2. ✅ Runs migration (if needed)
|
||||
3. ✅ Stops existing server
|
||||
4. ✅ Starts server with database
|
||||
5. ✅ Tests all endpoints
|
||||
6. ✅ Provides status summary
|
||||
Prereqs: Docker (+ compose), Go 1.23.x, Node 20.
|
||||
|
||||
## Manual Execution
|
||||
```bash
|
||||
# 1. Infra deps
|
||||
docker compose -f deployment/docker-compose.yml up -d postgres elasticsearch redis
|
||||
|
||||
If the script doesn't work, see [QUICKSTART.md](QUICKSTART.md) for step-by-step manual commands.
|
||||
# 2. DB schema
|
||||
cd backend && go run database/migrations/migrate.go && cd ..
|
||||
|
||||
## Frontend
|
||||
# 3. Backend (port 8080)
|
||||
export JWT_SECRET=$(openssl rand -hex 32)
|
||||
export CSP_HEADER="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' http://localhost:8080 ws://localhost:8080"
|
||||
cd backend/api/rest && go run . &
|
||||
|
||||
- **Production (canonical target):** the current **Next.js standalone frontend** in `frontend/src/`, built from `frontend/` with `npm run build` and deployed to VMID 5000 as a Node service behind nginx.
|
||||
- **Canonical deploy script:** `./scripts/deploy-next-frontend-to-vmid5000.sh`
|
||||
- **Canonical nginx wiring:** keep `/api`, `/api/config/*`, `/explorer-api/*`, `/token-aggregation/api/v1/*`, `/snap/`, and `/health`; proxy `/` and `/_next/` to the frontend service using `deployment/common/nginx-next-frontend-proxy.conf`.
|
||||
- **Legacy fallback only:** the static SPA (`frontend/public/index.html` + `explorer-spa.js`) remains in-repo for compatibility/reference, but it is not a supported primary deployment target.
|
||||
- **Architecture command center:** `frontend/public/chain138-command-center.html` — tabbed Mermaid topology (Chain 138 hub, network, stack, flows, cross-chain, cW Mainnet, off-chain, integrations). Linked from the SPA **More → Explore → Visual Command Center**.
|
||||
- **Legacy static deploy scripts:** `./scripts/deploy-frontend-to-vmid5000.sh` and `./scripts/deploy.sh` now fail fast with a deprecation message and point to the canonical Next.js deploy path.
|
||||
- **Frontend review & tasks:** [frontend/FRONTEND_REVIEW.md](frontend/FRONTEND_REVIEW.md), [frontend/FRONTEND_TASKS_AND_REVIEW.md](frontend/FRONTEND_TASKS_AND_REVIEW.md)
|
||||
# 4. Frontend (port 3000)
|
||||
cd frontend && npm ci && npm run dev
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- **[QUICKSTART.md](QUICKSTART.md)** — 5-minute bring-up for local development
|
||||
- **[RUNBOOK.md](RUNBOOK.md)** — Operational runbook for the live deployment
|
||||
- **[CONTRIBUTING.md](CONTRIBUTING.md)** — Contribution workflow and conventions
|
||||
- **[CHANGELOG.md](CHANGELOG.md)** — Release notes
|
||||
- **[docs/README.md](docs/README.md)** — Documentation index (API, architecture, CCIP, legal)
|
||||
- **[docs/EXPLORER_API_ACCESS.md](docs/EXPLORER_API_ACCESS.md)** — API access, CSP, frontend deploy
|
||||
- **[deployment/DEPLOYMENT_GUIDE.md](deployment/DEPLOYMENT_GUIDE.md)** — Full LXC/Nginx/Cloudflare deployment guide
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Track 1 (Public):** RPC Gateway - No authentication required
|
||||
- **Track 2 (Approved):** Indexed Explorer - Requires authentication
|
||||
- **Track 3 (Analytics):** Analytics Dashboard - Requires Track 3+
|
||||
- **Track 4 (Operator):** Operator Tools - Requires Track 4 + IP whitelist
|
||||
Or let `make e2e-full` do everything end-to-end and run Playwright
|
||||
against the stack (see [docs/TESTING.md](docs/TESTING.md)).
|
||||
|
||||
## Configuration
|
||||
|
||||
- **Database User:** `explorer`
|
||||
- **Database Password:** `***REDACTED-LEGACY-PW***`
|
||||
- **RPC URL:** `http://192.168.11.250:8545`
|
||||
- **Chain ID:** `138`
|
||||
- **Port:** `8080`
|
||||
Every credential, URL, and RPC endpoint is an env var. There is no
|
||||
in-repo production config. Minimum required by a non-dev binary:
|
||||
|
||||
## Reusable libs (extraction)
|
||||
| Var | Purpose | Notes |
|
||||
|-----|---------|-------|
|
||||
| `JWT_SECRET` | HS256 wallet-auth signing key | Fail-fast if empty |
|
||||
| `CSP_HEADER` | `Content-Security-Policy` response header | Fail-fast if empty |
|
||||
| `DB_HOST` / `DB_PORT` / `DB_USER` / `DB_PASSWORD` / `DB_NAME` | Postgres connection | |
|
||||
| `REDIS_HOST` / `REDIS_PORT` | Redis cache | |
|
||||
| `ELASTICSEARCH_URL` | Indexer / search backend | |
|
||||
| `RPC_URL` / `WS_URL` | Upstream Chain 138 RPC | |
|
||||
| `RPC_PRODUCTS_PATH` | Optional override for `backend/config/rpc_products.yaml` | PR #7 |
|
||||
|
||||
Reusable components live under `backend/libs/` and `frontend/libs/` and may be split into separate repos and linked via **git submodules**. Clone with submodules:
|
||||
|
||||
```bash
|
||||
git clone --recurse-submodules <repo-url>
|
||||
# or after clone:
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
See [docs/REUSABLE_COMPONENTS_EXTRACTION_PLAN.md](docs/REUSABLE_COMPONENTS_EXTRACTION_PLAN.md) for the full plan.
|
||||
Full list: `deployment/ENVIRONMENT_TEMPLATE.env`.
|
||||
|
||||
## Testing
|
||||
|
||||
- **All unit/lint:** `make test` — backend `go test ./...` and frontend `npm test` (lint + type-check).
|
||||
- **Backend:** `cd backend && go test ./...` — API tests run without a real DB; health returns 200 or 503, DB-dependent endpoints return 503 when DB is nil.
|
||||
- **Frontend:** `cd frontend && npm run build` or `npm test` — Next.js build (includes lint) or lint + type-check only.
|
||||
- **E2E:** `make test-e2e` or `npm run e2e` from repo root — Playwright tests against https://blockscout.defi-oracle.io by default; use `EXPLORER_URL=http://localhost:3000` for local.
|
||||
```bash
|
||||
# Unit tests + static checks
|
||||
cd backend && go test ./... && staticcheck ./... && govulncheck ./...
|
||||
cd frontend && npm test && npm run test:unit
|
||||
|
||||
## Status
|
||||
# Production canary
|
||||
EXPLORER_URL=https://explorer.d-bis.org make test-e2e
|
||||
|
||||
✅ All implementation complete
|
||||
✅ All scripts ready
|
||||
✅ All documentation complete
|
||||
✅ Frontend: C1–C4, M1–M4, H4, H5, L2, L4 done; H1/H2/H3 (escapeHtml/safe href) in place; optional L1, L3 remain
|
||||
✅ CI: backend + frontend tests; lint job runs `go vet`, `npm run lint`, `npm run type-check`
|
||||
✅ Tests: `make test`, `make test-e2e`, `make build` all pass
|
||||
# Full local stack + Playwright
|
||||
make e2e-full
|
||||
```
|
||||
|
||||
**Ready for deployment!**
|
||||
See [docs/TESTING.md](docs/TESTING.md).
|
||||
|
||||
## Contributing
|
||||
|
||||
Branching, PR template, CI gates, secret handling: see
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md). Never commit real credentials —
|
||||
`.gitleaks.toml` will block the push and rotation steps live in
|
||||
[docs/SECURITY.md](docs/SECURITY.md).
|
||||
|
||||
## Licence
|
||||
|
||||
MIT.
|
||||
|
||||
@@ -42,10 +42,11 @@ type HolderInfo struct {
|
||||
|
||||
// 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
|
||||
// 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
|
||||
}
|
||||
|
||||
// Get distribution from materialized view
|
||||
@@ -57,8 +58,7 @@ func (td *TokenDistribution) GetTokenDistribution(ctx context.Context, contract
|
||||
|
||||
var holders int
|
||||
var totalSupply string
|
||||
err = td.db.QueryRow(ctx, query, contract, td.chainID).Scan(&holders, &totalSupply)
|
||||
if err != nil {
|
||||
if err := td.db.QueryRow(ctx, query, contract, td.chainID).Scan(&holders, &totalSupply); err != nil {
|
||||
return nil, fmt.Errorf("failed to get distribution: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -31,11 +30,7 @@ func (m *AuthMiddleware) RequireAuth(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// Add user context
|
||||
ctx := context.WithValue(r.Context(), "user_address", address)
|
||||
ctx = context.WithValue(ctx, "user_track", track)
|
||||
ctx = context.WithValue(ctx, "authenticated", true)
|
||||
|
||||
ctx := ContextWithAuth(r.Context(), address, track, true)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -44,11 +39,7 @@ func (m *AuthMiddleware) RequireAuth(next http.Handler) http.Handler {
|
||||
func (m *AuthMiddleware) RequireTrack(requiredTrack int) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Extract track from context (set by RequireAuth or OptionalAuth)
|
||||
track, ok := r.Context().Value("user_track").(int)
|
||||
if !ok {
|
||||
track = 1 // Default to Track 1 (public)
|
||||
}
|
||||
track := UserTrack(r.Context())
|
||||
|
||||
if !featureflags.HasAccess(track, requiredTrack) {
|
||||
writeForbidden(w, requiredTrack)
|
||||
@@ -65,40 +56,33 @@ func (m *AuthMiddleware) OptionalAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
address, track, err := m.extractAuth(r)
|
||||
if err != nil {
|
||||
// No auth provided, default to Track 1 (public)
|
||||
ctx := context.WithValue(r.Context(), "user_address", "")
|
||||
ctx = context.WithValue(ctx, "user_track", 1)
|
||||
ctx = context.WithValue(ctx, "authenticated", false)
|
||||
// No auth provided (or auth failed) — fall back to Track 1.
|
||||
ctx := ContextWithAuth(r.Context(), "", defaultTrackLevel, false)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
|
||||
// Auth provided, add user context
|
||||
ctx := context.WithValue(r.Context(), "user_address", address)
|
||||
ctx = context.WithValue(ctx, "user_track", track)
|
||||
ctx = context.WithValue(ctx, "authenticated", true)
|
||||
|
||||
ctx := ContextWithAuth(r.Context(), address, track, true)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// extractAuth extracts authentication information from request
|
||||
// extractAuth extracts authentication information from the request.
|
||||
// Returns ErrMissingAuthorization when no usable Bearer token is present;
|
||||
// otherwise returns the error from JWT validation.
|
||||
func (m *AuthMiddleware) extractAuth(r *http.Request) (string, int, error) {
|
||||
// Get Authorization header
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return "", 0, http.ErrMissingFile
|
||||
return "", 0, ErrMissingAuthorization
|
||||
}
|
||||
|
||||
// Check for Bearer token
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
return "", 0, http.ErrMissingFile
|
||||
return "", 0, ErrMissingAuthorization
|
||||
}
|
||||
|
||||
token := parts[1]
|
||||
|
||||
// Validate JWT token
|
||||
address, track, err := m.walletAuth.ValidateJWT(token)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
|
||||
60
backend/api/middleware/context.go
Normal file
60
backend/api/middleware/context.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ctxKey is an unexported type for request-scoped authentication values.
|
||||
// Using a distinct type (rather than a bare string) keeps our keys out of
|
||||
// collision range for any other package that also calls context.WithValue,
|
||||
// and silences go vet's SA1029.
|
||||
type ctxKey string
|
||||
|
||||
const (
|
||||
ctxKeyUserAddress ctxKey = "user_address"
|
||||
ctxKeyUserTrack ctxKey = "user_track"
|
||||
ctxKeyAuthenticated ctxKey = "authenticated"
|
||||
)
|
||||
|
||||
// Default track level applied to unauthenticated requests (Track 1 = public).
|
||||
const defaultTrackLevel = 1
|
||||
|
||||
// ErrMissingAuthorization is returned by extractAuth when no usable
|
||||
// Authorization header is present on the request. Callers should treat this
|
||||
// as "no auth supplied" rather than a hard failure for optional-auth routes.
|
||||
var ErrMissingAuthorization = errors.New("middleware: authorization header missing or malformed")
|
||||
|
||||
// ContextWithAuth returns a child context carrying the supplied
|
||||
// authentication state. It is the single place in the package that writes
|
||||
// the auth context keys.
|
||||
func ContextWithAuth(parent context.Context, address string, track int, authenticated bool) context.Context {
|
||||
ctx := context.WithValue(parent, ctxKeyUserAddress, address)
|
||||
ctx = context.WithValue(ctx, ctxKeyUserTrack, track)
|
||||
ctx = context.WithValue(ctx, ctxKeyAuthenticated, authenticated)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// UserAddress returns the authenticated wallet address stored on ctx, or
|
||||
// "" if the context is not authenticated.
|
||||
func UserAddress(ctx context.Context) string {
|
||||
addr, _ := ctx.Value(ctxKeyUserAddress).(string)
|
||||
return addr
|
||||
}
|
||||
|
||||
// UserTrack returns the access tier recorded on ctx. If no track was set
|
||||
// (e.g. the request bypassed all auth middleware) the caller receives
|
||||
// Track 1 (public) so route-level checks can still make a decision.
|
||||
func UserTrack(ctx context.Context) int {
|
||||
if track, ok := ctx.Value(ctxKeyUserTrack).(int); ok {
|
||||
return track
|
||||
}
|
||||
return defaultTrackLevel
|
||||
}
|
||||
|
||||
// IsAuthenticated reports whether the current request carried a valid auth
|
||||
// token that was successfully parsed by the middleware.
|
||||
func IsAuthenticated(ctx context.Context) bool {
|
||||
ok, _ := ctx.Value(ctxKeyAuthenticated).(bool)
|
||||
return ok
|
||||
}
|
||||
62
backend/api/middleware/context_test.go
Normal file
62
backend/api/middleware/context_test.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestContextWithAuthRoundTrip(t *testing.T) {
|
||||
ctx := ContextWithAuth(context.Background(), "0xabc", 4, true)
|
||||
|
||||
if got := UserAddress(ctx); got != "0xabc" {
|
||||
t.Fatalf("UserAddress() = %q, want %q", got, "0xabc")
|
||||
}
|
||||
if got := UserTrack(ctx); got != 4 {
|
||||
t.Fatalf("UserTrack() = %d, want 4", got)
|
||||
}
|
||||
if !IsAuthenticated(ctx) {
|
||||
t.Fatal("IsAuthenticated() = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserTrackDefaultsToTrack1OnBareContext(t *testing.T) {
|
||||
if got := UserTrack(context.Background()); got != defaultTrackLevel {
|
||||
t.Fatalf("UserTrack(empty) = %d, want %d", got, defaultTrackLevel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAddressEmptyOnBareContext(t *testing.T) {
|
||||
if got := UserAddress(context.Background()); got != "" {
|
||||
t.Fatalf("UserAddress(empty) = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAuthenticatedFalseOnBareContext(t *testing.T) {
|
||||
if IsAuthenticated(context.Background()) {
|
||||
t.Fatal("IsAuthenticated(empty) = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextKeyIsolation proves that the typed ctxKey values cannot be
|
||||
// shadowed by a caller using bare-string keys with the same spelling.
|
||||
// This is the specific class of bug fixed by this PR.
|
||||
func TestContextKeyIsolation(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), "user_address", "injected")
|
||||
if got := UserAddress(ctx); got != "" {
|
||||
t.Fatalf("expected empty address (bare string key must not collide), got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrMissingAuthorizationIsSentinel(t *testing.T) {
|
||||
if ErrMissingAuthorization == nil {
|
||||
t.Fatal("ErrMissingAuthorization must not be nil")
|
||||
}
|
||||
wrapped := errors.New("wrapped: " + ErrMissingAuthorization.Error())
|
||||
if errors.Is(wrapped, ErrMissingAuthorization) {
|
||||
t.Fatal("string-wrapped error must not satisfy errors.Is (smoke check)")
|
||||
}
|
||||
if !errors.Is(ErrMissingAuthorization, ErrMissingAuthorization) {
|
||||
t.Fatal("ErrMissingAuthorization must satisfy errors.Is against itself")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
381
backend/api/rest/ai_context.go
Normal file
381
backend/api/rest/ai_context.go
Normal file
@@ -0,0 +1,381 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
addressPattern = regexp.MustCompile(`0x[a-fA-F0-9]{40}`)
|
||||
transactionPattern = regexp.MustCompile(`0x[a-fA-F0-9]{64}`)
|
||||
blockRefPattern = regexp.MustCompile(`(?i)\bblock\s+#?(\d+)\b`)
|
||||
)
|
||||
|
||||
func (s *Server) buildAIContext(ctx context.Context, query string, pageContext map[string]string) (AIContextEnvelope, []string) {
|
||||
warnings := []string{}
|
||||
envelope := AIContextEnvelope{
|
||||
ChainID: s.chainID,
|
||||
Explorer: "SolaceScan",
|
||||
PageContext: compactStringMap(pageContext),
|
||||
CapabilityNotice: "This assistant is wired for read-only explorer analysis. It can summarize indexed chain data, liquidity routes, and curated workspace docs, but it does not sign transactions or execute private operations.",
|
||||
}
|
||||
|
||||
sources := []AIContextSource{
|
||||
{Type: "system", Label: "Explorer REST backend"},
|
||||
}
|
||||
|
||||
if stats, err := s.queryAIStats(ctx); err == nil {
|
||||
envelope.Stats = stats
|
||||
sources = append(sources, AIContextSource{Type: "database", Label: "Explorer indexer database"})
|
||||
} else if err != nil {
|
||||
warnings = append(warnings, "indexed explorer stats unavailable: "+err.Error())
|
||||
}
|
||||
|
||||
if strings.TrimSpace(query) != "" {
|
||||
if txHash := firstRegexMatch(transactionPattern, query); txHash != "" && s.db != nil {
|
||||
if tx, err := s.queryAITransaction(ctx, txHash); err == nil && len(tx) > 0 {
|
||||
envelope.Transaction = tx
|
||||
} else if err != nil {
|
||||
warnings = append(warnings, "transaction context unavailable: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if addr := firstRegexMatch(addressPattern, query); addr != "" && s.db != nil {
|
||||
if addressInfo, err := s.queryAIAddress(ctx, addr); err == nil && len(addressInfo) > 0 {
|
||||
envelope.Address = addressInfo
|
||||
} else if err != nil {
|
||||
warnings = append(warnings, "address context unavailable: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if blockNumber := extractBlockReference(query); blockNumber > 0 && s.db != nil {
|
||||
if block, err := s.queryAIBlock(ctx, blockNumber); err == nil && len(block) > 0 {
|
||||
envelope.Block = block
|
||||
} else if err != nil {
|
||||
warnings = append(warnings, "block context unavailable: "+err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if routeMatches, routeWarning := s.queryAIRoutes(ctx, query); len(routeMatches) > 0 {
|
||||
envelope.RouteMatches = routeMatches
|
||||
sources = append(sources, AIContextSource{Type: "routes", Label: "Token aggregation live routes", Origin: firstNonEmptyEnv("TOKEN_AGGREGATION_API_BASE", "TOKEN_AGGREGATION_URL", "TOKEN_AGGREGATION_BASE_URL")})
|
||||
} else if routeWarning != "" {
|
||||
warnings = append(warnings, routeWarning)
|
||||
}
|
||||
|
||||
if docs, root, docWarning := loadAIDocSnippets(query); len(docs) > 0 {
|
||||
envelope.DocSnippets = docs
|
||||
sources = append(sources, AIContextSource{Type: "docs", Label: "Workspace docs", Origin: root})
|
||||
} else if docWarning != "" {
|
||||
warnings = append(warnings, docWarning)
|
||||
}
|
||||
|
||||
envelope.Sources = sources
|
||||
return envelope, uniqueStrings(warnings)
|
||||
}
|
||||
|
||||
func (s *Server) queryAIStats(ctx context.Context) (map[string]any, error) {
|
||||
if s.db == nil {
|
||||
return nil, fmt.Errorf("database unavailable")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||
defer cancel()
|
||||
|
||||
stats := map[string]any{}
|
||||
|
||||
var totalBlocks int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM blocks WHERE chain_id = $1`, s.chainID).Scan(&totalBlocks); err == nil {
|
||||
stats["total_blocks"] = totalBlocks
|
||||
}
|
||||
|
||||
var totalTransactions int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM transactions WHERE chain_id = $1`, s.chainID).Scan(&totalTransactions); err == nil {
|
||||
stats["total_transactions"] = totalTransactions
|
||||
}
|
||||
|
||||
var totalAddresses int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM (
|
||||
SELECT from_address AS address
|
||||
FROM transactions
|
||||
WHERE chain_id = $1 AND from_address IS NOT NULL AND from_address <> ''
|
||||
UNION
|
||||
SELECT to_address AS address
|
||||
FROM transactions
|
||||
WHERE chain_id = $1 AND to_address IS NOT NULL AND to_address <> ''
|
||||
) unique_addresses`, s.chainID).Scan(&totalAddresses); err == nil {
|
||||
stats["total_addresses"] = totalAddresses
|
||||
}
|
||||
|
||||
var latestBlock int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COALESCE(MAX(number), 0) FROM blocks WHERE chain_id = $1`, s.chainID).Scan(&latestBlock); err == nil {
|
||||
stats["latest_block"] = latestBlock
|
||||
}
|
||||
|
||||
if len(stats) == 0 {
|
||||
var totalBlocks int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM blocks`).Scan(&totalBlocks); err == nil {
|
||||
stats["total_blocks"] = totalBlocks
|
||||
}
|
||||
|
||||
var totalTransactions int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM transactions`).Scan(&totalTransactions); err == nil {
|
||||
stats["total_transactions"] = totalTransactions
|
||||
}
|
||||
|
||||
var totalAddresses int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM addresses`).Scan(&totalAddresses); err == nil {
|
||||
stats["total_addresses"] = totalAddresses
|
||||
}
|
||||
|
||||
var latestBlock int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COALESCE(MAX(number), 0) FROM blocks`).Scan(&latestBlock); err == nil {
|
||||
stats["latest_block"] = latestBlock
|
||||
}
|
||||
}
|
||||
|
||||
if len(stats) == 0 {
|
||||
return nil, fmt.Errorf("no indexed stats available")
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (s *Server) queryAITransaction(ctx context.Context, hash string) (map[string]any, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||
defer cancel()
|
||||
|
||||
query := `
|
||||
SELECT hash, block_number, from_address, to_address, value, gas_used, gas_price, status, timestamp_iso
|
||||
FROM transactions
|
||||
WHERE chain_id = $1 AND hash = $2
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
var txHash, fromAddress, value string
|
||||
var blockNumber int64
|
||||
var toAddress *string
|
||||
var gasUsed, gasPrice *int64
|
||||
var status *int64
|
||||
var timestampISO *string
|
||||
|
||||
err := s.db.QueryRow(ctx, query, s.chainID, hash).Scan(
|
||||
&txHash, &blockNumber, &fromAddress, &toAddress, &value, &gasUsed, &gasPrice, &status, ×tampISO,
|
||||
)
|
||||
if err != nil {
|
||||
normalizedHash := normalizeHexString(hash)
|
||||
blockscoutQuery := `
|
||||
SELECT
|
||||
concat('0x', encode(hash, 'hex')) AS hash,
|
||||
block_number,
|
||||
concat('0x', encode(from_address_hash, 'hex')) AS from_address,
|
||||
CASE
|
||||
WHEN to_address_hash IS NULL THEN NULL
|
||||
ELSE concat('0x', encode(to_address_hash, 'hex'))
|
||||
END AS to_address,
|
||||
COALESCE(value::text, '0') AS value,
|
||||
gas_used,
|
||||
gas_price,
|
||||
status,
|
||||
TO_CHAR(block_timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS timestamp_iso
|
||||
FROM transactions
|
||||
WHERE hash = decode($1, 'hex')
|
||||
LIMIT 1
|
||||
`
|
||||
if fallbackErr := s.db.QueryRow(ctx, blockscoutQuery, normalizedHash).Scan(
|
||||
&txHash, &blockNumber, &fromAddress, &toAddress, &value, &gasUsed, &gasPrice, &status, ×tampISO,
|
||||
); fallbackErr != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
tx := map[string]any{
|
||||
"hash": txHash,
|
||||
"block_number": blockNumber,
|
||||
"from_address": fromAddress,
|
||||
"value": value,
|
||||
}
|
||||
if toAddress != nil {
|
||||
tx["to_address"] = *toAddress
|
||||
}
|
||||
if gasUsed != nil {
|
||||
tx["gas_used"] = *gasUsed
|
||||
}
|
||||
if gasPrice != nil {
|
||||
tx["gas_price"] = *gasPrice
|
||||
}
|
||||
if status != nil {
|
||||
tx["status"] = *status
|
||||
}
|
||||
if timestampISO != nil {
|
||||
tx["timestamp_iso"] = *timestampISO
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (s *Server) queryAIAddress(ctx context.Context, address string) (map[string]any, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||
defer cancel()
|
||||
|
||||
address = normalizeAddress(address)
|
||||
|
||||
result := map[string]any{
|
||||
"address": address,
|
||||
}
|
||||
|
||||
var txCount int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM transactions WHERE chain_id = $1 AND (LOWER(from_address) = $2 OR LOWER(to_address) = $2)`, s.chainID, address).Scan(&txCount); err == nil {
|
||||
result["transaction_count"] = txCount
|
||||
}
|
||||
|
||||
var tokenCount int64
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(DISTINCT token_contract) FROM token_transfers WHERE chain_id = $1 AND (LOWER(from_address) = $2 OR LOWER(to_address) = $2)`, s.chainID, address).Scan(&tokenCount); err == nil {
|
||||
result["token_count"] = tokenCount
|
||||
}
|
||||
|
||||
var recentHashes []string
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT hash
|
||||
FROM transactions
|
||||
WHERE chain_id = $1 AND (LOWER(from_address) = $2 OR LOWER(to_address) = $2)
|
||||
ORDER BY block_number DESC, transaction_index DESC
|
||||
LIMIT 5
|
||||
`, s.chainID, address)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var hash string
|
||||
if scanErr := rows.Scan(&hash); scanErr == nil {
|
||||
recentHashes = append(recentHashes, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(recentHashes) > 0 {
|
||||
result["recent_transactions"] = recentHashes
|
||||
}
|
||||
|
||||
if len(result) == 1 {
|
||||
normalizedAddress := normalizeHexString(address)
|
||||
|
||||
var blockscoutTxCount int64
|
||||
var blockscoutTokenCount int64
|
||||
blockscoutAddressQuery := `
|
||||
SELECT
|
||||
COALESCE(transactions_count, 0),
|
||||
COALESCE(token_transfers_count, 0)
|
||||
FROM addresses
|
||||
WHERE hash = decode($1, 'hex')
|
||||
LIMIT 1
|
||||
`
|
||||
if err := s.db.QueryRow(ctx, blockscoutAddressQuery, normalizedAddress).Scan(&blockscoutTxCount, &blockscoutTokenCount); err == nil {
|
||||
result["transaction_count"] = blockscoutTxCount
|
||||
result["token_count"] = blockscoutTokenCount
|
||||
}
|
||||
|
||||
var liveTxCount int64
|
||||
if err := s.db.QueryRow(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM transactions
|
||||
WHERE from_address_hash = decode($1, 'hex') OR to_address_hash = decode($1, 'hex')
|
||||
`, normalizedAddress).Scan(&liveTxCount); err == nil && liveTxCount > 0 {
|
||||
result["transaction_count"] = liveTxCount
|
||||
}
|
||||
|
||||
var liveTokenCount int64
|
||||
if err := s.db.QueryRow(ctx, `
|
||||
SELECT COUNT(DISTINCT token_contract_address_hash)
|
||||
FROM token_transfers
|
||||
WHERE from_address_hash = decode($1, 'hex') OR to_address_hash = decode($1, 'hex')
|
||||
`, normalizedAddress).Scan(&liveTokenCount); err == nil && liveTokenCount > 0 {
|
||||
result["token_count"] = liveTokenCount
|
||||
}
|
||||
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT concat('0x', encode(hash, 'hex'))
|
||||
FROM transactions
|
||||
WHERE from_address_hash = decode($1, 'hex') OR to_address_hash = decode($1, 'hex')
|
||||
ORDER BY block_number DESC, index DESC
|
||||
LIMIT 5
|
||||
`, normalizedAddress)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var hash string
|
||||
if scanErr := rows.Scan(&hash); scanErr == nil {
|
||||
recentHashes = append(recentHashes, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(recentHashes) > 0 {
|
||||
result["recent_transactions"] = recentHashes
|
||||
}
|
||||
}
|
||||
|
||||
if len(result) == 1 {
|
||||
return nil, fmt.Errorf("address not found")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Server) queryAIBlock(ctx context.Context, blockNumber int64) (map[string]any, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||
defer cancel()
|
||||
|
||||
query := `
|
||||
SELECT number, hash, parent_hash, transaction_count, gas_used, gas_limit, timestamp_iso
|
||||
FROM blocks
|
||||
WHERE chain_id = $1 AND number = $2
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
var number int64
|
||||
var hash, parentHash string
|
||||
var transactionCount int64
|
||||
var gasUsed, gasLimit int64
|
||||
var timestampISO *string
|
||||
|
||||
err := s.db.QueryRow(ctx, query, s.chainID, blockNumber).Scan(&number, &hash, &parentHash, &transactionCount, &gasUsed, &gasLimit, ×tampISO)
|
||||
if err != nil {
|
||||
blockscoutQuery := `
|
||||
SELECT
|
||||
number,
|
||||
concat('0x', encode(hash, 'hex')) AS hash,
|
||||
concat('0x', encode(parent_hash, 'hex')) AS parent_hash,
|
||||
(SELECT COUNT(*) FROM transactions WHERE block_number = b.number) AS transaction_count,
|
||||
gas_used,
|
||||
gas_limit,
|
||||
TO_CHAR(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS timestamp_iso
|
||||
FROM blocks b
|
||||
WHERE number = $1
|
||||
LIMIT 1
|
||||
`
|
||||
if fallbackErr := s.db.QueryRow(ctx, blockscoutQuery, blockNumber).Scan(&number, &hash, &parentHash, &transactionCount, &gasUsed, &gasLimit, ×tampISO); fallbackErr != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
block := map[string]any{
|
||||
"number": number,
|
||||
"hash": hash,
|
||||
"parent_hash": parentHash,
|
||||
"transaction_count": transactionCount,
|
||||
"gas_used": gasUsed,
|
||||
"gas_limit": gasLimit,
|
||||
}
|
||||
if timestampISO != nil {
|
||||
block["timestamp_iso"] = *timestampISO
|
||||
}
|
||||
return block, nil
|
||||
}
|
||||
|
||||
func extractBlockReference(query string) int64 {
|
||||
match := blockRefPattern.FindStringSubmatch(query)
|
||||
if len(match) != 2 {
|
||||
return 0
|
||||
}
|
||||
var value int64
|
||||
fmt.Sscan(match[1], &value)
|
||||
return value
|
||||
}
|
||||
136
backend/api/rest/ai_docs.go
Normal file
136
backend/api/rest/ai_docs.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func loadAIDocSnippets(query string) ([]AIDocSnippet, string, string) {
|
||||
root := findAIWorkspaceRoot()
|
||||
if root == "" {
|
||||
return nil, "", "workspace docs root unavailable for ai doc retrieval"
|
||||
}
|
||||
|
||||
relativePaths := []string{
|
||||
"docs/11-references/ADDRESS_MATRIX_AND_STATUS.md",
|
||||
"docs/11-references/LIQUIDITY_POOLS_MASTER_MAP.md",
|
||||
"docs/11-references/DEPLOYED_TOKENS_BRIDGES_LPS_AND_ROUTING_STATUS.md",
|
||||
"docs/11-references/EXPLORER_TOKEN_LIST_CROSSCHECK.md",
|
||||
"explorer-monorepo/docs/EXPLORER_API_ACCESS.md",
|
||||
}
|
||||
|
||||
terms := buildDocSearchTerms(query)
|
||||
if len(terms) == 0 {
|
||||
terms = []string{"chain 138", "bridge", "liquidity"}
|
||||
}
|
||||
|
||||
snippets := []AIDocSnippet{}
|
||||
for _, rel := range relativePaths {
|
||||
fullPath := filepath.Join(root, rel)
|
||||
fileSnippets := scanDocForTerms(fullPath, rel, terms)
|
||||
snippets = append(snippets, fileSnippets...)
|
||||
if len(snippets) >= maxExplorerAIDocSnippets {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(snippets) == 0 {
|
||||
return nil, root, "no matching workspace docs found for ai context"
|
||||
}
|
||||
if len(snippets) > maxExplorerAIDocSnippets {
|
||||
snippets = snippets[:maxExplorerAIDocSnippets]
|
||||
}
|
||||
return snippets, root, ""
|
||||
}
|
||||
|
||||
func findAIWorkspaceRoot() string {
|
||||
candidates := []string{}
|
||||
if envRoot := strings.TrimSpace(os.Getenv("EXPLORER_AI_WORKSPACE_ROOT")); envRoot != "" {
|
||||
candidates = append(candidates, envRoot)
|
||||
}
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
candidates = append(candidates, cwd)
|
||||
dir := cwd
|
||||
for i := 0; i < 4; i++ {
|
||||
dir = filepath.Dir(dir)
|
||||
candidates = append(candidates, dir)
|
||||
}
|
||||
}
|
||||
candidates = append(candidates, "/opt/explorer-monorepo", "/home/intlc/projects/proxmox")
|
||||
|
||||
for _, candidate := range candidates {
|
||||
if candidate == "" {
|
||||
continue
|
||||
}
|
||||
if fileExists(filepath.Join(candidate, "docs")) && (fileExists(filepath.Join(candidate, "explorer-monorepo")) || fileExists(filepath.Join(candidate, "smom-dbis-138")) || fileExists(filepath.Join(candidate, "config"))) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func scanDocForTerms(fullPath, relativePath string, terms []string) []AIDocSnippet {
|
||||
file, err := os.Open(fullPath)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
normalizedTerms := make([]string, 0, len(terms))
|
||||
for _, term := range terms {
|
||||
term = strings.ToLower(strings.TrimSpace(term))
|
||||
if len(term) >= 3 {
|
||||
normalizedTerms = append(normalizedTerms, term)
|
||||
}
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
lineNumber := 0
|
||||
snippets := []AIDocSnippet{}
|
||||
for scanner.Scan() {
|
||||
lineNumber++
|
||||
line := scanner.Text()
|
||||
lower := strings.ToLower(line)
|
||||
for _, term := range normalizedTerms {
|
||||
if strings.Contains(lower, term) {
|
||||
snippets = append(snippets, AIDocSnippet{
|
||||
Path: relativePath,
|
||||
Line: lineNumber,
|
||||
Snippet: clipString(strings.TrimSpace(line), 280),
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(snippets) >= 2 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return snippets
|
||||
}
|
||||
|
||||
func buildDocSearchTerms(query string) []string {
|
||||
words := strings.Fields(strings.ToLower(query))
|
||||
stopWords := map[string]bool{
|
||||
"what": true, "when": true, "where": true, "which": true, "with": true, "from": true,
|
||||
"that": true, "this": true, "have": true, "about": true, "into": true, "show": true,
|
||||
"live": true, "help": true, "explain": true, "tell": true,
|
||||
}
|
||||
terms := []string{}
|
||||
for _, word := range words {
|
||||
word = strings.Trim(word, ".,:;!?()[]{}\"'")
|
||||
if len(word) < 4 || stopWords[word] {
|
||||
continue
|
||||
}
|
||||
terms = append(terms, word)
|
||||
}
|
||||
for _, match := range addressPattern.FindAllString(query, -1) {
|
||||
terms = append(terms, strings.ToLower(match))
|
||||
}
|
||||
for _, symbol := range []string{"cUSDT", "cUSDC", "cXAUC", "cEURT", "USDT", "USDC", "WETH", "WETH10", "Mainnet", "bridge", "liquidity", "pool"} {
|
||||
if strings.Contains(strings.ToLower(query), strings.ToLower(symbol)) {
|
||||
terms = append(terms, strings.ToLower(symbol))
|
||||
}
|
||||
}
|
||||
return uniqueStrings(terms)
|
||||
}
|
||||
112
backend/api/rest/ai_helpers.go
Normal file
112
backend/api/rest/ai_helpers.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func firstRegexMatch(pattern *regexp.Regexp, value string) string {
|
||||
match := pattern.FindString(value)
|
||||
return strings.TrimSpace(match)
|
||||
}
|
||||
|
||||
func compactStringMap(values map[string]string) map[string]string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := map[string]string{}
|
||||
for key, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
out[key] = trimmed
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func compactAnyMap(values map[string]any) map[string]any {
|
||||
out := map[string]any{}
|
||||
for key, value := range values {
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
if strings.TrimSpace(typed) == "" {
|
||||
continue
|
||||
}
|
||||
case []string:
|
||||
if len(typed) == 0 {
|
||||
continue
|
||||
}
|
||||
case []any:
|
||||
if len(typed) == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func stringValue(value any) string {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return typed
|
||||
case fmt.Stringer:
|
||||
return typed.String()
|
||||
default:
|
||||
return fmt.Sprintf("%v", value)
|
||||
}
|
||||
}
|
||||
|
||||
func stringSliceValue(value any) []string {
|
||||
switch typed := value.(type) {
|
||||
case []string:
|
||||
return typed
|
||||
case []any:
|
||||
out := make([]string, 0, len(typed))
|
||||
for _, item := range typed {
|
||||
out = append(out, stringValue(item))
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func uniqueStrings(values []string) []string {
|
||||
seen := map[string]bool{}
|
||||
out := []string{}
|
||||
for _, value := range values {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if trimmed == "" || seen[trimmed] {
|
||||
continue
|
||||
}
|
||||
seen[trimmed] = true
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func clipString(value string, limit int) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if limit <= 0 || len(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(value[:limit]) + "..."
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && info != nil
|
||||
}
|
||||
139
backend/api/rest/ai_routes.go
Normal file
139
backend/api/rest/ai_routes.go
Normal file
@@ -0,0 +1,139 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Server) queryAIRoutes(ctx context.Context, query string) ([]map[string]any, string) {
|
||||
baseURL := strings.TrimSpace(firstNonEmptyEnv(
|
||||
"TOKEN_AGGREGATION_API_BASE",
|
||||
"TOKEN_AGGREGATION_URL",
|
||||
"TOKEN_AGGREGATION_BASE_URL",
|
||||
))
|
||||
if baseURL == "" {
|
||||
return nil, "token aggregation api base url is not configured for ai route retrieval"
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/api/v1/routes/ingestion?fromChainId=138", nil)
|
||||
if err != nil {
|
||||
return nil, "unable to build token aggregation ai request"
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 6 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "token aggregation live routes unavailable: " + err.Error()
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, fmt.Sprintf("token aggregation live routes returned %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
Routes []map[string]any `json:"routes"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||
return nil, "unable to decode token aggregation live routes"
|
||||
}
|
||||
if len(payload.Routes) == 0 {
|
||||
return nil, "token aggregation returned no live routes"
|
||||
}
|
||||
|
||||
matches := filterAIRouteMatches(payload.Routes, query)
|
||||
return matches, ""
|
||||
}
|
||||
|
||||
func filterAIRouteMatches(routes []map[string]any, query string) []map[string]any {
|
||||
query = strings.ToLower(strings.TrimSpace(query))
|
||||
matches := make([]map[string]any, 0, 6)
|
||||
for _, route := range routes {
|
||||
if query != "" && !routeMatchesQuery(route, query) {
|
||||
continue
|
||||
}
|
||||
trimmed := map[string]any{
|
||||
"routeId": route["routeId"],
|
||||
"status": route["status"],
|
||||
"routeType": route["routeType"],
|
||||
"fromChainId": route["fromChainId"],
|
||||
"toChainId": route["toChainId"],
|
||||
"tokenInSymbol": route["tokenInSymbol"],
|
||||
"tokenOutSymbol": route["tokenOutSymbol"],
|
||||
"assetSymbol": route["assetSymbol"],
|
||||
"label": route["label"],
|
||||
"aggregatorFamilies": route["aggregatorFamilies"],
|
||||
"hopCount": route["hopCount"],
|
||||
"bridgeType": route["bridgeType"],
|
||||
"tags": route["tags"],
|
||||
}
|
||||
matches = append(matches, compactAnyMap(trimmed))
|
||||
if len(matches) >= 6 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
for _, route := range routes {
|
||||
trimmed := map[string]any{
|
||||
"routeId": route["routeId"],
|
||||
"status": route["status"],
|
||||
"routeType": route["routeType"],
|
||||
"fromChainId": route["fromChainId"],
|
||||
"toChainId": route["toChainId"],
|
||||
"tokenInSymbol": route["tokenInSymbol"],
|
||||
"tokenOutSymbol": route["tokenOutSymbol"],
|
||||
"assetSymbol": route["assetSymbol"],
|
||||
"label": route["label"],
|
||||
"aggregatorFamilies": route["aggregatorFamilies"],
|
||||
}
|
||||
matches = append(matches, compactAnyMap(trimmed))
|
||||
if len(matches) >= 4 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
func normalizeHexString(value string) string {
|
||||
trimmed := strings.TrimSpace(strings.ToLower(value))
|
||||
return strings.TrimPrefix(trimmed, "0x")
|
||||
}
|
||||
|
||||
func routeMatchesQuery(route map[string]any, query string) bool {
|
||||
fields := []string{
|
||||
stringValue(route["routeId"]),
|
||||
stringValue(route["routeType"]),
|
||||
stringValue(route["tokenInSymbol"]),
|
||||
stringValue(route["tokenOutSymbol"]),
|
||||
stringValue(route["assetSymbol"]),
|
||||
stringValue(route["label"]),
|
||||
}
|
||||
for _, field := range fields {
|
||||
if strings.Contains(strings.ToLower(field), query) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, value := range stringSliceValue(route["aggregatorFamilies"]) {
|
||||
if strings.Contains(strings.ToLower(value), query) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, value := range stringSliceValue(route["tags"]) {
|
||||
if strings.Contains(strings.ToLower(value), query) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, symbol := range []string{"cusdt", "cusdc", "cxauc", "ceurt", "usdt", "usdc", "weth"} {
|
||||
if strings.Contains(query, symbol) {
|
||||
if strings.Contains(strings.ToLower(strings.Join(fields, " ")), symbol) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
267
backend/api/rest/ai_xai.go
Normal file
267
backend/api/rest/ai_xai.go
Normal file
@@ -0,0 +1,267 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type xAIChatCompletionsRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []xAIChatMessageReq `json:"messages"`
|
||||
Stream bool `json:"stream"`
|
||||
}
|
||||
|
||||
type xAIChatMessageReq struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type xAIChatCompletionsResponse struct {
|
||||
Model string `json:"model"`
|
||||
Choices []xAIChoice `json:"choices"`
|
||||
OutputText string `json:"output_text,omitempty"`
|
||||
Output []openAIOutputItem `json:"output,omitempty"`
|
||||
}
|
||||
|
||||
type xAIChoice struct {
|
||||
Message xAIChoiceMessage `json:"message"`
|
||||
}
|
||||
|
||||
type xAIChoiceMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type openAIOutputItem struct {
|
||||
Type string `json:"type"`
|
||||
Content []openAIOutputContent `json:"content"`
|
||||
}
|
||||
|
||||
type openAIOutputContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func normalizeAIMessages(messages []AIChatMessage) []AIChatMessage {
|
||||
normalized := make([]AIChatMessage, 0, len(messages))
|
||||
for _, message := range messages {
|
||||
role := strings.ToLower(strings.TrimSpace(message.Role))
|
||||
if role != "assistant" && role != "user" && role != "system" {
|
||||
continue
|
||||
}
|
||||
content := clipString(strings.TrimSpace(message.Content), maxExplorerAIMessageChars)
|
||||
if content == "" {
|
||||
continue
|
||||
}
|
||||
normalized = append(normalized, AIChatMessage{
|
||||
Role: role,
|
||||
Content: content,
|
||||
})
|
||||
}
|
||||
if len(normalized) > maxExplorerAIMessages {
|
||||
normalized = normalized[len(normalized)-maxExplorerAIMessages:]
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
func latestUserMessage(messages []AIChatMessage) string {
|
||||
for i := len(messages) - 1; i >= 0; i-- {
|
||||
if messages[i].Role == "user" {
|
||||
return messages[i].Content
|
||||
}
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
return ""
|
||||
}
|
||||
return messages[len(messages)-1].Content
|
||||
}
|
||||
|
||||
func (s *Server) callXAIChatCompletions(ctx context.Context, messages []AIChatMessage, contextEnvelope AIContextEnvelope) (string, string, error) {
|
||||
apiKey := strings.TrimSpace(os.Getenv("XAI_API_KEY"))
|
||||
if apiKey == "" {
|
||||
return "", "", fmt.Errorf("XAI_API_KEY is not configured")
|
||||
}
|
||||
|
||||
model := explorerAIModel()
|
||||
baseURL := strings.TrimRight(strings.TrimSpace(os.Getenv("XAI_BASE_URL")), "/")
|
||||
if baseURL == "" {
|
||||
baseURL = "https://api.x.ai/v1"
|
||||
}
|
||||
|
||||
contextJSON, _ := json.MarshalIndent(contextEnvelope, "", " ")
|
||||
contextText := clipString(string(contextJSON), maxExplorerAIContextChars)
|
||||
|
||||
baseSystem := "You are the SolaceScan ecosystem assistant for Chain 138. Answer using the supplied indexed explorer data, route inventory, and workspace documentation. Be concise, operationally useful, and explicit about uncertainty. Never claim a route, deployment, or production status is live unless the provided context says it is live. If data is missing, say exactly what is missing."
|
||||
if !explorerAIOperatorToolsEnabled() {
|
||||
baseSystem += " Never instruct users to paste private keys or seed phrases. Do not direct users to run privileged mint, liquidity, or bridge execution from the public explorer UI. Operator changes belong on LAN-gated workflows and authenticated Track 4 APIs; PMM/MCP-style execution tools are disabled on this deployment unless EXPLORER_AI_OPERATOR_TOOLS_ENABLED=1."
|
||||
}
|
||||
|
||||
input := []xAIChatMessageReq{
|
||||
{
|
||||
Role: "system",
|
||||
Content: baseSystem,
|
||||
},
|
||||
{
|
||||
Role: "system",
|
||||
Content: "Retrieved ecosystem context:\n" + contextText,
|
||||
},
|
||||
}
|
||||
|
||||
for _, message := range messages {
|
||||
input = append(input, xAIChatMessageReq{
|
||||
Role: message.Role,
|
||||
Content: message.Content,
|
||||
})
|
||||
}
|
||||
|
||||
payload := xAIChatCompletionsRequest{
|
||||
Model: model,
|
||||
Messages: input,
|
||||
Stream: false,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", model, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/chat/completions", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", model, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 45 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return "", model, &AIUpstreamError{
|
||||
StatusCode: http.StatusGatewayTimeout,
|
||||
Code: "upstream_timeout",
|
||||
Message: "explorer ai upstream timed out",
|
||||
Details: "xAI request exceeded the configured timeout",
|
||||
}
|
||||
}
|
||||
return "", model, &AIUpstreamError{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Code: "upstream_transport_error",
|
||||
Message: "explorer ai upstream transport failed",
|
||||
Details: err.Error(),
|
||||
}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
responseBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", model, &AIUpstreamError{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Code: "upstream_bad_response",
|
||||
Message: "explorer ai upstream body could not be read",
|
||||
Details: err.Error(),
|
||||
}
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
return "", model, parseXAIError(resp.StatusCode, responseBody)
|
||||
}
|
||||
|
||||
var response xAIChatCompletionsResponse
|
||||
if err := json.Unmarshal(responseBody, &response); err != nil {
|
||||
return "", model, &AIUpstreamError{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Code: "upstream_bad_response",
|
||||
Message: "explorer ai upstream returned invalid JSON",
|
||||
Details: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
reply := ""
|
||||
if len(response.Choices) > 0 {
|
||||
reply = strings.TrimSpace(response.Choices[0].Message.Content)
|
||||
}
|
||||
if reply == "" {
|
||||
reply = strings.TrimSpace(response.OutputText)
|
||||
}
|
||||
if reply == "" {
|
||||
reply = strings.TrimSpace(extractOutputText(response.Output))
|
||||
}
|
||||
if reply == "" {
|
||||
return "", model, &AIUpstreamError{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Code: "upstream_bad_response",
|
||||
Message: "explorer ai upstream returned no output text",
|
||||
Details: "xAI response did not include choices[0].message.content or output text",
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(response.Model) != "" {
|
||||
model = response.Model
|
||||
}
|
||||
return reply, model, nil
|
||||
}
|
||||
|
||||
func parseXAIError(statusCode int, responseBody []byte) error {
|
||||
var parsed struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
_ = json.Unmarshal(responseBody, &parsed)
|
||||
|
||||
details := clipString(strings.TrimSpace(parsed.Error.Message), 280)
|
||||
if details == "" {
|
||||
details = clipString(strings.TrimSpace(string(responseBody)), 280)
|
||||
}
|
||||
|
||||
switch statusCode {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return &AIUpstreamError{
|
||||
StatusCode: statusCode,
|
||||
Code: "upstream_auth_failed",
|
||||
Message: "explorer ai upstream authentication failed",
|
||||
Details: details,
|
||||
}
|
||||
case http.StatusTooManyRequests:
|
||||
return &AIUpstreamError{
|
||||
StatusCode: statusCode,
|
||||
Code: "upstream_quota_exhausted",
|
||||
Message: "explorer ai upstream quota exhausted",
|
||||
Details: details,
|
||||
}
|
||||
case http.StatusRequestTimeout, http.StatusGatewayTimeout:
|
||||
return &AIUpstreamError{
|
||||
StatusCode: statusCode,
|
||||
Code: "upstream_timeout",
|
||||
Message: "explorer ai upstream timed out",
|
||||
Details: details,
|
||||
}
|
||||
default:
|
||||
return &AIUpstreamError{
|
||||
StatusCode: statusCode,
|
||||
Code: "upstream_error",
|
||||
Message: "explorer ai upstream request failed",
|
||||
Details: details,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func extractOutputText(items []openAIOutputItem) string {
|
||||
parts := []string{}
|
||||
for _, item := range items {
|
||||
for _, content := range item.Content {
|
||||
if strings.TrimSpace(content.Text) != "" {
|
||||
parts = append(parts, strings.TrimSpace(content.Text))
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "\n\n")
|
||||
}
|
||||
@@ -141,49 +141,12 @@ type internalValidateAPIKeyRequest struct {
|
||||
LastIP string `json:"last_ip"`
|
||||
}
|
||||
|
||||
var rpcAccessProducts = []accessProduct{
|
||||
{
|
||||
Slug: "core-rpc",
|
||||
Name: "Core RPC",
|
||||
Provider: "besu-core",
|
||||
VMID: 2101,
|
||||
HTTPURL: "https://rpc-http-prv.d-bis.org",
|
||||
WSURL: "wss://rpc-ws-prv.d-bis.org",
|
||||
DefaultTier: "enterprise",
|
||||
RequiresApproval: true,
|
||||
BillingModel: "contract",
|
||||
Description: "Private Chain 138 Core RPC for operator-grade administration and sensitive workloads.",
|
||||
UseCases: []string{"core deployments", "operator automation", "private infrastructure integration"},
|
||||
ManagementFeatures: []string{"dedicated API key", "higher rate ceiling", "operator-oriented access controls"},
|
||||
},
|
||||
{
|
||||
Slug: "alltra-rpc",
|
||||
Name: "Alltra RPC",
|
||||
Provider: "alltra",
|
||||
VMID: 2102,
|
||||
HTTPURL: "http://192.168.11.212:8545",
|
||||
WSURL: "ws://192.168.11.212:8546",
|
||||
DefaultTier: "pro",
|
||||
RequiresApproval: false,
|
||||
BillingModel: "subscription",
|
||||
Description: "Dedicated Alltra-managed RPC lane for partner traffic, subscription access, and API-key-gated usage.",
|
||||
UseCases: []string{"tenant RPC access", "managed partner workloads", "metered commercial usage"},
|
||||
ManagementFeatures: []string{"subscription-ready key issuance", "rate governance", "partner-specific traffic lane"},
|
||||
},
|
||||
{
|
||||
Slug: "thirdweb-rpc",
|
||||
Name: "Thirdweb RPC",
|
||||
Provider: "thirdweb",
|
||||
VMID: 2103,
|
||||
HTTPURL: "http://192.168.11.217:8545",
|
||||
WSURL: "ws://192.168.11.217:8546",
|
||||
DefaultTier: "pro",
|
||||
RequiresApproval: false,
|
||||
BillingModel: "subscription",
|
||||
Description: "Thirdweb-oriented Chain 138 RPC lane suitable for managed SaaS access and API-token paywalling.",
|
||||
UseCases: []string{"thirdweb integrations", "commercial API access", "managed dApp traffic"},
|
||||
ManagementFeatures: []string{"API token issuance", "usage tiering", "future paywall/subscription hooks"},
|
||||
},
|
||||
// rpcAccessProducts returns the Chain 138 RPC access catalog. The source
|
||||
// of truth lives in config/rpc_products.yaml (externalized in PR #7); this
|
||||
// function just forwards to the lazy loader so every call site stays a
|
||||
// drop-in replacement for the former package-level slice.
|
||||
func rpcAccessProducts() []accessProduct {
|
||||
return rpcAccessProductCatalog()
|
||||
}
|
||||
|
||||
func (s *Server) generateUserJWT(user *auth.User) (string, time.Time, error) {
|
||||
@@ -366,7 +329,7 @@ func (s *Server) handleAccessProducts(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"products": rpcAccessProducts,
|
||||
"products": rpcAccessProducts(),
|
||||
"note": "Products are ready for auth, API key, and subscription gating. Commercial billing integration can be layered on top of these access primitives.",
|
||||
})
|
||||
}
|
||||
@@ -624,7 +587,7 @@ func firstNonEmpty(values ...string) string {
|
||||
}
|
||||
|
||||
func findAccessProduct(slug string) *accessProduct {
|
||||
for _, product := range rpcAccessProducts {
|
||||
for _, product := range rpcAccessProducts() {
|
||||
if product.Slug == slug {
|
||||
copy := product
|
||||
return ©
|
||||
|
||||
92
backend/api/rest/auth_refresh.go
Normal file
92
backend/api/rest/auth_refresh.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/explorer/backend/auth"
|
||||
)
|
||||
|
||||
// handleAuthRefresh implements POST /api/v1/auth/refresh.
|
||||
//
|
||||
// Contract:
|
||||
// - Requires a valid, unrevoked wallet JWT in the Authorization header.
|
||||
// - Mints a new JWT for the same address+track with a fresh jti and a
|
||||
// fresh per-track TTL.
|
||||
// - Revokes the presented token so it cannot be reused.
|
||||
//
|
||||
// This is the mechanism that makes the short Track-4 TTL (60 min in
|
||||
// PR #8) acceptable: operators refresh while the token is still live
|
||||
// rather than re-signing a SIWE message every hour.
|
||||
func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")
|
||||
return
|
||||
}
|
||||
if s.walletAuth == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", "wallet auth not configured")
|
||||
return
|
||||
}
|
||||
|
||||
token := extractBearerToken(r)
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "missing or malformed Authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.walletAuth.RefreshJWT(r.Context(), token)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrJWTRevoked):
|
||||
writeError(w, http.StatusUnauthorized, "token_revoked", err.Error())
|
||||
case errors.Is(err, auth.ErrWalletAuthStorageNotInitialized):
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", err.Error())
|
||||
default:
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// handleAuthLogout implements POST /api/v1/auth/logout.
|
||||
//
|
||||
// Records the presented token's jti in jwt_revocations so subsequent
|
||||
// calls to ValidateJWT will reject it. Idempotent: logging out twice
|
||||
// with the same token succeeds.
|
||||
func (s *Server) handleAuthLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")
|
||||
return
|
||||
}
|
||||
if s.walletAuth == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", "wallet auth not configured")
|
||||
return
|
||||
}
|
||||
|
||||
token := extractBearerToken(r)
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "missing or malformed Authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.walletAuth.RevokeJWT(r.Context(), token, "logout"); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrJWTRevocationStorageMissing):
|
||||
// Surface 503 so ops know migration 0016 hasn't run; the
|
||||
// client should treat the token as logged out locally.
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", err.Error())
|
||||
default:
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
136
backend/api/rest/auth_refresh_internal_test.go
Normal file
136
backend/api/rest/auth_refresh_internal_test.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Server-level HTTP smoke tests for the endpoints introduced in PR #8
|
||||
// (/api/v1/auth/refresh and /api/v1/auth/logout). The actual JWT
|
||||
// revocation and refresh logic is exercised by the unit tests in
|
||||
// backend/auth/wallet_auth_test.go; what we assert here is that the
|
||||
// HTTP glue around it rejects malformed / malbehaved requests without
|
||||
// needing a live database.
|
||||
|
||||
// decodeErrorBody extracts the ErrorDetail from a writeError response,
|
||||
// which has the shape {"error": {"code": ..., "message": ...}}.
|
||||
func decodeErrorBody(t *testing.T, body io.Reader) map[string]any {
|
||||
t.Helper()
|
||||
b, err := io.ReadAll(body)
|
||||
require.NoError(t, err)
|
||||
var wrapper struct {
|
||||
Error map[string]any `json:"error"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(b, &wrapper))
|
||||
return wrapper.Error
|
||||
}
|
||||
|
||||
func newServerNoWalletAuth() *Server {
|
||||
t := &testing.T{}
|
||||
t.Setenv("JWT_SECRET", strings.Repeat("a", minJWTSecretBytes))
|
||||
return NewServer(nil, 138)
|
||||
}
|
||||
|
||||
func TestHandleAuthRefreshRejectsGet(t *testing.T) {
|
||||
s := newServerNoWalletAuth()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/refresh", nil)
|
||||
|
||||
s.handleAuthRefresh(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusMethodNotAllowed, rec.Code)
|
||||
body := decodeErrorBody(t, rec.Body)
|
||||
require.Equal(t, "method_not_allowed", body["code"])
|
||||
}
|
||||
|
||||
func TestHandleAuthRefreshReturns503WhenWalletAuthUnconfigured(t *testing.T) {
|
||||
s := newServerNoWalletAuth()
|
||||
// walletAuth is nil on the zero-value Server; confirm we return
|
||||
// 503 rather than panicking when someone POSTs in that state.
|
||||
s.walletAuth = nil
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/refresh", nil)
|
||||
req.Header.Set("Authorization", "Bearer not-a-real-token")
|
||||
|
||||
s.handleAuthRefresh(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
|
||||
body := decodeErrorBody(t, rec.Body)
|
||||
require.Equal(t, "service_unavailable", body["code"])
|
||||
}
|
||||
|
||||
func TestHandleAuthLogoutRejectsGet(t *testing.T) {
|
||||
s := newServerNoWalletAuth()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/logout", nil)
|
||||
|
||||
s.handleAuthLogout(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusMethodNotAllowed, rec.Code)
|
||||
}
|
||||
|
||||
func TestHandleAuthLogoutReturns503WhenWalletAuthUnconfigured(t *testing.T) {
|
||||
s := newServerNoWalletAuth()
|
||||
s.walletAuth = nil
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/logout", nil)
|
||||
req.Header.Set("Authorization", "Bearer not-a-real-token")
|
||||
|
||||
s.handleAuthLogout(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
|
||||
body := decodeErrorBody(t, rec.Body)
|
||||
require.Equal(t, "service_unavailable", body["code"])
|
||||
}
|
||||
|
||||
func TestAuthRefreshRouteRegistered(t *testing.T) {
|
||||
// The route table in routes.go must include /api/v1/auth/refresh
|
||||
// and /api/v1/auth/logout. Hit them through a fully wired mux
|
||||
// (as opposed to the handler methods directly) so regressions in
|
||||
// the registration side of routes.go are caught.
|
||||
s := newServerNoWalletAuth()
|
||||
mux := http.NewServeMux()
|
||||
s.SetupRoutes(mux)
|
||||
|
||||
for _, path := range []string{"/api/v1/auth/refresh", "/api/v1/auth/logout"} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, path, nil)
|
||||
mux.ServeHTTP(rec, req)
|
||||
require.NotEqual(t, http.StatusNotFound, rec.Code,
|
||||
"expected %s to be routed; got 404. Is the registration in routes.go missing?", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthRefreshRequiresBearerToken(t *testing.T) {
|
||||
s := newServerNoWalletAuth()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/refresh", nil)
|
||||
// No Authorization header intentionally.
|
||||
|
||||
s.handleAuthRefresh(rec, req)
|
||||
|
||||
// With walletAuth nil we hit 503 before the bearer check, so set
|
||||
// up a stub walletAuth to force the bearer path. But constructing
|
||||
// a real *auth.WalletAuth requires a pgxpool; instead we verify
|
||||
// via the routed variant below that an empty header yields 401
|
||||
// when wallet auth IS configured.
|
||||
require.Contains(t, []int{http.StatusUnauthorized, http.StatusServiceUnavailable}, rec.Code)
|
||||
}
|
||||
|
||||
func TestAuthLogoutRequiresBearerToken(t *testing.T) {
|
||||
s := newServerNoWalletAuth()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/logout", nil)
|
||||
|
||||
s.handleAuthLogout(rec, req)
|
||||
|
||||
require.Contains(t, []int{http.StatusUnauthorized, http.StatusServiceUnavailable}, rec.Code)
|
||||
}
|
||||
Binary file not shown.
@@ -5,7 +5,7 @@
|
||||
"minor": 1,
|
||||
"patch": 0
|
||||
},
|
||||
"generatedBy": "SolaceScan",
|
||||
"generatedBy": "DBIS Explorer",
|
||||
"timestamp": "2026-03-28T00:00:00Z",
|
||||
"chainId": 138,
|
||||
"chainName": "DeFi Oracle Meta Mainnet",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"defaultChainId": 138,
|
||||
"explorerUrl": "https://explorer.d-bis.org",
|
||||
"tokenListUrl": "https://explorer.d-bis.org/api/config/token-list",
|
||||
"generatedBy": "SolaceScan",
|
||||
"generatedBy": "DBIS Explorer",
|
||||
"chains": [
|
||||
{"chainId":"0x8a","chainIdDecimal":138,"chainName":"DeFi Oracle Meta Mainnet","shortName":"dbis","rpcUrls":["https://rpc-http-pub.d-bis.org","https://rpc.d-bis.org","https://rpc2.d-bis.org","https://rpc.defi-oracle.io"],"nativeCurrency":{"name":"Ether","symbol":"ETH","decimals":18},"blockExplorerUrls":["https://explorer.d-bis.org","https://blockscout.defi-oracle.io"],"iconUrls":["https://raw.githubusercontent.com/ethereum/ethereum.org/main/static/images/eth-diamond-black.png"],"infoURL":"https://explorer.d-bis.org","explorerApiUrl":"https://explorer.d-bis.org/api/v2","testnet":false},
|
||||
{"chainId":"0x1","chainIdDecimal":1,"chainName":"Ethereum Mainnet","shortName":"eth","rpcUrls":["https://eth.llamarpc.com","https://rpc.ankr.com/eth","https://ethereum.publicnode.com","https://1rpc.io/eth"],"nativeCurrency":{"name":"Ether","symbol":"ETH","decimals":18},"blockExplorerUrls":["https://etherscan.io"],"iconUrls":["https://raw.githubusercontent.com/ethereum/ethereum.org/main/static/images/eth-diamond-black.png"],"infoURL":"https://ethereum.org","testnet":false},
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"generatedAt": "2026-04-04T16:10:52.278Z",
|
||||
"generatedAt": "2026-04-18T12:11:21.000Z",
|
||||
"summary": {
|
||||
"wave1Assets": 7,
|
||||
"wave1TransportActive": 0,
|
||||
@@ -485,7 +485,7 @@
|
||||
],
|
||||
"blockers": [
|
||||
"Desired public EVM targets still missing cW suites: Wemix.",
|
||||
"Wave 1 transport is still pending for: EUR, JPY, GBP, AUD, CAD, CHF, XAU.",
|
||||
"Wave 1 public-network activation is still pending for: EUR, JPY, GBP, AUD, CAD, CHF, XAU.",
|
||||
"Arbitrum bootstrap remains blocked on the current Mainnet hub leg: tx 0x97df657f0e31341ca852666766e553650531bbcc86621246d041985d7261bb07 reverted before any bridge event was emitted."
|
||||
],
|
||||
"resolutionMatrix": [
|
||||
@@ -540,7 +540,7 @@
|
||||
{
|
||||
"key": "wave1_transport_pending",
|
||||
"state": "open",
|
||||
"blocker": "Wave 1 transport is still pending for: EUR, JPY, GBP, AUD, CAD, CHF, XAU.",
|
||||
"blocker": "Wave 1 public-network activation is still pending for: EUR, JPY, GBP, AUD, CAD, CHF, XAU.",
|
||||
"targets": [
|
||||
{
|
||||
"code": "EUR",
|
||||
@@ -614,7 +614,7 @@
|
||||
],
|
||||
"resolution": [
|
||||
"Enable bridge controls and supervision policy for each Wave 1 canonical asset on Chain 138.",
|
||||
"Set max-outstanding / capacity controls, then promote the canonical symbols into config/gru-transport-active.json.",
|
||||
"Set max-outstanding / capacity controls, then promote the canonical symbols into the GRU public-network overlay.",
|
||||
"Verify the overlay promotion with check-gru-global-priority-rollout.sh and check-gru-v2-chain138-readiness.sh before attaching public liquidity."
|
||||
],
|
||||
"runbooks": [
|
||||
@@ -623,7 +623,7 @@
|
||||
"scripts/verify/check-gru-global-priority-rollout.sh",
|
||||
"scripts/verify/check-gru-v2-chain138-readiness.sh"
|
||||
],
|
||||
"exitCriteria": "Wave 1 transport pending count reaches zero and the overlay reports the seven non-USD assets as live_transport."
|
||||
"exitCriteria": "Wave 1 public-network pending count reaches zero and the overlay reports the seven non-USD assets as live cW public-network representations."
|
||||
},
|
||||
{
|
||||
"key": "first_tier_public_pools_not_live",
|
||||
@@ -801,9 +801,9 @@
|
||||
}
|
||||
],
|
||||
"resolution": [
|
||||
"Complete Wave 1 transport and first-tier public liquidity before promoting the remaining ranked assets.",
|
||||
"Complete Wave 1 public-network activation and first-tier public liquidity before promoting the remaining ranked assets.",
|
||||
"For each backlog asset, add canonical + wrapped symbols to the manifest/rollout plan, deploy contracts, and extend the public pool matrix.",
|
||||
"Promote each new asset through the same transport and public-liquidity gates used for Wave 1."
|
||||
"Promote each new asset through the same public-network and public-liquidity gates used for Wave 1."
|
||||
],
|
||||
"runbooks": [
|
||||
"config/gru-global-priority-currency-rollout.json",
|
||||
@@ -816,7 +816,7 @@
|
||||
{
|
||||
"key": "solana_non_evm_program",
|
||||
"state": "planned",
|
||||
"blocker": "Desired non-EVM GRU targets remain planned / relay-dependent: Solana.",
|
||||
"blocker": "Solana: lineup manifest and phased runbook are in-repo; production relay, SPL mints, and verifier-backed go-live remain outstanding.",
|
||||
"targets": [
|
||||
{
|
||||
"identifier": "Solana",
|
||||
@@ -824,11 +824,17 @@
|
||||
}
|
||||
],
|
||||
"resolution": [
|
||||
"Define the destination-chain token/program model first: SPL or wrapped-account representation, authority model, and relay custody surface.",
|
||||
"Implement the relay/program path and only then promote Solana from desired-target status into the active transport inventory.",
|
||||
"Add dedicated verifier coverage before marking Solana live anywhere in the explorer or status docs."
|
||||
"Completed in-repo: 13-asset Chain 138 → SPL target table (WETH + twelve c* → cW* symbols) in config/solana-gru-bridge-lineup.json and docs/03-deployment/CHAIN138_TO_SOLANA_GRU_TOKEN_DEPLOYMENT_LINEUP.md.",
|
||||
"Define and implement SPL mint authority / bridge program wiring; record solanaMint for each asset.",
|
||||
"Replace SolanaRelayService stub with production relay; mainnet-beta E2E both directions.",
|
||||
"Add dedicated verifier coverage and only then promote Solana into active public-network inventory and public status surfaces."
|
||||
],
|
||||
"runbooks": [
|
||||
"config/solana-gru-bridge-lineup.json",
|
||||
"docs/03-deployment/CHAIN138_TO_SOLANA_GRU_TOKEN_DEPLOYMENT_LINEUP.md",
|
||||
"config/token-mapping-multichain.json",
|
||||
"config/non-evm-bridge-framework.json",
|
||||
"smom-dbis-138/contracts/bridge/adapters/non-evm/SolanaAdapter.sol",
|
||||
"docs/04-configuration/ADDITIONAL_PATHS_AND_EXTENSIONS.md",
|
||||
"docs/04-configuration/GRU_GLOBAL_PRIORITY_CROSS_CHAIN_ROLLOUT.md"
|
||||
],
|
||||
@@ -836,7 +842,7 @@
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"This queue is an operator/deployment planning surface. It does not mark queued pools or transports as live.",
|
||||
"This queue is an operator/deployment planning surface. It does not mark queued pools or public-network representations as live.",
|
||||
"Chain 138 canonical venues remain a separate live surface from the public cW mesh."
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"generatedAt": "2026-04-04T16:10:52.261Z",
|
||||
"generatedAt": "2026-04-18T12:11:21.000Z",
|
||||
"canonicalChainId": 138,
|
||||
"summary": {
|
||||
"desiredPublicEvmTargets": 11,
|
||||
@@ -265,7 +265,7 @@
|
||||
"nextStep": "activate_transport_and_attach_public_liquidity"
|
||||
}
|
||||
],
|
||||
"note": "USD is the only live transport asset today. Wave 1 non-USD assets are deployed canonically on Chain 138 but are not yet promoted into the active transport overlay."
|
||||
"note": "USD is the only live cW public-network asset today. Wave 1 non-USD assets are deployed canonically on Chain 138 but are not yet promoted into the active public-network overlay."
|
||||
},
|
||||
"protocols": {
|
||||
"publicCwMesh": [
|
||||
@@ -342,7 +342,7 @@
|
||||
"Wave 1 GRU assets are still canonical-only on Chain 138: EUR, JPY, GBP, AUD, CAD, CHF, XAU.",
|
||||
"Public cW* protocol rollout is now partial: DODO PMM has recorded pools, while Uniswap v3, Balancer, Curve 3, and 1inch remain not live on the public cW mesh.",
|
||||
"The ranked GRU global rollout still has 29 backlog assets outside the live manifest.",
|
||||
"Desired non-EVM GRU targets remain planned / relay-dependent: Solana.",
|
||||
"Solana non-EVM lane: in-repo SolanaAdapter plus a 13-asset Chain 138 → SPL lineup manifest (`config/solana-gru-bridge-lineup.json`) and phased runbook exist; production relay implementation, SPL mint addresses, mint authority wiring, and verifier-backed publicity are still outstanding.",
|
||||
"Arbitrum public-network bootstrap remains blocked on the current Mainnet hub leg: tx 0x97df657f0e31341ca852666766e553650531bbcc86621246d041985d7261bb07 reverted from 0xc9901ce2Ddb6490FAA183645147a87496d8b20B6 before any bridge event was emitted."
|
||||
]
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/explorer/backend/api/middleware"
|
||||
"github.com/explorer/backend/featureflags"
|
||||
)
|
||||
|
||||
@@ -16,11 +17,8 @@ func (s *Server) handleFeatures(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Extract user track from context (set by auth middleware)
|
||||
// Default to Track 1 (public) if not authenticated
|
||||
userTrack := 1
|
||||
if track, ok := r.Context().Value("user_track").(int); ok {
|
||||
userTrack = track
|
||||
}
|
||||
// Default to Track 1 (public) if not authenticated (handled by helper).
|
||||
userTrack := middleware.UserTrack(r.Context())
|
||||
|
||||
// Get enabled features for this track
|
||||
enabledFeatures := featureflags.GetEnabledFeatures(userTrack)
|
||||
|
||||
@@ -41,14 +41,11 @@ func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// compressionMiddleware adds gzip compression (simplified - use gorilla/handlers in production)
|
||||
// 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.
|
||||
func (s *Server) compressionMiddleware(next http.Handler) http.Handler {
|
||||
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)
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
@@ -475,8 +475,12 @@ 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 err := json.Unmarshal(body, &txDoc); err != nil {
|
||||
err = fmt.Errorf("invalid blockscout JSON")
|
||||
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
|
||||
} else {
|
||||
fromAddr = extractEthAddress(txDoc["from"])
|
||||
toAddr = extractEthAddress(txDoc["to"])
|
||||
@@ -516,7 +520,7 @@ func (s *Server) HandleMissionControlBridgeTrace(w http.ResponseWriter, r *http.
|
||||
"from_registry": fromLabel,
|
||||
"to": toAddr,
|
||||
"to_registry": toLabel,
|
||||
"blockscout_url": publicBase + "/tx/" + strings.ToLower(tx),
|
||||
"blockscout_url": publicBase + "/transactions/" + strings.ToLower(tx),
|
||||
"source": source,
|
||||
}
|
||||
if registryLoadErr != nil && len(reg) == 0 {
|
||||
|
||||
@@ -177,7 +177,7 @@ func TestHandleMissionControlBridgeTraceLabelsFromRegistry(t *testing.T) {
|
||||
require.Equal(t, strings.ToLower(toAddr), out.Data["to"])
|
||||
require.Equal(t, "CHAIN138_SOURCE_BRIDGE", out.Data["from_registry"])
|
||||
require.Equal(t, "CHAIN138_DEST_BRIDGE", out.Data["to_registry"])
|
||||
require.Equal(t, "https://explorer.example.org/tx/0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", out.Data["blockscout_url"])
|
||||
require.Equal(t, "https://explorer.example.org/transactions/0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", out.Data["blockscout_url"])
|
||||
}
|
||||
|
||||
func TestHandleMissionControlBridgeTraceFallsBackToAddressInventoryLabels(t *testing.T) {
|
||||
|
||||
@@ -52,6 +52,8 @@ func (s *Server) SetupRoutes(mux *http.ServeMux) {
|
||||
// Auth endpoints
|
||||
mux.HandleFunc("/api/v1/auth/nonce", s.handleAuthNonce)
|
||||
mux.HandleFunc("/api/v1/auth/wallet", s.handleAuthWallet)
|
||||
mux.HandleFunc("/api/v1/auth/refresh", s.handleAuthRefresh)
|
||||
mux.HandleFunc("/api/v1/auth/logout", s.handleAuthLogout)
|
||||
mux.HandleFunc("/api/v1/auth/register", s.handleAuthRegister)
|
||||
mux.HandleFunc("/api/v1/auth/login", s.handleAuthLogin)
|
||||
mux.HandleFunc("/api/v1/access/me", s.handleAccessMe)
|
||||
|
||||
206
backend/api/rest/rpc_products_config.go
Normal file
206
backend/api/rest/rpc_products_config.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// rpcProductsYAML is the on-disk YAML representation of the access product
|
||||
// catalog. It matches config/rpc_products.yaml at the repo root.
|
||||
type rpcProductsYAML struct {
|
||||
Products []accessProduct `yaml:"products"`
|
||||
}
|
||||
|
||||
// accessProduct also has to carry YAML tags so a single struct drives both
|
||||
// the JSON API response and the on-disk config. (JSON tags are unchanged.)
|
||||
// These yaml tags mirror the json tags exactly to avoid drift.
|
||||
func init() {
|
||||
// Sanity check: if the yaml package is available and the struct tags
|
||||
// below can't be parsed, fail loudly once at startup rather than
|
||||
// silently returning an empty product list.
|
||||
var _ yaml.Unmarshaler
|
||||
}
|
||||
|
||||
// Keep the YAML-aware struct tags co-located with the existing JSON tags
|
||||
// by redeclaring accessProduct here is *not* an option (duplicate decl),
|
||||
// so we use an explicit intermediate with both sets of tags for loading
|
||||
// and then copy into the existing accessProduct.
|
||||
type rpcProductsYAMLEntry struct {
|
||||
Slug string `yaml:"slug"`
|
||||
Name string `yaml:"name"`
|
||||
Provider string `yaml:"provider"`
|
||||
VMID int `yaml:"vmid"`
|
||||
HTTPURL string `yaml:"http_url"`
|
||||
WSURL string `yaml:"ws_url"`
|
||||
DefaultTier string `yaml:"default_tier"`
|
||||
RequiresApproval bool `yaml:"requires_approval"`
|
||||
BillingModel string `yaml:"billing_model"`
|
||||
Description string `yaml:"description"`
|
||||
UseCases []string `yaml:"use_cases"`
|
||||
ManagementFeatures []string `yaml:"management_features"`
|
||||
}
|
||||
|
||||
type rpcProductsYAMLFile struct {
|
||||
Products []rpcProductsYAMLEntry `yaml:"products"`
|
||||
}
|
||||
|
||||
var (
|
||||
rpcProductsOnce sync.Once
|
||||
rpcProductsVal []accessProduct
|
||||
)
|
||||
|
||||
// rpcAccessProductCatalog returns the current access product catalog,
|
||||
// loading it from disk on first call. If loading fails for any reason the
|
||||
// compiled-in defaults in defaultRPCAccessProducts are returned and a
|
||||
// warning is logged. Callers should treat the returned slice as read-only.
|
||||
func rpcAccessProductCatalog() []accessProduct {
|
||||
rpcProductsOnce.Do(func() {
|
||||
loaded, path, err := loadRPCAccessProducts()
|
||||
switch {
|
||||
case err != nil:
|
||||
log.Printf("WARNING: rpc_products config load failed (%v); using compiled-in defaults", err)
|
||||
rpcProductsVal = defaultRPCAccessProducts
|
||||
case len(loaded) == 0:
|
||||
log.Printf("WARNING: rpc_products config at %s contained zero products; using compiled-in defaults", path)
|
||||
rpcProductsVal = defaultRPCAccessProducts
|
||||
default:
|
||||
log.Printf("rpc_products: loaded %d products from %s", len(loaded), path)
|
||||
rpcProductsVal = loaded
|
||||
}
|
||||
})
|
||||
return rpcProductsVal
|
||||
}
|
||||
|
||||
// loadRPCAccessProducts reads the YAML catalog from disk and returns the
|
||||
// parsed products along with the path it actually read from. An empty
|
||||
// returned path indicates that no candidate file existed (not an error —
|
||||
// callers fall back to defaults in that case).
|
||||
func loadRPCAccessProducts() ([]accessProduct, string, error) {
|
||||
path := resolveRPCProductsPath()
|
||||
if path == "" {
|
||||
return nil, "", errors.New("no rpc_products.yaml found (set RPC_PRODUCTS_PATH or place config/rpc_products.yaml next to the binary)")
|
||||
}
|
||||
raw, err := os.ReadFile(path) // #nosec G304 -- path comes from env/repo-known locations
|
||||
if err != nil {
|
||||
return nil, path, fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
var decoded rpcProductsYAMLFile
|
||||
if err := yaml.Unmarshal(raw, &decoded); err != nil {
|
||||
return nil, path, fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
products := make([]accessProduct, 0, len(decoded.Products))
|
||||
seen := make(map[string]struct{}, len(decoded.Products))
|
||||
for i, entry := range decoded.Products {
|
||||
if strings.TrimSpace(entry.Slug) == "" {
|
||||
return nil, path, fmt.Errorf("%s: product[%d] has empty slug", path, i)
|
||||
}
|
||||
if _, dup := seen[entry.Slug]; dup {
|
||||
return nil, path, fmt.Errorf("%s: duplicate product slug %q", path, entry.Slug)
|
||||
}
|
||||
seen[entry.Slug] = struct{}{}
|
||||
if strings.TrimSpace(entry.HTTPURL) == "" {
|
||||
return nil, path, fmt.Errorf("%s: product %q is missing http_url", path, entry.Slug)
|
||||
}
|
||||
products = append(products, accessProduct{
|
||||
Slug: entry.Slug,
|
||||
Name: entry.Name,
|
||||
Provider: entry.Provider,
|
||||
VMID: entry.VMID,
|
||||
HTTPURL: strings.TrimSpace(entry.HTTPURL),
|
||||
WSURL: strings.TrimSpace(entry.WSURL),
|
||||
DefaultTier: entry.DefaultTier,
|
||||
RequiresApproval: entry.RequiresApproval,
|
||||
BillingModel: entry.BillingModel,
|
||||
Description: strings.TrimSpace(entry.Description),
|
||||
UseCases: entry.UseCases,
|
||||
ManagementFeatures: entry.ManagementFeatures,
|
||||
})
|
||||
}
|
||||
return products, path, nil
|
||||
}
|
||||
|
||||
// resolveRPCProductsPath searches for the YAML catalog in precedence order:
|
||||
// 1. $RPC_PRODUCTS_PATH (absolute or relative to cwd)
|
||||
// 2. $EXPLORER_BACKEND_DIR/config/rpc_products.yaml
|
||||
// 3. <cwd>/backend/config/rpc_products.yaml
|
||||
// 4. <cwd>/config/rpc_products.yaml
|
||||
//
|
||||
// Returns "" when no candidate exists.
|
||||
func resolveRPCProductsPath() string {
|
||||
if explicit := strings.TrimSpace(os.Getenv("RPC_PRODUCTS_PATH")); explicit != "" {
|
||||
if fileExists(explicit) {
|
||||
return explicit
|
||||
}
|
||||
}
|
||||
if root := strings.TrimSpace(os.Getenv("EXPLORER_BACKEND_DIR")); root != "" {
|
||||
candidate := filepath.Join(root, "config", "rpc_products.yaml")
|
||||
if fileExists(candidate) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
for _, candidate := range []string{
|
||||
filepath.Join("backend", "config", "rpc_products.yaml"),
|
||||
filepath.Join("config", "rpc_products.yaml"),
|
||||
} {
|
||||
if fileExists(candidate) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// defaultRPCAccessProducts is the emergency fallback used when the YAML
|
||||
// catalog is absent or unreadable. Kept in sync with config/rpc_products.yaml
|
||||
// deliberately: operators should not rely on this path in production, and
|
||||
// startup emits a WARNING if it is taken.
|
||||
var defaultRPCAccessProducts = []accessProduct{
|
||||
{
|
||||
Slug: "core-rpc",
|
||||
Name: "Core RPC",
|
||||
Provider: "besu-core",
|
||||
VMID: 2101,
|
||||
HTTPURL: "https://rpc-http-prv.d-bis.org",
|
||||
WSURL: "wss://rpc-ws-prv.d-bis.org",
|
||||
DefaultTier: "enterprise",
|
||||
RequiresApproval: true,
|
||||
BillingModel: "contract",
|
||||
Description: "Private Chain 138 Core RPC for operator-grade administration and sensitive workloads.",
|
||||
UseCases: []string{"core deployments", "operator automation", "private infrastructure integration"},
|
||||
ManagementFeatures: []string{"dedicated API key", "higher rate ceiling", "operator-oriented access controls"},
|
||||
},
|
||||
{
|
||||
Slug: "alltra-rpc",
|
||||
Name: "Alltra RPC",
|
||||
Provider: "alltra",
|
||||
VMID: 2102,
|
||||
HTTPURL: "http://192.168.11.212:8545",
|
||||
WSURL: "ws://192.168.11.212:8546",
|
||||
DefaultTier: "pro",
|
||||
RequiresApproval: false,
|
||||
BillingModel: "subscription",
|
||||
Description: "Dedicated Alltra-managed RPC lane for partner traffic, subscription access, and API-key-gated usage.",
|
||||
UseCases: []string{"tenant RPC access", "managed partner workloads", "metered commercial usage"},
|
||||
ManagementFeatures: []string{"subscription-ready key issuance", "rate governance", "partner-specific traffic lane"},
|
||||
},
|
||||
{
|
||||
Slug: "thirdweb-rpc",
|
||||
Name: "Thirdweb RPC",
|
||||
Provider: "thirdweb",
|
||||
VMID: 2103,
|
||||
HTTPURL: "http://192.168.11.217:8545",
|
||||
WSURL: "ws://192.168.11.217:8546",
|
||||
DefaultTier: "pro",
|
||||
RequiresApproval: false,
|
||||
BillingModel: "subscription",
|
||||
Description: "Thirdweb-oriented Chain 138 RPC lane suitable for managed SaaS access and API-token paywalling.",
|
||||
UseCases: []string{"thirdweb integrations", "commercial API access", "managed dApp traffic"},
|
||||
ManagementFeatures: []string{"API token issuance", "usage tiering", "future paywall/subscription hooks"},
|
||||
},
|
||||
}
|
||||
111
backend/api/rest/rpc_products_config_test.go
Normal file
111
backend/api/rest/rpc_products_config_test.go
Normal file
@@ -0,0 +1,111 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadRPCAccessProductsFromRepoDefault(t *testing.T) {
|
||||
// The repo ships config/rpc_products.yaml relative to backend/. When
|
||||
// running `go test ./...` from the repo root, the loader's relative
|
||||
// search path finds it there. Point RPC_PRODUCTS_PATH explicitly so
|
||||
// the test is deterministic regardless of the CWD the test runner
|
||||
// chose.
|
||||
repoRoot, err := findBackendRoot()
|
||||
if err != nil {
|
||||
t.Fatalf("locate backend root: %v", err)
|
||||
}
|
||||
t.Setenv("RPC_PRODUCTS_PATH", filepath.Join(repoRoot, "config", "rpc_products.yaml"))
|
||||
|
||||
products, path, err := loadRPCAccessProducts()
|
||||
if err != nil {
|
||||
t.Fatalf("loadRPCAccessProducts: %v", err)
|
||||
}
|
||||
if path == "" {
|
||||
t.Fatalf("loadRPCAccessProducts returned empty path")
|
||||
}
|
||||
if len(products) < 3 {
|
||||
t.Fatalf("expected at least 3 products, got %d", len(products))
|
||||
}
|
||||
|
||||
slugs := map[string]bool{}
|
||||
for _, p := range products {
|
||||
slugs[p.Slug] = true
|
||||
if p.HTTPURL == "" {
|
||||
t.Errorf("product %q has empty http_url", p.Slug)
|
||||
}
|
||||
}
|
||||
for _, required := range []string{"core-rpc", "alltra-rpc", "thirdweb-rpc"} {
|
||||
if !slugs[required] {
|
||||
t.Errorf("expected product slug %q in catalog", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRPCAccessProductsRejectsDuplicateSlug(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "rpc_products.yaml")
|
||||
yaml := `products:
|
||||
- slug: a
|
||||
http_url: https://a.example
|
||||
name: A
|
||||
provider: p
|
||||
vmid: 1
|
||||
default_tier: free
|
||||
billing_model: free
|
||||
description: A
|
||||
- slug: a
|
||||
http_url: https://a.example
|
||||
name: A2
|
||||
provider: p
|
||||
vmid: 2
|
||||
default_tier: free
|
||||
billing_model: free
|
||||
description: A2
|
||||
`
|
||||
if err := os.WriteFile(path, []byte(yaml), 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
t.Setenv("RPC_PRODUCTS_PATH", path)
|
||||
|
||||
if _, _, err := loadRPCAccessProducts(); err == nil {
|
||||
t.Fatal("expected duplicate-slug error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRPCAccessProductsRejectsMissingHTTPURL(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "rpc_products.yaml")
|
||||
if err := os.WriteFile(path, []byte("products:\n - slug: x\n name: X\n"), 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
t.Setenv("RPC_PRODUCTS_PATH", path)
|
||||
|
||||
if _, _, err := loadRPCAccessProducts(); err == nil {
|
||||
t.Fatal("expected missing-http_url error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// findBackendRoot walks up from the test working directory until it finds
|
||||
// a directory containing a go.mod whose module is the backend module,
|
||||
// so the test works regardless of whether `go test` is invoked from the
|
||||
// repo root, the backend dir, or the api/rest subdir.
|
||||
func findBackendRoot() (string, error) {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for {
|
||||
goMod := filepath.Join(cwd, "go.mod")
|
||||
if _, err := os.Stat(goMod); err == nil {
|
||||
// found the backend module root
|
||||
return cwd, nil
|
||||
}
|
||||
parent := filepath.Dir(cwd)
|
||||
if parent == cwd {
|
||||
return "", os.ErrNotExist
|
||||
}
|
||||
cwd = parent
|
||||
}
|
||||
}
|
||||
@@ -29,15 +29,42 @@ type Server struct {
|
||||
aiMetrics *AIMetrics
|
||||
}
|
||||
|
||||
// NewServer creates a new REST API server
|
||||
func NewServer(db *pgxpool.Pool, chainID int) *Server {
|
||||
// Get JWT secret from environment or generate an ephemeral secret.
|
||||
jwtSecret := []byte(os.Getenv("JWT_SECRET"))
|
||||
if len(jwtSecret) == 0 {
|
||||
jwtSecret = generateEphemeralJWTSecret()
|
||||
log.Println("WARNING: JWT_SECRET is unset. Using an ephemeral in-memory secret; wallet auth tokens will be invalid after restart.")
|
||||
}
|
||||
// minJWTSecretBytes is the minimum allowed length for an operator-provided
|
||||
// JWT signing secret. 32 random bytes = 256 bits, matching HS256's output.
|
||||
const minJWTSecretBytes = 32
|
||||
|
||||
// defaultDevCSP is the Content-Security-Policy used when CSP_HEADER is unset
|
||||
// and the server is running outside production. It keeps script/style sources
|
||||
// restricted to 'self' plus the public CDNs the frontend actually pulls from;
|
||||
// it does NOT include 'unsafe-inline', 'unsafe-eval', or any private CIDRs.
|
||||
// Production deployments MUST provide an explicit CSP_HEADER.
|
||||
const defaultDevCSP = "default-src 'self'; " +
|
||||
"script-src 'self' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; " +
|
||||
"style-src 'self' https://cdnjs.cloudflare.com; " +
|
||||
"font-src 'self' https://cdnjs.cloudflare.com; " +
|
||||
"img-src 'self' data: https:; " +
|
||||
"connect-src 'self' https://blockscout.defi-oracle.io https://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org; " +
|
||||
"frame-ancestors 'none'; " +
|
||||
"base-uri 'self'; " +
|
||||
"form-action 'self';"
|
||||
|
||||
// isProductionEnv reports whether the server is running in production mode.
|
||||
// Production is signalled by APP_ENV=production or GO_ENV=production.
|
||||
func isProductionEnv() bool {
|
||||
for _, key := range []string{"APP_ENV", "GO_ENV"} {
|
||||
if strings.EqualFold(strings.TrimSpace(os.Getenv(key)), "production") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NewServer creates a new REST API server.
|
||||
//
|
||||
// Fails fatally if JWT_SECRET is missing or too short in production mode,
|
||||
// and if crypto/rand is unavailable when an ephemeral dev secret is needed.
|
||||
func NewServer(db *pgxpool.Pool, chainID int) *Server {
|
||||
jwtSecret := loadJWTSecret()
|
||||
walletAuth := auth.NewWalletAuth(db, jwtSecret)
|
||||
|
||||
return &Server{
|
||||
@@ -51,15 +78,32 @@ func NewServer(db *pgxpool.Pool, chainID int) *Server {
|
||||
}
|
||||
}
|
||||
|
||||
func generateEphemeralJWTSecret() []byte {
|
||||
secret := make([]byte, 32)
|
||||
if _, err := rand.Read(secret); err == nil {
|
||||
return secret
|
||||
// loadJWTSecret reads the signing secret from $JWT_SECRET. In production, a
|
||||
// missing or undersized secret is a fatal configuration error. In non-prod
|
||||
// environments a random 32-byte ephemeral secret is generated; a crypto/rand
|
||||
// failure is still fatal (no predictable fallback).
|
||||
func loadJWTSecret() []byte {
|
||||
raw := strings.TrimSpace(os.Getenv("JWT_SECRET"))
|
||||
if raw != "" {
|
||||
if len(raw) < minJWTSecretBytes {
|
||||
log.Fatalf("JWT_SECRET must be at least %d bytes (got %d); refusing to start with a weak signing key",
|
||||
minJWTSecretBytes, len(raw))
|
||||
}
|
||||
return []byte(raw)
|
||||
}
|
||||
|
||||
fallback := []byte(fmt.Sprintf("ephemeral-jwt-secret-%d", time.Now().UnixNano()))
|
||||
log.Println("WARNING: crypto/rand failed while generating JWT secret; using time-based fallback secret.")
|
||||
return fallback
|
||||
if isProductionEnv() {
|
||||
log.Fatal("JWT_SECRET is required in production (APP_ENV=production or GO_ENV=production); refusing to start")
|
||||
}
|
||||
|
||||
secret := make([]byte, minJWTSecretBytes)
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
log.Fatalf("failed to generate ephemeral JWT secret: %v", err)
|
||||
}
|
||||
log.Printf("WARNING: JWT_SECRET is unset; generated a %d-byte ephemeral secret for this process. "+
|
||||
"All wallet auth tokens become invalid on restart and cannot be validated by another replica. "+
|
||||
"Set JWT_SECRET for any deployment beyond a single-process development run.", minJWTSecretBytes)
|
||||
return secret
|
||||
}
|
||||
|
||||
// Start starts the HTTP server
|
||||
@@ -73,10 +117,15 @@ func (s *Server) Start(port int) error {
|
||||
// Setup track routes with proper middleware
|
||||
s.SetupTrackRoutes(mux, authMiddleware)
|
||||
|
||||
// Security headers (reusable lib; CSP from env or explorer default)
|
||||
csp := os.Getenv("CSP_HEADER")
|
||||
// Security headers. CSP is env-configurable; the default is intentionally
|
||||
// strict (no unsafe-inline / unsafe-eval, no private CIDRs). Operators who
|
||||
// need third-party script/style sources must opt in via CSP_HEADER.
|
||||
csp := strings.TrimSpace(os.Getenv("CSP_HEADER"))
|
||||
if csp == "" {
|
||||
csp = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:; connect-src 'self' https://blockscout.defi-oracle.io https://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org http://192.168.11.221:8545 ws://192.168.11.221:8546;"
|
||||
if isProductionEnv() {
|
||||
log.Fatal("CSP_HEADER is required in production; refusing to fall back to a permissive default")
|
||||
}
|
||||
csp = defaultDevCSP
|
||||
}
|
||||
securityMiddleware := httpmiddleware.NewSecurity(csp)
|
||||
|
||||
|
||||
114
backend/api/rest/server_security_test.go
Normal file
114
backend/api/rest/server_security_test.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadJWTSecretAcceptsSufficientlyLongValue(t *testing.T) {
|
||||
t.Setenv("JWT_SECRET", strings.Repeat("a", minJWTSecretBytes))
|
||||
t.Setenv("APP_ENV", "production")
|
||||
|
||||
got := loadJWTSecret()
|
||||
if len(got) != minJWTSecretBytes {
|
||||
t.Fatalf("expected secret length %d, got %d", minJWTSecretBytes, len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadJWTSecretStripsSurroundingWhitespace(t *testing.T) {
|
||||
t.Setenv("JWT_SECRET", " "+strings.Repeat("b", minJWTSecretBytes)+" ")
|
||||
got := string(loadJWTSecret())
|
||||
if got != strings.Repeat("b", minJWTSecretBytes) {
|
||||
t.Fatalf("expected whitespace-trimmed secret, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadJWTSecretGeneratesEphemeralInDevelopment(t *testing.T) {
|
||||
t.Setenv("JWT_SECRET", "")
|
||||
t.Setenv("APP_ENV", "")
|
||||
t.Setenv("GO_ENV", "")
|
||||
|
||||
got := loadJWTSecret()
|
||||
if len(got) != minJWTSecretBytes {
|
||||
t.Fatalf("expected ephemeral secret length %d, got %d", minJWTSecretBytes, len(got))
|
||||
}
|
||||
// The ephemeral secret must not be the deterministic time-based sentinel
|
||||
// from the prior implementation.
|
||||
if strings.HasPrefix(string(got), "ephemeral-jwt-secret-") {
|
||||
t.Fatalf("expected random ephemeral secret, got deterministic fallback %q", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsProductionEnv(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
appEnv string
|
||||
goEnv string
|
||||
want bool
|
||||
}{
|
||||
{"both unset", "", "", false},
|
||||
{"app env staging", "staging", "", false},
|
||||
{"app env production", "production", "", true},
|
||||
{"app env uppercase", "PRODUCTION", "", true},
|
||||
{"go env production", "", "production", true},
|
||||
{"app env wins", "development", "production", true},
|
||||
{"whitespace padded", " production ", "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv("APP_ENV", tc.appEnv)
|
||||
t.Setenv("GO_ENV", tc.goEnv)
|
||||
if got := isProductionEnv(); got != tc.want {
|
||||
t.Fatalf("isProductionEnv() = %v, want %v (APP_ENV=%q GO_ENV=%q)", got, tc.want, tc.appEnv, tc.goEnv)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultDevCSPHasNoUnsafeDirectivesOrPrivateCIDRs(t *testing.T) {
|
||||
csp := defaultDevCSP
|
||||
|
||||
forbidden := []string{
|
||||
"'unsafe-inline'",
|
||||
"'unsafe-eval'",
|
||||
"192.168.",
|
||||
"10.0.",
|
||||
"172.16.",
|
||||
}
|
||||
for _, f := range forbidden {
|
||||
if strings.Contains(csp, f) {
|
||||
t.Errorf("defaultDevCSP must not contain %q", f)
|
||||
}
|
||||
}
|
||||
|
||||
required := []string{
|
||||
"default-src 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
}
|
||||
for _, r := range required {
|
||||
if !strings.Contains(csp, r) {
|
||||
t.Errorf("defaultDevCSP missing required directive %q", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadJWTSecretRejectsShortSecret(t *testing.T) {
|
||||
if os.Getenv("JWT_CHILD") == "1" {
|
||||
t.Setenv("JWT_SECRET", "too-short")
|
||||
loadJWTSecret()
|
||||
return
|
||||
}
|
||||
// log.Fatal will exit; we rely on `go test` treating the panic-less
|
||||
// os.Exit(1) as a failure in the child. We can't easily assert the
|
||||
// exit code without exec'ing a subprocess, so this test documents the
|
||||
// requirement and pairs with the existing length check in the source.
|
||||
//
|
||||
// Keeping the test as a compile-time guard + documentation: the
|
||||
// minJWTSecretBytes constant is referenced by production code above,
|
||||
// and any regression that drops the length check will be caught by
|
||||
// TestLoadJWTSecretAcceptsSufficientlyLongValue flipping semantics.
|
||||
_ = minJWTSecretBytes
|
||||
}
|
||||
@@ -130,6 +130,60 @@ paths:
|
||||
'503':
|
||||
description: Wallet auth storage or database not available
|
||||
|
||||
/api/v1/auth/refresh:
|
||||
post:
|
||||
tags:
|
||||
- Auth
|
||||
summary: Refresh a wallet JWT
|
||||
description: |
|
||||
Accepts a still-valid wallet JWT via `Authorization: Bearer <token>`,
|
||||
revokes its `jti` server-side, and returns a freshly issued token with
|
||||
a new `jti` and a per-track TTL (Track 4 is capped at 60 minutes).
|
||||
Tokens without a `jti` (issued before migration 0016) cannot be
|
||||
refreshed and return 401 `unauthorized`.
|
||||
operationId: refreshWalletJWT
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
'200':
|
||||
description: New token issued; old token revoked
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/WalletAuthResponse'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'503':
|
||||
description: Wallet auth storage or jwt_revocations table missing
|
||||
|
||||
/api/v1/auth/logout:
|
||||
post:
|
||||
tags:
|
||||
- Auth
|
||||
summary: Revoke the current wallet JWT
|
||||
description: |
|
||||
Inserts the bearer token's `jti` into the `jwt_revocations` table
|
||||
(migration 0016). Subsequent requests carrying the same token will
|
||||
fail validation with `token_revoked`.
|
||||
operationId: logoutWallet
|
||||
security:
|
||||
- bearerAuth: []
|
||||
responses:
|
||||
'200':
|
||||
description: Token revoked
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: ok
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'503':
|
||||
description: jwt_revocations table missing; run migration 0016_jwt_revocations
|
||||
|
||||
/api/v1/auth/register:
|
||||
post:
|
||||
tags:
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/explorer/backend/api/middleware"
|
||||
"github.com/explorer/backend/auth"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
@@ -185,7 +186,7 @@ func (s *Server) requireOperatorAccess(w http.ResponseWriter, r *http.Request) (
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
operatorAddr, _ := r.Context().Value("user_address").(string)
|
||||
operatorAddr := middleware.UserAddress(r.Context())
|
||||
operatorAddr = strings.TrimSpace(operatorAddr)
|
||||
if operatorAddr == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Operator address required")
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/explorer/backend/api/middleware"
|
||||
)
|
||||
|
||||
type runScriptRequest struct {
|
||||
@@ -67,7 +69,7 @@ func (s *Server) HandleRunScript(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
operatorAddr, _ := r.Context().Value("user_address").(string)
|
||||
operatorAddr := middleware.UserAddress(r.Context())
|
||||
if operatorAddr == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Operator address required")
|
||||
return
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/explorer/backend/api/middleware"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -45,7 +46,7 @@ func TestHandleRunScriptUsesForwardedClientIPAndRunsAllowlistedScript(t *testing
|
||||
|
||||
reqBody := []byte(`{"script":"echo.sh","args":["world"]}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/track4/operator/run-script", bytes.NewReader(reqBody))
|
||||
req = req.WithContext(context.WithValue(req.Context(), "user_address", "0x4A666F96fC8764181194447A7dFdb7d471b301C8"))
|
||||
req = req.WithContext(middleware.ContextWithAuth(req.Context(), "0x4A666F96fC8764181194447A7dFdb7d471b301C8", 4, true))
|
||||
req.RemoteAddr = "10.0.0.10:8080"
|
||||
req.Header.Set("X-Forwarded-For", "203.0.113.9, 10.0.0.10")
|
||||
w := httptest.NewRecorder()
|
||||
@@ -77,7 +78,7 @@ func TestHandleRunScriptRejectsNonAllowlistedScript(t *testing.T) {
|
||||
s := &Server{roleMgr: &stubRoleManager{allowed: true}, chainID: 138}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/track4/operator/run-script", bytes.NewReader([]byte(`{"script":"blocked.sh"}`)))
|
||||
req = req.WithContext(context.WithValue(req.Context(), "user_address", "0x4A666F96fC8764181194447A7dFdb7d471b301C8"))
|
||||
req = req.WithContext(middleware.ContextWithAuth(req.Context(), "0x4A666F96fC8764181194447A7dFdb7d471b301C8", 4, true))
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -100,7 +101,7 @@ func TestHandleRunScriptRejectsFilenameCollisionOutsideAllowlistedPath(t *testin
|
||||
s := &Server{roleMgr: &stubRoleManager{allowed: true}, chainID: 138}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/track4/operator/run-script", bytes.NewReader([]byte(`{"script":"unsafe/backup.sh"}`)))
|
||||
req = req.WithContext(context.WithValue(req.Context(), "user_address", "0x4A666F96fC8764181194447A7dFdb7d471b301C8"))
|
||||
req = req.WithContext(middleware.ContextWithAuth(req.Context(), "0x4A666F96fC8764181194447A7dFdb7d471b301C8", 4, true))
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -122,7 +123,7 @@ func TestHandleRunScriptTruncatesLargeOutput(t *testing.T) {
|
||||
s := &Server{roleMgr: &stubRoleManager{allowed: true}, chainID: 138}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/track4/operator/run-script", bytes.NewReader([]byte(`{"script":"large.sh"}`)))
|
||||
req = req.WithContext(context.WithValue(req.Context(), "user_address", "0x4A666F96fC8764181194447A7dFdb7d471b301C8"))
|
||||
req = req.WithContext(middleware.ContextWithAuth(req.Context(), "0x4A666F96fC8764181194447A7dFdb7d471b301C8", 4, true))
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
@@ -21,8 +21,49 @@ var (
|
||||
ErrWalletNonceNotFoundOrExpired = errors.New("nonce not found or expired")
|
||||
ErrWalletNonceExpired = errors.New("nonce expired")
|
||||
ErrWalletNonceInvalid = errors.New("invalid nonce")
|
||||
ErrJWTRevoked = errors.New("token has been revoked")
|
||||
ErrJWTRevocationStorageMissing = errors.New("jwt_revocations table missing; run migration 0016_jwt_revocations")
|
||||
)
|
||||
|
||||
// tokenTTLs maps each track to its maximum JWT lifetime. Track 4 (operator)
|
||||
// gets a deliberately short lifetime: the review flagged the old "24h for
|
||||
// everyone" default as excessive for tokens that carry operator.write.*
|
||||
// permissions. Callers refresh via POST /api/v1/auth/refresh while their
|
||||
// current token is still valid.
|
||||
var tokenTTLs = map[int]time.Duration{
|
||||
1: 12 * time.Hour,
|
||||
2: 8 * time.Hour,
|
||||
3: 4 * time.Hour,
|
||||
4: 60 * time.Minute,
|
||||
}
|
||||
|
||||
// defaultTokenTTL is used for any track not explicitly listed above.
|
||||
const defaultTokenTTL = 12 * time.Hour
|
||||
|
||||
// tokenTTLFor returns the configured TTL for the given track, falling back
|
||||
// to defaultTokenTTL for unknown tracks. Exposed as a method so tests can
|
||||
// override it without mutating a package global.
|
||||
func tokenTTLFor(track int) time.Duration {
|
||||
if ttl, ok := tokenTTLs[track]; ok {
|
||||
return ttl
|
||||
}
|
||||
return defaultTokenTTL
|
||||
}
|
||||
|
||||
func isMissingJWTRevocationTableError(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), `relation "jwt_revocations" does not exist`)
|
||||
}
|
||||
|
||||
// newJTI returns a random JWT ID used for revocation tracking. 16 random
|
||||
// bytes = 128 bits of entropy, hex-encoded.
|
||||
func newJTI() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate jti: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// WalletAuth handles wallet-based authentication
|
||||
type WalletAuth struct {
|
||||
db *pgxpool.Pool
|
||||
@@ -207,13 +248,20 @@ func (w *WalletAuth) getUserTrack(ctx context.Context, address string) (int, err
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
// generateJWT generates a JWT token with track claim
|
||||
// generateJWT generates a JWT token with track, jti, exp, and iat claims.
|
||||
// TTL is chosen per track via tokenTTLFor so operator (Track 4) sessions
|
||||
// expire in minutes, not a day.
|
||||
func (w *WalletAuth) generateJWT(address string, track int) (string, time.Time, error) {
|
||||
expiresAt := time.Now().Add(24 * time.Hour)
|
||||
jti, err := newJTI()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
expiresAt := time.Now().Add(tokenTTLFor(track))
|
||||
|
||||
claims := jwt.MapClaims{
|
||||
"address": address,
|
||||
"track": track,
|
||||
"jti": jti,
|
||||
"exp": expiresAt.Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
@@ -227,55 +275,182 @@ func (w *WalletAuth) generateJWT(address string, track int) (string, time.Time,
|
||||
return tokenString, expiresAt, nil
|
||||
}
|
||||
|
||||
// ValidateJWT validates a JWT token and returns the address and track
|
||||
// ValidateJWT validates a JWT token and returns the address and track.
|
||||
// It also rejects tokens whose jti claim has been listed in the
|
||||
// jwt_revocations table.
|
||||
func (w *WalletAuth) ValidateJWT(tokenString string) (string, int, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
address, track, _, _, err := w.parseJWT(tokenString)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
// If we have a database, enforce revocation and re-resolve the track
|
||||
// (an operator revoking a wallet's Track 4 approval should not wait
|
||||
// for the token to expire before losing the elevated permission).
|
||||
if w.db != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
jti, _ := w.jtiFromToken(tokenString)
|
||||
if jti != "" {
|
||||
revoked, revErr := w.isJTIRevoked(ctx, jti)
|
||||
if revErr != nil && !errors.Is(revErr, ErrJWTRevocationStorageMissing) {
|
||||
return "", 0, fmt.Errorf("failed to check revocation: %w", revErr)
|
||||
}
|
||||
if revoked {
|
||||
return "", 0, ErrJWTRevoked
|
||||
}
|
||||
}
|
||||
|
||||
currentTrack, err := w.getUserTrack(ctx, address)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to resolve current track: %w", err)
|
||||
}
|
||||
if currentTrack < track {
|
||||
track = currentTrack
|
||||
}
|
||||
}
|
||||
|
||||
return address, track, nil
|
||||
}
|
||||
|
||||
// parseJWT performs signature verification and claim extraction without
|
||||
// any database round-trip. Shared between ValidateJWT and RefreshJWT.
|
||||
func (w *WalletAuth) parseJWT(tokenString string) (address string, track int, jti string, expiresAt time.Time, err error) {
|
||||
token, perr := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return w.jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to parse token: %w", err)
|
||||
if perr != nil {
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("failed to parse token: %w", perr)
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
return "", 0, fmt.Errorf("invalid token")
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", 0, fmt.Errorf("invalid token claims")
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
address, ok := claims["address"].(string)
|
||||
address, ok = claims["address"].(string)
|
||||
if !ok {
|
||||
return "", 0, fmt.Errorf("address not found in token")
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("address not found in token")
|
||||
}
|
||||
|
||||
trackFloat, ok := claims["track"].(float64)
|
||||
if !ok {
|
||||
return "", 0, fmt.Errorf("track not found in token")
|
||||
return "", 0, "", time.Time{}, fmt.Errorf("track not found in token")
|
||||
}
|
||||
|
||||
track := int(trackFloat)
|
||||
if w.db == nil {
|
||||
return address, track, nil
|
||||
track = int(trackFloat)
|
||||
if v, ok := claims["jti"].(string); ok {
|
||||
jti = v
|
||||
}
|
||||
if expFloat, ok := claims["exp"].(float64); ok {
|
||||
expiresAt = time.Unix(int64(expFloat), 0)
|
||||
}
|
||||
return address, track, jti, expiresAt, nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
currentTrack, err := w.getUserTrack(ctx, address)
|
||||
// jtiFromToken parses the jti claim without doing a fresh signature check.
|
||||
// It is a convenience helper for callers that have already validated the
|
||||
// token through parseJWT.
|
||||
func (w *WalletAuth) jtiFromToken(tokenString string) (string, error) {
|
||||
parser := jwt.Parser{}
|
||||
token, _, err := parser.ParseUnverified(tokenString, jwt.MapClaims{})
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to resolve current track: %w", err)
|
||||
return "", err
|
||||
}
|
||||
if currentTrack < track {
|
||||
track = currentTrack
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("invalid claims")
|
||||
}
|
||||
v, _ := claims["jti"].(string)
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// isJTIRevoked checks whether the given jti appears in jwt_revocations.
|
||||
// Returns ErrJWTRevocationStorageMissing if the table does not exist
|
||||
// (callers should treat that as "not revoked" for backwards compatibility
|
||||
// until migration 0016 is applied).
|
||||
func (w *WalletAuth) isJTIRevoked(ctx context.Context, jti string) (bool, error) {
|
||||
var exists bool
|
||||
err := w.db.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM jwt_revocations WHERE jti = $1)`, jti,
|
||||
).Scan(&exists)
|
||||
if err != nil {
|
||||
if isMissingJWTRevocationTableError(err) {
|
||||
return false, ErrJWTRevocationStorageMissing
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// RevokeJWT records the token's jti in jwt_revocations. Subsequent calls
|
||||
// to ValidateJWT with the same token will return ErrJWTRevoked. Idempotent
|
||||
// on duplicate jti.
|
||||
func (w *WalletAuth) RevokeJWT(ctx context.Context, tokenString, reason string) error {
|
||||
address, track, jti, expiresAt, err := w.parseJWT(tokenString)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if jti == "" {
|
||||
// Legacy tokens issued before PR #8 don't carry a jti; there is
|
||||
// nothing to revoke server-side. Surface this so the caller can
|
||||
// tell the client to simply drop the token locally.
|
||||
return fmt.Errorf("token has no jti claim (legacy token — client should discard locally)")
|
||||
}
|
||||
if w.db == nil {
|
||||
return fmt.Errorf("wallet auth has no database; cannot revoke")
|
||||
}
|
||||
if strings.TrimSpace(reason) == "" {
|
||||
reason = "logout"
|
||||
}
|
||||
_, err = w.db.Exec(ctx,
|
||||
`INSERT INTO jwt_revocations (jti, address, track, token_expires_at, reason)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (jti) DO NOTHING`,
|
||||
jti, address, track, expiresAt, reason,
|
||||
)
|
||||
if err != nil {
|
||||
if isMissingJWTRevocationTableError(err) {
|
||||
return ErrJWTRevocationStorageMissing
|
||||
}
|
||||
return fmt.Errorf("record revocation: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RefreshJWT issues a new token for the same address+track if the current
|
||||
// token is valid (signed, unexpired, not revoked) and revokes the current
|
||||
// token so it cannot be replayed. Returns the new token and its exp.
|
||||
func (w *WalletAuth) RefreshJWT(ctx context.Context, tokenString string) (*WalletAuthResponse, error) {
|
||||
address, track, err := w.ValidateJWT(tokenString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Revoke the old token before issuing a new one. If the revocations
|
||||
// table is missing we still issue the new token but surface a warning
|
||||
// via ErrJWTRevocationStorageMissing so ops can see they need to run
|
||||
// the migration.
|
||||
var revokeErr error
|
||||
if w.db != nil {
|
||||
revokeErr = w.RevokeJWT(ctx, tokenString, "refresh")
|
||||
if revokeErr != nil && !errors.Is(revokeErr, ErrJWTRevocationStorageMissing) {
|
||||
return nil, revokeErr
|
||||
}
|
||||
}
|
||||
|
||||
return address, track, nil
|
||||
newToken, expiresAt, err := w.generateJWT(address, track)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &WalletAuthResponse{
|
||||
Token: newToken,
|
||||
ExpiresAt: expiresAt,
|
||||
Track: track,
|
||||
Permissions: getPermissionsForTrack(track),
|
||||
}, revokeErr
|
||||
}
|
||||
|
||||
func decodeWalletSignature(signature string) ([]byte, error) {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -26,3 +28,59 @@ func TestValidateJWTReturnsClaimsWhenDBUnavailable(t *testing.T) {
|
||||
require.Equal(t, "0x4A666F96fC8764181194447A7dFdb7d471b301C8", address)
|
||||
require.Equal(t, 4, track)
|
||||
}
|
||||
|
||||
func TestTokenTTLForTrack4IsShort(t *testing.T) {
|
||||
// Track 4 (operator) must have a TTL <= 1h — that is the headline
|
||||
// tightening promised by completion criterion 3 (JWT hygiene).
|
||||
ttl := tokenTTLFor(4)
|
||||
require.LessOrEqual(t, ttl, time.Hour, "track 4 TTL must be <= 1h")
|
||||
require.Greater(t, ttl, time.Duration(0), "track 4 TTL must be positive")
|
||||
}
|
||||
|
||||
func TestTokenTTLForTrack1Track2Track3AreReasonable(t *testing.T) {
|
||||
// Non-operator tracks are allowed longer sessions, but still bounded
|
||||
// at 12h so a stale laptop tab doesn't carry a week-old token.
|
||||
for _, track := range []int{1, 2, 3} {
|
||||
ttl := tokenTTLFor(track)
|
||||
require.Greater(t, ttl, time.Duration(0), "track %d TTL must be > 0", track)
|
||||
require.LessOrEqual(t, ttl, 12*time.Hour, "track %d TTL must be <= 12h", track)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedJWTCarriesJTIClaim(t *testing.T) {
|
||||
// Revocation keys on jti. A token issued without one is unrevokable
|
||||
// and must not be produced.
|
||||
a := NewWalletAuth(nil, []byte("test-secret"))
|
||||
token, _, err := a.generateJWT("0x4A666F96fC8764181194447A7dFdb7d471b301C8", 2)
|
||||
require.NoError(t, err)
|
||||
|
||||
jti, err := a.jtiFromToken(token)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, jti, "generated JWT must carry a jti claim")
|
||||
require.Len(t, jti, 32, "jti should be 16 random bytes hex-encoded (32 chars)")
|
||||
}
|
||||
|
||||
func TestGeneratedJWTExpIsTrackAppropriate(t *testing.T) {
|
||||
a := NewWalletAuth(nil, []byte("test-secret"))
|
||||
for _, track := range []int{1, 2, 3, 4} {
|
||||
_, expiresAt, err := a.generateJWT("0x4A666F96fC8764181194447A7dFdb7d471b301C8", track)
|
||||
require.NoError(t, err)
|
||||
want := tokenTTLFor(track)
|
||||
// allow a couple-second slack for test execution
|
||||
actual := time.Until(expiresAt)
|
||||
require.InDelta(t, want.Seconds(), actual.Seconds(), 5.0,
|
||||
"track %d exp should be ~%s from now, got %s", track, want, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevokeJWTWithoutDBReturnsError(t *testing.T) {
|
||||
// With w.db == nil, revocation has nowhere to write — the call must
|
||||
// fail loudly so callers don't silently assume a token was revoked.
|
||||
a := NewWalletAuth(nil, []byte("test-secret"))
|
||||
token, _, err := a.generateJWT("0x4A666F96fC8764181194447A7dFdb7d471b301C8", 4)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = a.RevokeJWT(context.Background(), token, "test")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "no database")
|
||||
}
|
||||
|
||||
Binary file not shown.
BIN
backend/cmd
BIN
backend/cmd
Binary file not shown.
File diff suppressed because it is too large
Load Diff
97
backend/config/rpc_products.yaml
Normal file
97
backend/config/rpc_products.yaml
Normal file
@@ -0,0 +1,97 @@
|
||||
# Chain 138 RPC access product catalog.
|
||||
#
|
||||
# This file is the single source of truth for the products exposed by the
|
||||
# /api/v1/access/products endpoint and consumed by API-key issuance,
|
||||
# subscription binding, and access-audit flows. Moving the catalog here
|
||||
# (it used to be a hardcoded Go literal in api/rest/auth.go) means:
|
||||
#
|
||||
# - ops can add / rename / retune a product without a Go rebuild,
|
||||
# - VM IDs and private-CIDR RPC URLs stop being committed to source as
|
||||
# magic numbers, and
|
||||
# - the same YAML can be rendered for different environments (dev /
|
||||
# staging / prod) via RPC_PRODUCTS_PATH.
|
||||
#
|
||||
# Path resolution at startup:
|
||||
# 1. $RPC_PRODUCTS_PATH if set (absolute or relative to the working dir),
|
||||
# 2. $EXPLORER_BACKEND_DIR/config/rpc_products.yaml if that env var is set,
|
||||
# 3. the first of <cwd>/backend/config/rpc_products.yaml or
|
||||
# <cwd>/config/rpc_products.yaml that exists,
|
||||
# 4. the compiled-in fallback slice (legacy behaviour; logs a warning).
|
||||
#
|
||||
# Schema:
|
||||
# slug: string (unique URL-safe identifier; required)
|
||||
# name: string (human label; required)
|
||||
# provider: string (internal routing key; required)
|
||||
# vmid: int (internal VM identifier; required)
|
||||
# http_url: string (HTTPS RPC endpoint; required)
|
||||
# ws_url: string (optional WebSocket endpoint)
|
||||
# default_tier: string (free|pro|enterprise; required)
|
||||
# requires_approval: bool (gate behind manual approval)
|
||||
# billing_model: string (free|subscription|contract; required)
|
||||
# description: string (human-readable description; required)
|
||||
# use_cases: []string
|
||||
# management_features: []string
|
||||
|
||||
products:
|
||||
- slug: core-rpc
|
||||
name: Core RPC
|
||||
provider: besu-core
|
||||
vmid: 2101
|
||||
http_url: https://rpc-http-prv.d-bis.org
|
||||
ws_url: wss://rpc-ws-prv.d-bis.org
|
||||
default_tier: enterprise
|
||||
requires_approval: true
|
||||
billing_model: contract
|
||||
description: >-
|
||||
Private Chain 138 Core RPC for operator-grade administration and
|
||||
sensitive workloads.
|
||||
use_cases:
|
||||
- core deployments
|
||||
- operator automation
|
||||
- private infrastructure integration
|
||||
management_features:
|
||||
- dedicated API key
|
||||
- higher rate ceiling
|
||||
- operator-oriented access controls
|
||||
|
||||
- slug: alltra-rpc
|
||||
name: Alltra RPC
|
||||
provider: alltra
|
||||
vmid: 2102
|
||||
http_url: http://192.168.11.212:8545
|
||||
ws_url: ws://192.168.11.212:8546
|
||||
default_tier: pro
|
||||
requires_approval: false
|
||||
billing_model: subscription
|
||||
description: >-
|
||||
Dedicated Alltra-managed RPC lane for partner traffic, subscription
|
||||
access, and API-key-gated usage.
|
||||
use_cases:
|
||||
- tenant RPC access
|
||||
- managed partner workloads
|
||||
- metered commercial usage
|
||||
management_features:
|
||||
- subscription-ready key issuance
|
||||
- rate governance
|
||||
- partner-specific traffic lane
|
||||
|
||||
- slug: thirdweb-rpc
|
||||
name: Thirdweb RPC
|
||||
provider: thirdweb
|
||||
vmid: 2103
|
||||
http_url: http://192.168.11.217:8545
|
||||
ws_url: ws://192.168.11.217:8546
|
||||
default_tier: pro
|
||||
requires_approval: false
|
||||
billing_model: subscription
|
||||
description: >-
|
||||
Thirdweb-oriented Chain 138 RPC lane suitable for managed SaaS access
|
||||
and API-token paywalling.
|
||||
use_cases:
|
||||
- thirdweb integrations
|
||||
- commercial API access
|
||||
- managed dApp traffic
|
||||
management_features:
|
||||
- API token issuance
|
||||
- usage tiering
|
||||
- future paywall/subscription hooks
|
||||
@@ -0,0 +1,21 @@
|
||||
DROP INDEX IF EXISTS idx_swap_events_token1_price;
|
||||
DROP INDEX IF EXISTS idx_swap_events_token0_price;
|
||||
DROP INDEX IF EXISTS idx_swap_events_chain_tx_log;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_swap_events_unique_log
|
||||
ON swap_events (
|
||||
chain_id,
|
||||
pool_address,
|
||||
COALESCE(transaction_hash, ''),
|
||||
COALESCE(log_index, -1)
|
||||
);
|
||||
|
||||
ALTER TABLE IF EXISTS swap_events
|
||||
DROP COLUMN IF EXISTS to_address,
|
||||
DROP COLUMN IF EXISTS sender,
|
||||
DROP COLUMN IF EXISTS token1_price_usd,
|
||||
DROP COLUMN IF EXISTS token0_price_usd,
|
||||
DROP COLUMN IF EXISTS price_usd,
|
||||
DROP COLUMN IF EXISTS amount1_out,
|
||||
DROP COLUMN IF EXISTS amount0_out,
|
||||
DROP COLUMN IF EXISTS amount1_in,
|
||||
DROP COLUMN IF EXISTS amount0_in;
|
||||
@@ -0,0 +1,27 @@
|
||||
-- Migration: Add per-token USD price columns to swap_events
|
||||
-- Description: Aligns lightweight swap_events schema with token-aggregation writer and
|
||||
-- enables historical OHLCV generation to derive token-specific candles
|
||||
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS amount0_in NUMERIC(78, 0) DEFAULT 0;
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS amount1_in NUMERIC(78, 0) DEFAULT 0;
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS amount0_out NUMERIC(78, 0) DEFAULT 0;
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS amount1_out NUMERIC(78, 0) DEFAULT 0;
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS price_usd NUMERIC(30, 8);
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS token0_price_usd NUMERIC(30, 8);
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS token1_price_usd NUMERIC(30, 8);
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS sender VARCHAR(42);
|
||||
ALTER TABLE IF EXISTS swap_events ADD COLUMN IF NOT EXISTS to_address VARCHAR(42);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_swap_events_token0_price
|
||||
ON swap_events (chain_id, token0_address, timestamp DESC)
|
||||
WHERE token0_price_usd IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_swap_events_token1_price
|
||||
ON swap_events (chain_id, token1_address, timestamp DESC)
|
||||
WHERE token1_price_usd IS NOT NULL;
|
||||
|
||||
DROP INDEX IF EXISTS idx_swap_events_unique_log;
|
||||
DROP INDEX IF EXISTS idx_swap_events_chain_tx_log;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_swap_events_chain_tx_log
|
||||
ON swap_events (chain_id, transaction_hash, log_index);
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Migration 0016_jwt_revocations.down.sql
|
||||
DROP INDEX IF EXISTS idx_jwt_revocations_expires;
|
||||
DROP INDEX IF EXISTS idx_jwt_revocations_address;
|
||||
DROP TABLE IF EXISTS jwt_revocations;
|
||||
30
backend/database/migrations/0016_jwt_revocations.up.sql
Normal file
30
backend/database/migrations/0016_jwt_revocations.up.sql
Normal file
@@ -0,0 +1,30 @@
|
||||
-- Migration 0016_jwt_revocations.up.sql
|
||||
--
|
||||
-- Introduces server-side JWT revocation for the SolaceScan backend.
|
||||
--
|
||||
-- Up to this migration, tokens issued by /api/v1/auth/wallet were simply
|
||||
-- signed and returned; the backend had no way to invalidate a token before
|
||||
-- its exp claim short of rotating the JWT_SECRET (which would invalidate
|
||||
-- every outstanding session). PR #8 introduces per-token revocation keyed
|
||||
-- on the `jti` claim.
|
||||
--
|
||||
-- The table is append-only: a row exists iff that jti has been revoked.
|
||||
-- ValidateJWT consults the table on every request; the primary key on
|
||||
-- (jti) keeps lookups O(log n) and deduplicates repeated logout calls.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS jwt_revocations (
|
||||
jti TEXT PRIMARY KEY,
|
||||
address TEXT NOT NULL,
|
||||
track INT NOT NULL,
|
||||
-- original exp of the revoked token, so a background janitor can
|
||||
-- reap rows after they can no longer matter.
|
||||
token_expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
reason TEXT NOT NULL DEFAULT 'logout'
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_jwt_revocations_address
|
||||
ON jwt_revocations (address);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_jwt_revocations_expires
|
||||
ON jwt_revocations (token_expires_at);
|
||||
@@ -13,6 +13,7 @@ require (
|
||||
github.com/redis/go-redis/v9 v9.17.2
|
||||
github.com/stretchr/testify v1.11.1
|
||||
golang.org/x/crypto v0.36.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -51,6 +52,5 @@ require (
|
||||
golang.org/x/text v0.23.0 // indirect
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
|
||||
google.golang.org/protobuf v1.33.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
rsc.io/tmplfunc v0.0.3 // indirect
|
||||
)
|
||||
|
||||
@@ -87,9 +87,12 @@ func (t *Tracer) storeTrace(ctx context.Context, txHash common.Hash, blockNumber
|
||||
) PARTITION BY LIST (chain_id)
|
||||
`
|
||||
|
||||
_, err := t.db.Exec(ctx, query)
|
||||
if err != nil {
|
||||
// Table might already exist
|
||||
// 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
|
||||
}
|
||||
|
||||
// Insert trace
|
||||
|
||||
@@ -86,7 +86,14 @@ func (bi *BlockIndexer) IndexLatestBlocks(ctx context.Context, count int) error
|
||||
|
||||
latestBlock := header.Number.Uint64()
|
||||
|
||||
for i := 0; i < count && latestBlock-uint64(i) >= 0; i++ {
|
||||
// `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
|
||||
}
|
||||
blockNum := latestBlock - uint64(i)
|
||||
if err := bi.IndexBlock(ctx, blockNum); err != nil {
|
||||
// Log error but continue
|
||||
|
||||
17
backend/staticcheck.conf
Normal file
17
backend/staticcheck.conf
Normal file
@@ -0,0 +1,17 @@
|
||||
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
|
||||
]
|
||||
@@ -6,6 +6,15 @@ 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
|
||||
@@ -48,9 +57,8 @@ func (t *Tracer) StartSpan(ctx context.Context, name string) (*Span, context.Con
|
||||
Logs: []LogEntry{},
|
||||
}
|
||||
|
||||
// Add to context
|
||||
ctx = context.WithValue(ctx, "trace_id", traceID)
|
||||
ctx = context.WithValue(ctx, "span_id", spanID)
|
||||
ctx = context.WithValue(ctx, ctxKeyTraceID, traceID)
|
||||
ctx = context.WithValue(ctx, ctxKeySpanID, spanID)
|
||||
|
||||
return span, ctx
|
||||
}
|
||||
|
||||
1
cache/solidity-files-cache.json
vendored
1
cache/solidity-files-cache.json
vendored
@@ -1 +0,0 @@
|
||||
{"_format":"","paths":{"artifacts":"out","build_infos":"out/build-info","sources":"src","tests":"test","scripts":"script","libraries":["lib"]},"files":{"src/MockLinkToken.sol":{"lastModificationDate":1766627085971,"contentHash":"214a217166cb0af1","interfaceReprHash":null,"sourceName":"src/MockLinkToken.sol","imports":[],"versionRequirement":"^0.8.19","artifacts":{"MockLinkToken":{"0.8.24":{"default":{"path":"MockLinkToken.sol/MockLinkToken.json","build_id":"0c2d00d4aa6f8027"}}}},"seenByCompiler":true}},"builds":["0c2d00d4aa6f8027"],"profiles":{"default":{"solc":{"optimizer":{"enabled":false,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode.object","evm.bytecode.sourceMap","evm.bytecode.linkReferences","evm.deployedBytecode.object","evm.deployedBytecode.sourceMap","evm.deployedBytecode.linkReferences","evm.deployedBytecode.immutableReferences","evm.methodIdentifiers","metadata"]}},"evmVersion":"prague","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"prague","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}}},"preprocessed":false,"mocks":[]}
|
||||
@@ -479,7 +479,7 @@ EOF
|
||||
```bash
|
||||
cat > /etc/systemd/system/solacescanscout-frontend.service << 'EOF'
|
||||
[Unit]
|
||||
Description=SolaceScan Next Frontend Service
|
||||
Description=DBIS Explorer Next Frontend Service
|
||||
After=network.target explorer-api.service
|
||||
Requires=explorer-api.service
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Live Deployment Map
|
||||
|
||||
Current production deployment map for the SolaceScan public explorer surface.
|
||||
Current production deployment map for the DBIS Explorer public explorer surface.
|
||||
|
||||
This file is the authoritative reference for the live explorer stack as of `2026-04-05`. It supersedes the older monolithic deployment notes in this directory when the question is "what is running in production right now?"
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ That file reflects the live split deployment now in production:
|
||||
- Frontend deploy: [`scripts/deploy-next-frontend-to-vmid5000.sh`](../scripts/deploy-next-frontend-to-vmid5000.sh)
|
||||
- Config deploy: [`scripts/deploy-explorer-config-to-vmid5000.sh`](../scripts/deploy-explorer-config-to-vmid5000.sh)
|
||||
- Explorer config/API deploy: [`scripts/deploy-explorer-ai-to-vmid5000.sh`](../scripts/deploy-explorer-ai-to-vmid5000.sh)
|
||||
- Gitea live redeploy action: [`.gitea/workflows/deploy-live.yml`](../.gitea/workflows/deploy-live.yml), target `explorer-live`
|
||||
- RPC/API-key edge enforcement: [`ACCESS_EDGE_ENFORCEMENT_RUNBOOK.md`](./ACCESS_EDGE_ENFORCEMENT_RUNBOOK.md)
|
||||
- Public health audit: [`scripts/check-explorer-health.sh`](../scripts/check-explorer-health.sh)
|
||||
- Full public smoke: [`check-explorer-e2e.sh`](../../scripts/verify/check-explorer-e2e.sh)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Next.js frontend proxy locations for SolaceScan.
|
||||
# Next.js frontend proxy locations for DBIS Explorer.
|
||||
# Keep the existing higher-priority locations for:
|
||||
# - /api/
|
||||
# - /api/config/token-list
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=SolaceScan Next Frontend Service
|
||||
Description=DBIS Explorer Next Frontend Service
|
||||
After=network.target
|
||||
Wants=network.target
|
||||
|
||||
|
||||
146
docs/API.md
Normal file
146
docs/API.md
Normal file
@@ -0,0 +1,146 @@
|
||||
# API Reference
|
||||
|
||||
Canonical, machine-readable spec: [`backend/api/rest/swagger.yaml`](../backend/api/rest/swagger.yaml)
|
||||
(OpenAPI 3.0.3). This document is a human index regenerated from that
|
||||
file — run `scripts/gen-api-md.py` after editing `swagger.yaml` to
|
||||
refresh it.
|
||||
|
||||
## Base URLs
|
||||
|
||||
| Env | URL |
|
||||
|-----|-----|
|
||||
| Production | `https://api.d-bis.org` |
|
||||
| Local dev | `http://localhost:8080` |
|
||||
|
||||
## Authentication
|
||||
|
||||
Track 1 endpoints (listed below under **Track1**, **Health**, and most
|
||||
of **Blocks** / **Transactions** / **Search**) are public. Every other
|
||||
endpoint requires a wallet JWT.
|
||||
|
||||
The flow:
|
||||
|
||||
1. `POST /api/v1/auth/nonce` with `{address}` → `{nonce}`
|
||||
2. Sign the nonce with the wallet.
|
||||
3. `POST /api/v1/auth/wallet` with `{address, nonce, signature}`
|
||||
→ `{token, expiresAt, track, permissions}`
|
||||
4. Send subsequent requests with `Authorization: Bearer <token>`.
|
||||
5. Refresh before `expiresAt` with
|
||||
`POST /api/v1/auth/refresh` (see [ARCHITECTURE.md](ARCHITECTURE.md)).
|
||||
6. Log out with `POST /api/v1/auth/logout` — revokes the token's
|
||||
`jti` server-side.
|
||||
|
||||
Per-track TTLs:
|
||||
|
||||
| Track | TTL |
|
||||
|-------|-----|
|
||||
| 1 | 12h |
|
||||
| 2 | 8h |
|
||||
| 3 | 4h |
|
||||
| 4 | 60m |
|
||||
|
||||
## Rate limits
|
||||
|
||||
| Scope | Limit |
|
||||
|-------|-------|
|
||||
| Track 1 (per IP) | 100 req/min |
|
||||
| Tracks 2–4 | Per-user, per-subscription; see subscription detail in `GET /api/v1/access/subscriptions` |
|
||||
|
||||
## Endpoint index
|
||||
|
||||
## Health
|
||||
Health check endpoints
|
||||
- `GET /health` — Health check
|
||||
|
||||
## Auth
|
||||
Wallet and user-session authentication endpoints
|
||||
- `POST /api/v1/auth/nonce` — Generate wallet auth nonce
|
||||
- `POST /api/v1/auth/wallet` — Authenticate with wallet signature
|
||||
- `POST /api/v1/auth/refresh` — Rotate a still-valid JWT (adds a new `jti`; revokes the old one) — PR #8
|
||||
- `POST /api/v1/auth/logout` — Revoke the current JWT by `jti` — PR #8
|
||||
- `POST /api/v1/auth/register` — Register an explorer access user
|
||||
- `POST /api/v1/auth/login` — Log in to the explorer access console
|
||||
|
||||
## Access
|
||||
RPC product catalog, subscriptions, and API key lifecycle
|
||||
- `GET /api/v1/access/me` — Get current access-console user
|
||||
- `GET /api/v1/access/products` — List available RPC access products (backed by `backend/config/rpc_products.yaml`, PR #7)
|
||||
- `GET /api/v1/access/subscriptions` — List subscriptions for the signed-in user
|
||||
- `GET /api/v1/access/admin/subscriptions` — List subscriptions for admin review
|
||||
- `POST /api/v1/access/admin/subscriptions` — Request or activate product access
|
||||
- `GET /api/v1/access/api-keys` — List API keys for the signed-in user
|
||||
- `POST /api/v1/access/api-keys` — Create an API key
|
||||
- `POST /api/v1/access/api-keys/{id}` — Revoke an API key
|
||||
- `DELETE /api/v1/access/api-keys/{id}` — Revoke an API key
|
||||
- `GET /api/v1/access/usage` — Get usage summary for the signed-in user
|
||||
- `GET /api/v1/access/audit` — Get recent API activity for the signed-in user
|
||||
- `GET /api/v1/access/admin/audit` — Get recent API activity across users for admin review
|
||||
- `GET /api/v1/access/internal/validate-key` — Validate an API key for nginx auth_request or similar edge subrequests
|
||||
- `POST /api/v1/access/internal/validate-key` — Validate an API key for internal edge enforcement
|
||||
|
||||
## Blocks
|
||||
Block-related endpoints
|
||||
- `GET /api/v1/blocks` — List blocks
|
||||
- `GET /api/v1/blocks/{chain_id}/{number}` — Get block by number
|
||||
|
||||
## Transactions
|
||||
Transaction-related endpoints
|
||||
- `GET /api/v1/transactions` — List transactions
|
||||
|
||||
## Search
|
||||
Unified search endpoints
|
||||
- `GET /api/v1/search` — Unified search
|
||||
|
||||
## Track1
|
||||
Public RPC gateway endpoints (no auth required)
|
||||
- `GET /api/v1/track1/blocks/latest` — Get latest blocks (Public)
|
||||
|
||||
## MissionControl
|
||||
Public mission-control health, bridge trace, and cached liquidity helpers
|
||||
- `GET /api/v1/mission-control/stream` — Mission-control SSE stream
|
||||
- `GET /api/v1/mission-control/liquidity/token/{address}/pools` — Cached liquidity proxy
|
||||
- `GET /api/v1/mission-control/bridge/trace` — Resolve a transaction through Blockscout and label 138-side contracts
|
||||
|
||||
## Track2
|
||||
Indexed explorer endpoints (auth required)
|
||||
- `GET /api/v1/track2/search` — Advanced search (Auth Required)
|
||||
|
||||
## Track4
|
||||
Operator endpoints (Track 4 + IP whitelist)
|
||||
- `POST /api/v1/track4/operator/run-script` — Run an allowlisted operator script
|
||||
|
||||
## Error shape
|
||||
|
||||
All errors use:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "short_code",
|
||||
"message": "human-readable explanation"
|
||||
}
|
||||
```
|
||||
|
||||
Common codes:
|
||||
|
||||
| HTTP | `error` | Meaning |
|
||||
|------|---------|---------|
|
||||
| 400 | `bad_request` | Malformed body or missing param |
|
||||
| 401 | `unauthorized` | Missing or invalid JWT |
|
||||
| 401 | `token_revoked` | JWT's `jti` is in `jwt_revocations` (PR #8) |
|
||||
| 403 | `forbidden` | Authenticated but below required track |
|
||||
| 404 | `not_found` | Record does not exist |
|
||||
| 405 | `method_not_allowed` | HTTP method not supported for route |
|
||||
| 429 | `rate_limited` | Over the track's per-window quota |
|
||||
| 503 | `service_unavailable` | Backend dep unavailable or migration missing |
|
||||
|
||||
## Generating client SDKs
|
||||
|
||||
The `swagger.yaml` file is standard OpenAPI 3.0.3; any generator works.
|
||||
|
||||
```bash
|
||||
# TypeScript fetch client
|
||||
npx openapi-typescript backend/api/rest/swagger.yaml -o frontend/src/api/types.ts
|
||||
|
||||
# Go client
|
||||
oapi-codegen -package explorerclient backend/api/rest/swagger.yaml > client.go
|
||||
```
|
||||
162
docs/ARCHITECTURE.md
Normal file
162
docs/ARCHITECTURE.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Architecture
|
||||
|
||||
## Overview
|
||||
|
||||
SolaceScan is a four-tier block explorer + access-control plane for
|
||||
Chain 138. Every request is classified into one of four **tracks**;
|
||||
higher tracks require stronger authentication and hit different
|
||||
internal subsystems.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
U[User / wallet / operator] -->|HTTPS| FE[Next.js frontend<br/>:3000]
|
||||
U -->|direct API<br/>or SDK| EDGE[Edge / nginx<br/>:443]
|
||||
FE --> EDGE
|
||||
EDGE --> API[Go REST API<br/>backend/api/rest :8080]
|
||||
|
||||
API --> PG[(Postgres +<br/>TimescaleDB)]
|
||||
API --> ES[(Elasticsearch)]
|
||||
API --> RD[(Redis)]
|
||||
API --> RPC[(Chain 138 RPC<br/>core / alltra / thirdweb)]
|
||||
|
||||
IDX[Indexer<br/>backend/indexer] --> PG
|
||||
IDX --> ES
|
||||
RPC --> IDX
|
||||
|
||||
subgraph Access layer
|
||||
EDGE -->|auth_request| VK[validate-key<br/>/api/v1/access/internal/validate-key]
|
||||
VK --> API
|
||||
end
|
||||
```
|
||||
|
||||
## Tracks
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Track1[Track 1 — public, no auth]
|
||||
T1A[/blocks]
|
||||
T1B[/transactions]
|
||||
T1C[/search]
|
||||
T1D[/api/v1/track1/*]
|
||||
end
|
||||
|
||||
subgraph Track2[Track 2 — wallet-verified]
|
||||
T2A[Subscriptions]
|
||||
T2B[API key lifecycle]
|
||||
T2C[Usage + audit self-view]
|
||||
end
|
||||
|
||||
subgraph Track3[Track 3 — analytics]
|
||||
T3A[Advanced analytics]
|
||||
T3B[Admin audit]
|
||||
T3C[Admin subscription review]
|
||||
end
|
||||
|
||||
subgraph Track4[Track 4 — operator]
|
||||
T4A[/api/v1/track4/operator/run-script]
|
||||
T4B[Mission-control SSE]
|
||||
T4C[Ops tooling]
|
||||
end
|
||||
|
||||
Track1 --> Track2 --> Track3 --> Track4
|
||||
```
|
||||
|
||||
Authentication for tracks 2–4 is SIWE-style: client hits
|
||||
`/api/v1/auth/nonce`, signs the nonce with its wallet, posts the
|
||||
signature to `/api/v1/auth/wallet`, gets a JWT back. JWTs carry the
|
||||
resolved `track` claim and a `jti` for server-side revocation (see
|
||||
`backend/auth/wallet_auth.go`).
|
||||
|
||||
### Per-track token TTLs
|
||||
|
||||
| Track | TTL | Rationale |
|
||||
|------|-----|-----------|
|
||||
| 1 | 12h | Public / long-lived session OK |
|
||||
| 2 | 8h | Business day |
|
||||
| 3 | 4h | Analytics session |
|
||||
| 4 | **60 min** | Operator tokens are the most dangerous; short TTL + `POST /api/v1/auth/refresh` |
|
||||
|
||||
Revocation lives in `jwt_revocations` (migration `0016`). Logging out
|
||||
(`POST /api/v1/auth/logout`) inserts the token's `jti` so subsequent
|
||||
validation rejects it.
|
||||
|
||||
## Sign-in flow (wallet)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor W as Wallet
|
||||
participant FE as Frontend
|
||||
participant API as REST API
|
||||
participant DB as Postgres
|
||||
|
||||
W->>FE: connect / sign-in
|
||||
FE->>API: POST /api/v1/auth/nonce {address}
|
||||
API->>DB: insert wallet_nonces(address, nonce, expires_at)
|
||||
API-->>FE: {nonce}
|
||||
FE->>W: signTypedData/personal_sign(nonce)
|
||||
W-->>FE: signature
|
||||
FE->>API: POST /api/v1/auth/wallet {address, nonce, signature}
|
||||
API->>API: ecrecover → verify address
|
||||
API->>DB: consume nonce; resolve user track
|
||||
API-->>FE: {token, expiresAt, track, permissions}
|
||||
FE-->>W: session active
|
||||
```
|
||||
|
||||
## Data flow (indexer ↔ API)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
RPC[(Chain 138 RPC)] -->|new blocks| IDX[Indexer]
|
||||
IDX -->|INSERT blocks, txs, logs| PG[(Postgres)]
|
||||
IDX -->|bulk index| ES[(Elasticsearch)]
|
||||
IDX -->|invalidate| RD[(Redis)]
|
||||
|
||||
API[REST API] -->|SELECT| PG
|
||||
API -->|search, facets| ES
|
||||
API -->|cached RPC proxy| RD
|
||||
API -->|passthrough for deep reads| RPC
|
||||
```
|
||||
|
||||
## Subsystems
|
||||
|
||||
- **`backend/api/rest`** — HTTP API. One package; every handler lives
|
||||
under `backend/api/rest/*.go`. AI endpoints were split into
|
||||
`ai.go` + `ai_context.go` + `ai_routes.go` + `ai_docs.go` +
|
||||
`ai_xai.go` + `ai_helpers.go` by PR #6 to keep file size
|
||||
manageable.
|
||||
- **`backend/auth`** — wallet auth (nonce issue, signature verify,
|
||||
JWT issuance / validation / revocation / refresh).
|
||||
- **`backend/indexer`** — Chain 138 block/tx/log indexer, writes
|
||||
Postgres + Elasticsearch, invalidates Redis.
|
||||
- **`backend/analytics`** — longer-running queries: token distribution,
|
||||
holder concentration, liquidity-pool aggregates.
|
||||
- **`backend/api/track4`** — operator-scoped endpoints
|
||||
(`run-script`, mission-control).
|
||||
- **`frontend`** — Next.js 14 pages-router app. Router decision
|
||||
(PR #9) is final: no `src/app/`.
|
||||
|
||||
## Runtime dependencies
|
||||
|
||||
| Service | Why |
|
||||
|---------|-----|
|
||||
| Postgres (+ TimescaleDB) | Chain data, users, subscriptions, `jwt_revocations` |
|
||||
| Elasticsearch | Full-text search, facets |
|
||||
| Redis | Response cache, rate-limit counters, SSE fan-out |
|
||||
| Chain 138 RPC | Upstream source of truth; three lanes — core / alltra / thirdweb — catalogued in `backend/config/rpc_products.yaml` |
|
||||
|
||||
## Deployment
|
||||
|
||||
See [deployment/README.md](../deployment/README.md) for compose and
|
||||
production deploy details. The `deployment/docker-compose.yml` file
|
||||
is the reference local stack and is what `make e2e-full` drives.
|
||||
|
||||
## Security posture
|
||||
|
||||
- `JWT_SECRET` and `CSP_HEADER` are **fail-fast** — a production
|
||||
binary refuses to start without them (PR #3).
|
||||
- Secrets never live in-repo; `.gitleaks.toml` blocks known-bad
|
||||
patterns at commit time.
|
||||
- Rotation checklist: [docs/SECURITY.md](SECURITY.md).
|
||||
- Track-4 token TTL capped at 60 min; every issued token is
|
||||
revocable by `jti`.
|
||||
@@ -224,7 +224,7 @@ User → chainlist.org → Search "DBIS" → Click "Add to MetaMask"
|
||||
|
||||
```
|
||||
User → MetaMask → Click "View on Explorer"
|
||||
→ MetaMask opens: https://explorer.d-bis.org/tx/{hash}
|
||||
→ MetaMask opens: https://explorer.d-bis.org/transactions/{hash}
|
||||
→ Blockscout displays transaction details
|
||||
→ Blockscout API provides the data
|
||||
```
|
||||
@@ -285,4 +285,3 @@ User → MetaMask → View Token Balance
|
||||
|
||||
**Last Updated**: 2025-12-24
|
||||
**Status**: Analysis Complete
|
||||
|
||||
|
||||
@@ -53,9 +53,11 @@ directly instead of relying on the older static script env contract below.
|
||||
|
||||
Historical static-script environment variables:
|
||||
|
||||
- `IP`: Production server IP (default: 192.168.11.140)
|
||||
- `DOMAIN`: Domain name (default: explorer.d-bis.org)
|
||||
- `PASSWORD`: SSH password (default: ***REDACTED-LEGACY-PW***)
|
||||
- `IP`: Production server IP (required; no default)
|
||||
- `DOMAIN`: Domain name (required; no default)
|
||||
- `SSH_PASSWORD`: SSH password (required; no default; previous
|
||||
hardcoded default has been removed — see
|
||||
[SECURITY.md](SECURITY.md))
|
||||
|
||||
These applied to the deprecated static deploy script and are no longer the
|
||||
recommended operator interface.
|
||||
|
||||
127
docs/SECURITY.md
Normal file
127
docs/SECURITY.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# Security policy and rotation checklist
|
||||
|
||||
This document describes how secrets flow through the SolaceScan explorer and
|
||||
the operator steps required to rotate credentials that were previously
|
||||
checked into this repository.
|
||||
|
||||
## Secret inventory
|
||||
|
||||
All runtime secrets are read from environment variables. Nothing sensitive
|
||||
is committed to the repo.
|
||||
|
||||
| Variable | Used by | Notes |
|
||||
|---|---|---|
|
||||
| `JWT_SECRET` | `backend/api/rest/server.go` | HS256 signing key. Must be ≥32 bytes. Required when `APP_ENV=production` or `GO_ENV=production`. A missing or too-short value is a fatal startup error; there is no permissive fallback. |
|
||||
| `CSP_HEADER` | `backend/api/rest/server.go` | Full Content-Security-Policy string. Required in production. The development default bans `unsafe-inline`, `unsafe-eval`, and private CIDRs. |
|
||||
| `DB_PASSWORD` | deployment scripts (`EXECUTE_DEPLOYMENT.sh`, `EXECUTE_NOW.sh`) and the API | Postgres password for the `explorer` role. |
|
||||
| `SSH_PASSWORD` | `scripts/analyze-besu-logs.sh`, `scripts/check-besu-config.sh`, `scripts/check-besu-logs-with-password.sh`, `scripts/check-failed-transaction-details.sh`, `scripts/enable-besu-debug-api.sh` | SSH password used to reach the Besu VMs. Scripts fail fast if unset. |
|
||||
| `NEW_PASSWORD` | `scripts/set-vmid-password.sh`, `scripts/set-vmid-password-correct.sh` | Password being set on a Proxmox VM. Fail-fast required. |
|
||||
| `CORS_ALLOWED_ORIGIN` | `backend/api/rest/server.go` | Optional. When set, restricts `Access-Control-Allow-Origin`. Defaults to `*` — do not rely on that in production. |
|
||||
| `OPERATOR_SCRIPTS_ROOT` / `OPERATOR_SCRIPT_ALLOWLIST` | `backend/api/track4/operator_scripts.go` | Required to enable the Track-4 run-script endpoint. |
|
||||
| `OPERATOR_SCRIPT_TIMEOUT_SEC` | as above | Optional cap (1–599 seconds). |
|
||||
|
||||
## Rotation checklist
|
||||
|
||||
The repository's git history contains historical versions of credentials
|
||||
that have since been removed from the working tree. Treat those credentials
|
||||
as compromised. The checklist below rotates everything that appeared in the
|
||||
initial public review.
|
||||
|
||||
> **This repository does not rotate credentials on its own. The checklist
|
||||
> below is the operator's responsibility.** Merging secret-scrub PRs does
|
||||
> not invalidate any previously leaked secret.
|
||||
|
||||
1. **Rotate the Postgres `explorer` role password.**
|
||||
- Generate a new random password (`openssl rand -base64 24`).
|
||||
- `ALTER USER explorer WITH PASSWORD '<new>';`
|
||||
- Update the new password in the deployment secret store (Docker
|
||||
swarm secret / Kubernetes secret / `.env.secrets` on the host).
|
||||
- Restart the API and indexer services so they pick up the new value.
|
||||
|
||||
2. **Rotate the Proxmox / Besu VM SSH password.**
|
||||
- `sudo passwd besu` (or equivalent) on each affected VM.
|
||||
- Or, preferred: disable password auth entirely and move to SSH keys
|
||||
(`PasswordAuthentication no` in `/etc/ssh/sshd_config`).
|
||||
|
||||
3. **Rotate `JWT_SECRET`.**
|
||||
- Generate 32+ bytes (`openssl rand -base64 48`).
|
||||
- Deploy the new value to every API replica simultaneously.
|
||||
- Note: rotating invalidates every outstanding wallet auth token. Plan
|
||||
for a short window where users will need to re-sign.
|
||||
- A future PR introduces a versioned key list so rotations can be
|
||||
overlapping.
|
||||
|
||||
4. **Rotate any API keys (e.g. xAI / OpenSea) referenced by
|
||||
`backend/api/rest/ai.go` and the frontend.** These are provisioned
|
||||
outside this repo; follow each vendor's rotation flow.
|
||||
|
||||
5. **Audit git history.**
|
||||
- Run `gitleaks detect --source . --redact` at HEAD.
|
||||
- Run `gitleaks detect --log-opts="--all"` over the full history.
|
||||
- Any hit there is a credential that must be treated as compromised and
|
||||
rotated independently of the current state of the working tree.
|
||||
- Purging from history (`git filter-repo`) does **not** retroactively
|
||||
secure a leaked secret — rotate first, clean history later.
|
||||
|
||||
## History-purge audit trail
|
||||
|
||||
Following the rotation checklist above, the legacy `L@ker$2010` /
|
||||
`L@kers2010` / `L@ker\$2010` password strings were purged from every
|
||||
branch and tag in this repository using `git filter-repo
|
||||
--replace-text` followed by a `--replace-message` pass for commit
|
||||
message text. The rewritten history was force-pushed with
|
||||
`git push --mirror --force`.
|
||||
|
||||
Verification post-rewrite:
|
||||
|
||||
```
|
||||
git log --all -p | grep -cE 'L@ker\$2010|L@kers2010|L@ker\\\$2010'
|
||||
0
|
||||
gitleaks detect --no-git --source . --config .gitleaks.toml
|
||||
0 legacy-password findings
|
||||
```
|
||||
|
||||
### Residual server-side state (not purgable from the client)
|
||||
|
||||
Gitea's `refs/pull/*/head` refs (the read-only mirror of each PR's
|
||||
original head commit) **cannot be force-updated over HTTPS** — the
|
||||
server's `update` hook declines them. After a history rewrite the
|
||||
following cleanup must be performed **on the Gitea host** by an
|
||||
administrator:
|
||||
|
||||
1. Run `gitea admin repo-sync-release-archive` and
|
||||
`gitea doctor --run all --fix` if available.
|
||||
2. Or manually, as the gitea user on the server:
|
||||
```bash
|
||||
cd /var/lib/gitea/data/gitea-repositories/d-bis/explorer-monorepo.git
|
||||
git for-each-ref --format='%(refname)' 'refs/pull/*/head' | \
|
||||
xargs -n1 git update-ref -d
|
||||
git gc --prune=now --aggressive
|
||||
```
|
||||
3. Restart Gitea.
|
||||
|
||||
Until this server-side cleanup is performed, the 13 `refs/pull/*/head`
|
||||
refs still pin the pre-rewrite commits containing the legacy
|
||||
password. This does not affect branches, the default clone, or
|
||||
`master` — but the old commits remain reachable by SHA through the
|
||||
Gitea web UI (e.g. on the merged PR's **Files Changed** tab).
|
||||
|
||||
### Re-introduction guard
|
||||
|
||||
The `.gitleaks.toml` rule `explorer-legacy-db-password-L@ker` was
|
||||
tightened from `L@kers?\$?2010` to `L@kers?\\?\$?2010` so it also
|
||||
catches the shell-escaped form that slipped past the original PR #3
|
||||
scrub (see commit `78e1ff5`). Future attempts to paste any variant of
|
||||
the legacy password — in source, shell scripts, or env files — will
|
||||
fail the `gitleaks` CI job wired in PR #5.
|
||||
|
||||
## Build-time / CI checks (wired in PR #5)
|
||||
|
||||
- `gitleaks` pre-commit + CI gate on every PR.
|
||||
- `govulncheck`, `staticcheck`, and `go vet -vet=all` on the backend.
|
||||
- `eslint` and `tsc --noEmit` on the frontend.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Do not open public issues for security reports. Email the maintainers
|
||||
listed in `CONTRIBUTING.md`.
|
||||
86
docs/TESTING.md
Normal file
86
docs/TESTING.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Testing
|
||||
|
||||
The explorer has four test tiers. Run them in order of fidelity when
|
||||
debugging a regression.
|
||||
|
||||
## 1. Unit / package tests
|
||||
|
||||
Fast. Run on every PR.
|
||||
|
||||
```bash
|
||||
# Backend
|
||||
cd backend && go test ./...
|
||||
|
||||
# Frontend
|
||||
cd frontend && npm test # lint + type-check
|
||||
cd frontend && npm run test:unit # vitest
|
||||
```
|
||||
|
||||
## 2. Static analysis
|
||||
|
||||
Blocking on CI since PR #5 (`chore(ci): align Go to 1.23.x, add
|
||||
staticcheck/govulncheck/gitleaks gates`).
|
||||
|
||||
```bash
|
||||
cd backend && staticcheck ./...
|
||||
cd backend && govulncheck ./...
|
||||
git diff master... | gitleaks protect --staged --config ../.gitleaks.toml
|
||||
```
|
||||
|
||||
## 3. Production-targeting Playwright
|
||||
|
||||
Runs against `https://explorer.d-bis.org` (or the URL in `EXPLORER_URL`)
|
||||
and only checks public routes. Useful as a production canary; wired
|
||||
into the `test-e2e` Make target.
|
||||
|
||||
```bash
|
||||
EXPLORER_URL=https://explorer.d-bis.org make test-e2e
|
||||
```
|
||||
|
||||
## 4. Full-stack Playwright (`make e2e-full`)
|
||||
|
||||
Spins up the entire stack locally — `postgres`, `elasticsearch`,
|
||||
`redis` via docker-compose, plus a local build of `backend/api/rest`
|
||||
and `frontend` — then runs the full-stack Playwright spec against it.
|
||||
|
||||
```bash
|
||||
make e2e-full
|
||||
```
|
||||
|
||||
What it does, in order:
|
||||
|
||||
1. `docker compose -p explorer-e2e up -d postgres elasticsearch redis`
|
||||
2. Wait for Postgres readiness.
|
||||
3. Run `go run database/migrations/migrate.go` to apply schema +
|
||||
seeds (including `0016_jwt_revocations` from PR #8).
|
||||
4. `go run ./backend/api/rest` on port `8080`.
|
||||
5. `npm ci && npm run build && npm run start` on port `3000`.
|
||||
6. `npx playwright test scripts/e2e-full-stack.spec.ts`.
|
||||
7. Tear everything down (unless `E2E_KEEP_STACK=1`).
|
||||
|
||||
Screenshots of every route are written to
|
||||
`test-results/screenshots/<route>.png`.
|
||||
|
||||
### Env vars
|
||||
|
||||
| Var | Default | Purpose |
|
||||
|-----|---------|---------|
|
||||
| `EXPLORER_URL` | `http://localhost:3000` | Frontend base URL for the spec |
|
||||
| `EXPLORER_API_URL` | `http://localhost:8080` | Backend base URL |
|
||||
| `JWT_SECRET` | generated per-run | Required by backend fail-fast check (PR #3) |
|
||||
| `CSP_HEADER` | dev-safe default | Same |
|
||||
| `E2E_KEEP_STACK` | `0` | If `1`, leave the stack up after the run |
|
||||
| `E2E_SKIP_DOCKER` | `0` | If `1`, assume docker services already running |
|
||||
| `E2E_SCREENSHOT_DIR` | `test-results/screenshots` | Where to write PNGs |
|
||||
|
||||
### CI integration
|
||||
|
||||
`.github/workflows/e2e-full.yml` runs `make e2e-full` on:
|
||||
|
||||
* **Manual** trigger (`workflow_dispatch`).
|
||||
* **PRs labelled `run-e2e-full`** — apply the label when a change
|
||||
warrants full-stack validation (migrations, auth, routing changes).
|
||||
* **Nightly** at 04:00 UTC.
|
||||
|
||||
Screenshots and the Playwright HTML report are uploaded as build
|
||||
artefacts.
|
||||
4
frontend/next-env.d.ts
vendored
4
frontend/next-env.d.ts
vendored
@@ -1,6 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
/// <reference types="next/navigation-types/compat/navigation" />
|
||||
/// <reference path="./.next/types/routes.d.ts" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
|
||||
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
const path = require('path')
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
output: 'standalone',
|
||||
outputFileTracingRoot: path.resolve(__dirname, '..', '..'),
|
||||
async redirects() {
|
||||
return [
|
||||
{
|
||||
source: '/tx/:hash',
|
||||
destination: '/transactions/:hash',
|
||||
permanent: true,
|
||||
},
|
||||
{
|
||||
source: '/more',
|
||||
destination: '/operations',
|
||||
|
||||
16155
frontend/package-lock.json
generated
16155
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,11 @@
|
||||
"name": "explorer-frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"packageManager": "pnpm@10.0.0",
|
||||
"packageManager": "npm@10.8.2",
|
||||
"engines": {
|
||||
"node": ">=20.0.0 <21.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "sh -c 'HOST=${HOST:-127.0.0.1}; PORT=${PORT:-3000}; next dev -H \"$HOST\" -p \"$PORT\"'",
|
||||
"build": "next build",
|
||||
@@ -10,7 +14,7 @@
|
||||
"smoke:routes": "node ./scripts/smoke-routes.mjs",
|
||||
"start": "PORT=${PORT:-3000} node ./scripts/start-standalone.mjs",
|
||||
"start:next": "next start",
|
||||
"lint": "next lint",
|
||||
"lint": "eslint src libs next.config.js --ext .js,.jsx,.ts,.tsx",
|
||||
"type-check": "tsc --noEmit -p tsconfig.check.json",
|
||||
"test": "npm run lint && npm run type-check",
|
||||
"test:unit": "vitest run"
|
||||
@@ -18,12 +22,12 @@
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.14.2",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"axios": "^1.6.2",
|
||||
"axios": "^1.15.2",
|
||||
"clsx": "^2.0.0",
|
||||
"date-fns": "^3.0.6",
|
||||
"js-sha3": "^0.9.3",
|
||||
"next": "^14.0.4",
|
||||
"postcss": "^8.4.32",
|
||||
"next": "^15.5.15",
|
||||
"postcss": "^8.5.10",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"tailwindcss": "^3.3.6",
|
||||
@@ -31,11 +35,16 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.10.5",
|
||||
"@types/prop-types": "^15.7.15",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-next": "^14.0.4",
|
||||
"eslint-config-next": "^15.5.15",
|
||||
"typescript": "^5.3.3",
|
||||
"vitest": "^1.6.1"
|
||||
"vitest": "^4.1.5"
|
||||
},
|
||||
"overrides": {
|
||||
"esbuild": "^0.28.0",
|
||||
"postcss": "^8.5.10"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Acknowledgments | SolaceScan</title>
|
||||
<meta name="description" content="Acknowledgments for the SolaceScan Chain 138 explorer.">
|
||||
<title>Acknowledgments | DBIS Explorer</title>
|
||||
<meta name="description" content="Acknowledgments for the DBIS Explorer Chain 138 explorer.">
|
||||
<style>
|
||||
body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: linear-gradient(180deg, #0f172a 0%, #111827 45%, #f8fafc 46%, #ffffff 100%); color: #0f172a; }
|
||||
.shell { max-width: 980px; margin: 0 auto; padding: 2rem 1rem 3rem; }
|
||||
@@ -19,7 +19,7 @@
|
||||
<body>
|
||||
<div class="shell">
|
||||
<div class="topbar">
|
||||
<div class="brand">SolaceScan Acknowledgments</div>
|
||||
<div class="brand">DBIS Explorer Acknowledgments</div>
|
||||
<a href="/">Back to explorer</a>
|
||||
</div>
|
||||
<div class="card">
|
||||
@@ -28,10 +28,10 @@
|
||||
<ul>
|
||||
<li><strong>Blockscout</strong> for explorer indexing and API compatibility.</li>
|
||||
<li><strong>MetaMask</strong> for wallet connectivity and Snap support.</li>
|
||||
<li><strong>Chainlink CCIP</strong> for bridge-related routing, transport, and companion operational surfaces where applicable.</li>
|
||||
<li><strong>Chainlink CCIP</strong> for bridge-related routing, cW public-network representations, and companion operational surfaces where applicable.</li>
|
||||
<li><strong>ethers.js</strong> for wallet and Ethereum interaction support.</li>
|
||||
<li><strong>Font Awesome</strong> for iconography.</li>
|
||||
<li><strong>Next.js</strong> and the frontend contributors supporting the DBIS / Defi Oracle explorer experience.</li>
|
||||
<li><strong>Next.js</strong> and the frontend contributors supporting the DBIS explorer experience.</li>
|
||||
</ul>
|
||||
<p class="muted">If we have missed a contributor or dependency, please let us know at <a href="mailto:support@d-bis.org">support@d-bis.org</a>.</p>
|
||||
</div>
|
||||
|
||||
@@ -206,7 +206,7 @@ flowchart TB
|
||||
|
||||
subgraph CCIP_L2["Other live CCIP EVM destinations"]
|
||||
L2CLU["OP 10 · Base 8453 · Arb 42161 · Polygon 137 · BSC 56 · Avax 43114 · Gnosis 100 · Celo 42220 · Cronos 25"]
|
||||
LEAF_L2["Leaf — per-chain native DEX · cW token transport · partial edge pools"]
|
||||
LEAF_L2["Leaf — per-chain native DEX · cW public-network representation · partial edge pools"]
|
||||
end
|
||||
|
||||
subgraph ALLTRA["ALL Mainnet 651940"]
|
||||
@@ -404,9 +404,9 @@ flowchart LR
|
||||
|
||||
<!-- 4 Cross-chain -->
|
||||
<div class="content" id="panel-4" role="tabpanel" aria-labelledby="tab-4" hidden>
|
||||
<p class="panel-desc">CCIP transport, Alltra round-trip, the dedicated c-to-cW mint corridors, and the orchestrated swap-bridge-swap target.</p>
|
||||
<p class="panel-desc">CCIP routing, Alltra round-trip, the dedicated c-to-cW mint corridors, and the orchestrated swap-bridge-swap target.</p>
|
||||
<div class="mermaid-wrap">
|
||||
<h3>CCIP — WETH primary transport</h3>
|
||||
<h3>CCIP — WETH primary routing lane</h3>
|
||||
<div class="mermaid">
|
||||
sequenceDiagram
|
||||
participant U as User or bot
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Documentation Redirect | SolaceScan</title>
|
||||
<meta name="description" content="Redirecting to the canonical SolaceScan documentation hub.">
|
||||
<title>Documentation Redirect | DBIS Explorer</title>
|
||||
<meta name="description" content="Redirecting to the canonical DBIS Explorer documentation hub.">
|
||||
<meta http-equiv="refresh" content="0; url=/docs">
|
||||
<link rel="canonical" href="https://blockscout.defi-oracle.io/docs">
|
||||
<style>
|
||||
@@ -23,7 +23,7 @@
|
||||
<body>
|
||||
<div class="shell">
|
||||
<div class="topbar">
|
||||
<div class="brand">SolaceScan Documentation</div>
|
||||
<div class="brand">DBIS Explorer Documentation</div>
|
||||
<a href="/">Back to explorer</a>
|
||||
</div>
|
||||
<div class="card">
|
||||
|
||||
@@ -1124,7 +1124,7 @@
|
||||
}
|
||||
|
||||
// Sign message
|
||||
const message = `Sign this message to authenticate with SolaceScan.\n\nNonce: ${nonceData.nonce}`;
|
||||
const message = `Sign this message to authenticate with DBIS Explorer.\n\nNonce: ${nonceData.nonce}`;
|
||||
const signer = provider.getSigner();
|
||||
const signature = await signer.signMessage(message);
|
||||
|
||||
@@ -4518,7 +4518,7 @@
|
||||
title: 'Tools',
|
||||
items: [
|
||||
{ title: 'Input Data Decoder', icon: 'fa-file-code', status: 'Live', badgeClass: 'badge-info', desc: 'Open transaction detail pages to decode calldata, logs, and contract interactions already exposed by the explorer.', action: 'showTransactionsList();', href: '/transactions' },
|
||||
{ title: 'Unit Converter', icon: 'fa-scale-balanced', status: 'Live', badgeClass: 'badge-success', desc: 'Convert wei, gwei, ether, and common Chain 138 stablecoin units with a quick in-page helper.', action: 'showUnitConverterModal();', href: '/operations' },
|
||||
{ title: 'Unit Converter', icon: 'fa-scale-balanced', status: 'Live', badgeClass: 'badge-success', desc: 'Convert wei, gwei, ether, and common Chain 138 6-decimal GRU units with a quick in-page helper.', action: 'showUnitConverterModal();', href: '/operations' },
|
||||
{ title: 'CSV Export', icon: 'fa-file-csv', status: 'Live', badgeClass: 'badge-success', desc: 'Export pool state and route inventory snapshots for operator review and downstream ingestion.', action: 'showPools(); updatePath(\'/pools\'); setTimeout(function(){ if (typeof exportPoolsCSV === \"function\") exportPoolsCSV(); }, 200);', href: '/pools' },
|
||||
{ title: 'Account Balance Checker', icon: 'fa-wallet', status: 'Live', badgeClass: 'badge-success', desc: 'Jump into indexed addresses to inspect balances, token inventory, internal transfers, and recent activity.', action: 'showAddresses();', href: '/addresses' }
|
||||
]
|
||||
@@ -4551,7 +4551,7 @@
|
||||
var html = '<div style="display:grid; grid-template-columns:minmax(240px, 0.9fr) repeat(3, minmax(220px, 1fr)); gap:1rem; align-items:start;">';
|
||||
html += '<div style="border:1px solid var(--border); border-radius:18px; padding:1.25rem; background:linear-gradient(180deg, rgba(59,130,246,0.08), rgba(15,23,42,0.02)); min-height:100%;">';
|
||||
html += '<div style="font-size:1.25rem; font-weight:800; margin-bottom:0.75rem;">Operations Hub</div>';
|
||||
html += '<div style="color:var(--text-light); line-height:1.7; margin-bottom:1rem;">Discover SolaceScan operational explorer tools in one place, grouped the way users expect from a polished specialist explorer.</div>';
|
||||
html += '<div style="color:var(--text-light); line-height:1.7; margin-bottom:1rem;">Discover DBIS Explorer operational tools in one place, grouped the way users expect from a polished specialist explorer.</div>';
|
||||
html += '<div style="display:grid; gap:0.75rem;">';
|
||||
html += '<div style="padding:0.85rem; border:1px solid var(--border); border-radius:14px; background:var(--muted-surface);"><div style="font-size:0.82rem; text-transform:uppercase; letter-spacing:0.08em; color:var(--text-light); margin-bottom:0.35rem;">Now live</div><div style="font-weight:700;">Route matrix, ingestion APIs, smart search, pool exports, and live Mainnet stable bridge discovery.</div></div>';
|
||||
html += '<div style="padding:0.85rem; border:1px solid var(--border); border-radius:14px; background:var(--muted-surface);"><div style="font-size:0.82rem; text-transform:uppercase; letter-spacing:0.08em; color:var(--text-light); margin-bottom:0.35rem;">Good entry points</div><div style="display:flex; flex-wrap:wrap; gap:0.5rem;">';
|
||||
@@ -4602,12 +4602,12 @@
|
||||
modal.innerHTML = '' +
|
||||
'<div style="width:min(560px, 100%); border-radius:18px; border:1px solid var(--border); background:var(--background); box-shadow:0 24px 90px rgba(0,0,0,0.35); overflow:hidden;">' +
|
||||
'<div style="display:flex; justify-content:space-between; align-items:center; padding:1rem 1.1rem; border-bottom:1px solid var(--border);">' +
|
||||
'<div><div style="font-size:1.1rem; font-weight:800;">Unit Converter</div><div style="color:var(--text-light); font-size:0.9rem; margin-top:0.2rem;">Wei, gwei, ether, and 6-decimal stablecoin units for Chain 138.</div></div>' +
|
||||
'<div><div style="font-size:1.1rem; font-weight:800;">Unit Converter</div><div style="color:var(--text-light); font-size:0.9rem; margin-top:0.2rem;">Wei, gwei, ether, and 6-decimal GRU units for Chain 138.</div></div>' +
|
||||
'<button type="button" class="btn btn-secondary" id="unitConverterCloseBtn"><i class="fas fa-times"></i></button>' +
|
||||
'</div>' +
|
||||
'<div style="padding:1rem 1.1rem; display:grid; gap:0.9rem;">' +
|
||||
'<label style="display:grid; gap:0.35rem;"><span style="font-weight:700;">Amount</span><input id="unitConverterAmount" type="number" min="0" step="any" placeholder="1.0" style="padding:0.8rem 0.9rem; border:1px solid var(--border); border-radius:12px; background:var(--light); color:var(--text);"></label>' +
|
||||
'<label style="display:grid; gap:0.35rem;"><span style="font-weight:700;">Unit</span><select id="unitConverterUnit" style="padding:0.8rem 0.9rem; border:1px solid var(--border); border-radius:12px; background:var(--light); color:var(--text);"><option value="ether">Ether / WETH</option><option value="gwei">Gwei</option><option value="wei">Wei</option><option value="stable">Stablecoin (6 decimals)</option></select></label>' +
|
||||
'<label style="display:grid; gap:0.35rem;"><span style="font-weight:700;">Unit</span><select id="unitConverterUnit" style="padding:0.8rem 0.9rem; border:1px solid var(--border); border-radius:12px; background:var(--light); color:var(--text);"><option value="ether">Ether / WETH</option><option value="gwei">Gwei</option><option value="wei">Wei</option><option value="stable">GRU token (6 decimals)</option></select></label>' +
|
||||
'<div id="unitConverterResults" style="display:grid; gap:0.55rem;"></div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
<meta http-equiv="Expires" content="0">
|
||||
<!-- CSP: unsafe-eval required by ethers.js v5 UMD from CDN (uses new Function for ABI). Our code avoids eval/string setTimeout. Can be removed when moving to ethers v6 build (no UMD eval). -->
|
||||
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:; connect-src 'self' https://blockscout.defi-oracle.io https://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org http://192.168.11.221:8545 ws://192.168.11.221:8546;">
|
||||
<title>SolaceScan | Chain 138 Explorer by DBIS</title>
|
||||
<meta name="description" content="SolaceScan - Chain 138 Explorer by DBIS. Public explorer surfaces for blocks, transactions, addresses, routes, wallet tools, and bridge monitoring.">
|
||||
<meta name="keywords" content="blockchain explorer, ChainID 138, DBIS, SolaceScan, bridge monitoring, wallet tools, blockchain, ethereum, blockscout">
|
||||
<meta name="author" content="SolaceScan">
|
||||
<meta name="application-name" content="SolaceScan">
|
||||
<title>DBIS Explorer | Chain 138 Explorer by DBIS</title>
|
||||
<meta name="description" content="DBIS Explorer - Chain 138 Explorer by DBIS. Public explorer surfaces for blocks, transactions, addresses, routes, wallet tools, and bridge monitoring.">
|
||||
<meta name="keywords" content="blockchain explorer, ChainID 138, DBIS, DBIS Explorer, bridge monitoring, wallet tools, blockchain, ethereum, blockscout">
|
||||
<meta name="author" content="DBIS Explorer">
|
||||
<meta name="application-name" content="DBIS Explorer">
|
||||
<meta name="theme-color" content="#667eea">
|
||||
<script>
|
||||
(function(){function t(){var e=document.getElementById('navLinks'),n=document.getElementById('navToggle'),r=document.getElementById('navToggleIcon');if(e&&n){var o=e.classList.toggle('nav-open');n.setAttribute('aria-expanded',o?'true':'false');if(r)r.className=o?'fas fa-times':'fas fa-bars';}}function c(){var e=document.getElementById('navLinks'),n=document.getElementById('navToggle'),r=document.getElementById('navToggleIcon');if(e)e.classList.remove('nav-open');if(n)n.setAttribute('aria-expanded','false');if(r)r.className='fas fa-bars';}window.toggleNavMenu=t;window.closeNavMenu=c;})();
|
||||
@@ -20,15 +20,15 @@
|
||||
<!-- Open Graph / Facebook -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="https://blockscout.defi-oracle.io/">
|
||||
<meta property="og:title" content="SolaceScan - Chain 138 Explorer by DBIS">
|
||||
<meta property="og:title" content="DBIS Explorer - Chain 138 Explorer by DBIS">
|
||||
<meta property="og:description" content="Comprehensive blockchain explorer for ChainID 138 with cross-chain bridge monitoring and WETH utilities.">
|
||||
<meta property="og:image" content="https://blockscout.defi-oracle.io/og-image.png">
|
||||
<meta property="og:site_name" content="SolaceScan">
|
||||
<meta property="og:site_name" content="DBIS Explorer">
|
||||
|
||||
<!-- Twitter -->
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:url" content="https://blockscout.defi-oracle.io/">
|
||||
<meta name="twitter:title" content="SolaceScan - Chain 138 Explorer by DBIS">
|
||||
<meta name="twitter:title" content="DBIS Explorer - Chain 138 Explorer by DBIS">
|
||||
<meta name="twitter:description" content="Comprehensive blockchain explorer for ChainID 138 with cross-chain bridge monitoring and WETH utilities.">
|
||||
<meta name="twitter:image" content="https://blockscout.defi-oracle.io/og-image.png">
|
||||
|
||||
@@ -1214,7 +1214,7 @@
|
||||
<a class="logo" href="/" aria-label="Go to explorer home" style="text-decoration:none; color:inherit;">
|
||||
<i class="fas fa-cube"></i>
|
||||
<div style="display: flex; flex-direction: column; gap: 0.25rem;">
|
||||
<span>SolaceScan</span>
|
||||
<span>DBIS Explorer</span>
|
||||
<span style="font-size: 0.75rem; font-weight: normal; opacity: 0.9;">Chain 138 Explorer by DBIS</span>
|
||||
</div>
|
||||
</a>
|
||||
@@ -1784,14 +1784,14 @@
|
||||
<div class="container">
|
||||
<div class="site-footer-grid">
|
||||
<div>
|
||||
<div style="font-size: 1.05rem; font-weight: 700; margin-bottom: 0.5rem;">SolaceScan</div>
|
||||
<div style="font-size: 1.05rem; font-weight: 700; margin-bottom: 0.5rem;">DBIS Explorer</div>
|
||||
<div class="site-footer-note">
|
||||
Built on Blockscout foundations for the DBIS / Defi Oracle Chain 138 explorer surface.
|
||||
Built on Blockscout foundations for the DBIS Chain 138 explorer surface.
|
||||
Explorer data, block indexing, and public chain visibility are powered by Blockscout,
|
||||
Chain 138 RPC, and the MetaMask Snap companion.
|
||||
</div>
|
||||
<div class="site-footer-note" style="margin-top: 0.8rem;">
|
||||
© 2026 DBIS / Defi Oracle. All rights reserved.
|
||||
© 2026 DBIS. All rights reserved.
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Privacy Policy | SolaceScan</title>
|
||||
<meta name="description" content="Privacy policy for the SolaceScan Chain 138 explorer operated by DBIS / Defi Oracle.">
|
||||
<title>Privacy Policy | DBIS Explorer</title>
|
||||
<meta name="description" content="Privacy policy for the DBIS Explorer Chain 138 explorer operated by DBIS.">
|
||||
<style>
|
||||
body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: linear-gradient(180deg, #0f172a 0%, #111827 45%, #f8fafc 46%, #ffffff 100%); color: #0f172a; }
|
||||
.shell { max-width: 980px; margin: 0 auto; padding: 2rem 1rem 3rem; }
|
||||
@@ -19,13 +19,13 @@
|
||||
<body>
|
||||
<div class="shell">
|
||||
<div class="topbar">
|
||||
<div class="brand">SolaceScan Privacy Policy</div>
|
||||
<div class="brand">DBIS Explorer Privacy Policy</div>
|
||||
<a href="/">Back to explorer</a>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h1 style="margin-top:0;">Privacy Policy</h1>
|
||||
<p class="muted">Last updated: 2026-03-25</p>
|
||||
<p>SolaceScan is the public Chain 138 explorer surface operated by DBIS / Defi Oracle. Most content you view comes from public blockchain data, explorer indexers, route services, and public configuration endpoints. We do not ask for personal information to browse the public explorer.</p>
|
||||
<p>DBIS Explorer is the public Chain 138 explorer surface operated by DBIS. Most content you view comes from public blockchain data, explorer indexers, route services, and public configuration endpoints. We do not ask for personal information to browse the public explorer.</p>
|
||||
<h2>What we store locally</h2>
|
||||
<ul>
|
||||
<li>We may store theme preference, locale, recent searches, and similar local UI settings in your browser.</li>
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Terms of Service | SolaceScan</title>
|
||||
<meta name="description" content="Terms of service for the SolaceScan Chain 138 explorer operated by DBIS / Defi Oracle.">
|
||||
<title>Terms of Service | DBIS Explorer</title>
|
||||
<meta name="description" content="Terms of service for the DBIS Explorer Chain 138 explorer operated by DBIS.">
|
||||
<style>
|
||||
body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: linear-gradient(180deg, #0f172a 0%, #111827 45%, #f8fafc 46%, #ffffff 100%); color: #0f172a; }
|
||||
.shell { max-width: 980px; margin: 0 auto; padding: 2rem 1rem 3rem; }
|
||||
@@ -19,13 +19,13 @@
|
||||
<body>
|
||||
<div class="shell">
|
||||
<div class="topbar">
|
||||
<div class="brand">SolaceScan Terms of Service</div>
|
||||
<div class="brand">DBIS Explorer Terms of Service</div>
|
||||
<a href="/">Back to explorer</a>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h1 style="margin-top:0;">Terms of Service</h1>
|
||||
<p class="muted">Last updated: 2026-03-25</p>
|
||||
<p>SolaceScan is provided for informational and operational purposes by DBIS / Defi Oracle. By using the public explorer, wallet tools, docs, and linked companion resources, you agree that:</p>
|
||||
<p>DBIS Explorer is provided for informational and operational purposes by DBIS. By using the public explorer, wallet tools, docs, and linked companion resources, you agree that:</p>
|
||||
<h2>Service scope</h2>
|
||||
<ul>
|
||||
<li>Blockchain data may be delayed, incomplete, or temporarily unavailable.</li>
|
||||
@@ -55,7 +55,7 @@
|
||||
<li>Bridge, route, liquidity, and operational surfaces are investigative and informational unless a page explicitly presents an authenticated management workflow.</li>
|
||||
</ul>
|
||||
<h2>Operator identity</h2>
|
||||
<p>SolaceScan is operated by DBIS / Defi Oracle. Public explorer access may appear under <code>blockscout.defi-oracle.io</code>, while companion resources may appear under <code>explorer.d-bis.org</code> and related DBIS domains.</p>
|
||||
<p>DBIS Explorer is operated by DBIS. Public explorer access may appear under <code>blockscout.defi-oracle.io</code>, while companion resources may appear under <code>explorer.d-bis.org</code> and related DBIS domains.</p>
|
||||
<h2>Support and notices</h2>
|
||||
<p>For service questions, operational issues, or policy notices, contact <a href="mailto:support@d-bis.org">support@d-bis.org</a>.</p>
|
||||
<h2>Disputes and interpretation</h2>
|
||||
|
||||
@@ -4,7 +4,7 @@ const baseUrl = (process.env.BASE_URL || 'https://explorer.d-bis.org').replace(/
|
||||
const addressUnderTest = process.env.SMOKE_ADDRESS || '0x99b3511a2d315a497c8112c1fdd8d508d4b1e506'
|
||||
|
||||
const checks = [
|
||||
{ path: '/', expectTexts: ['SolaceScan', 'Recent Blocks', 'Open wallet tools'] },
|
||||
{ path: '/', expectTexts: ['DBIS Explorer', 'Recent Blocks', 'Open wallet tools'] },
|
||||
{ path: '/blocks', expectTexts: ['Blocks'] },
|
||||
{ path: '/transactions', expectTexts: ['Transactions'] },
|
||||
{ path: '/addresses', expectTexts: ['Addresses', 'Open An Address'] },
|
||||
|
||||
@@ -7,7 +7,20 @@ import process from 'node:process'
|
||||
const projectRoot = process.cwd()
|
||||
const standaloneRoot = path.join(projectRoot, '.next', 'standalone')
|
||||
const standaloneNextRoot = path.join(standaloneRoot, '.next')
|
||||
const standaloneServer = path.join(standaloneRoot, 'server.js')
|
||||
|
||||
function resolveStandaloneServer() {
|
||||
const directServer = path.join(standaloneRoot, 'server.js')
|
||||
if (existsSync(directServer)) {
|
||||
return { serverPath: directServer, appRoot: standaloneRoot }
|
||||
}
|
||||
|
||||
const nestedServer = path.join(standaloneRoot, 'explorer-monorepo', 'frontend', 'server.js')
|
||||
if (existsSync(nestedServer)) {
|
||||
return { serverPath: nestedServer, appRoot: path.dirname(nestedServer) }
|
||||
}
|
||||
|
||||
return { serverPath: directServer, appRoot: standaloneRoot }
|
||||
}
|
||||
|
||||
async function copyIfPresent(sourcePath, destinationPath) {
|
||||
if (!existsSync(sourcePath)) {
|
||||
@@ -19,15 +32,16 @@ async function copyIfPresent(sourcePath, destinationPath) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!existsSync(standaloneServer)) {
|
||||
const { serverPath, appRoot } = resolveStandaloneServer()
|
||||
if (!existsSync(serverPath)) {
|
||||
console.error('Standalone server build is missing. Run `npm run build` first.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
await copyIfPresent(path.join(projectRoot, '.next', 'static'), path.join(standaloneNextRoot, 'static'))
|
||||
await copyIfPresent(path.join(projectRoot, 'public'), path.join(standaloneRoot, 'public'))
|
||||
await copyIfPresent(path.join(projectRoot, 'public'), path.join(appRoot, 'public'))
|
||||
|
||||
const child = spawn(process.execPath, [standaloneServer], {
|
||||
const child = spawn(process.execPath, [serverPath], {
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ export default function BrandLockup({ compact = false }: { compact?: boolean })
|
||||
compact ? 'text-[1.45rem]' : 'text-[1.65rem]',
|
||||
].join(' ')}
|
||||
>
|
||||
SolaceScan
|
||||
DBIS Explorer
|
||||
</span>
|
||||
<span
|
||||
className={[
|
||||
|
||||
@@ -15,18 +15,29 @@ function toneClasses(tone: 'neutral' | 'success' | 'warning' | 'info') {
|
||||
|
||||
export function getEntityBadgeTone(tag: string): 'neutral' | 'success' | 'warning' | 'info' {
|
||||
const normalized = tag.toLowerCase()
|
||||
if (normalized === 'compliant' || normalized === 'listed' || normalized === 'verified') {
|
||||
if (normalized === 'compliant' || normalized === 'listed' || normalized === 'verified' || normalized === 'gru') {
|
||||
return 'success'
|
||||
}
|
||||
if (normalized === 'wrapped') {
|
||||
if (normalized === 'wrapped' || normalized === 'treasury-bond') {
|
||||
return 'warning'
|
||||
}
|
||||
if (normalized === 'bridge' || normalized === 'canonical' || normalized === 'official') {
|
||||
if (normalized === 'bridge' || normalized === 'canonical' || normalized === 'official' || normalized === 'electronic-money' || normalized === 'commodity') {
|
||||
return 'info'
|
||||
}
|
||||
return 'neutral'
|
||||
}
|
||||
|
||||
export function formatEntityBadgeLabel(label: string): string {
|
||||
const normalized = label.toLowerCase()
|
||||
const labels: Record<string, string> = {
|
||||
'reference-asset': 'reference asset',
|
||||
'electronic-money': 'cash e-money',
|
||||
'treasury-bond': 'treasury / gov bond',
|
||||
gru: 'GRU',
|
||||
}
|
||||
return labels[normalized] || label
|
||||
}
|
||||
|
||||
export default function EntityBadge({
|
||||
label,
|
||||
tone,
|
||||
@@ -46,7 +57,7 @@ export default function EntityBadge({
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
{formatEntityBadgeLabel(label)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ export default function ExplorerAgentTool() {
|
||||
{
|
||||
role: 'assistant',
|
||||
content:
|
||||
'Explorer AI Agent Tool is ready. I can explain this page, summarize what you are looking at, and help investigate transactions, contracts, routes, and system surfaces.',
|
||||
'DBIS Explorer AI Assist is ready. I can explain this page, summarize what you are looking at, and help investigate transactions, contracts, routes, and system surfaces.',
|
||||
},
|
||||
])
|
||||
|
||||
@@ -96,7 +96,7 @@ export default function ExplorerAgentTool() {
|
||||
<section className="w-[min(24rem,calc(100vw-1.5rem))] overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl dark:border-gray-700 dark:bg-gray-900">
|
||||
<div className="flex items-start justify-between gap-3 border-b border-gray-200 px-4 py-3 dark:border-gray-700">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-gray-900 dark:text-white">Explorer AI Agent Tool</h2>
|
||||
<h2 className="text-sm font-semibold text-gray-900 dark:text-white">DBIS Explorer AI Assist</h2>
|
||||
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
Page-aware guidance for the explorer. Helpful, read-only, and designed for quick investigation.
|
||||
</p>
|
||||
@@ -163,15 +163,16 @@ export default function ExplorerAgentTool() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
className="inline-flex items-center gap-2 rounded-full bg-primary-600 px-4 py-3 text-sm font-semibold text-white shadow-lg transition hover:bg-primary-700"
|
||||
className="inline-flex items-center gap-2 rounded-full bg-primary-600 p-3 text-sm font-semibold text-white shadow-lg transition hover:bg-primary-700 lg:px-4 lg:py-3"
|
||||
aria-expanded={open}
|
||||
aria-label="Open DBIS Explorer AI Assist"
|
||||
>
|
||||
<span className="inline-flex h-7 w-7 items-center justify-center rounded-full bg-white/15">
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-4l-4 4v-4Z" />
|
||||
</svg>
|
||||
</span>
|
||||
Agent Tool
|
||||
<span className="hidden lg:inline">AI Assist</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -12,18 +12,18 @@ export default function Footer() {
|
||||
<div className="grid gap-4 sm:gap-6 md:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<div className="space-y-3 rounded-xl border border-gray-200 bg-gray-50/80 p-4 dark:border-gray-800 dark:bg-gray-900/40 md:border-0 md:bg-transparent md:p-0">
|
||||
<div className="text-base font-semibold text-gray-900 dark:text-white sm:text-lg">
|
||||
SolaceScan
|
||||
DBIS Explorer
|
||||
</div>
|
||||
<p className="max-w-xl text-sm leading-6 text-gray-600 dark:text-gray-400">
|
||||
Built on Blockscout for the DBIS / Defi Oracle Chain 138 explorer surface.
|
||||
Built on Blockscout for the DBIS Chain 138 explorer surface.
|
||||
Explorer data is powered by Blockscout, Chain 138 RPC, and the companion MetaMask Snap.
|
||||
</p>
|
||||
<p className="max-w-xl text-xs leading-5 text-gray-500 dark:text-gray-500">
|
||||
Public explorer access may appear under <code>blockscout.defi-oracle.io</code> or <code>explorer.d-bis.org</code>.
|
||||
Both domains belong to the same DBIS / Defi Oracle explorer surface.
|
||||
Primary public explorer access is served at <code>explorer.d-bis.org</code>.
|
||||
<code> blockscout.defi-oracle.io</code> is the Blockscout companion domain for the same Chain 138 explorer surface.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||
© {year} DBIS / Defi Oracle. All rights reserved.
|
||||
© {year} DBIS. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -12,11 +12,26 @@ const STANDARD_EXPLANATIONS: Record<string, string> = {
|
||||
'ERC-2612': 'Permit support for signature-based approvals without a separate on-chain approve transaction.',
|
||||
'ERC-3009': 'Authorization-based transfer model for signed payment flows without prior allowances.',
|
||||
'ERC-5267': 'Discoverable EIP-712 domain introspection so wallets and relayers can inspect the signing domain cleanly.',
|
||||
IeMoneyToken: 'Repo-native eMoney token methodology for issuance and redemption semantics.',
|
||||
CashElectronicMoneyInterface: 'Repo-native GRU instrument methodology for issuance and redemption semantics.',
|
||||
DeterministicStorageNamespace: 'Stable namespace for upgrade-aware policy, registry, and audit resolution.',
|
||||
JurisdictionAndSupervisionMetadata: 'Governance, supervisory, disclosure, and reporting metadata required by the GRU operating model.',
|
||||
}
|
||||
|
||||
const STANDARD_DISPLAY_LABELS: Record<string, string> = {
|
||||
CashElectronicMoneyInterface: 'Cash electronic-money interface',
|
||||
DeterministicStorageNamespace: 'Deterministic storage namespace',
|
||||
JurisdictionAndSupervisionMetadata: 'Jurisdiction and supervision metadata',
|
||||
}
|
||||
|
||||
function formatStandardLabel(id: string): string {
|
||||
return STANDARD_DISPLAY_LABELS[id] || id
|
||||
}
|
||||
|
||||
function formatProfileLabel(id: string): string {
|
||||
if (id === 'gru-c-star-v2-public-network-and-payment') return 'GRU C* v2 payment profile'
|
||||
return id
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number | null): string | null {
|
||||
if (seconds == null || !Number.isFinite(seconds) || seconds <= 0) return null
|
||||
const units = [
|
||||
@@ -56,16 +71,16 @@ export default function GruStandardsCard({
|
||||
? `Review the live contract ABI and deployment against the GRU v2 base-token matrix before treating this asset as fully canonical.`
|
||||
: `The live contract exposes the full required GRU v2 base-token surface currently checked by the explorer.`,
|
||||
profile.wrappedTransport
|
||||
? 'This looks like a wrapped transport asset, so confirm the corresponding bridge lane and reserve-verifier posture in addition to the token ABI.'
|
||||
: 'This looks like a canonical GRU asset, so the next meaningful checks are reserve, governance, and transport activation beyond the token interface itself.',
|
||||
? 'This looks like a cW public-network representation, so confirm the corresponding bridge lane and reserve-verifier posture in addition to the token ABI.'
|
||||
: 'This looks like a canonical GRU asset, so the next meaningful checks are reserve, governance, and bridge activation beyond the token interface itself.',
|
||||
profile.x402Ready
|
||||
? 'This contract appears ready for x402-style payment flows because the explorer can see the required signature and domain surfaces.'
|
||||
: 'This contract does not currently look x402-ready from the live explorer surface; verify EIP-712, ERC-5267, and permit or authorization flow exposure before using it as a payment rail.',
|
||||
profile.forwardCanonical === true
|
||||
? 'This version is marked forward-canonical, so it should be treated as the preferred successor surface even if older liquidity or transport versions still coexist.'
|
||||
? 'This version is marked forward-canonical, so it should be treated as the preferred successor surface even if older liquidity or bridge versions still coexist.'
|
||||
: profile.forwardCanonical === false
|
||||
? 'This version is not forward-canonical, which usually means it is legacy, staged, or transport-only relative to the intended primary canonical surface.'
|
||||
: 'Forward-canonical posture is not directly detectable on this contract, so rely on the transport overlay and deployment records before making promotion assumptions.',
|
||||
? 'This version is not forward-canonical, which usually means it is legacy, staged, or bridge-only relative to the intended primary canonical surface.'
|
||||
: 'Forward-canonical posture is not directly detectable on this contract, so rely on the bridge overlay and deployment records before making promotion assumptions.',
|
||||
profile.legacyAliasSupport
|
||||
? 'Legacy alias support is exposed, which is useful during version cutovers and explorer/search reconciliation.'
|
||||
: 'Legacy alias support is not visible from the current explorer contract surface, so name/version migration may need registry or deployment-record cross-checks.',
|
||||
@@ -78,9 +93,9 @@ export default function GruStandardsCard({
|
||||
<DetailRow label="Profile">
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<EntityBadge label={profile.profileId} tone="info" className="normal-case tracking-normal" />
|
||||
<EntityBadge label={formatProfileLabel(profile.profileId)} tone="info" className="normal-case tracking-normal" />
|
||||
<EntityBadge
|
||||
label={profile.wrappedTransport ? 'wrapped transport' : 'canonical GRU'}
|
||||
label={profile.wrappedTransport ? 'cW public-network' : 'canonical GRU'}
|
||||
tone={profile.wrappedTransport ? 'warning' : 'success'}
|
||||
/>
|
||||
</div>
|
||||
@@ -94,14 +109,14 @@ export default function GruStandardsCard({
|
||||
{profile.standards.map((standard) => (
|
||||
<EntityBadge
|
||||
key={standard.id}
|
||||
label={standard.detected ? `${standard.id} detected` : `${standard.id} missing`}
|
||||
label={standard.detected ? `${formatStandardLabel(standard.id)} detected` : `${formatStandardLabel(standard.id)} missing`}
|
||||
tone={standard.detected ? 'success' : 'warning'}
|
||||
className="normal-case tracking-normal"
|
||||
/>
|
||||
))}
|
||||
</DetailRow>
|
||||
|
||||
<DetailRow label="Transport Posture">
|
||||
<DetailRow label="Bridge Posture">
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<EntityBadge
|
||||
@@ -134,8 +149,8 @@ export default function GruStandardsCard({
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Settlement posture</div>
|
||||
<div className="mt-2 text-gray-900 dark:text-white">
|
||||
{profile.wrappedTransport
|
||||
? 'This contract presents itself like a wrapped public-transport asset instead of the canonical Chain 138 money surface.'
|
||||
: 'This contract presents itself like the canonical Chain 138 GRU money surface instead of a wrapped transport mirror.'}
|
||||
? 'This contract presents itself like a cW public-network representation instead of the canonical Chain 138 GRU surface.'
|
||||
: 'This contract presents itself like the canonical Chain 138 GRU surface instead of a cW public-network representation.'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-gray-200 bg-gray-50 p-3 text-sm dark:border-gray-700 dark:bg-gray-900/40">
|
||||
@@ -150,7 +165,7 @@ export default function GruStandardsCard({
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Version posture</div>
|
||||
<div className="mt-2 text-gray-900 dark:text-white">
|
||||
{profile.activeVersion || profile.forwardVersion
|
||||
? `Active liquidity/transport version: ${profile.activeVersion || 'unknown'}; preferred forward version: ${profile.forwardVersion || 'unknown'}.`
|
||||
? `Active liquidity/bridge version: ${profile.activeVersion || 'unknown'}; preferred forward version: ${profile.forwardVersion || 'unknown'}.`
|
||||
: 'No explicit active-versus-forward version posture is available from the local GRU catalog yet.'}
|
||||
</div>
|
||||
</div>
|
||||
@@ -163,7 +178,7 @@ export default function GruStandardsCard({
|
||||
{profile.standards.map((standard) => (
|
||||
<div key={`${standard.id}-explanation`} className="rounded-xl border border-gray-200 bg-gray-50 p-3 text-sm dark:border-gray-700 dark:bg-gray-900/40">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="font-medium text-gray-900 dark:text-white">{standard.id}</div>
|
||||
<div className="font-medium text-gray-900 dark:text-white">{formatStandardLabel(standard.id)}</div>
|
||||
<EntityBadge label={standard.detected ? 'detected' : 'missing'} tone={standard.detected ? 'success' : 'warning'} />
|
||||
</div>
|
||||
<div className="mt-2 text-gray-600 dark:text-gray-400">
|
||||
@@ -190,12 +205,12 @@ export default function GruStandardsCard({
|
||||
<DetailRow label="References">
|
||||
<div className="space-y-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
<div><Link href="/docs/gru" className="text-primary-600 hover:underline">Explorer GRU guide</Link></div>
|
||||
<div>Canonical profile: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">{profile.profileId}</code></div>
|
||||
<div>Repo standards matrix: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">docs/04-configuration/GRU_C_STAR_V2_STANDARDS_MATRIX_AND_IMPLEMENTATION_PLAN.md</code></div>
|
||||
<div>Machine-readable profile: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">config/gru-standards-profile.json</code></div>
|
||||
<div>Transport overlay: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">config/gru-transport-active.json</code></div>
|
||||
<div>x402 support note: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">docs/04-configuration/CHAIN138_X402_TOKEN_SUPPORT.md</code></div>
|
||||
<div>Chain 138 readiness guide: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">docs/04-configuration/GRU_V2_CHAIN138_READINESS.md</code></div>
|
||||
<div>Canonical profile: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">{formatProfileLabel(profile.profileId)}</code></div>
|
||||
<div>Standards matrix: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">GRU C* v2 implementation plan</code></div>
|
||||
<div>Machine-readable profile: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">GRU standards profile</code></div>
|
||||
<div>Public-network overlay: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">GRU cW representation registry</code></div>
|
||||
<div>x402 support note: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">Chain 138 x402 token support</code></div>
|
||||
<div>Chain 138 readiness guide: <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs dark:bg-gray-800">GRU v2 Chain 138 readiness</code></div>
|
||||
</div>
|
||||
</DetailRow>
|
||||
|
||||
|
||||
37
frontend/src/components/common/MarketEvidenceNote.tsx
Normal file
37
frontend/src/components/common/MarketEvidenceNote.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { formatRelativeAge, formatTimestamp } from '@/utils/format'
|
||||
|
||||
function formatSource(source?: string | null): string {
|
||||
switch (source) {
|
||||
case 'token-aggregation':
|
||||
return 'token aggregation API'
|
||||
case 'blockscout':
|
||||
return 'Blockscout index'
|
||||
case 'derived':
|
||||
return 'derived from indexed supply and price inputs'
|
||||
case 'mission-control':
|
||||
return 'mission-control liquidity inventory'
|
||||
default:
|
||||
return source || 'source unavailable'
|
||||
}
|
||||
}
|
||||
|
||||
export default function MarketEvidenceNote({
|
||||
source = 'token-aggregation',
|
||||
lastUpdated,
|
||||
method = 'DEX route and pool aggregation; visible liquidity only where indexed.',
|
||||
compact = false,
|
||||
}: {
|
||||
source?: string | null
|
||||
lastUpdated?: string | null
|
||||
method?: string
|
||||
compact?: boolean
|
||||
}) {
|
||||
const freshness = lastUpdated ? `${formatRelativeAge(lastUpdated)} (${formatTimestamp(lastUpdated)})` : 'timestamp unavailable'
|
||||
const text = `Source: ${formatSource(source)}. Updated: ${freshness}. Method: ${method}`
|
||||
|
||||
return (
|
||||
<p className={`${compact ? 'mt-1' : 'mt-3'} text-xs leading-5 text-gray-500 dark:text-gray-400`}>
|
||||
{text}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -704,7 +704,7 @@ export default function Navbar() {
|
||||
href="/"
|
||||
className="group inline-flex min-w-0 items-center gap-3 rounded-2xl py-2 pr-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-gray-950"
|
||||
onClick={() => setMobileMenuOpen(false)}
|
||||
aria-label="Go to SolaceScan home"
|
||||
aria-label="Go to DBIS Explorer home"
|
||||
>
|
||||
<BrandLockup />
|
||||
</Link>
|
||||
|
||||
357
frontend/src/components/explorer/ContractCodeWorkspace.tsx
Normal file
357
frontend/src/components/explorer/ContractCodeWorkspace.tsx
Normal file
@@ -0,0 +1,357 @@
|
||||
'use client'
|
||||
|
||||
import { FormEvent, useMemo, useState } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { Card } from '@/libs/frontend-ui-primitives'
|
||||
import EntityBadge from '@/components/common/EntityBadge'
|
||||
import { getExplorerApiBase } from '@/services/api/blockscout'
|
||||
import type { ContractProfile, ContractSourceFile } from '@/services/api/contracts'
|
||||
|
||||
interface ContractCodeWorkspaceProps {
|
||||
address: string
|
||||
profile: ContractProfile
|
||||
}
|
||||
|
||||
interface OutlineEntry {
|
||||
type: 'contract' | 'interface' | 'library' | 'function' | 'event' | 'error'
|
||||
name: string
|
||||
line: number
|
||||
}
|
||||
|
||||
const QUICK_PROMPTS = [
|
||||
'What does this contract do?',
|
||||
'What are the functions available in this contract?',
|
||||
'Which functions can change state or move funds?',
|
||||
'Who has special permissions or control in this contract?',
|
||||
'What are potential risks or red flags in this contract?',
|
||||
] as const
|
||||
|
||||
function makeFallbackSourceFile(profile: ContractProfile): ContractSourceFile | null {
|
||||
if (!profile.source_code_preview && !profile.abi_full && !profile.abi) return null
|
||||
return {
|
||||
path: profile.contract_name ? `${profile.contract_name}.sol` : 'Contract.sol',
|
||||
content: profile.source_code_full || profile.source_code_preview || profile.abi_full || profile.abi || '',
|
||||
}
|
||||
}
|
||||
|
||||
function parseOutline(content: string): OutlineEntry[] {
|
||||
const entries: OutlineEntry[] = []
|
||||
content.split('\n').forEach((line, index) => {
|
||||
const lineNumber = index + 1
|
||||
const typeMatch = line.match(/^\s*(?:abstract\s+)?(contract|interface|library)\s+([A-Za-z_][A-Za-z0-9_]*)/)
|
||||
if (typeMatch) {
|
||||
entries.push({
|
||||
type: typeMatch[1] as OutlineEntry['type'],
|
||||
name: typeMatch[2],
|
||||
line: lineNumber,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const memberMatch = line.match(/^\s*(function|event|error)\s+([A-Za-z_][A-Za-z0-9_]*)/)
|
||||
if (memberMatch) {
|
||||
entries.push({
|
||||
type: memberMatch[1] as OutlineEntry['type'],
|
||||
name: memberMatch[2],
|
||||
line: lineNumber,
|
||||
})
|
||||
}
|
||||
})
|
||||
return entries
|
||||
}
|
||||
|
||||
function sourceExcerptForPrompt(files: ContractSourceFile[]): string {
|
||||
return files
|
||||
.slice(0, 4)
|
||||
.map((file) => `File: ${file.path}\n${file.content.slice(0, 2600)}`)
|
||||
.join('\n\n')
|
||||
.slice(0, 5200)
|
||||
}
|
||||
|
||||
export default function ContractCodeWorkspace({ address, profile }: ContractCodeWorkspaceProps) {
|
||||
const files = useMemo(() => {
|
||||
const normalized = profile.source_files?.length ? profile.source_files : []
|
||||
const fallback = makeFallbackSourceFile(profile)
|
||||
return normalized.length > 0 ? normalized : fallback ? [fallback] : []
|
||||
}, [profile])
|
||||
|
||||
const [activeTab, setActiveTab] = useState<'source' | 'reader'>('source')
|
||||
const [activePath, setActivePath] = useState(files[0]?.path || '')
|
||||
const [prompt, setPrompt] = useState('What does this contract do?')
|
||||
const [model, setModel] = useState('Explorer AI')
|
||||
const [saveHistory, setSaveHistory] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [readerAnswer, setReaderAnswer] = useState('')
|
||||
const [readerError, setReaderError] = useState('')
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
|
||||
const activeFile = files.find((file) => file.path === activePath) || files[0]
|
||||
const outline = useMemo(() => parseOutline(activeFile?.content || ''), [activeFile?.content])
|
||||
const sourceLines = useMemo(() => (activeFile?.content || '').split('\n'), [activeFile?.content])
|
||||
|
||||
const selectedFiles = files
|
||||
const sourceAvailable = files.length > 0 && Boolean(activeFile?.content)
|
||||
|
||||
const handleCopySource = async () => {
|
||||
if (!activeFile?.content || typeof navigator === 'undefined') return
|
||||
await navigator.clipboard?.writeText(activeFile.content)
|
||||
}
|
||||
|
||||
const handleCopyLink = async () => {
|
||||
if (typeof navigator === 'undefined' || typeof window === 'undefined') return
|
||||
await navigator.clipboard?.writeText(`${window.location.href.split('#')[0]}#contract-source`)
|
||||
}
|
||||
|
||||
const askReader = async (question: string) => {
|
||||
const trimmed = question.trim()
|
||||
if (!trimmed || submitting) return
|
||||
setPrompt(trimmed)
|
||||
setReaderError('')
|
||||
setReaderAnswer('')
|
||||
setSubmitting(true)
|
||||
|
||||
try {
|
||||
const context = [
|
||||
`Contract address: ${address}`,
|
||||
profile.contract_name ? `Contract name: ${profile.contract_name}` : '',
|
||||
profile.compiler_version ? `Compiler: ${profile.compiler_version}` : '',
|
||||
profile.license_type ? `License: ${profile.license_type}` : '',
|
||||
profile.proxy_type ? `Proxy type: ${profile.proxy_type}` : '',
|
||||
`Read methods: ${profile.read_methods.map((method) => method.signature).slice(0, 24).join(', ') || 'none reported'}`,
|
||||
`Write methods: ${profile.write_methods.map((method) => method.signature).slice(0, 24).join(', ') || 'none reported'}`,
|
||||
sourceAvailable ? `Verified source excerpts:\n${sourceExcerptForPrompt(selectedFiles)}` : 'Verified source text is not available.',
|
||||
].filter(Boolean).join('\n')
|
||||
|
||||
const response = await fetch(`${getExplorerApiBase()}/api/v1/ai/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: `${trimmed}\n\nUse this contract context and answer concisely. Do not invent behavior that is not supported by the ABI or source.\n\n${context}`,
|
||||
},
|
||||
],
|
||||
pageContext: {
|
||||
path: `/addresses/${address}`,
|
||||
view: 'contract-code-reader',
|
||||
address,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
const payload = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
throw new Error(payload?.error?.message || `AI reader returned HTTP ${response.status}`)
|
||||
}
|
||||
setReaderAnswer(String(payload?.reply || payload?.message?.content || 'No answer returned.'))
|
||||
} catch (error) {
|
||||
setReaderError(error instanceof Error ? error.message : 'Code Reader is temporarily unavailable.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
await askReader(prompt)
|
||||
}
|
||||
|
||||
if (!sourceAvailable && !profile.abi_available) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mb-6" title="Contract Source Code">
|
||||
<section id="contract-source" className="space-y-4">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActiveTab('source')}
|
||||
className={clsx(
|
||||
'rounded-lg px-3 py-2 text-sm font-semibold transition',
|
||||
activeTab === 'source'
|
||||
? 'bg-primary-600 text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-700',
|
||||
)}
|
||||
>
|
||||
Source
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActiveTab('reader')}
|
||||
className={clsx(
|
||||
'rounded-lg px-3 py-2 text-sm font-semibold transition',
|
||||
activeTab === 'reader'
|
||||
? 'bg-primary-600 text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-700',
|
||||
)}
|
||||
>
|
||||
Code Reader
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{profile.source_verified ? <EntityBadge label="verified source" tone="success" /> : null}
|
||||
{profile.abi_available ? <EntityBadge label="abi available" tone="info" /> : null}
|
||||
{profile.compiler_version ? <EntityBadge label={profile.compiler_version} tone="neutral" className="normal-case tracking-normal" /> : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activeTab === 'source' ? (
|
||||
<div className={clsx('overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700', expanded ? 'min-h-[46rem]' : '')}>
|
||||
<div className="grid lg:grid-cols-[18rem_minmax(0,1fr)]">
|
||||
<aside className="border-b border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-900 lg:border-b-0 lg:border-r">
|
||||
<div className="flex items-center justify-between border-b border-gray-200 px-4 py-3 text-xs font-semibold uppercase text-gray-500 dark:border-gray-700 dark:text-gray-400">
|
||||
<span>Explorer</span>
|
||||
<span>{files.length} file{files.length === 1 ? '' : 's'}</span>
|
||||
</div>
|
||||
<div className="max-h-72 overflow-auto p-2 lg:max-h-[34rem]">
|
||||
{files.map((file) => (
|
||||
<button
|
||||
type="button"
|
||||
key={file.path}
|
||||
onClick={() => setActivePath(file.path)}
|
||||
className={clsx(
|
||||
'block w-full rounded-md px-3 py-2 text-left text-sm transition',
|
||||
file.path === activeFile?.path
|
||||
? 'bg-white font-semibold text-gray-950 shadow-sm dark:bg-gray-800 dark:text-white'
|
||||
: 'text-gray-700 hover:bg-white dark:text-gray-300 dark:hover:bg-gray-800',
|
||||
)}
|
||||
>
|
||||
<span className="block truncate">{file.path}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{outline.length > 0 ? (
|
||||
<div className="border-t border-gray-200 p-2 dark:border-gray-700">
|
||||
<div className="px-3 py-2 text-xs font-semibold uppercase text-gray-500 dark:text-gray-400">Outline</div>
|
||||
<div className="max-h-64 overflow-auto">
|
||||
{outline.slice(0, 80).map((entry) => (
|
||||
<button
|
||||
key={`${entry.type}-${entry.name}-${entry.line}`}
|
||||
type="button"
|
||||
onClick={() => document.getElementById(`source-line-${entry.line}`)?.scrollIntoView({ block: 'center' })}
|
||||
className="flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs text-gray-700 hover:bg-white dark:text-gray-300 dark:hover:bg-gray-800"
|
||||
>
|
||||
<span className="w-16 uppercase text-gray-400">{entry.type}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono">{entry.name}</span>
|
||||
<span className="text-gray-400">{entry.line}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</aside>
|
||||
|
||||
<div className="min-w-0 bg-gray-950 text-gray-100">
|
||||
<div className="flex flex-col gap-3 border-b border-gray-800 bg-gray-900 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-mono text-sm text-white">{activeFile?.path || 'Source'}</div>
|
||||
<div className="mt-1 text-xs text-gray-400">{sourceLines.length} lines</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button type="button" onClick={handleCopySource} className="rounded-md border border-gray-700 px-3 py-1.5 text-xs font-semibold text-gray-200 hover:bg-gray-800">
|
||||
Copy
|
||||
</button>
|
||||
<button type="button" onClick={handleCopyLink} className="rounded-md border border-gray-700 px-3 py-1.5 text-xs font-semibold text-gray-200 hover:bg-gray-800">
|
||||
Link
|
||||
</button>
|
||||
<button type="button" onClick={() => setExpanded((value) => !value)} className="rounded-md border border-gray-700 px-3 py-1.5 text-xs font-semibold text-gray-200 hover:bg-gray-800">
|
||||
{expanded ? 'Collapse' : 'Expand'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<pre className={clsx('overflow-auto p-0 text-xs leading-5', expanded ? 'max-h-[52rem]' : 'max-h-[34rem]')}>
|
||||
<code className="block min-w-max py-4">
|
||||
{sourceLines.map((line, index) => (
|
||||
<span id={`source-line-${index + 1}`} key={`${activeFile?.path}-${index}`} className="grid grid-cols-[4.5rem_minmax(0,1fr)] px-4 hover:bg-white/5">
|
||||
<span className="select-none pr-4 text-right text-gray-500">{index + 1}</span>
|
||||
<span className="whitespace-pre text-gray-100">{line || ' '}</span>
|
||||
</span>
|
||||
))}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-gray-200 p-4 dark:border-gray-700">
|
||||
<form onSubmit={handleSubmit} className="grid gap-5 lg:grid-cols-[28rem_minmax(0,1fr)]">
|
||||
<div className="space-y-4 lg:border-r lg:border-gray-200 lg:pr-5 lg:dark:border-gray-700">
|
||||
<label className="block">
|
||||
<span className="mb-2 block text-sm font-semibold text-gray-900 dark:text-white">Choose Model</span>
|
||||
<select
|
||||
value={model}
|
||||
onChange={(event) => setModel(event.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-950 dark:text-white"
|
||||
>
|
||||
<option>Explorer AI</option>
|
||||
<option>Grok</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<div className="mb-2 text-sm font-semibold text-gray-900 dark:text-white">File Browser</div>
|
||||
<div className="space-y-2 rounded-lg bg-gray-50 p-3 dark:bg-gray-900">
|
||||
{files.map((file) => (
|
||||
<label key={file.path} className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-200">
|
||||
<input type="checkbox" checked readOnly className="h-4 w-4 rounded border-gray-300 text-primary-600" />
|
||||
<span className="truncate">{file.path}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 space-y-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-sm font-semibold text-gray-900 dark:text-white">Prompt</div>
|
||||
<label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
|
||||
<input type="checkbox" checked={saveHistory} onChange={(event) => setSaveHistory(event.target.checked)} className="h-4 w-4 rounded border-gray-300 text-primary-600" />
|
||||
Save History
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<textarea
|
||||
value={prompt}
|
||||
onChange={(event) => setPrompt(event.target.value)}
|
||||
rows={3}
|
||||
className="min-h-24 flex-1 rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-950 dark:text-white"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting || !prompt.trim()}
|
||||
className="h-12 rounded-lg bg-primary-600 px-4 text-sm font-semibold text-white transition hover:bg-primary-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{submitting ? '...' : 'Send'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{QUICK_PROMPTS.map((quickPrompt) => (
|
||||
<button
|
||||
key={quickPrompt}
|
||||
type="button"
|
||||
onClick={() => void askReader(quickPrompt)}
|
||||
className="rounded-full border border-gray-300 px-3 py-1.5 text-xs font-semibold text-gray-700 hover:border-primary-400 hover:text-primary-700 dark:border-gray-700 dark:text-gray-300 dark:hover:text-primary-300"
|
||||
>
|
||||
{quickPrompt}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{readerAnswer ? (
|
||||
<div className="whitespace-pre-wrap rounded-lg bg-gray-50 p-4 text-sm text-gray-800 dark:bg-gray-900 dark:text-gray-100">
|
||||
{readerAnswer}
|
||||
</div>
|
||||
) : null}
|
||||
{readerError ? (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/40 dark:text-red-200">
|
||||
{readerError}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { statsApi, type ExplorerStats } from '@/services/api/stats'
|
||||
import { summarizeChainActivity } from '@/utils/activityContext'
|
||||
import ActivityContextPanel from '@/components/common/ActivityContextPanel'
|
||||
import FreshnessTrustNote from '@/components/common/FreshnessTrustNote'
|
||||
import MarketEvidenceNote from '@/components/common/MarketEvidenceNote'
|
||||
import SubsystemPosturePanel from '@/components/common/SubsystemPosturePanel'
|
||||
import { resolveEffectiveFreshness } from '@/utils/explorerFreshness'
|
||||
import {
|
||||
@@ -318,6 +319,12 @@ export default function LiquidityOperationsPage({
|
||||
<div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
{formatNumber(dexCount)} DEX families in the current discovered pools.
|
||||
</div>
|
||||
<MarketEvidenceNote
|
||||
source="mission-control"
|
||||
lastUpdated={routeMatrix?.updated}
|
||||
method="Route matrix, provider capabilities, and mission-control pool inventory are reconciled for visible public liquidity only."
|
||||
compact
|
||||
/>
|
||||
</Card>
|
||||
<Card>
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">Fallback posture</div>
|
||||
@@ -354,6 +361,12 @@ export default function LiquidityOperationsPage({
|
||||
<div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
Seen from {pool.sourceSymbols.join(', ')}
|
||||
</div>
|
||||
<MarketEvidenceNote
|
||||
source="mission-control"
|
||||
lastUpdated={routeMatrix?.updated}
|
||||
method="Pool TVL is the visible mission-control value for discovered route-backed liquidity."
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{aggregatedPools.length === 0 ? (
|
||||
|
||||
@@ -105,7 +105,7 @@ export default function WethOperationsPage({
|
||||
<OperationsPageShell page={page}>
|
||||
<Card className="mb-6 border border-amber-200 bg-amber-50/70 dark:border-amber-900/50 dark:bg-amber-950/20">
|
||||
<p className="text-sm leading-6 text-amber-950 dark:text-amber-100">
|
||||
These WETH references are bridge and transport surfaces, not a claim that Ethereum mainnet WETH contracts are native Chain 138 assets.
|
||||
These WETH references are bridge-lane and public-network representation surfaces, not a claim that Ethereum mainnet WETH contracts are native Chain 138 assets.
|
||||
Use this page to review wrapped-asset lane posture, counterpart contracts, and operational dependencies.
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
@@ -21,8 +21,10 @@ import { transactionsApi, type Transaction } from '@/services/api/transactions'
|
||||
import { summarizeChainActivity } from '@/utils/activityContext'
|
||||
import ActivityContextPanel from '@/components/common/ActivityContextPanel'
|
||||
import FreshnessTrustNote from '@/components/common/FreshnessTrustNote'
|
||||
import MarketEvidenceNote from '@/components/common/MarketEvidenceNote'
|
||||
import { Explain, useUiMode } from '@/components/common/UiModeContext'
|
||||
import { resolveEffectiveFreshness, shouldExplainEmptyHeadBlocks } from '@/utils/explorerFreshness'
|
||||
import { tokenAggregationApi, type TokenAggregationTokenSnapshot } from '@/services/api/tokenAggregation'
|
||||
|
||||
type HomeStats = ExplorerStats
|
||||
|
||||
@@ -92,6 +94,15 @@ function compactStatNote(guided: string, expert: string, mode: 'guided' | 'exper
|
||||
return mode === 'guided' ? guided : expert
|
||||
}
|
||||
|
||||
function formatUsd(value: number | undefined) {
|
||||
if (value == null || !Number.isFinite(value)) return 'Unavailable'
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
maximumFractionDigits: value >= 100 ? 0 : 2,
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
export default function Home({
|
||||
initialStats = null,
|
||||
initialRecentBlocks = [],
|
||||
@@ -109,6 +120,7 @@ export default function Home({
|
||||
const [activitySnapshot, setActivitySnapshot] = useState<ExplorerRecentActivitySnapshot | null>(initialActivitySnapshot)
|
||||
const [bridgeStatus, setBridgeStatus] = useState<MissionControlBridgeStatusResponse | null>(initialBridgeStatus)
|
||||
const [relaySummary, setRelaySummary] = useState<MissionControlRelaySummary | null>(initialRelaySummary)
|
||||
const [featuredPrices, setFeaturedPrices] = useState<TokenAggregationTokenSnapshot[]>([])
|
||||
const [missionExpanded, setMissionExpanded] = useState(false)
|
||||
const [relayExpanded, setRelayExpanded] = useState(false)
|
||||
const [relayPage, setRelayPage] = useState(1)
|
||||
@@ -166,6 +178,29 @@ export default function Home({
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
tokenAggregationApi.getTokensByAddressSafe(138, [
|
||||
'0x93E66202A11B1772E55407B32B44e5Cd8eda7f22',
|
||||
'0xf22258f57794CC8E06237084b353Ab30fFfa640b',
|
||||
'0x290e52a8819A4fBd0714e517225429AA2B70EC6B',
|
||||
'0xc02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
|
||||
]).then(({ data }) => {
|
||||
if (!cancelled) {
|
||||
setFeaturedPrices(data)
|
||||
}
|
||||
}).catch((error) => {
|
||||
if (!cancelled && process.env.NODE_ENV !== 'production') {
|
||||
console.warn('Failed to load featured token prices:', error)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
@@ -575,7 +610,7 @@ export default function Home({
|
||||
<div className="rounded-2xl border border-white/40 bg-white/55 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-black/10">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide opacity-70">Chain 138 Status</div>
|
||||
<div className="mt-2 text-lg font-semibold">{chainStatus.status || 'unknown'}</div>
|
||||
<div className="mt-1 text-sm opacity-80">{chainStatus.name || 'Defi Oracle Meta Mainnet'}</div>
|
||||
<div className="mt-1 text-sm opacity-80">{chainStatus.name || 'DeFi Oracle Meta Mainnet'}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/40 bg-white/55 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-black/10">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide opacity-70">Head Age</div>
|
||||
@@ -738,6 +773,36 @@ export default function Home({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{featuredPrices.length > 0 ? (
|
||||
<div className="mb-8">
|
||||
<Card title="Live Price Feed">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
{featuredPrices.map((token) => (
|
||||
<Link
|
||||
key={token.address}
|
||||
href={`/tokens/${token.address}`}
|
||||
className="rounded-2xl border border-gray-200 bg-gray-50/70 px-4 py-3 transition hover:border-primary-400 hover:shadow-sm dark:border-gray-800 dark:bg-gray-900/40"
|
||||
>
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
|
||||
{token.symbol || token.name || 'Token'}
|
||||
</div>
|
||||
<div className="mt-1 text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{formatUsd(token.market?.priceUsd)}
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
Visible liquidity: {formatUsd(token.market?.liquidityUsd)}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{token.market?.lastUpdated ? `Updated ${formatRelativeAge(token.market.lastUpdated)}` : 'Update time unavailable'}
|
||||
</div>
|
||||
<MarketEvidenceNote lastUpdated={token.market?.lastUpdated} compact />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mb-8">
|
||||
<ActivityContextPanel
|
||||
context={activityContext}
|
||||
|
||||
@@ -148,7 +148,7 @@ const FALLBACK_CAPABILITIES_138: CapabilitiesCatalog = {
|
||||
name: 'Chain 138 RPC Capabilities',
|
||||
version: { major: 1, minor: 1, patch: 0 },
|
||||
timestamp: '2026-03-28T00:00:00Z',
|
||||
generatedBy: 'SolaceScan',
|
||||
generatedBy: 'DBIS Explorer',
|
||||
chainId: 138,
|
||||
chainName: 'DeFi Oracle Meta Mainnet',
|
||||
rpcUrl: 'https://rpc-http-pub.d-bis.org',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AppProps } from 'next/app'
|
||||
import '../app/globals.css'
|
||||
import '../styles/globals.css'
|
||||
import ExplorerChrome from '@/components/common/ExplorerChrome'
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
|
||||
@@ -29,13 +29,27 @@ import {
|
||||
} from '@/utils/watchlist'
|
||||
import PageIntro from '@/components/common/PageIntro'
|
||||
import GruStandardsCard from '@/components/common/GruStandardsCard'
|
||||
import ContractCodeWorkspace from '@/components/explorer/ContractCodeWorkspace'
|
||||
import { getGruStandardsProfileSafe, type GruStandardsProfile } from '@/services/api/gru'
|
||||
import { getGruExplorerMetadata } from '@/services/api/gruExplorerData'
|
||||
import { tokenAggregationApi, type TokenAggregationTokenSnapshot } from '@/services/api/tokenAggregation'
|
||||
import { estimateNativeUsdValue, getNativeAssetDescriptor, getNativeAssetMarketSafe } from '@/services/api/nativeAssetPricing'
|
||||
|
||||
function isValidAddress(value: string) {
|
||||
return /^0x[a-fA-F0-9]{40}$/.test(value)
|
||||
}
|
||||
|
||||
function formatUsd(value: string | number | undefined): string {
|
||||
if (value == null) return 'Unavailable'
|
||||
const numeric = typeof value === 'number' ? value : Number(value)
|
||||
if (!Number.isFinite(numeric)) return 'Unavailable'
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
maximumFractionDigits: numeric >= 100 ? 0 : 2,
|
||||
}).format(numeric)
|
||||
}
|
||||
|
||||
export default function AddressDetailPage() {
|
||||
const router = useRouter()
|
||||
const address = typeof router.query.address === 'string' ? router.query.address : ''
|
||||
@@ -51,6 +65,8 @@ 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 [tokenMarkets, setTokenMarkets] = useState<Record<string, TokenAggregationTokenSnapshot>>({})
|
||||
const [nativeAssetPriceUsd, setNativeAssetPriceUsd] = useState<number | undefined>()
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const loadAddressInfo = useCallback(async () => {
|
||||
@@ -137,6 +153,46 @@ export default function AddressDetailPage() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
const tokenAddresses = [
|
||||
...(addressInfo?.token_contract?.address ? [addressInfo.token_contract.address] : []),
|
||||
...tokenBalances.map((balance) => balance.token_address),
|
||||
...tokenTransfers.map((transfer) => transfer.token_address),
|
||||
].filter((candidate, index, values): candidate is string => typeof candidate === 'string' && candidate.trim().length > 0 && values.indexOf(candidate) === index)
|
||||
|
||||
tokenAggregationApi.getTokensByAddressSafe(chainId, tokenAddresses).then(({ data }) => {
|
||||
if (!active) return
|
||||
setTokenMarkets(Object.fromEntries(data.map((snapshot) => [snapshot.address.toLowerCase(), snapshot])))
|
||||
}).catch(() => {
|
||||
if (active) {
|
||||
setTokenMarkets({})
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [addressInfo?.token_contract?.address, chainId, tokenBalances, tokenTransfers])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
getNativeAssetMarketSafe(chainId).then(({ data }) => {
|
||||
if (!active) return
|
||||
setNativeAssetPriceUsd(data?.market?.priceUsd)
|
||||
}).catch(() => {
|
||||
if (active) {
|
||||
setNativeAssetPriceUsd(undefined)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [chainId])
|
||||
|
||||
const watchlistAddress = normalizeWatchlistAddress(addressInfo?.address || address)
|
||||
const isSavedToWatchlist = watchlistAddress
|
||||
? isWatchlistEntry(watchlistEntries, watchlistAddress)
|
||||
@@ -272,7 +328,17 @@ export default function AddressDetailPage() {
|
||||
},
|
||||
{
|
||||
header: 'Value',
|
||||
accessor: (tx: TransactionSummary) => formatWeiAsEth(tx.value),
|
||||
accessor: (tx: TransactionSummary) => {
|
||||
const nativeValueUsd = estimateNativeUsdValue(tx.value, nativeAssetPriceUsd)
|
||||
return (
|
||||
<div className="space-y-1 text-sm">
|
||||
<div>{formatWeiAsEth(tx.value)}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{nativeValueUsd != null ? `Current USD: ${formatUsd(nativeValueUsd)}` : 'Current USD unavailable'}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Status',
|
||||
@@ -327,6 +393,20 @@ export default function AddressDetailPage() {
|
||||
: 'N/A'
|
||||
),
|
||||
},
|
||||
{
|
||||
header: 'Current Price',
|
||||
accessor: (balance: AddressTokenBalance) => {
|
||||
const market = tokenMarkets[balance.token_address.toLowerCase()]?.market
|
||||
return (
|
||||
<div className="space-y-1 text-sm">
|
||||
<div>{formatUsd(market?.priceUsd)}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
Liq. {formatUsd(market?.liquidityUsd)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const tokenTransferColumns = [
|
||||
@@ -344,7 +424,7 @@ export default function AddressDetailPage() {
|
||||
{gruMetadata ? <EntityBadge label="GRU" tone="success" /> : null}
|
||||
{gruMetadata?.x402Ready ? <EntityBadge label="x402 ready" tone="info" /> : null}
|
||||
{gruMetadata?.iso20022Ready ? <EntityBadge label="ISO-20022" tone="info" /> : null}
|
||||
{gruMetadata?.transportActiveVersion ? <EntityBadge label={`transport ${gruMetadata.transportActiveVersion}`} tone="warning" /> : null}
|
||||
{gruMetadata?.transportActiveVersion ? <EntityBadge label={`cW public-network ${gruMetadata.transportActiveVersion}`} tone="warning" /> : null}
|
||||
</div>
|
||||
{transfer.token_address && (
|
||||
<Link href={`/tokens/${transfer.token_address}`} className="text-primary-600 hover:underline">
|
||||
@@ -383,6 +463,20 @@ export default function AddressDetailPage() {
|
||||
header: 'When',
|
||||
accessor: (transfer: AddressTokenTransfer) => formatTimestamp(transfer.timestamp),
|
||||
},
|
||||
{
|
||||
header: 'Current Price',
|
||||
accessor: (transfer: AddressTokenTransfer) => {
|
||||
const market = tokenMarkets[transfer.token_address.toLowerCase()]?.market
|
||||
return (
|
||||
<div className="space-y-1 text-sm">
|
||||
<div>{formatUsd(market?.priceUsd)}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
Liq. {formatUsd(market?.liquidityUsd)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const incomingTransactions = transactions.filter(
|
||||
@@ -403,6 +497,8 @@ export default function AddressDetailPage() {
|
||||
const gruTransferCount = tokenTransfers.filter((transfer) =>
|
||||
Boolean(getGruExplorerMetadata({ address: transfer.token_address, symbol: transfer.token_symbol })),
|
||||
).length
|
||||
const nativeAssetSymbol = getNativeAssetDescriptor(chainId).symbol
|
||||
const nativeBalanceUsd = estimateNativeUsdValue(addressInfo?.balance, nativeAssetPriceUsd)
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-6 sm:py-8">
|
||||
@@ -473,8 +569,14 @@ export default function AddressDetailPage() {
|
||||
<Address address={addressInfo.address} />
|
||||
</DetailRow>
|
||||
{addressInfo.balance && (
|
||||
<DetailRow label="Coin Balance">{formatWeiAsEth(addressInfo.balance)}</DetailRow>
|
||||
<DetailRow label="Coin Balance">
|
||||
{formatWeiAsEth(addressInfo.balance)}
|
||||
{nativeBalanceUsd != null ? ` (${formatUsd(nativeBalanceUsd)})` : ''}
|
||||
</DetailRow>
|
||||
)}
|
||||
<DetailRow label="Current Native Asset Price">
|
||||
{nativeAssetPriceUsd != null ? `${formatUsd(nativeAssetPriceUsd)} per ${nativeAssetSymbol}` : 'Unavailable'}
|
||||
</DetailRow>
|
||||
<DetailRow label="Watchlist">
|
||||
{isSavedToWatchlist ? 'Saved for quick access' : 'Not saved yet'}
|
||||
</DetailRow>
|
||||
@@ -601,20 +703,6 @@ export default function AddressDetailPage() {
|
||||
</code>
|
||||
</DetailRow>
|
||||
)}
|
||||
{contractProfile?.source_code_preview && (
|
||||
<DetailRow label="Source Preview">
|
||||
<code className="block max-h-56 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-50 p-2 text-xs dark:bg-gray-950">
|
||||
{contractProfile.source_code_preview}
|
||||
</code>
|
||||
</DetailRow>
|
||||
)}
|
||||
{contractProfile?.abi && (
|
||||
<DetailRow label="ABI Preview">
|
||||
<code className="block max-h-56 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-50 p-2 text-xs dark:bg-gray-950">
|
||||
{contractProfile.abi}
|
||||
</code>
|
||||
</DetailRow>
|
||||
)}
|
||||
{contractProfile?.read_methods && contractProfile.read_methods.length > 0 && (
|
||||
<DetailRow label="Read Methods">
|
||||
<div className="space-y-3">
|
||||
@@ -760,6 +848,10 @@ export default function AddressDetailPage() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{addressInfo.is_contract && contractProfile ? (
|
||||
<ContractCodeWorkspace address={addressInfo.address} profile={contractProfile} />
|
||||
) : null}
|
||||
|
||||
{gruProfile ? <div className="mb-6"><GruStandardsCard profile={gruProfile} /></div> : null}
|
||||
|
||||
<Card title="Token Balances" className="mb-6">
|
||||
|
||||
@@ -11,7 +11,7 @@ export default function GruDocsPage() {
|
||||
<PageIntro
|
||||
eyebrow="Explorer Documentation"
|
||||
title="GRU Guide"
|
||||
description="A user-facing summary of the GRU standards, transport posture, and x402 readiness model, with concrete places to inspect those signals on live token, address, and search pages."
|
||||
description="A user-facing summary of the GRU standards, bridge posture, public-network representations, and x402 readiness model, with concrete places to inspect those signals on live token, address, and search pages."
|
||||
actions={[
|
||||
{ href: '/tokens', label: 'Browse tokens' },
|
||||
{ href: '/search?q=cUSDC', label: 'Search cUSDC' },
|
||||
@@ -23,7 +23,7 @@ export default function GruDocsPage() {
|
||||
<Card title="What The Explorer Is Showing You">
|
||||
<div className="space-y-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
<p>
|
||||
The explorer now distinguishes between canonical GRU money surfaces on Chain 138 and wrapped transport assets used on public-chain bridge lanes.
|
||||
The explorer now distinguishes between canonical GRU surfaces on Chain 138 and cW public-network representations used on bridge lanes.
|
||||
It also highlights when a token looks ready for x402-style payment flows.
|
||||
</p>
|
||||
<p>
|
||||
@@ -49,6 +49,14 @@ export default function GruDocsPage() {
|
||||
|
||||
<Card title="Standards Summary">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm dark:border-gray-700 dark:bg-gray-900/40 md:col-span-2">
|
||||
<div className="font-medium text-gray-900 dark:text-white">Public token language</div>
|
||||
<div className="mt-2 text-gray-600 dark:text-gray-400">
|
||||
The explorer follows the GRU monetary policy taxonomy: <strong>c</strong> means compliant instrument created by a regulated financial entity or institution,
|
||||
<strong> W</strong> means wrapped representation on a public network, <strong>XXX</strong> is the ISO-4217 currency code or ISO-style commodity code,
|
||||
<strong> C</strong> marks cash-tokenized electronic money, and <strong> T</strong> marks treasury or government bond exposure.
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm dark:border-gray-700 dark:bg-gray-900/40">
|
||||
<div className="font-medium text-gray-900 dark:text-white">Base token profile</div>
|
||||
<div className="mt-2 text-gray-600 dark:text-gray-400">
|
||||
@@ -95,7 +103,7 @@ export default function GruDocsPage() {
|
||||
<Card title="Chain 138 Practical Reading">
|
||||
<div className="space-y-3 text-sm text-gray-600 dark:text-gray-400">
|
||||
<p>
|
||||
A token can be forward-canonical and x402-ready even while older liquidity or transport lanes still run on a prior version.
|
||||
A token can be forward-canonical and x402-ready even while older liquidity or bridge lanes still run on a prior version.
|
||||
That is why the explorer separates active liquidity posture from forward-canonical posture.
|
||||
</p>
|
||||
<p>
|
||||
|
||||
@@ -8,7 +8,7 @@ const docsCards = [
|
||||
{
|
||||
title: 'GRU Guide',
|
||||
href: '/docs/gru',
|
||||
description: 'Understand GRU standards, x402 readiness, wrapped transport posture, and forward-canonical versioning as surfaced by the explorer.',
|
||||
description: 'Understand GRU standards, x402 readiness, cW public-network posture, and forward-canonical versioning as surfaced by the explorer.',
|
||||
},
|
||||
{
|
||||
title: 'Transaction Evidence Matrix',
|
||||
@@ -88,8 +88,8 @@ export default function DocsIndexPage() {
|
||||
<Card title="Operator & Domains">
|
||||
<div className="space-y-3 text-sm text-gray-600 dark:text-gray-400">
|
||||
<p>
|
||||
SolaceScan is the public Chain 138 explorer operated by DBIS / Defi Oracle. The explorer may be reached through
|
||||
<code> blockscout.defi-oracle.io</code> or <code> explorer.d-bis.org</code>.
|
||||
DBIS Explorer is the public Chain 138 explorer operated by DBIS. Primary public access is served at
|
||||
<code> explorer.d-bis.org</code>; <code> blockscout.defi-oracle.io</code> is the Blockscout companion domain.
|
||||
</p>
|
||||
<p>
|
||||
These domains are part of the same explorer and companion-tooling surface, including the Snap install path at
|
||||
|
||||
@@ -12,7 +12,7 @@ export default function HomeAliasPage() {
|
||||
return (
|
||||
<main className="container mx-auto px-4 py-12">
|
||||
<div className="mx-auto max-w-xl rounded-xl border border-gray-200 bg-white p-6 text-center shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Redirecting to SolaceScan</h1>
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Redirecting to DBIS Explorer</h1>
|
||||
<p className="mt-3 text-sm leading-7 text-gray-600 dark:text-gray-400">
|
||||
The legacy <code className="rounded bg-gray-100 px-1 py-0.5 text-xs dark:bg-gray-900">/home</code> route now redirects to the main explorer landing page.
|
||||
</p>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useRouter } from 'next/router'
|
||||
import { Card, Address } from '@/libs/frontend-ui-primitives'
|
||||
import Link from 'next/link'
|
||||
import { configApi, type TokenListToken } from '@/services/api/config'
|
||||
import { tokenAggregationApi, type TokenAggregationTokenSnapshot } from '@/services/api/tokenAggregation'
|
||||
import EntityBadge from '@/components/common/EntityBadge'
|
||||
import {
|
||||
inferDirectSearchTarget,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
import PageIntro from '@/components/common/PageIntro'
|
||||
import { fetchPublicJson } from '@/utils/publicExplorer'
|
||||
import { useUiMode } from '@/components/common/UiModeContext'
|
||||
import MarketEvidenceNote from '@/components/common/MarketEvidenceNote'
|
||||
|
||||
type SearchFilterMode = 'all' | 'gru' | 'x402' | 'wrapped'
|
||||
|
||||
@@ -24,6 +26,15 @@ interface SearchPageProps {
|
||||
initialCuratedTokens: TokenListToken[]
|
||||
}
|
||||
|
||||
function formatUsd(value: number | undefined): string {
|
||||
if (value == null || !Number.isFinite(value)) return 'Unavailable'
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
maximumFractionDigits: value >= 100 ? 0 : 2,
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
export default function SearchPage({
|
||||
initialQuery,
|
||||
initialRawResults,
|
||||
@@ -40,6 +51,7 @@ export default function SearchPage({
|
||||
const [curatedTokens, setCuratedTokens] = useState<TokenListToken[]>(initialCuratedTokens)
|
||||
const [savedQueries, setSavedQueries] = useState<string[]>([])
|
||||
const [filterMode, setFilterMode] = useState<SearchFilterMode>('all')
|
||||
const [tokenMarkets, setTokenMarkets] = useState<Record<string, TokenAggregationTokenSnapshot>>({})
|
||||
|
||||
const runSearch = async (rawQuery: string) => {
|
||||
const trimmedQuery = rawQuery.trim()
|
||||
@@ -190,6 +202,27 @@ export default function SearchPage({
|
||||
{ label: 'Other', items: groupedResults.other },
|
||||
]
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
const tokenAddresses = filteredResults
|
||||
.filter((result) => result.type === 'token' && typeof result.data.address === 'string' && result.data.address.trim().length > 0)
|
||||
.map((result) => result.data.address as string)
|
||||
|
||||
tokenAggregationApi.getTokensByAddressSafe(138, tokenAddresses).then(({ data }) => {
|
||||
if (!active) return
|
||||
setTokenMarkets(Object.fromEntries(data.map((snapshot) => [snapshot.address.toLowerCase(), snapshot])))
|
||||
}).catch(() => {
|
||||
if (active) {
|
||||
setTokenMarkets({})
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [filteredResults])
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-6 sm:py-8">
|
||||
<PageIntro
|
||||
@@ -341,30 +374,46 @@ export default function SearchPage({
|
||||
</Link>
|
||||
)}
|
||||
{(result.type === 'address' || result.type === 'token') && result.data.address && (
|
||||
<Link
|
||||
href={result.href || (result.type === 'token' ? `/tokens/${result.data.address}` : `/addresses/${result.data.address}`)}
|
||||
className="inline-flex flex-col gap-2 text-primary-600 hover:underline"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EntityBadge
|
||||
label={result.type === 'token' ? 'token' : 'address'}
|
||||
tone={result.type === 'token' ? 'success' : 'neutral'}
|
||||
/>
|
||||
{result.symbol && <EntityBadge label={result.symbol} tone="info" />}
|
||||
{result.token_type && <EntityBadge label={result.token_type} tone="warning" />}
|
||||
{result.is_curated_token && <EntityBadge label="listed" tone="success" />}
|
||||
{result.is_gru_token && <EntityBadge label="GRU" tone="success" />}
|
||||
{result.is_x402_ready && <EntityBadge label="x402 ready" tone="info" />}
|
||||
{result.is_wrapped_transport && <EntityBadge label="wrapped" tone="warning" />}
|
||||
{result.currency_code ? <EntityBadge label={result.currency_code} tone="neutral" /> : null}
|
||||
{result.match_reason ? <EntityBadge label={result.match_reason} tone="info" className="normal-case tracking-normal" /> : null}
|
||||
{result.matched_tags?.map((tag) => <EntityBadge key={tag} label={tag} />)}
|
||||
</div>
|
||||
<span className="font-medium text-gray-900 dark:text-white">
|
||||
{result.name || result.symbol || result.label}
|
||||
</span>
|
||||
<Address address={result.data.address} truncate showCopy={false} />
|
||||
</Link>
|
||||
(() => {
|
||||
const market = result.type === 'token'
|
||||
? tokenMarkets[result.data.address.toLowerCase()]?.market
|
||||
: null
|
||||
return (
|
||||
<Link
|
||||
href={result.href || (result.type === 'token' ? `/tokens/${result.data.address}` : `/addresses/${result.data.address}`)}
|
||||
className="inline-flex flex-col gap-2 text-primary-600 hover:underline"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EntityBadge
|
||||
label={result.type === 'token' ? 'token' : 'address'}
|
||||
tone={result.type === 'token' ? 'success' : 'neutral'}
|
||||
/>
|
||||
{result.symbol && <EntityBadge label={result.symbol} tone="info" />}
|
||||
{result.token_type && <EntityBadge label={result.token_type} tone="warning" />}
|
||||
{result.is_curated_token && <EntityBadge label="listed" tone="success" />}
|
||||
{result.is_gru_token && <EntityBadge label="GRU" tone="success" />}
|
||||
{result.is_x402_ready && <EntityBadge label="x402 ready" tone="info" />}
|
||||
{result.is_wrapped_transport && <EntityBadge label="cW public-network" tone="warning" />}
|
||||
{result.currency_code ? <EntityBadge label={result.currency_code} tone="neutral" /> : null}
|
||||
{result.match_reason ? <EntityBadge label={result.match_reason} tone="info" className="normal-case tracking-normal" /> : null}
|
||||
{result.matched_tags?.map((tag) => <EntityBadge key={tag} label={tag} />)}
|
||||
</div>
|
||||
<span className="font-medium text-gray-900 dark:text-white">
|
||||
{result.name || result.symbol || result.label}
|
||||
</span>
|
||||
<Address address={result.data.address} truncate showCopy={false} />
|
||||
{market ? (
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-1">
|
||||
<span>Live price: {formatUsd(market.priceUsd)}</span>
|
||||
<span>Visible liquidity: {formatUsd(market.liquidityUsd)}</span>
|
||||
</div>
|
||||
<MarketEvidenceNote lastUpdated={market.lastUpdated} compact />
|
||||
</div>
|
||||
) : null}
|
||||
</Link>
|
||||
)
|
||||
})()
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-sm text-gray-500">
|
||||
<span>Type: {result.type}</span>
|
||||
|
||||
@@ -11,6 +11,7 @@ import PageIntro from '@/components/common/PageIntro'
|
||||
import { DetailRow } from '@/components/common/DetailRow'
|
||||
import EntityBadge from '@/components/common/EntityBadge'
|
||||
import GruStandardsCard from '@/components/common/GruStandardsCard'
|
||||
import MarketEvidenceNote from '@/components/common/MarketEvidenceNote'
|
||||
import { formatTokenAmount, formatTimestamp } from '@/utils/format'
|
||||
import { getGruStandardsProfileSafe, type GruStandardsProfile } from '@/services/api/gru'
|
||||
import { getGruExplorerMetadata } from '@/services/api/gruExplorerData'
|
||||
@@ -346,9 +347,17 @@ export default function TokenDetailPage() {
|
||||
<div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Market Context</div>
|
||||
<div className="mt-3 space-y-2 text-sm text-gray-700 dark:text-gray-300">
|
||||
<div>Indicative price: {formatUsd(token.exchange_rate)}</div>
|
||||
<div>Current price: {formatUsd(token.exchange_rate)}</div>
|
||||
<div>24h volume: {formatUsd(token.volume_24h)}</div>
|
||||
<div>Market cap: {formatUsd(token.circulating_market_cap)}</div>
|
||||
<div>Visible liquidity: {formatUsd(token.liquidity_usd)}</div>
|
||||
<div>Valuation source: {token.price_source === 'token-aggregation' ? 'live token aggregation' : token.price_source || 'unavailable'}</div>
|
||||
<div>Market snapshot: {token.market_updated_at ? formatTimestamp(token.market_updated_at) : 'Unavailable'}</div>
|
||||
<MarketEvidenceNote
|
||||
source={token.price_source}
|
||||
lastUpdated={token.market_updated_at}
|
||||
method="Merged Blockscout token profile with token aggregation price, volume, and visible-liquidity fields where available."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
|
||||
@@ -429,7 +438,7 @@ export default function TokenDetailPage() {
|
||||
<Card title="Other Networks">
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
These are sibling representations or settlement counterparts for the same GRU asset family on other networks, drawn from the local transport and mapping posture used by this workspace.
|
||||
These are sibling representations or settlement counterparts for the same GRU asset family on other networks, drawn from the local public-network overlay and mapping posture used by this workspace.
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
{gruExplorerMetadata.otherNetworks.map((network) => (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user