
Summary: Managing protocol treasuries and token distributions requires transparent on-chain mechanics rather than trust in private keys. Pushing revenue through loops to multiple recipients creates denial-of-service vulnerabilities if a single recipient reverts; PaymentSplit replaces this with an immutable cumulative pull pattern. For team and investor allocations, TokenVesting and TokenLocker contracts enforce programmatic release curves and cliff schedules. At the administrative level, a TimelockController introduces mandatory review delays before governance decisions execute. This guide examines the mathematical formulas, state models, and Foundry tests behind these four core treasury primitives.
1. Proportional Revenue Distribution: PaymentSplit.sol
Temporal control: managing progressive token unlocks over time alongside mandatory governance review delays.
When an application receives continuous protocol fees or NFT primary sales revenue that must be split among multiple contributors (e.g., founders, artists, platform DAO), iterating over an array to push transfers introduces fatal failure modes: 1. Denial-of-Service: If one recipient is a contract that reverts on receipt (or lacks a payable fallback), the entire loop reverts, freezing funds for all other payees. 2. Gas Overhead: Distributing funds to dozens of recipients in a single transaction risks exceeding the block gas limit.
PaymentSplit implements a cumulative pull model: incoming ETH or tokens accumulate in the contract balance, and each payee independently calls release() to withdraw their proportional share.
From the open-source repository imminer668/Solidity-Guide (foundry_projects/07_distribution/30_PaymentSplit/src/raw/PaymentSplit.sol):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract PaymentSplit {
uint256 public totalShares;
uint256 public totalReleased;
mapping(address => uint256) public shares;
mapping(address => uint256) public released;
address[] public payees;
event PayeeAdded(address account, uint256 shares_);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
constructor(address[] memory _payees, uint256[] memory _shares) {
require(_payees.length == _shares.length, "Length mismatch");
require(_payees.length > 0, "No payees");
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
// Direct transfers accumulate in balance
receive() external payable virtual {
emit PaymentReceived(msg.sender, msg.value);
}
function _addPayee(address _account, uint256 _accountShares) private {
require(_account != address(0), "Zero address");
require(_accountShares > 0, "Zero shares");
require(shares[_account] == 0, "Duplicate payee");
payees.push(_account);
shares[_account] = _accountShares;
totalShares += _accountShares;
emit PayeeAdded(_account, _accountShares);
}
// Cumulative accounting formula
function releasable(address _account) public view returns (uint256) {
uint256 totalReceived = address(this).balance + totalReleased;
return pendingPayment(_account, totalReceived, released[_account]);
}
function pendingPayment(
address _account,
uint256 _totalReceived,
uint256 _alreadyReleased
) public view returns (uint256) {
return (_totalReceived * shares[_account]) / totalShares - _alreadyReleased;
}
function release(address payable _account) public virtual {
require(shares[_account] > 0, "No shares");
uint256 payment = releasable(_account);
require(payment != 0, "Not due payment");
// 1. Effects: update accounting before transfer
totalReleased += payment;
released[_account] += payment;
// 2. Interactions: transfer funds
(bool success, ) = _account.call{value: payment}("");
require(success, "Transfer failed");
emit PaymentReleased(_account, payment);
}
}
1.1 Why totalReceived = balance + totalReleased Works
If a contract receives 4 ETH, User A (holding 25% of shares) claims 1 ETH. The contract balance drops to 3 ETH. If a naive formula used balance * shares / totalShares, User A’s share would recalculate incorrectly on subsequent queries.
By defining: The contract recalculates lifetime earnings dynamically. If another 8 ETH arrives later, lifetime receipts equal . User A’s lifetime entitlement is . Subtracting their previously released 1 ETH leaves exactly 2 ETH available to claim.
2. Linear Token Vesting: TokenVesting.sol
Token allocations for core contributors and early investors are typically subjected to multi-year vesting schedules with an optional lockup period (cliff).
From foundry_projects/07_distribution/31_TokenVesting/src/raw/TokenVesting.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {IERC20} from "./IERC20.sol";
contract TokenVesting {
mapping(address => uint256) public erc20Released;
address public immutable beneficiary;
uint256 public immutable start;
uint256 public immutable duration;
event ERC20Released(address indexed token, uint256 amount);
constructor(address beneficiaryAddress, uint256 durationSeconds) {
require(beneficiaryAddress != address(0), "Zero address");
beneficiary = beneficiaryAddress;
start = block.timestamp;
duration = durationSeconds;
}
function vestedAmount(address token, uint256 timestamp) public view returns (uint256) {
uint256 totalAllocation = IERC20(token).balanceOf(address(this)) + erc20Released[token];
if (timestamp < start) {
return 0;
} else if (timestamp > start + duration) {
return totalAllocation;
} else {
return (totalAllocation * (timestamp - start)) / duration;
}
}
function release(address token) public {
uint256 releasable = vestedAmount(token, block.timestamp) - erc20Released[token];
require(releasable > 0, "No tokens to release");
erc20Released[token] += releasable;
emit ERC20Released(token, releasable);
IERC20(token).transfer(beneficiary, releasable);
}
}Timeline:
t = start -> 0% vested
t = start + (duration / 2) -> 50% vested
t = start + duration -> 100% vested
Like PaymentSplit, TokenVesting derives total allocation from balance + released, meaning additional tokens transferred into the contract automatically follow the same vesting schedule without manual state reconfiguration.
3. Discretionary Timelock Governance: Timelock.sol
When protocol administrators hold keys to adjust system fees, upgrade logic contracts, or migrate treasuries, direct execution creates counterparty risk. A TimelockController forces all administrative actions into a two-stage queue:
1. Queue Transaction:
Admin proposes tx: target, value, calldata, salt.
Contract asserts: eta >= block.timestamp + minDelay (e.g. 48 hours).
Emits QueueTransaction event.
2. Public Review Window (48 Hours):
Community and tokenholders monitor the queue on-chain.
If malicious, users have time to withdraw liquidity or exit the protocol.
3. Execute Transaction:
Admin calls executeTransaction once eta has elapsed and before grace period expires.
From foundry_projects/07_distribution/33_Timelock/src/raw/Timelock.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
error NotAdmin();
error ExecutionTooEarly();
error ExecutionExpired();
contract Timelock {
address public admin;
uint256 public constant MIN_DELAY = 2 days;
uint256 public constant GRACE_PERIOD = 7 days;
mapping(bytes32 => bool) public queuedTransactions;
event QueueTransaction(bytes32 indexed txHash, address target, uint256 value, bytes data, uint256 eta);
event ExecuteTransaction(bytes32 indexed txHash, address target, uint256 value, bytes data, uint256 eta);
constructor() {
admin = msg.sender;
}
function queueTransaction(address target, uint256 value, bytes calldata data, uint256 eta) external returns (bytes32) {
if (msg.sender != admin) revert NotAdmin();
if (eta < block.timestamp + MIN_DELAY) revert ExecutionTooEarly();
bytes32 txHash = keccak256(abi.encode(target, value, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function executeTransaction(address target, uint256 value, bytes calldata data, uint256 eta) external payable returns (bytes memory) {
if (msg.sender != admin) revert NotAdmin();
bytes32 txHash = keccak256(abi.encode(target, value, data, eta));
require(queuedTransactions[txHash], "Transaction not queued");
if (block.timestamp < eta) revert ExecutionTooEarly();
if (block.timestamp > eta + GRACE_PERIOD) revert ExecutionExpired();
queuedTransactions[txHash] = false;
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Transaction execution reverted");
emit ExecuteTransaction(txHash, target, value, data, eta);
return returnData;
}
}
4. Testing with Foundry
Testing time-dependent financial contracts in Foundry relies on vm.warp to simulate the passage of days or months:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {Test} from "forge-std/Test.sol";
import {TokenVesting} from "../src/raw/TokenVesting.sol";
import {ERC20} from "../src/raw/ERC20.sol";
contract TokenVestingTest is Test {
TokenVesting public vesting;
ERC20 public token;
address beneficiary = address(0x1);
function setUp() public {
token = new ERC20();
// 100-second vesting duration for testing
vesting = new TokenVesting(beneficiary, 100);
deal(address(token), address(vesting), 10_000 ether);
}
function testLinearReleaseAtFiftyPercent() public {
// Warp block timestamp forward 50 seconds (50% elapsed)
vm.warp(block.timestamp + 50);
vesting.release(address(token));
// Exactly 5,000 tokens should be transferred
assertEq(token.balanceOf(beneficiary), 5_000 ether);
}
}
5. Production Systems Context
In production Web3 products: – Fone MusicFlow (中文版): Applies cumulative split accounting to distribute music streaming revenue and licensing royalties across multiple contributors and rights holders, resolving rounding dust systematically (see Revenue Split Rounding for Music Licensing Platforms). – White-Label DEX (中文版): Integrates TokenVesting and TokenLocker contracts into its launch kit, allowing teams to enforce transparent team lockups and liquidity pool commitments before launching public trading pairs.
Review live systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.
Treasury & Tokenomics Primitives Comparison
| Treasury Primitive | Core Mathematical / State Rule | Release Trigger | Primary Production Role |
|---|---|---|---|
PaymentSplit.sol (30_PaymentSplit) |
$ ext{Payable}_i = – ext{Released}_i$ | Pull by any payee (release(account)) |
Multi-creator royalty splits and protocol fee sharing |
TokenVesting.sol (31_TokenVesting) |
Linear interpolation between start and start + duration |
Beneficiary claims unlocked delta | Team, advisor, and institutional investor token unlock schedules |
TokenLocker.sol (32_TokenLocker) |
Binary cliff check: block.timestamp >= unlockTime |
Beneficiary withdraws 100% after cliff | AMM LP token locking to prove liquidity commitment |
Timelock.sol (33_Timelock) |
eta >= block.timestamp + delay and block.timestamp <= eta + GRACE_PERIOD |
queueTransaction wait executeTransaction |
Delaying sensitive governance upgrades so users can exit before malicious changes take effect |
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/07_distribution/31_TokenVesting):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/07_distribution/31_TokenVesting && forge test -vvv
Expected local verification output:
[PASS] test_LinearVestingSchedule() (gas: 61820)
[PASS] test_ReleaseHalfwayThroughSchedule() (gas: 58410)
Suite result: ok. 2 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
What happens to integer division remainder dust in PaymentSplit?
Because Solidity integer division truncates toward zero, splitting 100 wei across 3 equal payees (33, 33, 33) leaves 1 wei of residual dust in the contract. Production royalty systems like Fone MusicFlow explicitly sweep accumulated division dust into a designated treasury reserve.
Why must TokenVesting include totalReleased in the totalAllocation calculation?
If vestedAmount only multiplied the vesting ratio against the current contract balance token.balanceOf(address(this)), every partial withdrawal would shrink the denominator for subsequent calculations. Adding totalReleased reconstructs the true cumulative historical inflow.
Why does Timelock enforce an upper GRACE_PERIOD boundary in addition to a minimum delay?
Without an expiration window (GRACE_PERIOD, typically 14 days), a queued administrative transaction that was shelved months ago could be unexpectedly executed at any point in the future when market or protocol conditions have completely changed.
Series & Related Engineering Guides
- Previous Lesson (S11): Web3 Growth & Batching in Solidity: Cooldown Faucets, Merkle Tree Airdrops, and Atomic MultiCall
- Next Lesson (S13): Market Mechanisms & Yield Vaults in Solidity: Dutch Auctions, Atomic NFT Swaps, and ERC4626 Vaults
- Companion Security & Architecture Deep-Dive (T08): The Practical Foundry Testing Cheat Sheet: Mastering vm.prank, expectRevert, vm.sign, and Time Manipulation
- Production Engineering Case Study: Versioning Offering Documents in an Investor Portal
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/07_distribution/31_TokenVesting) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering