---
name: megapot-claim-referral-fees
description: Claim accumulated USDC referral fees from Megapot via Jackpot.claimReferralFees. Single-call, no arguments, claims full accrued balance.
---

# Claim Megapot Referral Fees

## What This Does

Reads your accumulated referral fee balance from `Jackpot.referralFees(address)` and, if greater than zero, calls `Jackpot.claimReferralFees` to transfer the full accrued USDC balance to your wallet in a single transaction.

## Prerequisites

- A wallet with a private key (EOA) connected to Base mainnet (chain ID 8453)
- Sufficient ETH for gas
- Accrued referral fees in the Jackpot contract (read via `referralFees(address)`)
- `viem` installed (`npm install viem`)

## Addresses

Base mainnet (chain ID 8453):

```ts
const JACKPOT_ADDRESS  = '0x3bAe643002069dBCbcd62B1A4eb4C4A397d042a2' as const;
```

Base Sepolia testnet (chain ID 84532):

```ts
const JACKPOT_ADDRESS  = '0x465dA3c859f193A3807386387bEE941B2A4c3279' as const;
```

> Base mainnet public RPC: `https://mainnet.base.org` (rate-limited; use [Alchemy](https://www.alchemy.com/) or [QuickNode](https://www.quicknode.com/) for production).

## ABI

Only the fragments needed for this task:

```ts
import { parseAbi } from 'viem';

const abi = parseAbi([
  // --- Jackpot reads ---
  "function referralFees(address) view returns (uint256)",
  "function currentDrawingId() view returns (uint256)",
  "function getDrawingState(uint256 _drawingId) view returns ((uint256 prizePool, uint256 ticketPrice, uint256 edgePerTicket, uint256 referralWinShare, uint256 referralFee, uint256 globalTicketsBought, uint256 lpEarnings, uint256 drawingTime, uint256 winningTicket, uint8 ballMax, uint8 bonusballMax, address payoutCalculator, bool jackpotLock))",

  // --- Jackpot write ---
  "function claimReferralFees()",

  // --- Jackpot events ---
  "event ReferralFeesClaimed(address indexed userAddress, uint256 amount)",

  // --- Jackpot errors ---
  "error NoReferralFeesToClaim()",
]);
```

## How Referral Fees Accrue

Referrers earn from two sources, both set at the protocol level per drawing:

### 1. Purchase fee — fraction of each ticket's price

When a user buys tickets with your address in the `_referrers` array, you receive a share of the ticket price:

```
your_fee = ticketPrice * referralFee * your_split_weight
```

- `referralFee` is readable from `getDrawingState(drawingId).referralFee` (1e18 scale; e.g. `0.05e18` = 5%)
- `your_split_weight` is the weight assigned to your address in the `_referralSplit` array (1e18 scale)

Example: ticket price = 1 USDC, referralFee = 5% (`0.05e18`), you're the sole referrer with weight `1e18` (100%) -> you earn 0.05 USDC per ticket sold.

### 2. Win share — fraction of referred users' winnings

When a ticket you referred wins and the user claims, you receive a share of their payout:

```
your_win_share = claimedWinnings * referralWinShare * your_split_weight
```

- `referralWinShare` is readable from `getDrawingState(drawingId).referralWinShare` (1e18 scale; e.g. `0.10e18` = 10%)

Both fees accumulate automatically in the Jackpot contract under `referralFees(yourAddress)` and are claimed together via `claimReferralFees()`.

### Reading current rates

```ts
const drawingId = await publicClient.readContract({
  address: JACKPOT_ADDRESS, abi, functionName: 'currentDrawingId'
});
const state = await publicClient.readContract({
  address: JACKPOT_ADDRESS, abi, functionName: 'getDrawingState', args: [drawingId]
});
console.log('Purchase fee rate:', Number(state.referralFee) / 1e18 * 100, '%');
console.log('Win share rate:', Number(state.referralWinShare) / 1e18 * 100, '%');
```

Note: rates are set per drawing and may change between drawings. Query the current drawing for active rates.

## Recipe

### Setup

```ts
import {
  createPublicClient,
  createWalletClient,
  http,
  parseAbi,
} from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';

// --- PLACEHOLDERS: replace with your values ---
const PRIVATE_KEY = '0xYOUR_PRIVATE_KEY' as `0x${string}`;  // placeholder
const RPC_URL     = 'https://mainnet.base.org';               // or your own RPC URL

const JACKPOT_ADDRESS = '0x3bAe643002069dBCbcd62B1A4eb4C4A397d042a2' as const;

// For Base Sepolia testnet: replace `base` with `baseSepolia` from 'viem/chains',
// swap addresses to the testnet values above, and use https://sepolia.base.org as RPC.

const abi = parseAbi([
  "function referralFees(address) view returns (uint256)",
  "function currentDrawingId() view returns (uint256)",
  "function getDrawingState(uint256 _drawingId) view returns ((uint256 prizePool, uint256 ticketPrice, uint256 edgePerTicket, uint256 referralWinShare, uint256 referralFee, uint256 globalTicketsBought, uint256 lpEarnings, uint256 drawingTime, uint256 winningTicket, uint8 ballMax, uint8 bonusballMax, address payoutCalculator, bool jackpotLock))",
  "function claimReferralFees()",
  "event ReferralFeesClaimed(address indexed userAddress, uint256 amount)",
  "error NoReferralFeesToClaim()",
]);

const account = privateKeyToAccount(PRIVATE_KEY);

const publicClient = createPublicClient({
  chain: base,
  transport: http(RPC_URL),
});

const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http(RPC_URL),
});
```

### Step 1 — Check referral fee balance

```ts
const claimableBalance = await publicClient.readContract({
  address: JACKPOT_ADDRESS,
  abi,
  functionName: 'referralFees',
  args: [account.address],
});
// e.g. 5_000_000n — 5 USDC at 6 decimals

console.log('Claimable referral fees:', claimableBalance);

if (claimableBalance === 0n) {
  console.log('No referral fees to claim.');
  process.exit(0);
}
```

### Step 2 — Claim referral fees

```ts
const claimTx = await walletClient.writeContract({
  address: JACKPOT_ADDRESS,
  abi,
  functionName: 'claimReferralFees',
});

const receipt = await publicClient.waitForTransactionReceipt({ hash: claimTx });
console.log('Referral fees claimed, tx:', claimTx);
console.log('Gas used:', receipt.gasUsed);
```

## Parameters

| Parameter | Type | Description |
|---|---|---|
| (none) | - | `claimReferralFees` accepts no parameters; it claims the full accrued balance for `msg.sender`. |

## State-Changing Functions

| Function | Returns | Description |
|---|---|---|
| `claimReferralFees()` | - | Transfer the full balance of `referralFees[msg.sender]` to the caller in USDC. Emits `ReferralFeesClaimed`. |

### View Functions

| Function | Returns | Description |
|---|---|---|
| `referralFees(address)` | `uint256` | Balance of accrued referral fees (in USDC, 6 decimals) for the given address. |

## Common Errors

| Error | Cause |
|---|---|
| `NoReferralFeesToClaim()` | Your referral fee balance is zero. Generate referral fees by having other users purchase tickets via your referral link/scheme. |

## Related

- `megapot-buy-tickets` — buy 1–10 tickets with custom numbers
- `megapot-buy-random` — buy up to 10 random tickets (no number selection needed)
- `megapot-buy-bulk` — buy 11+ tickets with custom numbers (batch)
- `megapot-contracts-reference` — full address table and complete ABI for all 13 contracts
- `megapot-claim-winnings` — claim prize winnings after a drawing settles
