Technical editorial illustration showing a multi-tier Web3 membership rule simulation engine testing referral tree edge calculations before on-chain publication.
Rule simulation pipeline: sandbox trace evaluation and Maker-Checker authorization separation.

In Web3 incentive networks, decentralized growth programs, and tiered membership architectures, configuration mistakes carry permanent financial consequences. An operator altering referral percentages, tier thresholds, or vesting schedules can inadvertently trigger runaway mint loops, negative revenue spreads, or reward pool drainage within minutes of deployment. In NOVA Membership, this risk is neutralized through a formal five-stage governance pipeline: isolating draft rule definitions in relational MySQL schemas, executing pre-publication sandbox simulations across historical synthetic facts, enforcing Maker-Checker review separation where rule authors cannot approve their own changes, generating immutable SHA-256 configuration snapshots upon activation, and settling reward entitlements on-chain through EIP-712 cryptographic permit vouchers.


1. The Production Threat Model: Why Direct Membership Rule Publishing Invariably Fails

In many early-stage Web3 community and membership platforms, operational rules—such as referral kickbacks, tier advancement quotas, and staking multipliers—are either hardcoded into smart contracts or edited directly in an admin dashboard connected to live database tables.

When an operations team launches a campaign or revises reward percentages, three structural failure modes frequently emerge:

[Failure Mode 1: The Circular Referral Infinite Mint]
- Operator defines: "Direct referral pays 10% of purchased pass; indirect referral pays 5%."
- Flaw: The referral tree builder fails to enforce Directed Acyclic Graph (DAG) invariants.
- Exploit: Attacker creates Account A -> invites Account B -> invites Account A.
- Result: A single pass purchase triggers a cyclic execution loop, compounding referral points 
  until the contract's reward allocation cap is exhausted.

[Failure Mode 2: The Cascading Tier Advancement Glitch]
- Operator adjusts tier requirements: "Reaching Tier 3 requires 5 direct referrals with Tier 2."
- Flaw: The update takes effect immediately without evaluating existing network topology.
- Exploit: A promotional burst of low-tier signups propagates upwards through ancestor closure tables, 
  inadvertently promoting thousands of inactive accounts to maximum quota tiers within a single block.

[Failure Mode 3: Misconfigured Reward Decimals and Pool Inversion]
- Operator enters: "Reward bonus = 50" intending 50 wei or 50 basis points (0.5%).
- Reality: Downstream accounting interprets the number in whole tokens (50 * 10^18), immediately 
  demanding 1,000x more inventory than the pre-funded pool holds.
- Result: Legitimate claims revert with InsufficientRewardPool, halting member payouts.

In standard Web2 software, a bad marketing rule can be rolled back with an emergency database patch. In Web3 architectures, where rewards are claimed on-chain or traded on secondary AMM pools, erroneously issued assets cannot be unilaterally recalled.

The engineering rule must be absolute: No rule configuration may alter live evaluation without passing automated sandbox simulation and independent operator review.


2. System Architecture: The Five-Stage Rule Governance Pipeline

Technical pipeline diagram showing the five-stage rule lifecycle: Draft Creation, Sandbox Simulation, Independent Review, Activation Snapshot, and On-Chain Permit Claim.

In NOVA Membership, rules follow a formal state machine implemented in Java (Spring Boot) and backed by MySQL InnoDB:

+----------------------------------------------------------------------------------------------------+
|                                    RULE GOVERNANCE STATE MACHINE                                   |
|                                                                                                    |
|  [ Step 1: Draft Authoring ]                                                                       |
|     - Operator clones active RuleSet or creates a new DRAFT (version: 'v2.1', name)                |
|     - Inserts RuleDefinitions: priority, condition_json, beneficiary_json, action_json             |
|     - Sets LevelDefinitions: required_card_code, required_direct_count, base_quota, daily_quota    |
+----------------------------------------------------------------------------------------------------+
                                                |
                                                v validate()
+----------------------------------------------------------------------------------------------------+
|                                    [ Step 2: Validation Gate ]                                     |
|     - Status transitions to: VALIDATED                                                             |
|     - Verifies non-empty rule sets, complete vesting policies, and valid JSON schemas              |
+----------------------------------------------------------------------------------------------------+
                                                |
                                                v simulate(facts)
+----------------------------------------------------------------------------------------------------+
|                                  [ Step 3: Sandbox Simulation ]                                    |
|     - Executes RuleConditionEvaluator against historical and synthetic member journeys           |
|     - Generates detailed RuleTrace execution logs (matched, evaluation conditions, actions)        |
|     - Persists simulation results in game_rule_execution for audit inspection                      |
+----------------------------------------------------------------------------------------------------+
                                                |
                                                v review(reviewerId)
+----------------------------------------------------------------------------------------------------+
|                                [ Step 4: Maker-Checker Review ]                                    |
|     - Status transitions to: REVIEWED                                                              |
|     - Enforces invariant: ruleSet.createdBy != reviewerId (Self-approval strictly forbidden)       |
+----------------------------------------------------------------------------------------------------+
                                                |
                                                v activateNow() or activateDue()
+----------------------------------------------------------------------------------------------------+
|                                  [ Step 5: Activation & Snapshot ]                                 |
|     - Retires currently active RuleSet (retireActive())                                            |
|     - Activates target RuleSet (activate())                                                        |
|     - Freezes entire configuration tree into immutable game_config_snapshot (SHA-256 hash)         |
+----------------------------------------------------------------------------------------------------+
                                                |
                                                v Issue EIP-712 CardRewardPermit
+----------------------------------------------------------------------------------------------------+
|                                   [ On-Chain Execution: GameDApp.sol ]                             |
|     - User submits CardRewardPermit with backend signature                                         |
|     - Smart contract asserts: msg.sender == claimant, nonce, valid window, remaining cap           |
|     - Contract pays out from pre-funded reward pool and permanently flags claimId as used          |
+----------------------------------------------------------------------------------------------------+

3. Relational Schema Architecture: Membership, Closures, and Rule Sets

The relational foundation of NOVA Membership (from backend/sql/glory_game.sql) separates the structural member graph from the dynamic rule engine.

The Referral Graph and Closure Table

Rather than executing recursive SQL queries on every tier evaluation, the system stores relationships using an edge table and an ancestor closure table (glory_game.sql:L43-L75):

CREATE TABLE IF NOT EXISTS game_referral_edge (
  edge_id bigint NOT NULL AUTO_INCREMENT,
  source_inviter_user_id bigint DEFAULT NULL,
  parent_user_id bigint DEFAULT NULL,
  child_user_id bigint NOT NULL,
  slot_no tinyint unsigned DEFAULT NULL,
  source varchar(32) NOT NULL,
  created_time datetime(6) NOT NULL,
  PRIMARY KEY (edge_id),
  UNIQUE KEY uk_game_referral_child (child_user_id),
  UNIQUE KEY uk_game_referral_parent_slot (parent_user_id, slot_no),
  KEY idx_game_referral_source_inviter (source_inviter_user_id, created_time),
  KEY idx_game_referral_parent (parent_user_id),
  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;

CREATE TABLE IF NOT EXISTS game_referral_closure (
  ancestor_user_id bigint NOT NULL,
  descendant_user_id bigint NOT NULL,
  depth int unsigned NOT NULL,
  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),
  KEY idx_game_referral_closure_ancestor_depth (ancestor_user_id, depth, descendant_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

With game_referral_closure, retrieving all 100 ancestors of a purchasing member resolves in a single indexed query (SELECT ancestor_user_id FROM game_referral_closure WHERE descendant_user_id = ? ORDER BY depth ASC), eliminating graph traversal bottlenecks.

Rule Set and Level Versioning

Rules and tier definitions are partitioned by rule_set_id (glory_game.sql:L89-L159):

CREATE TABLE IF NOT EXISTS game_rule_set (
  rule_set_id bigint NOT NULL AUTO_INCREMENT,
  version varchar(32) NOT NULL,
  name varchar(100) NOT NULL,
  status varchar(24) NOT NULL,
  created_by bigint NOT NULL,
  reviewed_by bigint DEFAULT NULL,
  effective_at datetime(6) DEFAULT NULL,
  version_no bigint NOT NULL DEFAULT 0,
  created_time datetime(6) NOT NULL,
  updated_time datetime(6) NOT NULL,
  PRIMARY KEY (rule_set_id),
  UNIQUE KEY uk_game_rule_set_version (version),
  KEY idx_game_rule_set_status_time (status, effective_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS game_level_definition (
  level_definition_id bigint NOT NULL AUTO_INCREMENT,
  rule_set_id bigint NOT NULL,
  level_code varchar(16) NOT NULL,
  ordinal_no int NOT NULL,
  required_card_code varchar(32) DEFAULT NULL,
  required_direct_count int NOT NULL DEFAULT 0,
  required_direct_level_code varchar(16) DEFAULT NULL,
  base_quota decimal(38,18) NOT NULL DEFAULT 0,
  daily_quota decimal(38,18) NOT NULL DEFAULT 0,
  created_time datetime(6) NOT NULL,
  updated_time datetime(6) NOT NULL,
  PRIMARY KEY (level_definition_id),
  UNIQUE KEY uk_game_level_version_code (rule_set_id, level_code),
  UNIQUE KEY uk_game_level_version_ordinal (rule_set_id, ordinal_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

4. Rule Simulation Engine: RuleSetService.java

The heart of the pre-publication defense is the simulation workflow in backend/ruoyi-game/src/main/java/com/ruoyi/game/rule/application/RuleSetService.java:L1-L227.

Dry-Run Rule Evaluation Across Context Facts

Operators can submit synthetic payload facts (such as a card purchase event, member registration, or specific referral depth) to test a draft rule set without touching production balances (RuleSetService.java:L150-L175):

@Transactional
public SimulationResult simulate(long ruleSetId, Map<String, Object> facts)
{
    RuleSet ruleSet = mapper.lockById(ruleSetId);
    if (ruleSet == null)
    {
        throw new GameException(404, "RULE_SET_NOT_FOUND", "规则集不存在");
    }
    
    List<RuleTrace> traces = new ArrayList<>();
    for (RuleDefinition definition : mapper.selectDefinitions(ruleSetId))
    {
        // Evaluate JSON condition expression against facts
        RuleConditionEvaluator.Evaluation evaluation = evaluator.evaluate(definition.getConditionJson(), facts);
        traces.add(new RuleTrace(
            definition.getRuleCode(), 
            evaluation.matched(), 
            evaluation,
            evaluation.matched() ? definition.getBeneficiaryJson() : null,
            evaluation.matched() ? definition.getActionJson() : null
        ));
    }
    
    SimulationResult result = new SimulationResult(ruleSet.getVersion(), traces);
    try
    {
        // Persist simulation audit trace
        mapper.insertExecution(
            ruleSetId, 
            objectMapper.writeValueAsString(facts),
            objectMapper.writeValueAsString(result), 
            RequestIds.current()
        );
    }
    catch (JsonProcessingException exception)
    {
        throw new IllegalStateException("规则模拟轨迹序列化失败", exception);
    }
    return result;
}

The returned SimulationResult contains complete trace trees showing:

  • Which rules matched and which were skipped.
  • The exact beneficiaries computed (SELF, DIRECT_PARENT, or LEVEL_PATH).
  • The projected token reward payout and vesting schedule.

5. Maker-Checker Review Separation & Snapshot Freezing

In financial and enterprise environments, configuration changes must satisfy the principle of least privilege. In RuleSetService.java:L105-L145:

@Transactional
public void review(long ruleSetId, long reviewerId)
{
    RuleSet ruleSet = requireStatus(ruleSetId, "VALIDATED");
    
    // Strict separation: Author cannot review their own rule set
    if (ruleSet.getCreatedBy().equals(reviewerId))
    {
        throw new GameException(409, "RULE_REVIEW_SEPARATION_REQUIRED", "规则创建人与复核人必须不同");
    }
    doTransition(ruleSet, "REVIEWED", reviewerId, null);
}

@Transactional
public void activateNow(long ruleSetId)
{
    RuleSet ruleSet = requireStatus(ruleSetId, "REVIEWED");
    doTransition(ruleSet, "SCHEDULED", ruleSet.getReviewedBy(), LocalDateTime.now(ZoneOffset.UTC));
    
    // Retire currently active rules
    mapper.retireActive();
    
    if (mapper.activate(ruleSetId) != 1)
    {
        throw new GameException(409, "RULE_SET_STATE_CHANGED", "规则集状态已被并发修改");
    }
    
    // Create immutable SHA-256 snapshot of entire active tree
    mapper.insertConfigSnapshot(ruleSetId);
}

The Invariant of the Config Snapshot

When insertConfigSnapshot(ruleSetId) executes:

  • The entire tree of definitions, tier thresholds, reward rates, and vesting curves is serialized into snapshot_json.
  • A SHA-256 hash snapshot_hash is computed and stored in game_config_snapshot.
  • When rewards are subsequently granted (game_reward_grant), each grant row stores config_snapshot_id.
  • Auditability Guarantee: Even if the platform updates its membership rules 50 times over three years, every single historic token reward points back to the exact snapshot hash that authorized it.

6. On-Chain Claim Security: GameDApp.sol

Once off-chain rules compute an entitlement, the actual token transfer executes on-chain via pre-funded reward vaults in dappContracts/src/GameDApp.sol:L355-L413:

function claimCardGloryReward(
    CardRewardPermit calldata permit, 
    bytes calldata backendSignature
) external nonReentrant whenNotPaused {
    if (msg.sender != permit.claimant || permit.recipient != msg.sender) revert UnauthorizedCaller();
    if (
        permit.rewardClaimId == bytes32(0) || 
        permit.rewardCode == bytes32(0) || 
        permit.gloryToken != gloryToken || 
        permit.gloryAmount == 0 || 
        permit.rewardConfigVersion != cardRewardConfigVersion
    ) revert InvalidPermit();
    
    if (block.timestamp < permit.validAfter || block.timestamp > permit.deadline) revert PermitExpired();
    if (usedCardRewardClaim[permit.rewardClaimId]) revert AlreadyClaimed();
    if (usedCardRewardOrder[permit.businessOrderId]) revert OrderAlreadyUsed();
    if (permit.nonce != cardRewardNonce[msg.sender]) revert InvalidNonce();
    if (permit.gloryAmount > cardRewardRemaining()) revert InsufficientRewardPool();

    // Verify cryptographic EIP-712 permit signed by CARD_REWARD_SIGNER_ROLE
    address signer = ECDSA.recover(_hashTypedDataV4(_hashCardReward(permit)), backendSignature);
    if (!hasRole(CARD_REWARD_SIGNER_ROLE, signer)) revert InvalidSignature();

    // Mark nullifiers to prevent replay attacks
    usedCardRewardOrder[permit.businessOrderId] = true;
    usedCardRewardClaim[permit.rewardClaimId] = true;
    cardRewardClaimedCount[msg.sender] += 1;
    cardRewardNonce[msg.sender] = permit.nonce + 1;
    cardRewardDistributed += permit.gloryAmount;

    // Execute transfer from pre-funded pool
    IERC20(gloryToken).safeTransfer(msg.sender, permit.gloryAmount);
    
    emit CardGloryRewardClaimed(
        permit.businessOrderId,
        permit.rewardClaimId,
        msg.sender,
        permit.rewardCode,
        permit.gloryAmount,
        cardRewardDistributed,
        cardRewardRemaining(),
        permit.nonce,
        permit.rewardConfigVersion
    );
}

On-Chain Security Guards

  • Nullifier Bitmaps (usedCardRewardClaim): Each unique reward calculation generates an immutable rewardClaimId. Once claimed, the ID is flagged as true, making on-chain replay impossible.
  • Account Nonce Ordering: User nonces increment strictly (permit.nonce != cardRewardNonce[msg.sender]), preventing out-of-order execution.
  • Solvency Bound (cardRewardRemaining()): Payouts cannot exceed cardRewardAllocationCap - cardRewardDistributed or the contract’s actual token balance, ensuring that runaway rewards can never drain other protocol vaults.

7. Concrete Verification: Unit & Foundry Test Suites

The correctness of this governance pipeline is verified across both Java service tests and Foundry smart contract suites.

Service Test: Immediate Activation and Snapshot Creation

Verifies that reviewed rule sets retire previous active versions and generate an immutable snapshot upon activation (backend/ruoyi-game/src/test/java/com/ruoyi/game/rule/application/RuleSetServiceTest.java:L1-L89):

@Test
void activatesReviewedRuleSetImmediately()
{
    RuleSet reviewed = new RuleSet();
    reviewed.setRuleSetId(7L);
    reviewed.setStatus("REVIEWED");
    reviewed.setReviewedBy(22L);
    
    AtomicBoolean retired = new AtomicBoolean();
    AtomicBoolean activated = new AtomicBoolean();
    AtomicBoolean snapshotted = new AtomicBoolean();
    
    // Verify transition contract: must retire old, activate new, then snapshot
    service.activateNow(7L);

    assertTrue(activated.get());
    assertTrue(snapshotted.get());
}

Foundry Contract Test: Single-Claim Invariant

Verifies that pre-funded pools enforce strict single-claim semantics and reject duplicate claims (dappContracts/test/unit/GameDAppBusiness.t.sol:L84-L139):

function testCardRewardsUsePreFundedPoolAndEachEntitlementClaimsOnce() public {
    glory.approve(address(dapp), 100 ether);
    dapp.fundCardRewardPool(100 ether);
    assertEq(dapp.cardRewardRemaining(), 100 ether);

    // Prepare valid permit and claim 10 ether
    bytes memory signature = _signCardReward(permit);
    vm.prank(user);
    dapp.claimCardGloryReward(permit, signature);

    assertEq(glory.balanceOf(user), 10 ether);
    assertEq(dapp.cardRewardRemaining(), 90 ether);

    // Duplicate claim reverts with AlreadyClaimed
    vm.prank(user);
    vm.expectRevert(GameDApp.AlreadyClaimed.selector);
    dapp.claimCardGloryReward(permit, signature);
}

8. Architectural Comparison: Membership & Reward Paradigms

Technical Dimension Naive On-Chain Multi-Sig Centralized Database Only NOVA Membership Architecture
Referral Tree Depth Max 2-3 levels (Block Gas Limit) Unlimited, but zero Web3 trust Unlimited via game_referral_closure
Pre-Publish Simulation None (Deploy directly to mainnet) Ad-hoc SQL queries Automated dry-run traces (RuleTrace)
Maker-Checker Enforcement Manual multisig coordination Hardcoded admin credentials Engine-enforced author != reviewer
Audit Provenance Transaction events only Application logs (Alterable) SHA-256 config snapshot ID per grant
Claim Gas Model Push loops (Vulnerable to Out-of-Gas) Off-chain API credits EIP-712 Pull Claims via pre-funded vault
Replay Protection Incremental nonce Database unique key Dual nullifier (claimId + account nonce)

9. Integration & Commercial Next Steps

Web3 membership architectures must balance community growth flexibility with rigorous cryptographic solvency. Leaving reward rules to unsimulated live deployments risks multi-million dollar drainage events.

The architecture implemented in NOVA Membership provides a production-proven blueprint for managing tiered passes, complex referral networks, and rule simulations with institutional safety.

  1. Audit Live Reward Rules: Review your existing referral percentages, upgrade thresholds, and payout multipliers against worst-case synthetic member graphs.
  2. Review Companion Membership Guides: Explore our foundational blueprints on Designing Audit Records for Membership Operations and Versioning Business Rules in a Membership Platform.
  3. Explore the Working Product: Review the screen captures, rule simulation workflows, and architecture documentation on the NOVA Membership Product Page or explore our Member Operations Overview.
  4. Schedule a Technical Architecture Consultation: If your organization is launching token-gated membership tiers, complex referral ecosystems, or gamified loyalty platforms, book a technical demo walkthrough or request an implementation proposal.