Real-time Sybil detection on Base with GoldRush: stream, score and gate rewards

Covalent TeamUpdated 27 min read

Catch Sybil farms on Base as they act: stream wallet activity with GoldRush, score each wallet against its history, and pay rewards only on signed attestations.

A Sybil attack is one operator posing as many users. On Base, where transactions are cheap, spinning up hundreds of wallets to farm an airdrop, a quest or a points program is cheap, and a script can fund the wallets, perform the qualifying actions and move the rewards out within minutes. A review that runs days later finds the farm after the rewards have gone.

This guide builds a detector that keeps pace. It streams every transaction that touches your campaign contract through the GoldRush Streaming API, scores each participating wallet in real time against its own history from the GoldRush Foundational API, and turns the verdict into a signed, expiring attestation that your reward contract checks before it pays. Every score comes with its reasons, so a human can review the borderline cases.

About the Streaming API docs. The GoldRush Streaming API's multi-chain reference is being rebuilt and returns in January 2027; Hyperliquid streaming is live today. The stream code here follows the types published in the GoldRush SDK (@covalenthq/client-sdk 3.0.9), which list Base for the Wallet Activity stream. Ask GoldRush support to confirm Base streaming is enabled for your key before you rely on it.

What a Sybil attack looks like on Base

Sybil farms target anything that pays per wallet: airdrops, quest and points programs, liquidity incentives and one-wallet-one-vote governance. The attacker's costs are gas, time and the effort of making wallets look independent. Low fees remove most of the first, and scripts remove most of the second, so on a cheap chain the defence has to raise the third and act before the payout.

That sets four design goals:

  • Fast. Score a wallet while it's taking part, not in a weekly batch.
  • Explainable. Every score lists the signals behind it, so you can review it, tune it and explain it to a user who appeals.
  • Biased towards real users. A false positive costs you a real user and their trust; a missed Sybil costs one reward. Deny only the clear cases and send the rest to review.
  • Private and cheap onchain. Use only public onchain data, no identity documents. Do the heavy work off-chain and put one signature check onchain.

The signals worth scoring

No single signal proves a Sybil. Real users also arrive in bursts after an announcement, and many are funded from the same exchange. What gives a farm away is several signals lining up across a group of wallets: the same funder, the same sequence of actions, minutes apart, from wallets with no history.

Signal What it looks like Where it comes from Caveat
Fresh wallet First Base activity hours or days before the campaign Earliest transactions (Foundational API) New users are fresh too; weight it lightly
Funding fan-out Many participants whose first incoming ETH came from the same address Earliest transactions (Foundational API) Exchanges and bridges fund thousands of real users: exclude them
Burst against baseline Far more transactions this hour than the wallet's normal hour Live stream + hourly history (Foundational API) Announcements cause real bursts
Identical action sequence Many wallets repeating the same three-step sequence within minutes Live stream One shared action means nothing: everyone calls the same contract
Thin history Few distinct counterparties over the baseline window Hourly history (Foundational API) Single-purpose wallets are legitimate for some users

How the detector works

The pipeline has five stages, each a small file with one job:

Stage What it does File
Ingest Streams every transaction touching the watched contracts on Base stream.ts
Live Keeps per-wallet live features: activity this hour, shared action sequences signals.ts
History Looks up each new wallet once: age, first funder, hourly baseline history.ts, baseline.ts
Score Combines the signals into one risk score in [0, 1] with reasons: allow, review or deny score.ts, detector.ts
Act Signs an expiring EIP-712 attestation for allowed wallets; the reward contract checks it attest.ts, index.ts

Only the last step touches the chain, and only to verify one signature, so the expensive work (streaming, state, history lookups) stays off-chain.

Set up the project

You need Node.js 22 or later (it has a built-in WebSocket, which the SDK uses) and a GoldRush API key. To sign attestations you also need an oracle key: a fresh wallet used only for signing, which never holds funds.

mkdir base-sybil-detector && cd base-sybil-detectornpm init -y && npm pkg set type=modulenpm install @covalenthq/client-sdk ethersnpm install --save-dev tsx typescript @types/node

Create .env. WATCH_ADDRESSES is your campaign or reward contract: everyone who takes part sends it a transaction, so it's the one address you need to stream.

GOLDRUSH_API_KEY=your_goldrush_keyWATCH_ADDRESSES=0xYourCampaignContractIGNORE_FUNDERS=            # exchange and bridge hot wallets you have verified, comma-separatedORACLE_PRIVATE_KEY=        # leave empty to log decisions without signingREWARD_CONTRACT=0xYourRewardContract

Every setting lives in src/config.ts. The defaults are a cautious starting point, not tuned values:

// Every setting in one place, read from .env. The defaults are a cautious starting point, not tuned values.const env = (name: string, fallback?: string) => {    const value = process.env[name] ?? fallback;    if (value === undefined) throw new Error(`Set ${name} in .env`);    return value;}; export const CONFIG = {    apiKey: env("GOLDRUSH_API_KEY"),    // Addresses to stream: your campaign or reward contract(s). Each participant is the other side of a transaction.    watch: env("WATCH_ADDRESSES")        .split(",")        .map((a) => a.trim().toLowerCase())        .filter(Boolean),    baselineDays: Number(env("BASELINE_DAYS", "30")), // history used for each wallet's baseline    minWalletAgeDays: Number(env("MIN_WALLET_AGE_DAYS", "7")), // younger wallets score as fresh    // Exchange and bridge hot wallets fund thousands of real users: list the ones you see so a shared funder    // there doesn't count as a cluster.    ignoreFunders: env("IGNORE_FUNDERS", "")        .split(",")        .map((a) => a.trim().toLowerCase())        .filter(Boolean),    clusterLimit: Number(env("CLUSTER_LIMIT", "5")), // wallets from one funder before the cluster signal maxes out    allowBelow: Number(env("ALLOW_BELOW", "0.3")), // risk under this: attest    denyAbove: Number(env("DENY_ABOVE", "0.7")), // risk at or over this: deny; in between: human review    attestPerFunder: Number(env("ATTEST_PER_FUNDER", "3")), // rate limit: attestations per funding cluster    oracleKey: env("ORACLE_PRIVATE_KEY", ""), // signs attestations; leave empty to only log decisions    rewardContract: env("REWARD_CONTRACT", "0x0000000000000000000000000000000000000000"),    campaignId: BigInt(env("CAMPAIGN_ID", "1")),};

Stream wallet activity on Base

The Wallet Activity stream pushes every transaction that touches the addresses you give it, with the stream's decoded type (transfer, swap, approval and so on) and the raw event logs. It's in beta and costs 1 per minute. The SDK wraps it as StreamingService.subscribeToWalletActivity and calls your next handler with an array of transactions.

Save this as src/stream.ts:

import { CONFIG } from "./config";import { GoldRushClient, StreamingChain, type WalletActivityStreamResponse } from "@covalenthq/client-sdk"; export type WalletTx = WalletActivityStreamResponse; // The SDK types each message as an array of transactions; accept a lone transaction too, so a change in// payload shape can't silently drop events.export function toTxList(payload: WalletTx[] | WalletTx | null | undefined): WalletTx[] {    if (Array.isArray(payload)) return payload;    return payload?.tx_hash ? [payload] : [];} // Stream every transaction that touches the watched addresses on Base. Returns a function that shuts down cleanly.export function startWalletStream(onTx: (tx: WalletTx) => void) {    const client = new GoldRushClient(        CONFIG.apiKey,        {},        {            onOpened: () => console.log("[stream] connected"),            onClosed: () => console.log("[stream] closed"),            onError: (err) => console.error("[stream] error", err),        }    );    const seen = new Set<string>(); // a transaction touching two watched addresses can arrive twice    const unsubscribe = client.StreamingService.subscribeToWalletActivity(        { chain_name: StreamingChain.BASE_MAINNET, wallet_addresses: CONFIG.watch },        {            next: (payload) => {                for (const tx of toTxList(payload)) {                    if (!tx.successful || seen.has(tx.tx_hash)) continue;                    seen.add(tx.tx_hash);                    if (seen.size > 50_000) seen.clear();                    onTx(tx);                }            },            error: (err) => console.error("[stream] subscription error", err),            complete: () => console.log("[stream] completed"),        }    );    return async () => {        unsubscribe();        await client.StreamingService.disconnect();    };}

Three details matter here:

  • Normalise the payload. toTxList accepts the array the SDK types promise and a lone transaction as well, so a change in payload shape shows up as data, not as silently dropped events.
  • Skip failed and repeated transactions. A reverted transaction did nothing, and a transaction that touches two watched addresses can arrive twice.
  • Shut down cleanly. The returned function unsubscribes and closes the WebSocket, so a restart doesn't leave a subscription running (and billing) in the background.

Before your campaign is live, check the connection against a busy Base contract such as USDC (0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) or WETH (0x4200000000000000000000000000000000000006) with this one-minute script, src/smoke.ts. Don't point the full detector at them: every new sender would trigger two paid history lookups.

import { startWalletStream } from "./stream"; // Connection check only: prints each transaction for one minute and makes no history lookups.const stop = startWalletStream((tx) =>    console.log(tx.block_signed_at, tx.decoded_type, tx.from_address, "->", tx.to_address, tx.tx_hash));setTimeout(async () => {    await stop();    process.exit(0);}, 60_000);
WATCH_ADDRESSES=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 npx tsx --env-file=.env src/smoke.ts

Turn transactions into live features

src/signals.ts keeps a little state per participant: the times of its recent transactions and its last ten actions. An action's fingerprint is what was done without who did it: the contract called, the stream's decoded type and the events emitted. Time comes from block_signed_at, not the clock, so replaying a recorded stream gives the same features.

import type { WalletTx } from "./stream"; const WINDOW_MS = 5 * 60_000; // cohort window: wallets repeating the same sequence within 5 minutesconst HOUR_MS = 60 * 60_000; // What a wallet did, without who did it: the contract it called, the stream's decoded type and the events it// emitted. Two wallets doing the same thing get the same fingerprint.export function fingerprint(tx: WalletTx): string {    const events = (tx.logs ?? []).map((l) => `${l.emitter_address.toLowerCase()}:${l.topics[0] ?? ""}`).join(",");    return `${tx.to_address?.toLowerCase()}|${tx.decoded_type ?? ""}|${events}`;} export type Live = { txLastHour: number; txLast5Min: number; distinctActions: number; cohortSize: number }; type WalletState = { times: number[]; actions: string[] };const wallets = new Map<string, WalletState>();const sequences = new Map<string, Map<string, number>>(); // sequence key -> wallet -> last seen (ms) // Update one participant's live state and return its real-time features. Time comes from the block, not the// clock, so replaying recorded payloads gives the same answers.export function observe(wallet: string, tx: WalletTx): Live {    const now = Date.parse(tx.block_signed_at);    const s = wallets.get(wallet) ?? { times: [], actions: [] };    wallets.set(wallet, s);    s.times = [...s.times.filter((t) => now - t < HOUR_MS), now];    s.actions = [...s.actions, fingerprint(tx)].slice(-10);     // Everyone in a campaign calls the same contract, so one shared action means nothing. A shared *sequence* of    // the last three actions, repeated by many wallets within minutes, is what scripts leave behind.    const key = s.actions.slice(-3).join(" > ");    const cohort = sequences.get(key) ?? new Map<string, number>();    sequences.set(key, cohort);    cohort.set(wallet, now);    for (const [w, t] of cohort) if (now - t > WINDOW_MS) cohort.delete(w);     return {        txLastHour: s.times.length,        txLast5Min: s.times.filter((t) => now - t < WINDOW_MS).length,        distinctActions: new Set(s.actions).size,        cohortSize: s.actions.length >= 3 ? cohort.size : 1,    };}

The cohort signal deserves a word. In a campaign, every participant calls the same contract, so a shared single action is expected. A shared sequence of three actions, repeated by many wallets within five minutes, is the trace a script leaves. It is still weak on its own (a popular tutorial produces the same sequence), which is why it is one weighted signal among five.

Backfill baselines from history

The live stream tells you what a wallet is doing now. To know whether that's unusual, you need what it normally does. For each new participant the detector makes two Foundational API lookups on base-mainnet, once, and caches the result:

Each hour of the window becomes one bucket with three features: transaction count, distinct counterparties and USD value sent. Hours with no activity count as zeros, so the baseline reflects how often the wallet is actually active. Save this as src/history.ts:

import { CONFIG } from "./config";import { GoldRushClient } from "@covalenthq/client-sdk"; const client = new GoldRushClient(CONFIG.apiKey); export type Funding = { firstSeen: Date | null; funder: string | null }; // Wallet age and first funder, from the wallet's earliest Base transactions.export async function getFunding(wallet: string): Promise<Funding> {    const res = await client.TransactionService.getEarliestTransactionsForAddress("base-mainnet", wallet, {        noLogs: true,    });    if (res.error) throw new Error(res.error_message ?? "GoldRush request failed");    const txs = (res.data?.items ?? [])        .filter((tx) => tx.block_signed_at)        .sort((a, b) => a.block_signed_at!.getTime() - b.block_signed_at!.getTime());    const firstIn = txs.find((tx) => tx.to_address?.toLowerCase() === wallet && (tx.value ?? 0n) > 0n);    return { firstSeen: txs[0]?.block_signed_at ?? null, funder: firstIn?.from_address?.toLowerCase() ?? null };} export type HourBucket = { txCount: number; counterparties: number; valueOutUsd: number };export type History = { hours: HourBucket[]; counterparties: number }; // The wallet's last `days` of Base history, bucketed by hour. Hours with no activity count as zeros, so the// baseline reflects how often the wallet is actually active.export async function getHistory(wallet: string, days = CONFIG.baselineDays): Promise<History> {    const hour = (t: number) => Math.floor(t / 3_600_000);    const now = Date.now();    const cutoff = now - days * 86_400_000;    const buckets = new Map<number, { txCount: number; peers: Set<string>; valueOutUsd: number }>();    const allPeers = new Set<string>();     // Newest first (the default order), so stop at the first transaction older than the window: you pay for    // the items you fetch.    scan: for await (const page of client.TransactionService.getAllTransactionsForAddress("base-mainnet", wallet, {        quoteCurrency: "USD",        noLogs: true,    })) {        if (page.error) throw new Error(page.error_message ?? "GoldRush request failed");        for (const tx of page.data?.items ?? []) {            const t = tx.block_signed_at?.getTime();            if (!t) continue;            if (t < cutoff) break scan;            const b = buckets.get(hour(t)) ?? { txCount: 0, peers: new Set<string>(), valueOutUsd: 0 };            buckets.set(hour(t), b);            const from = tx.from_address?.toLowerCase();            const other = from === wallet ? tx.to_address?.toLowerCase() : from;            b.txCount += 1;            if (other) {                b.peers.add(other);                allPeers.add(other);            }            if (from === wallet) b.valueOutUsd += tx.value_quote ?? 0;        }    }     const hours: HourBucket[] = [];    for (let h = hour(cutoff); h <= hour(now); h++) {        const b = buckets.get(h);        hours.push({ txCount: b?.txCount ?? 0, counterparties: b?.peers.size ?? 0, valueOutUsd: b?.valueOutUsd ?? 0 });    }    return { hours, counterparties: allPeers.size };}

To compare a live hour with the baseline, src/baseline.ts uses a robust z-score: the distance from the median in units of the scaled median absolute deviation (MAD), z = (x − median) / (1.4826 × MAD). Unlike a mean and standard deviation, one past burst doesn't inflate the baseline and hide the next one. The scale never drops below 1, so a quiet wallet (median 0, MAD 0) measures a burst in transactions instead of dividing by zero:

import type { History } from "./history"; const median = (xs: number[]) => {    if (!xs.length) return 0;    const s = [...xs].sort((a, b) => a - b);    const m = Math.floor(s.length / 2);    return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;}; // Median and scaled median absolute deviation: unlike mean and standard deviation, one past burst doesn't// inflate the baseline and hide the next one. The scale never drops below 1, so a quiet wallet (median 0,// MAD 0) measures a burst in transactions rather than dividing by zero.export type Stat = { median: number; scale: number };export function robust(xs: number[]): Stat {    const m = median(xs);    return { median: m, scale: Math.max(1.4826 * median(xs.map((x) => Math.abs(x - m))), 1) };} export const robustZ = (x: number, s: Stat) => (x - s.median) / s.scale; export type Baseline = {    txPerHour: Stat;    peersPerHour: Stat;    valueOutUsdPerHour: Stat;    counterparties: number;    activeHours: number;}; export function toBaseline(h: History): Baseline {    return {        txPerHour: robust(h.hours.map((b) => b.txCount)),        peersPerHour: robust(h.hours.map((b) => b.counterparties)),        valueOutUsdPerHour: robust(h.hours.map((b) => b.valueOutUsd)),        counterparties: h.counterparties,        activeHours: h.hours.filter((b) => b.txCount > 0).length,    };}

The score below uses the transaction-count baseline and the counterparty total. The per-hour counterparty and value-out baselines are there for your own features, and for the exploit signals at the end of this guide.

One caveat: the stream only sees transactions that touch your watched contracts, while the baseline counts all of the wallet's Base activity. So the live count is a lower bound and the burst z-score understates, never overstates, how unusual the hour is.

Score each wallet

src/score.ts scales each signal to [0, 1], weights it and sums them into one risk score, also in [0, 1]. Any signal at half strength or more is listed as a reason. Below ALLOW_BELOW the wallet is allowed, at or above DENY_ABOVE it's denied, and anything in between goes to human review.

import type { Baseline } from "./baseline";import { robustZ } from "./baseline";import { CONFIG } from "./config";import type { Funding } from "./history";import type { Live } from "./signals"; export type Decision = "allow" | "review" | "deny";export type Verdict = { wallet: string; funder: string | null; risk: number; decision: Decision; reasons: string[] }; const clamp = (x: number) => Math.min(Math.max(x, 0), 1);const short = (a: string) => `${a.slice(0, 6)}…${a.slice(-4)}`; // Starting weights, not tuned values: re-fit them on wallets your reviewers have labelled.const WEIGHTS = { fresh: 0.2, cluster: 0.3, burst: 0.2, cohort: 0.2, thinHistory: 0.1 }; // One explainable risk score in [0, 1] from five signals, each also scaled to [0, 1].export function scoreWallet(    wallet: string,    live: Live,    funding: Funding,    clusterSize: number,    base: Baseline,    now: number): Verdict {    const ageDays = funding.firstSeen ? (now - funding.firstSeen.getTime()) / 86_400_000 : 0;    const burstZ = robustZ(live.txLastHour, base.txPerHour); // the stream sees a subset, so this understates    const signals: [keyof typeof WEIGHTS, number, string][] = [        ["fresh", clamp(1 - ageDays / CONFIG.minWalletAgeDays), `wallet first active ${ageDays.toFixed(1)} days ago`],        [            "cluster",            clamp((clusterSize - 1) / (CONFIG.clusterLimit - 1)),            `funder ${funding.funder ? short(funding.funder) : "unknown"} funded ${clusterSize} wallets seen here`,        ],        ["burst", clamp(burstZ / 6), `${live.txLastHour} tx in the last hour, robust z ${burstZ.toFixed(1)}`],        ["cohort", clamp((live.cohortSize - 1) / 9), `same 3-step sequence as ${live.cohortSize - 1} other wallets`],        ["thinHistory", clamp(1 - base.counterparties / 5), `${base.counterparties} counterparties in history`],    ];    const risk = signals.reduce((sum, [name, value]) => sum + WEIGHTS[name] * value, 0);    const reasons = signals.filter(([, value]) => value >= 0.5).map(([, , why]) => why);    const decision: Decision = risk >= CONFIG.denyAbove ? "deny" : risk >= CONFIG.allowBelow ? "review" : "allow";    return { wallet, funder: funding.funder, risk: Number(risk.toFixed(3)), decision, reasons };}

The weights are a starting point, not a tuned model. Once reviewers have labelled a few hundred wallets, fit the weights (a logistic regression on the five signal values is enough) and move the thresholds to the false positive rate you can accept.

src/detector.ts runs the pipeline for one transaction. The participant is the side of the transaction that isn't a watched address. History lookups are passed in rather than imported, so a test can replay recorded stream payloads with stubbed lookups and no API key:

import { toBaseline, type Baseline } from "./baseline";import { CONFIG } from "./config";import type { Funding, History } from "./history";import { scoreWallet, type Verdict } from "./score";import { observe } from "./signals";import type { WalletTx } from "./stream"; type Deps = {    getFunding: (wallet: string) => Promise<Funding>;    getHistory: (wallet: string) => Promise<History>;    onVerdict: (v: Verdict, tx: WalletTx) => Promise<void> | void;}; // The pipeline for one transaction: who took part, what they did live, what their history says, one verdict.// History lookups are injected, so tests can replay recorded payloads without an API key.export function createDetector({ getFunding, getHistory, onVerdict }: Deps) {    const watch = new Set(CONFIG.watch);    const ignored = new Set(CONFIG.ignoreFunders);    const funding = new Map<string, Promise<Funding>>(); // one lookup per wallet, cached    const baselines = new Map<string, Promise<Baseline>>();    const funded = new Map<string, Set<string>>(); // funder -> participants it funded     return async function handle(tx: WalletTx) {        const from = tx.from_address?.toLowerCase();        const wallet = watch.has(from) ? tx.to_address?.toLowerCase() : from;        if (!wallet || watch.has(wallet)) return;         const live = observe(wallet, tx);        if (!funding.has(wallet)) funding.set(wallet, getFunding(wallet));        if (!baselines.has(wallet)) baselines.set(wallet, getHistory(wallet).then(toBaseline));        const [found, base] = await Promise.all([funding.get(wallet)!, baselines.get(wallet)!]);        const f = found.funder && ignored.has(found.funder) ? { ...found, funder: null } : found;         const cluster = f.funder ? (funded.get(f.funder) ?? new Set<string>()) : new Set<string>();        if (f.funder) funded.set(f.funder, cluster.add(wallet));        const verdict = scoreWallet(wallet, live, f, Math.max(cluster.size, 1), base, Date.parse(tx.block_signed_at));        await onVerdict(verdict, tx);    };}

Run the detector

src/index.ts wires the stream to the detector, logs every verdict to verdicts.jsonl and signs an attestation for each allowed wallet, at most ATTEST_PER_FUNDER per funding cluster:

import { attest } from "./attest";import { CONFIG } from "./config";import { createDetector } from "./detector";import { getFunding, getHistory } from "./history";import { startWalletStream } from "./stream";import { appendFileSync } from "node:fs"; const attested = new Set<string>();const perFunder = new Map<string, number>(); const handle = createDetector({    getFunding,    getHistory,    onVerdict: async (v, tx) => {        console.log(`[${v.decision}] ${v.wallet} risk=${v.risk} ${v.reasons.join("; ")}`);        appendFileSync("verdicts.jsonl", JSON.stringify({ ...v, tx: tx.tx_hash, at: tx.block_signed_at }) + "\n");        if (v.decision !== "allow" || attested.has(v.wallet)) return;         // Rate limit per funding cluster: one funder can't collect more than ATTEST_PER_FUNDER attestations.        const used = v.funder ? (perFunder.get(v.funder) ?? 0) : 0;        if (v.funder && used >= CONFIG.attestPerFunder) return console.log(`[hold] ${v.wallet}: cluster limit`);         const att = await attest(v.wallet, v.risk);        if (!att) return; // no ORACLE_PRIVATE_KEY: decisions only        attested.add(v.wallet);        if (v.funder) perFunder.set(v.funder, used + 1);        appendFileSync(            "attestations.jsonl",            JSON.stringify(att, (_, x) => (typeof x === "bigint" ? String(x) : x)) + "\n"        );    },}); console.log(`[sybil] watching ${CONFIG.watch.length} address(es) on Base`);const stop = startWalletStream((tx) => handle(tx).catch((err) => console.error("[sybil] skipped:", err.message))); process.on("SIGINT", async () => {    await stop();    process.exit(0);});
npx tsx --env-file=.env src/index.ts

Each transaction prints one line with the decision, the score and the reasons. Replaying eight synthetic wallets funded by one address, each repeating the same deposit, stake and claim sequence seconds apart, gives:

[deny] 0xb000000000000000000000000000000000000007 risk=0.83 wallet first active 0.2 days ago; funder 0x4444…4444 funded 8 wallets seen here; 3 tx in the last hour, robust z 3.0; same 3-step sequence as 7 other wallets; 1 counterparties in history

while a wallet with a year of history and 40 counterparties scores 0.067 and is allowed.

Two costs to watch. The stream is billed by the minute while it's connected, and each new participant costs one earliest-transactions lookup and one history scan, billed per item returned. Lower BASELINE_DAYS if your participants are very active wallets.

Gate rewards with signed attestations

The scorer never pays anyone. For an allowed wallet it signs an EIP-712 attestation: this account, this campaign, this risk score, valid until this time. The wallet submits it to the reward contract, which checks it and pays. Save this as src/attest.ts:

import { CONFIG } from "./config";import { Wallet } from "ethers"; // EIP-712 domain and type the reward contract verifies. chainId 8453 is Base mainnet (84532 for Base Sepolia).const domain = { name: "SybilGatedRewards", version: "1", chainId: 8453, verifyingContract: CONFIG.rewardContract };const types = {    Eligibility: [        { name: "account", type: "address" },        { name: "campaignId", type: "uint256" },        { name: "riskBps", type: "uint16" },        { name: "expiry", type: "uint64" },    ],}; const oracle = CONFIG.oracleKey ? new Wallet(CONFIG.oracleKey) : null; // A signed, expiring statement that this wallet passed the scorer. It pays nothing by itself: the wallet submits// it to the reward contract, which checks the signer, the expiry and the risk ceiling.export async function attest(account: string, risk: number, ttlSeconds = 3600) {    if (!oracle) return null;    const value = {        account,        campaignId: CONFIG.campaignId,        riskBps: Math.round(risk * 10_000),        expiry: BigInt(Math.floor(Date.now() / 1000) + ttlSeconds),    };    const signature = await oracle.signTypedData(domain, types, value);    return { ...value, signature };}

The reward contract below (Solidity 0.8.24 or later, OpenZeppelin Contracts 5) stores only the oracle's address. claim checks the expiry, the risk ceiling and that the signature was made by the oracle for msg.sender, so an attestation can't be used by another wallet. A claim then waits out a delay before anyone can release it, and during the delay the owner can void a claim that review or a later score flags:

// SPDX-License-Identifier: MITpragma solidity ^0.8.24; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; /// Pays a fixed reward to wallets the off-chain scorer attested, after a delay in which a reviewer can void a claim.contract SybilGatedRewards is EIP712, Ownable {    using SafeERC20 for IERC20;     bytes32 private constant ELIGIBILITY_TYPEHASH =        keccak256("Eligibility(address account,uint256 campaignId,uint16 riskBps,uint64 expiry)");     enum Status { None, Pending, Voided, Paid }     IERC20 public immutable token;    uint256 public immutable campaignId;    uint256 public immutable reward;    uint64 public immutable delay;    address public oracle;    uint16 public maxRiskBps;     mapping(address => Status) public status;    mapping(address => uint64) public unlockAt;     error Expired();    error RiskTooHigh();    error AlreadyClaimed();    error BadSignature();    error NotReleasable();     event Claimed(address indexed account, uint16 riskBps, uint64 unlockAt);    event Voided(address indexed account);    event Paid(address indexed account, uint256 amount);     constructor(IERC20 token_, address oracle_, uint256 campaignId_, uint256 reward_, uint16 maxRiskBps_, uint64 delay_)        EIP712("SybilGatedRewards", "1")        Ownable(msg.sender)    {        token = token_;        oracle = oracle_;        campaignId = campaignId_;        reward = reward_;        maxRiskBps = maxRiskBps_;        delay = delay_;    }     /// The caller submits its own attestation: it is bound to msg.sender, so it can't be used by another wallet.    function claim(uint16 riskBps, uint64 expiry, bytes calldata signature) external {        if (block.timestamp > expiry) revert Expired();        if (riskBps > maxRiskBps) revert RiskTooHigh();        if (status[msg.sender] != Status.None) revert AlreadyClaimed();        bytes32 digest = _hashTypedDataV4(            keccak256(abi.encode(ELIGIBILITY_TYPEHASH, msg.sender, campaignId, riskBps, expiry))        );        if (ECDSA.recover(digest, signature) != oracle) revert BadSignature();        status[msg.sender] = Status.Pending;        unlockAt[msg.sender] = uint64(block.timestamp) + delay;        emit Claimed(msg.sender, riskBps, unlockAt[msg.sender]);    }     /// During the delay, a reviewer can void a claim the scorer flags later. A voided wallet can't claim again.    function voidClaim(address account) external onlyOwner {        if (status[account] != Status.Pending) revert NotReleasable();        status[account] = Status.Voided;        emit Voided(account);    }     /// Anyone can release a claim once its delay has passed, so a relayer can batch payouts.    function release(address account) external {        if (status[account] != Status.Pending || block.timestamp < unlockAt[account]) revert NotReleasable();        status[account] = Status.Paid;        token.safeTransfer(account, reward);        emit Paid(account, reward);    }     function setOracle(address oracle_) external onlyOwner {        oracle = oracle_;    }     function setMaxRiskBps(uint16 maxRiskBps_) external onlyOwner {        maxRiskBps = maxRiskBps_;    }}

Deploy it on Base Sepolia (chain ID 84532) first, with chainId in attest.ts set to match, then on Base mainnet (8453). release is open to anyone, so a relayer can pay out many claims in one run once their delays pass instead of each user paying gas to withdraw.

Designing Sybil-resistant incentives

Detection helps most when the incentive is designed to make farming expensive. The rules that matter:

  • Gate eligibility on the score. Pay only wallets with a current attestation below your risk ceiling, as the contract above does, instead of anyone who calls the contract.
  • Require provenance. A minimum wallet age and some history across different counterparties forces the attacker to spend time, which is the cost cheap gas doesn't remove.
  • Rate-limit per cluster, not per wallet. Cap the rewards one funding cluster can collect (ATTEST_PER_FUNDER), so a hundred wallets from one funder earn what a few do.
  • Delay or vest payouts. A delay between claim and payment gives review time to catch what the live score missed. Vesting over weeks also rewards the users who stay.
  • Pay attestations, not transactions. The scorer signs; the contract verifies and pays. Rotating the oracle key or tightening the ceiling needs no contract migration.
  • Grade rewards by risk. Instead of a binary allow or deny, scale the reward by the score, so a slightly suspicious wallet gets less rather than nothing.
  • Make achievements non-transferable. Badges and reputation as soulbound (non-transferable) tokens can't be consolidated into one master wallet and sold.

And the practices that keep it working:

  • Behaviour first, friction rarely. Onchain behaviour is private and scales. Keep identity checks or proof of personhood for the few cases that need high assurance, such as a critical vote, and as an appeal route.
  • Review the middle band. Send borderline scores to people, not to an automatic ban, and feed their labels back into the weights.
  • Adapt the heuristics. Farmers add random delays and noise transactions to dodge fixed rules. Re-fit on new labels regularly.
  • Reward contribution, not volume. Long-held liquidity, governance participation and other actions that are costly to fake attract far fewer farms than raw transaction counts.

Extend the detector to exploit signals

The same pipeline (stream, live state, baseline, explainable tags) also watches your own protocol for the onchain symptoms that precede or accompany an exploit. Point a second watch list at your treasury, multisig, pools and admin-controlled contracts, and tag:

  • Ownership and admin changes. OwnershipTransferred, AdminChanged or Upgraded emitted by a watched contract: an owner, proxy admin or implementation changed.
  • Approval bursts. Several Approval events from a watched address in a short window, the pattern of a compromised key or a malicious signature request.
  • Liquidity drains and transfer bursts. Many Transfer events out of a watched pool or treasury in a short window.

The sequence matters as much as each event: an admin change, then an upgrade, then outflows is a classic exploit shape. Save this as src/exploit.ts:

import type { WalletTx } from "./stream";import { id } from "ethers"; // topic0 of the events that mark the usual exploit symptoms.const TOPIC = {    ownership: id("OwnershipTransferred(address,address)"),    admin: id("AdminChanged(address,address)"),    upgrade: id("Upgraded(address)"),    approval: id("Approval(address,address,uint256)"),    transfer: id("Transfer(address,address,uint256)"),};const WINDOW_MS = 10 * 60_000;const BURST = { approval: 5, outflow: 20 }; // per watched address per 10 minutes: tune to its baseline const topicAddress = (topic?: string) => (topic ? `0x${topic.slice(26)}`.toLowerCase() : "");const recent = new Map<string, number[]>(); // "<kind>:<address>" -> event times function bump(key: string, now: number) {    const times = [...(recent.get(key) ?? []).filter((t) => now - t < WINDOW_MS), now];    recent.set(key, times);    return times.length;} // Tags for one transaction touching a watched treasury, multisig, pool or protocol contract.export function exploitTags(tx: WalletTx, watch: Set<string>): string[] {    const now = Date.parse(tx.block_signed_at);    const tags = new Set<string>();    for (const log of tx.logs ?? []) {        const [topic0, a, b] = log.topics;        const emitter = log.emitter_address.toLowerCase();        if ([TOPIC.ownership, TOPIC.admin, TOPIC.upgrade].includes(topic0) && watch.has(emitter)) {            tags.add("admin_change"); // owner, proxy admin or implementation changed        }        if (topic0 === TOPIC.approval && watch.has(topicAddress(a))) {            if (bump(`approval:${topicAddress(a)}`, now) >= BURST.approval) tags.add("approval_burst");        }        if (topic0 === TOPIC.transfer && watch.has(topicAddress(a)) && topicAddress(b) !== topicAddress(a)) {            if (bump(`outflow:${topicAddress(a)}`, now) >= BURST.outflow) tags.add("outflow_burst"); // drain or transfer burst        }    }    return [...tags];}

The fixed burst thresholds are placeholders. Replace them with a robust z-score against the watched address's own hourly baseline from history.ts (valueOutUsdPerHour and txPerHour), exactly as the Sybil scorer does for participants.

Measure whether it works

Track two sides: how well it stops farms, and whether real users stay.

  • False positive rate. The share of reviewed, genuine wallets the detector flagged. Keep it low above all.
  • Leakage. The share of wallets later found to be Sybils that received a reward.
  • Attacker cost. What a farm has to spend in gas, time and wallet history per reward it gets. Every rule above should raise it.
  • Retention of attested users. Whether wallets that received an attestation are still active weeks later. If they aren't, the campaign is paying for activity, not users.
  • Spend efficiency. The share of rewards that went to wallets that were never flagged.

Limitations, privacy and appeals

  • Heuristics can be evaded. Real-time rules catch fast, careless farms. Patient operators who age wallets and vary their scripts need slower graph analysis over weeks of history, run alongside this detector.
  • Speed costs context. A live score sees a wallet's last hour and its history summary, not its whole relationship graph.
  • Only public data. The detector reads public, pseudonymous onchain activity and stores a score against an address. It collects no personal information.
  • Give flagged users a way back. Publish how scoring works in general terms, re-score flagged wallets after a while, and offer an appeal: human review, or an optional proof of personhood for users who want it.

Troubleshooting

  • Connected but no events. Check WATCH_ADDRESSES is the contract participants call, on Base mainnet. Run src/smoke.ts against USDC to confirm the stream itself works.
  • Set GOLDRUSH_API_KEY in .env. Run from the project root with --env-file=.env.
  • Every wallet is reviewed or denied. Your campaign may genuinely attract new wallets. Lower the fresh weight or MIN_WALLET_AGE_DAYS, and add the exchanges and bridges your users fund from to IGNORE_FUNDERS.
  • History lookups are slow or expensive. Lower BASELINE_DAYS. Lookups are cached per wallet for the life of the process.
  • No attestations written. ORACLE_PRIVATE_KEY is empty, or the wallet hit its cluster's ATTEST_PER_FUNDER limit (look for [hold] lines).

Frequently asked questions

What is a Sybil attack in crypto?

One person or group controlling many wallets to look like many independent users, to collect rewards, airdrops or votes meant for individuals. On low-fee chains like Base the wallets cost almost nothing to create and use, so farming per-wallet incentives is cheap.

How do you detect Sybil wallets in real time?

Stream the transactions that touch your campaign contract, keep live features per participating wallet, and compare them with that wallet's history. The strongest evidence is several signals lining up across a group: a shared funder, the same action sequence minutes apart, wallets only hours old and a burst far above their normal activity.

Why not run graph analysis after the campaign ends?

Run it too, but not instead. Batch analysis finds patient, well-hidden clusters; it is too slow to stop a farm that funds, qualifies and withdraws in minutes. A real-time score stops the fast farms before payout, and a payout delay gives the slower analysis time to void what the live score missed.

Does the detector need any personal data?

No. It uses only public onchain activity on Base from GoldRush, and stores a risk score against a pseudonymous address. Identity checks are optional, for appeals or high-stakes cases.

How does the reward contract trust the off-chain score?

The scorer signs an EIP-712 attestation with a dedicated oracle key: the account, the campaign, the risk score and an expiry. The contract stores the oracle's address and checks the signature, the expiry and the risk ceiling before it records a claim, so it never has to trust the transaction that delivers it.

Can I use the same pipeline to detect DeFi exploits?

Yes. Watch your treasury, multisig, pools and admin-controlled contracts instead of a campaign contract, and tag ownership or admin changes, approval bursts and transfer bursts out of watched addresses, scored against each address's own baseline.

Can I stream Base wallet activity with GoldRush today?

The GoldRush SDK lists Base for the Wallet Activity stream, which is in beta, and Hyperliquid streaming is live today. The Streaming API's multi-chain reference returns in January 2027; ask GoldRush support to confirm Base streaming for your key.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.