O(1) Royalty Distribution for Evolving Contributor Teams: Handling Share Updates Without Corrupting Unclaimed Balances

Payment splitting is a core component of creator-economy and Web3 digital-rights platforms. Songwriters, arrangers, and mastering engineers commonly share the commercial licensing revenue from a song or generative-AI asset.

Most full-stack engineers implementing this feature start by copying OpenZeppelin’s PaymentSplitter.sol. In practice, however, a serious flaw can quickly emerge and anger founding contributors:

Suppose a track earns 10,000 USDC in its first month. Its original team consists of a composer and lyricist, each holding 50%, or 5,000 basis points. Because of gas costs or personal tax considerations, neither withdraws, leaving all 10,000 USDC in the vault.

In month two, the team brings in a top mixing engineer to produce a new accompaniment. They agree that the mixer will receive 20% of future revenue, while the original contributors each move to 40%.

The administrator updates the contract’s shares. When the mixer first calls the withdrawal function, the mixer withdraws 2,000 USDC in one transaction.

That 2,000 USDC was earned before the mixer joined and belongs to the two original contributors. By applying the latest shares to all vault assets, the contract lets a new agreement take historical earnings from existing creators.

This is the unclaimed-balance dilution exploit, a damaging vulnerability in DeFi and royalty-distribution systems.


1. Why OpenZeppelin’s PaymentSplitter Cannot Dynamically Change Shares

O(1) Royalty Distribution for Evolving Contributor Teams: Handling Share Updates Without Corrupting Unclaimed Balances

The cause becomes clear from the classic OpenZeppelin PaymentSplitter formula:

Releasablei=(totalReceived)⋅sharesitotalShares−alreadyReleasedi\text{Releasable}_i = \frac{(\text{totalReceived}) \cdot \text{shares}_i}{\text{totalShares}} - \text{alreadyReleased}_i

Here, totalReceived is the cumulative amount ever received by the contract. As long as sharesi is immutable, the formula distributes each participant’s proper proportional share.

But real commercial teams are not static: bands add members, copyrights are partially transferred, and shares change with contribution phases. Adding an updateShare(address payee, uint256 newShare) modifier to PaymentSplitter breaks the formula’s multiplier assumptions:

+----------------------------------------------------------------------------------------------------+
|                       Historical-Fund Dilution After Dynamically Changing Shares                   |
+----------------------------------------------------------------------------------------------------+

   [ Epoch 1: Two-person team (A: 50%, B: 50%) ]
   - Historical revenue: 10,000 USDC
   - A unclaimed: 5,000 USDC
   - B unclaimed: 5,000 USDC
   - Vault balance: 10,000 USDC
                │
                ▼ Administrator calls updateShares(A: 40%, B: 40%, C: 20%)
                │
   [ Epoch 2: Three-person team (A: 40%, B: 40%, C: 20%) ]
   - New revenue so far: 0 USDC
   - New contributor C withdraws:
     Releasable(C) = (10,000 * 20%) - 0 = 2,000 USDC!
     
   Critical failure:
   Before generating any new revenue, C takes 2,000 USDC of historical assets belonging to A and B!
   A later receives only: (10,000 * 40%) - 0 = 4,000 USDC (net loss: 1,000 USDC)
+----------------------------------------------------------------------------------------------------+

Once teams notice this problem, some try to distribute every historical balance through a forced push loop before changing shares. This is dangerous on-chain: a creator using a contract without a receive callback, or a participant list exceeding dozens of addresses, can cause the loop to exceed the gas limit and permanently deadlock the contract.


2. The O(1) Revenue Accumulator Model Inspired by MasterChef

To change shares at any time and let any number of creators withdraw independently without gas explosions or historical dilution, use a constant-time O(1) accumulator engine, proven at the US$100 billion scale in modern DeFi systems such as Uniswap, MasterChef, and Compound.

1. Core Mathematical Derivation

Define a globally monotonic accumulated-revenue-per-basis-point value, accRevenuePerBps, scaled by 1018 to eliminate integer-rounding errors:

When the vault receives new royalties ΔRevenue, update the global accumulator:

accRevenuePerBpsnew=accRevenuePerBpsold+ΔRevenue⋅1018TOTAL_BPS(其中 TOTAL_BPS=10,000)\text{accRevenuePerBps}_{\text{new}} = \text{accRevenuePerBps}_{\text{old}} + \frac{\Delta \text{Revenue} \cdot 10^{18}}{\text{TOTAL\_BPS}} \quad (\text{其中 TOTAL\_BPS} = 10,000)

For any contributor i, incremental earnings in the current period are:

ΔPendingi=sharesBpsi⋅(accRevenuePerBpscurrent−accRevenuePerBpslastUpdated)1018\Delta \text{Pending}_i = \frac{\text{sharesBps}_i \cdot (\text{accRevenuePerBps}_{\text{current}} - \text{accRevenuePerBps}_{\text{lastUpdated}})}{10^{18}}

To avoid storing each contributor’s accRevenuePerBpslastUpdated, introduce reward debt (rewardDebt):

PendingBalancei=sharesBpsi⋅accRevenuePerBps1018−rewardDebti\text{PendingBalance}_i = \frac{\text{sharesBps}_i \cdot \text{accRevenuePerBps}}{10^{18}} - \text{rewardDebt}_i

2. Atomic Snapshots When Shares Change

When an administrator or consensus multisig changes contributor i‘s share, the contract performs three atomic operations in one transaction:

  1. Harvest past revenue: Calculate contributor i‘s earned but unwithdrawn revenue at the current accumulator value and add it to the contributor’s static accruedBalance[i] ledger;
  2. Update share basis points: Change contributor i‘s old share to newSharesBps;
  3. Reset reward debt: Update the debt anchor: rewardDebti=newSharesBps⋅accRevenuePerBps1018\text{rewardDebt}_i = \frac{\text{newSharesBps} \cdot \text{accRevenuePerBps}}{10^{18}}

Every unit earned at the old share is fixed in accruedBalance, while the new share applies only to future royalties. Even if a new member receives 90% of the shares, their claim on historical unwithdrawn assets is exactly zero.


3. MusicFlow’s Dynamic Royalty Contract (DynamicRoyaltyAccumulator.sol)

In the production Fone MusicFlow implementation, the algorithm is packaged into a compact Solidity library with very little code that has undergone tens of thousands of fuzz tests:

// musicflow/contracts/src/DynamicRoyaltyAccumulator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

error InvariantSharesNotExhaustive(uint256 totalBps);
error ZeroAddressPayee();
error NoClaimableBalance();

contract DynamicRoyaltyAccumulator is Ownable2Step, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 public constant TOTAL_BPS = 10000; // 100.00%
    IERC20 public immutable paymentToken;

    // Globally monotonic accumulator (scaled to 1e18 precision)
    uint256 public accRevenuePerBps;
    uint256 public totalHistoricalRevenue;

    struct Contributor {
        uint256 sharesBps;       // Current basis-point share, e.g. 5000 = 50%
        uint256 rewardDebt;      // Reward-debt alignment anchor
        uint256 accruedBalance;  // Fixed historical unwithdrawn balance
    }

    mapping(address => Contributor) public contributors;
    address[] public contributorList;

    event RevenueDeposited(address indexed sender, uint256 amount, uint256 newAccRevenuePerBps);
    event SharesUpdated(address indexed payee, uint256 oldBps, uint256 newBps);
    event RoyaltyWithdrawn(address indexed payee, uint256 amount);

    constructor(IERC20 _token, address initialOwner) Ownable(initialOwner) {
        paymentToken = _token;
    }

    /**
     * @notice Royalty revenue entry (triggered by buyer payment)
     * Update the global accumulator in strict O(1) time, however small the deposit
     */
    function depositRevenue(uint256 amount) external nonReentrant {
        require(amount > 0, "INVALID_AMOUNT");
        paymentToken.safeTransferFrom(msg.sender, address(this), amount);

        totalHistoricalRevenue += amount;
        // Core accumulation: add revenue per basis point
        accRevenuePerBps += (amount * 1e18) / TOTAL_BPS;

        emit RevenueDeposited(msg.sender, amount, accRevenuePerBps);
    }

    /**
     * @notice Query total withdrawable earnings (current accrual + fixed historical earnings)
     */
    function pendingRoyalty(address payee) public view returns (uint256) {
        Contributor memory c = contributors[payee];
        if (c.sharesBps == 0 && c.accruedBalance == 0) return 0;

        uint256 currentAccumulated = (c.sharesBps * accRevenuePerBps) / 1e18;
        uint256 unharvested = currentAccumulated > c.rewardDebt ? currentAccumulated - c.rewardDebt : 0;
        return c.accruedBalance + unharvested;
    }

    /**
     * @notice Safely update contributor shares without diluting historical assets
     */
    function setContributorShare(address payee, uint256 newSharesBps) external onlyOwner {
        if (payee == address(0)) revert ZeroAddressPayee();

        Contributor storage c = contributors[payee];
        uint256 oldBps = c.sharesBps;

        // Step 1: settle and preserve historical unwithdrawn earnings at the current share
        if (oldBps > 0) {
            uint256 currentAccumulated = (oldBps * accRevenuePerBps) / 1e18;
            if (currentAccumulated > c.rewardDebt) {
                c.accruedBalance += (currentAccumulated - c.rewardDebt);
            }
        }

        // Step 2: apply the new share
        c.sharesBps = newSharesBps;

        // Step 3: realign reward debt so the new share's net gain at the current accumulator is exactly zero
        c.rewardDebt = (newSharesBps * accRevenuePerBps) / 1e18;

        emit SharesUpdated(payee, oldBps, newSharesBps);
    }

    /**
     * @notice Creator-initiated pull withdrawal
     */
    function withdraw() external nonReentrant {
        Contributor storage c = contributors[msg.sender];
        uint256 claimable = pendingRoyalty(msg.sender);
        if (claimable == 0) revert NoClaimableBalance();

        // Reset state
        c.accruedBalance = 0;
        c.rewardDebt = (c.sharesBps * accRevenuePerBps) / 1e18;

        paymentToken.safeTransfer(msg.sender, claimable);
        emit RoyaltyWithdrawn(msg.sender, claimable);
    }
}

4. Foundry Fuzz Tests: Reproducing Dilution and Verifying Conservation

To demonstrate safety across arbitrary share changes and concurrent deposits and withdrawals, we wrote strict Foundry assertions:

// musicflow/contracts/test/DynamicRoyaltyAccumulator.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "forge-std/Test.sol";
import "../src/DynamicRoyaltyAccumulator.sol";

contract DynamicRoyaltyAccumulatorTest is Test {
    DynamicRoyaltyAccumulator public accumulator;
    // Mock test token and addresses...

    function test_NoHistoricalDilutionWhenNewPayeeJoins() public {
        // 1. Original two-person team: A 50%, B 50%
        accumulator.setContributorShare(authorA, 5000);
        accumulator.setContributorShare(authorB, 5000);

        // 2. Deposit 10,000 USDC revenue (A and B each earn 5,000)
        deal(address(usdc), address(this), 10_000 * 1e6);
        usdc.approve(address(accumulator), 10_000 * 1e6);
        accumulator.depositRevenue(10_000 * 1e6);

        // 3. Mixer C joins; shares become A: 40%, B: 40%, C: 20%
        accumulator.setContributorShare(authorA, 4000);
        accumulator.setContributorShare(authorB, 4000);
        accumulator.setContributorShare(mixerC, 2000);

        // 4. Core invariant: mixer C's withdrawable amount must be exactly 0
        assertEq(accumulator.pendingRoyalty(mixerC), 0, "New contributor C must have 0 historical claim");

        // 5. A and B's historical 5,000 USDC must remain undiluted
        assertEq(accumulator.pendingRoyalty(authorA), 5_000 * 1e6, "Author A historical funds preserved");
        assertEq(accumulator.pendingRoyalty(authorB), 5_000 * 1e6, "Author B historical funds preserved");

        // 6. Deposit 1,000 USDC in the second phase and verify the new split
        deal(address(usdc), address(this), 1_000 * 1e6);
        usdc.approve(address(accumulator), 1_000 * 1e6);
        accumulator.depositRevenue(1_000 * 1e6);

        // C earns 20% of new revenue = 200 USDC
        assertEq(accumulator.pendingRoyalty(mixerC), 200 * 1e6);
        // A earns historical 5,000 + new 400 = 5,400 USDC
        assertEq(accumulator.pendingRoyalty(authorA), 5_400 * 1e6);
    }
}

5. Comparing Static OpenZeppelin Splits, Push-Loop Settlement, and O(1) Accumulators

The following table compares the engineering feasibility of three royalty-splitting approaches for changing teams:

Architecture dimension A: Original static OpenZeppelin model B: Forced push transfers when changing shares C: MusicFlow O(1) dynamic accumulator
Dynamic share changes Unsupported (changes cause financial failure) Supported, but expensive on every update Fully supported, with changes at any time and no side effects
Historical unclaimed earnings Severely diluted (new members claim old funds) Protected in theory, but one revert can break settlement Mathematical isolation in code fixes historical earnings with zero dilution
Gas per share update N/A O(N); more than 50 participants inevitably runs out of gas Strict O(1), updating only one contributor’s storage
Gas per deposit Low (global-variable increment only) Low Very low (updates only accRevenuePerBps)
Malicious-recipient tolerance A malicious creator contract can block others’ withdrawals Extremely fragile: one revert prevents all share changes Fully immune (pull withdrawals isolate creators from one another)

6. Integrating Licensing Purchases and Frontend Interactions

The dynamic accumulator is the accounting core of the Web3 licensing economy and integrates with the other infrastructure:

  1. Multilevel licensing state-machine integration: With the Mutually Exclusive Multilevel Digital Licensing Design, personal licenses, commercial sync rights, and exclusive buyouts worth tens of thousands of dollars all trigger depositRevenue, allowing every collaborator to accrue earnings smoothly at the same moment.
  2. Gas economics for on-demand withdrawals: Following Gas Economics and Architecture Choices for Creator-Platform Payouts, creators can withdraw each receipt immediately or accumulate earnings before calling withdraw once, maximizing gas efficiency on Arbitrum, Base, or Ethereum L1.

Consulting and Source-Code Delivery

If you are building Web3 audio streaming, digital-art revenue sharing, AI creator collectives, or multitenant SaaS revenue distribution, and want to eliminate historical-earnings disputes and gas explosions caused by share changes: