
Referral and affiliate trees are widely regarded as one of the strongest acquisition mechanisms in Web3 growth, GameFi, and community membership platforms.
But in a low-barrier or permissionless blockchain environment, a referral system built around “generate an invitation code → bind a wallet → issue tokens or points” can encounter industrial-scale scripted Sybil attacks and self-referential arbitrage loops within 24 hours of launch:
- Zero-cost address flooding drains the reward pool: An attacker scripts the creation of 10,000 temporary wallets, with wallet A inviting B, B inviting C, and so on. If tokens are airdropped at registration or binding, a few dollars of gas can drain the entire marketing budget in half an hour, leaving only disposable, inactive users in the metrics;
- Circular referral loops and unbounded recursion: In a multi-level payout topology without strict one-way assertions, an attacker can construct a cycle (A → B → C → A) for recursive arbitrage. When an order triggers upstream commission settlement, the cycle can trap processing in an infinite loop and crash the service with OOM, or repeatedly distribute rewards within the cycle until the pool is insolvent;
- Split-brain placement under concurrent registration: When thousands of new users enter the same KOL’s invitation code and sign on-chain in the same millisecond, missing atomic row locks and slot-occupancy checks at the branch root can place multiple children in the same referral slot. The tree becomes malformed, and the KOL loses the team-level rewards they should receive.
In production work on NOVA Membership, our commercial membership and referral system, we replaced this artificial-growth model. This article explains how DAG closure tables, branch locks for unlimited direct referrals versus ternary placement, real paid Card Mint purchases, and the on-chain EIP-712 CardRewardPermit authorization boundary combine into a Sybil-resistant referral engine.
The Referral Pipeline: From Relationship Binding to On-Chain Settlement

NOVA Membership divides referrals into four business layers: topology registration, payment-backed value, tiered commission simulation, and on-chain withdrawals with duplicate-claim protection:
+-----------------------------------------------------------------------------------+
| NOVA Membership Anti-Sybil Referral Pipeline |
+-----------------------------------------------------------------------------------+
| 1. Referral Binding and Strictly Acyclic Topology (DAG Closure Table) |
| - Persist edges: game_referral_edge (direct inviter and physical placement parent) |
| - Store every path: game_referral_closure (ancestor, descendant, depth) |
| - DAG Invariant: forbid A -> B -> A cycles and self-referrals |
| - Branch-lock concurrency: lockBranchRoot protects slot allocation (DIRECT vs SPILLOVER) |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| 2. Value-Anchored Payment Gate: Card Purchase Event |
| - Zero rewards for free registration: wallet registration or code binding issues no funds |
| - Require a real on-chain purchase: buyGloryCard / buyPremiumGloryCard (real USDC) |
| - Event-driven settlement: dispatch NORMAL_CARD_PURCHASED only after deposit confirmation |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| 3. Commission Rule Engine and Historical Snapshot Isolation |
| - RuleRewardExecutor: trace beneficiary paths upward through the closure (LEVEL_PATH) |
| - Double-entry accounting: ledger_transaction and ledger_entry record debits and credits |
| - Unique business index: game_reward_grant enforces (event_type, event_id, rule, user) |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| 4. Secure On-Chain Redemption (GameDApp.sol CardRewardPermit) |
| - Isolated prefunded pool: fundCardRewardPool sets the allocationCap hard limit |
| - EIP-712 typed signatures: backend signs permits with rewardClaimId and businessOrderId |
| - Dual replay protection: usedCardRewardOrder and usedCardRewardClaim atomically set true |
+-----------------------------------------------------------------------------------+
Architecture Comparison: Traditional Referrals vs. NOVA’s Anti-Sybil Design
| Dimension | Traditional Web2 / Simple Web3 Referrals | Naive Fully On-Chain Multi-Branch Tree | NOVA Membership Hybrid Defense |
|---|---|---|---|
| Sybil resistance | Very low (registration yields free funds) | Very low (scripted wallets drain the pool) | 100% immune (free registration earns nothing; real on-chain card purchase required) |
| Circular binding protection | Recursive queries can lock up on deep cycles | Extremely expensive gas, prone to OOM | game_referral_closure asserts a one-way acyclic structure at write time |
| Concurrent placement | No concurrency control; lost orders or overwritten slots | High friction from queued on-chain transactions | Branch row locks (lockBranchRoot) provide atomic placement in milliseconds |
| Network shape | Unlimited direct referrals only (can flatten the pyramid) | Fixed tree is difficult to upgrade | Two dynamically locked modes: unpaid unlimited direct referrals; paid ternary Spillover |
| Payout security | Centralized backend transfers without public evidence | Unbounded transfer loops can exhaust gas | Prefunded pool + unique EIP-712 order binding + incrementing Nonce for on-chain withdrawals |
Implementation 1: Closure Tables and Cycle Prevention
The simplest way to represent a tree or graph in a relational database is to store a parent_id in the user table. Querying 10 generations of ancestors or calculating referral earnings then requires a Recursive CTE or repeated database I/O. If an attacker introduces a cycle, recursive queries can run indefinitely and overwhelm database CPU.
1. Edge and Closure Tables (glory_game.sql)
NOVA Membership uses the classic graph-theory Closure Table approach: when a relationship is inserted, the depth relationships along its entire ancestor chain are materialized as flat rows:
-- Excerpt from nova-membership/backend/sql/glory_game.sql
-- 1. Physical edges: direct referrer and actual placement
CREATE TABLE IF NOT EXISTS game_referral_edge (
edge_id bigint NOT NULL AUTO_INCREMENT,
source_inviter_user_id bigint DEFAULT NULL, -- Actual business inviter
parent_user_id bigint DEFAULT NULL, -- Immediate parent in the topology (may differ from the inviter in ternary spillover mode)
child_user_id bigint NOT NULL, -- Newly joined user
slot_no tinyint unsigned DEFAULT NULL, -- Slot number (1 ~ 3)
source varchar(32) NOT NULL, -- DIRECT / SPILLOVER / DIRECT_UNLIMITED
created_time datetime(6) NOT NULL,
PRIMARY KEY (edge_id),
UNIQUE KEY uk_game_referral_child (child_user_id), -- Each person has exactly one placement parent!
UNIQUE KEY uk_game_referral_parent_slot (parent_user_id, slot_no), -- Every slot under a parent is strictly unique!
KEY idx_game_referral_source_inviter (source_inviter_user_id, created_time),
CONSTRAINT ck_game_referral_slot CHECK (
(source='VIRTUAL_ROOT' AND source_inviter_user_id IS NULL AND parent_user_id IS NULL AND slot_no IS NULL)
OR (source IN ('DIRECT','SPILLOVER') AND source_inviter_user_id IS NOT NULL AND parent_user_id IS NOT NULL AND slot_no BETWEEN 1 AND 3)
OR (source='DIRECT_UNLIMITED' AND source_inviter_user_id IS NOT NULL AND parent_user_id=source_inviter_user_id AND slot_no IS NULL)
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 2. Transitive closure: store all paths and depths between any two nodes as flat rows
CREATE TABLE IF NOT EXISTS game_referral_closure (
ancestor_user_id bigint NOT NULL, -- Ancestor node
descendant_user_id bigint NOT NULL, -- Descendant node
depth int unsigned NOT NULL, -- Distance (1 = direct referral, 2 = indirect referral...)
created_time datetime(6) NOT NULL,
PRIMARY KEY (ancestor_user_id, descendant_user_id),
KEY idx_game_referral_closure_descendant (descendant_user_id, depth, ancestor_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2. Atomic Writes and Closure Completion
When a new user registers through a referrer, a single transaction performs two operations:
- Insert the self-closure: Record
(newUserId, newUserId, 0); - Inherit ancestor closures: Select all ancestors of the placement parent in one query, pair them with
newUserId, increment each depth by 1, and batch-insert the results:
-- SQL for completing the closure
INSERT INTO game_referral_closure (ancestor_user_id, descendant_user_id, depth, created_time)
SELECT c.ancestor_user_id, #{newUserId}, c.depth + 1, NOW(6)
FROM game_referral_closure c
WHERE c.descendant_user_id = #{parentUserId}
UNION ALL
SELECT #{newUserId}, #{newUserId}, 0, NOW(6);
Why does this design prevent circular binding?
- Before inserting,
SELECT 1 FROM game_referral_closure WHERE ancestor_user_id = #{newUserId} AND descendant_user_id = #{parentUserId}checks in milliseconds whether the new user is already an ancestor of the referrer; - A match indicates an attempted reverse cycle, A → B → A. The system throws an invalid-topology exception and aborts the transaction, eliminating infinite recursive loops.
Implementation 2: Branch Locks for Unlimited Direct Referrals and Ternary Placement
Different referral business models need different placement rules:
- Ordinary members (free players): Use the basic UNLIMITED_DIRECT mode. New users attach directly beneath them, without team spillover benefits;
- Paid members (cardholders): Activate TERNARY_PLACEMENT. Each node has at most 3 direct slots (Slot 1~3). Further users automatically spill over to the shallowest active descendant, supporting team-based referral growth.
In nova-membership/backend/src/main/java/com/ruoyi/game/referral/application/ReferralPlacementService.java, an exclusive branch-root lock (lockBranchRoot) resolves slot contention when tens of thousands of users register concurrently:
// Excerpt from nova-membership/backend/src/main/java/com/ruoyi/game/referral/application/ReferralPlacementService.java
@Service
public class ReferralPlacementService {
private final ReferralMapper mapper;
@Transactional
public Placement place(Long referrerUserId, long newUserId) {
// Without a referrer, attach directly to the virtual root
if (referrerUserId == null) {
mapper.insertEdge(null, null, newUserId, null, "VIRTUAL_ROOT");
mapper.insertSelfClosure(newUserId);
return new Placement(null, null, 0, "VIRTUAL_ROOT");
}
// 1. Core concurrency lock: lock the root of the referrer's branch to establish an exclusive barrier
Long branchRoot = mapper.selectBranchRoot(referrerUserId);
if (branchRoot == null || mapper.lockBranchRoot(branchRoot) == null) {
throw new GameException(409, "REFERRAL_TREE_INCOMPLETE", "邀请人的安置树数据不完整");
}
ReferralMapper.UserPlacementState state = mapper.lockUserPlacementState(referrerUserId);
// 2. If the referrer is locked into unlimited direct mode, attach directly
if ("UNLIMITED_DIRECT".equals(state.getNetworkMode())) {
return placeUnlimited(referrerUserId, newUserId, state.getChildCount());
}
// 3. In PENDING mode with fewer than 3 children, fill slots 1~3 first
if ("PENDING".equals(state.getNetworkMode()) && state.getChildCount() < 3) {
return placeInSlot(referrerUserId, referrerUserId, newUserId, state.getChildCount(), 0, "DIRECT");
}
// 4. On the fourth referral, permanently lock the mode based on paid membership card ownership
if ("PENDING".equals(state.getNetworkMode())) {
// No confirmed normal card purchase: lock into unlimited direct referrals
if (mapper.countConfirmedNormalCard(referrerUserId) == 0) {
if (mapper.activateUnlimitedAndReserve(referrerUserId, state.getChildCount()) != 1) {
throw new GameException(409, "REFERRAL_MODE_CONFLICT", "网络模式发生并发冲突");
}
return insertUnlimitedEdge(referrerUserId, newUserId);
}
// Confirmed membership card purchase: lock into ternary matrix spillover mode
if (mapper.updateNetworkMode(referrerUserId, "PENDING", "TERNARY_PLACEMENT") != 1) {
throw new GameException(409, "REFERRAL_MODE_CONFLICT", "网络模式发生并发冲突");
}
}
// 5. In ternary mode, find the shallowest descendant with an available slot
ReferralMapper.PlacementCandidate candidate = mapper.selectPlacementCandidate(referrerUserId);
String source = candidate.getUserId().equals(referrerUserId) ? "DIRECT" : "SPILLOVER";
return placeInSlot(referrerUserId, candidate.getUserId(), newUserId,
candidate.getChildCount(), candidate.getDepth(), source);
}
}
Implementation 3: Payment-Backed Value and EIP-712 Redemption (GameDApp.sol)
To eliminate Sybil attacks, NOVA enforces one rule: registration and relationship binding never create withdrawable tokens out of nothing.
Referral earnings are calculated by the event-driven engine only after the referred user actually calls the on-chain contract and pays real funds—for example, 100 USDC—to buy a membership card (buyGloryCard).
1. Off-Chain Rules Drive Double-Entry Accounting (RuleRewardExecutor.java)
After an on-chain deposit is confirmed, the server starts RuleRewardExecutor:
// Excerpt from nova-membership/backend/src/main/java/com/ruoyi/game/reward/application/RuleRewardExecutor.java
public void executeCardPurchase(long sourceEventId, long buyerUserId, Long snapshotId) {
// Trigger revenue sharing only after a real card purchase is confirmed, anchoring value to on-chain deposits
execute("NORMAL_CARD_PURCHASED", sourceEventId, buyerUserId, snapshotId);
}
Using closure-table depths, the system calculates upstream shares for eligible referrers, atomically writes the double-entry ledger, and creates reward records (game_reward_grant) with globally unique idempotency constraints.
2. Controlled Prefunded Pool and EIP-712 Claims (GameDApp.sol)
When a user requests a commission withdrawal in the frontend, the contract does not blindly trust client parameters. Final redemption requires a controlled prefunded reward pool (fundCardRewardPool) and an EIP-712 signature (CardRewardPermit) from the authorized backend key:
// Excerpt from nova-membership/contracts/src/GameDApp.sol
struct CardRewardPermit {
bytes32 businessOrderId; // Unique off-chain card purchase order identifier (replay protection)
bytes32 rewardClaimId; // Allocation identifier for this withdrawal
bytes32 rewardCode; // Reward type code
address claimant; // Claimant address
address recipient; // Actual recipient address
address gloryToken; // Reward token address
uint256 gloryAmount; // Withdrawal amount
uint48 validAfter; // Start timestamp
uint48 deadline; // Expiry timestamp
uint256 nonce; // Per-user incrementing nonce preventing reuse in the contract
uint256 rewardConfigVersion; // Bound rule version
}
function claimCardGloryReward(
CardRewardPermit calldata permit,
bytes calldata backendSignature
) external nonReentrant whenNotPaused {
// 1. Assert caller and recipient identity
if (msg.sender != permit.claimant || permit.recipient != msg.sender) {
revert UnauthorizedCaller();
}
if (permit.gloryAmount == 0 || permit.rewardConfigVersion != cardRewardConfigVersion) {
revert InvalidPermit();
}
// 2. Validate the time window
if (block.timestamp < permit.validAfter || block.timestamp > permit.deadline) {
revert PermitExpired();
}
// 3. Core double-spend check: each business order and claim ID can be used only once
if (usedCardRewardClaim[permit.rewardClaimId]) revert AlreadyClaimed();
if (usedCardRewardOrder[permit.businessOrderId]) revert OrderAlreadyUsed();
if (permit.nonce != cardRewardNonce[msg.sender]) revert InvalidNonce();
// 4. Reward pool boundary: withdrawal cannot exceed the prefunded balance or allocation cap
if (permit.gloryAmount > cardRewardRemaining()) revert InsufficientRewardPool();
// 5. Verify the EIP-712 signature of the designated backend signer
address signer = ECDSA.recover(_hashTypedDataV4(_hashCardReward(permit)), backendSignature);
if (!hasRole(CARD_REWARD_SIGNER_ROLE, signer)) revert InvalidSignature();
// 6. Atomically mark state, increment the nonce, and transfer tokens
usedCardRewardOrder[permit.businessOrderId] = true;
usedCardRewardClaim[permit.rewardClaimId] = true;
cardRewardNonce[msg.sender] = permit.nonce + 1;
cardRewardDistributed += permit.gloryAmount;
IERC20(gloryToken).safeTransfer(msg.sender, permit.gloryAmount);
emit CardGloryRewardClaimed(permit.businessOrderId, permit.rewardClaimId, msg.sender, permit.gloryAmount);
}
Verification with the Foundry Test Suite
The nova-membership/contracts/test/unit/GameDAppBusiness.t.sol suite verifies the prefunded pool’s hard boundaries and the protection against claiming twice with the same permit:
// Excerpt from nova-membership/contracts/test/unit/GameDAppBusiness.t.sol
function testCardRewardsUsePreFundedPoolAndEachEntitlementClaimsOnce() public {
// 1. Prefund the reward pool with 100 ether
glory.approve(address(dapp), 100 ether);
dapp.fundCardRewardPool(100 ether);
assertEq(dapp.cardRewardRemaining(), 100 ether);
// 2. User makes a real membership card purchase
vm.startPrank(user);
gameCoin.approve(address(dapp), 200 ether);
dapp.buyPremiumGloryCard();
vm.stopPrank();
// 3. Generate a valid claim permit and backend signature
CardRewardPermit memory permit = CardRewardPermit({
businessOrderId: keccak256("reward-order-001"),
rewardClaimId: keccak256("claim-001"),
rewardCode: keccak256("PREMIUM_PURCHASE"),
claimant: user,
recipient: user,
gloryToken: address(glory),
gloryAmount: 10 ether,
validAfter: uint48(block.timestamp - 1),
deadline: uint48(block.timestamp + 1 hours),
nonce: 0,
rewardConfigVersion: 1
});
bytes memory signature = _signCardReward(permit);
// 4. First withdrawal succeeds
vm.prank(user);
dapp.claimCardGloryReward(permit, signature);
assertEq(glory.balanceOf(user), 10 ether);
assertEq(dapp.cardRewardRemaining(), 90 ether);
// 5. Negative case: a second withdrawal using the same permit reverts with AlreadyClaimed
vm.prank(user);
vm.expectRevert(GameDApp.AlreadyClaimed.selector);
dapp.claimCardGloryReward(permit, signature);
}
Four Rules for Production Anti-Sybil Referrals
- Never issue withdrawable funds for zero-cost registration: Airdropped tokens should serve only non-liquid test experiences. Withdrawable tokens or commissions must be atomically tied to a downstream user’s real on-chain purchase (Card Mint / Stake);
- Assert a DAG when writing relationships: Before inserting an edge, use the Closure Table to check reverse ancestor containment, eliminating A → B → A arbitrage loops at the data-structure level;
- Lock branch roots for concurrent registration: Avoid a global whole-table lock. An exclusive
lockBranchRootconfines contention to the specific referral team; - Deduplicate on-chain withdrawals by order number and Nonce: The contract must check
usedCardRewardOrder[businessOrderId]so one off-chain invoice cannot generate repeated withdrawal requests.
Enterprise Web3 Growth and Membership Architecture Consulting
Fone builds Sybil-resistant, low-latency membership and referral engines for large Web3 games, decentralized communities, KOL alliances, and creator platforms. Our NOVA Membership solution runs the full production workflow from closure-based placement and prepublication rule simulation to secure EIP-712 redemption:
- Read about rule simulation and prepublication risk controls: Rule Simulation Before Publication: Preventing Configuration-Driven Insolvency
- Explore wallet-login failure states: Engineering Web3 Wallet Login: Resolving Chain-Switching and Account-Switching Races
- Explore multi-chain stablecoin checkout architecture: StableIn Solution
- Book a revenue-sharing model audit and system assessment with a senior growth architect: Discuss a Custom Implementation with Fone