# 4.1 Analytics Suite

Understand how your dApp performs and how your users behave end to end. The GRX Chain Analytics Suite combines explorer data, contract event streams, and lightweight APIs so teams can monitor usage, optimise costs, and make data-driven decisions.

### What you get

* **and Real-time views:** Near-real-time transaction and event ingestion from GRX Chain.
* **Actionable dashboards:** Prebuilt boards for usage, cost, reliability plus custom widgets.
* **Programmable alerts:** Threshold or anomaly alerts delivered to email/webhooks.
* **Open interfaces:** Pull data from **GRXscan**, JSON-RPC, and your own indexers.

### Core capabilities

#### 1) Monitor transaction flows

* Track **tx volumes, values, success rates**, and **peak usage** by hour/day.
* Slice by **contract**, **method**, **address cohort**, or your off-chain segments.

#### 2) Evaluate smart-contract performance

* Analyse **gas per function**, **execution success**, **revert reasons**, and **hot paths**.
* Detect regressions with **gas snapshots** and method-level trend lines.

#### 3) Understand user engagement

* Measure **DAU/WAU/MAU**, **new vs returning wallets**, **feature usage**, and **funnels** (e.g., connect → approve → swap).
* Run **cohort retention** (D1/D7/D30) using first-seen timestamps.

#### 4) Track token & liquidity metrics

* For ERC-20s/NFTs: **transfers, unique holders, holder concentration**.
* For DeFi: **pool TVL**, **volume**, **fees/APR** on **GRXswap**, **LP churn**, **price impact** bands.

#### 5) Assess network health (context)

* Follow **block-time variance**, **validator participation**, **pending-tx backlog**, and **gas-price** bands.

#### 6) Custom dashboards & alerts

* Compose widgets for **top methods**, **top spenders**, **error heatmaps**.
* Alerts on **revert spikes**, **liquidity drops**, **oracle staleness**, **admin role changes**.

***

### Metrics catalog (starter set)

**Reliability**

* Tx **success rate** (%), **revert rate** by method
* **P50/P95** inclusion time (submit → mined)
* **Outlier** detection on gas used per call

**Cost**

* **Avg/Median gas** per function
* **Gas per user action** (end-to-end flow)
* **Daily gas spend** by contract/module

**Engagement**

* **DAU/WAU/MAU**, **new wallets/day**, **retention (D1/D7/D30)**
* **Feature adoption** (% of active wallets calling method X)
* **Conversion funnels** (connect → approve → swap)

**Token / Liquidity**

* **Transfers/day**, **unique holders**, **top-N holders share**
* **Pool TVL/volume/fees/APR** (GRXswap)
* **Mint/Burn/Sync** event trends

**Security signals**

* **Admin/role** changes, **proxy upgrades**, **pause/unpause**
* **Large outflows**, **price deviation vs oracle** (if used)
* **Permit** misuse (if ERC-2612 enabled)

***

### Data sources

**GRXscan (Explorer) API** — tx lists, logs, balances, verification status

```bash
# Tx by hash
curl -s "https://grxscan.io/api?module=transaction&action=gettxinfo&txhash=<TX_HASH>"
```

**JSON-RPC (node)** — low-latency reads & custom filters

```bash
# Current gas price
curl -s -X POST https://rpc.grxchain.io \
 -H "Content-Type: application/json" \
 -d '{"jsonrpc":"2.0","id":1,"method":"eth_gasPrice","params":[]}'
```

```js
// ethers v6: listen to a contract event
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider("https://rpc.grxchain.io");
const abi = ["event Swap(address indexed user,uint256 in,uint256 out)"];
const dex = new ethers.Contract("<DEX_ADDRESS>", abi, provider);
dex.on("Swap", (user, _in, _out, evt) => {
  // push to your analytics pipeline
});
```

**Your indexer / ETL** — index events/logs to a DB/warehouse; build Grafana/Metabase dashboards.

***

### Prebuilt dashboards (suggested)

* **Operations:** success rate, inclusion time, gas bands, reorg buffer hits
* **Product:** DAU/WAU, conversion funnel, feature usage, retention
* **Finance/Token:** holders, top inflows/outflows, pool TVL/volume/fees
* **Security:** admin/role changes, upgrades, pause events, large transfers

***

### Alerts (ready-made rules)

* **Revert spike:** `revert_rate > 5% for 10m` (by contract or method)
* **Gas regression:** `median_gas(function) > baseline + 20% for 1h`
* **Liquidity drop:** `TVL(pool) down > 10% in 30m`
* **Oracle stale:** `price_age > 120s` (if using oracles)
* **Role change:** any `AccessControl`/`Ownable` admin change → immediate alert
* **Whale transfer:** transfer > X% of supply or > N std devs

Deliver via **webhook**, **email**, or your incident channel. Tie critical alerts to your **SEV-2/SEV-1** workflow (see Security & Privacy → IRP).

***

### Data Access & Limits

* **Explorer API fair use:** 10 req/s/IP (burst 50 for 10s); paginate large queries.
* **RPC best practice:** batch reads; avoid full-range `eth_getLogs`—scan in **2k–5k** block windows.
* **API keys (if enabled):** rotate quarterly. Header: `X-API-Key: <key>`; per-key quotas listed in your dashboard.

***

### Standard Event ABIs (for indexers)

**ERC-20 Transfer & Approval**

```json
[
  {"anonymous":false,"inputs":[
    {"indexed":true,"name":"from","type":"address"},
    {"indexed":true,"name":"to","type":"address"},
    {"indexed":false,"name":"value","type":"uint256"}],
   "name":"Transfer","type":"event"},
  {"anonymous":false,"inputs":[
    {"indexed":true,"name":"owner","type":"address"},
    {"indexed":true,"name":"spender","type":"address"},
    {"indexed":false,"name":"value","type":"uint256"}],
   "name":"Approval","type":"event"}
]
```

**GRXswap (UniswapV2-style)**

```json
[
  {"anonymous":false,"inputs":[
    {"indexed":true,"name":"sender","type":"address"},
    {"indexed":false,"name":"amount0In","type":"uint256"},
    {"indexed":false,"name":"amount1In","type":"uint256"},
    {"indexed":false,"name":"amount0Out","type":"uint256"},
    {"indexed":false,"name":"amount1Out","type":"uint256"},
    {"indexed":true,"name":"to","type":"address"}],
   "name":"Swap","type":"event"},
  {"anonymous":false,"inputs":[
    {"indexed":true,"name":"sender","type":"address"},
    {"indexed":false,"name":"amount0","type":"uint256"},
    {"indexed":false,"name":"amount1","type":"uint256"}],
   "name":"Mint","type":"event"},
  {"anonymous":false,"inputs":[
    {"indexed":true,"name":"sender","type":"address"},
    {"indexed":false,"name":"amount0","type":"uint256"},
    {"indexed":false,"name":"amount1","type":"uint256"},
    {"indexed":true,"name":"to","type":"address"}],
   "name":"Burn","type":"event"},
  {"anonymous":false,"inputs":[
    {"indexed":false,"name":"reserve0","type":"uint112"},
    {"indexed":false,"name":"reserve1","type":"uint112"},
    {"indexed":false,"name":"blockTimestampLast","type":"uint32"}],
   "name":"Sync","type":"event"}
]
```

***

### Example Alert Payloads (webhook/email)

**Revert spike**

```json
{
  "type": "revert_spike",
  "contract": "0xYourContract",
  "method": "swapExactTokensForTokens",
  "revert_rate": 0.083,
  "window": "10m",
  "baseline": 0.02,
  "tx_sample": ["0xabc...", "0xdef..."],
  "severity": "SEV-2",
  "runbook": "https://docs.your.site/runbooks/reverts"
}
```

**Liquidity drop**

```json
{
  "type": "liquidity_drop",
  "pool": "WGRX-USDT",
  "tvl_change_pct": -12.6,
  "interval": "30m",
  "dex": "GRXswap",
  "pair": ["0x45C7287F897B3A79Cd3f6e4F14B4CE568f023bD5","0x1d3bc9646d126D379b4da4d71c8a4fa6b830Dd20"],
  "severity": "SEV-2",
  "action": "Investigate LP removals; check announcements"
}
```

***

### Starter SQL (warehouse or DuckDB)

**Daily holders (distinct wallets)**

```sql
SELECT date_trunc('day', block_time) AS day,
       COUNT(DISTINCT holder) AS holders
FROM (
  SELECT block_time, "to"   AS holder FROM erc20_transfers
  WHERE token='0x45C7287F897B3A79Cd3f6e4F14B4CE568f023bD5'
  UNION ALL
  SELECT block_time, "from" AS holder FROM erc20_transfers
  WHERE token='0x45C7287F897B3A79Cd3f6e4F14B4CE568f023bD5'
) t
GROUP BY 1
ORDER BY 1;
```

**Cohort retention (first-seen week → D7)**

```sql
WITH first_seen AS (
  SELECT wallet, min(date_trunc('week', block_time)) AS cohort_week
  FROM contract_calls WHERE app='your_dapp'
  GROUP BY wallet
),
active AS (
  SELECT wallet, date_trunc('day', block_time) AS day
  FROM contract_calls WHERE app='your_dapp'
)
SELECT cohort_week,
       COUNT(DISTINCT CASE WHEN day <= cohort_week + INTERVAL '7 day' THEN wallet END)::float
       / COUNT(DISTINCT wallet) AS d7_retention
FROM first_seen f
LEFT JOIN active a USING (wallet)
GROUP BY cohort_week
ORDER BY cohort_week;
```

***

### Grafana panel ideas (titles you can lift)

* Tx Success & Revert Rate (P95)
* Median Inclusion Time (s)
* Gas per Function (Top 10)
* DAU / WAU / MAU
* Holders & Concentration (Top 10)
* GRXswap TVL / Volume / Fees
* Admin & Role Changes (24h)

***

### Computation notes (publish to avoid disputes)

* **DAU/WAU/MAU:** unique wallets calling your contracts within 1/7/30 days.
* **Holders:** distinct addresses with `balance > 0` at day end.
* **DEX volume:** sum notional per swap using mid-price from pool reserves at the block.
* **Fees/APR:** fees = `volume × feeRate`; APR ≈ `(fees / TVL) × 365` (simple).
* **Gas per action:** median gas across successful txs for a labeled flow.

***

### SDK snippet (ethers v6)

```js
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider("https://rpc.grxchain.io");

export async function getGasStats() {
  const gp = await provider.send("eth_gasPrice", []);
  return { gasPriceWei: BigInt(gp).toString() };
}

export function watchEvents(addr, abi, onEvent) {
  const c = new ethers.Contract(addr, abi, provider);
  c.on("*", (...args) => onEvent(args.pop())); // last arg is the event object
  return () => c.removeAllListeners();
}
```

***

### Data governance & SLA

* **Metric catalog:** publish definitions next to dashboards; any change requires a Changelog entry.
* **SLA (best-effort):** dashboards ingest within **<1 min**; alerts fire within **≤60s** of threshold.
* **Backfill policy:** major re-indexes are announced in the Changelog; dashboards show a “data backfill in progress” banner.

### Retention & privacy

* **Raw logs:** 90 days • **Aggregates:** 12 months (extendable for audits).
* **PII:** avoid by default. If you enrich, store separately, encrypt, and purge per policy.
* **Opt-out:** provide a “Do Not Track” toggle for app telemetry.

### UTM & attribution (growth)

* Standardise `utm_source`, `utm_medium`, `utm_campaign`, `utm_content`.
* Log **referrer → connect → approve → swap** funnel with non-PII session IDs.
* Weekly **scorecard:** first-swap conversion, D7 retention, median gas per happy path.

***

### Quick start checklist

* [ ] Connect to **GRXscan API** & **RPC**; confirm rate limits
* [ ] Stand up a lightweight indexer (events you care about)
* [ ] Create Ops/Product/Security dashboards (at least one each)
* [ ] Configure alerts (reverts, gas regression, liquidity drop, oracle stale, role change)
* [ ] Add weekly scorecard + owners + escalation path
* [ ] Document KPI definitions next to each chart

***

### Useful references

* **Explorer:** `https://grxscan.io`
* **RPC (mainnet):** `https://rpc.grxchain.io` (Chain ID **1110**)
* **RPC (testnet):** `https://testnet.grxchain.io` (Chain ID **2507**)
* **DEX:** `https://grxswap.io`
* **Governance:** `https://proposal.grxchain.io`
* **Staking:** `https://staking.grxchain.io`
* **Support:** **<admingrovex@grovex.io>**

> **Safety note:** Only trust addresses/endpoints listed in the Knowledge Base and visible on **GRXscan**. For bridging, use **grovex.io** (current official).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.grxchain.io/4-features-and-tools/4.1-analytics-suite.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
