Engineering On-Chain Music Licensing & Automated Contributor Royalty Splits with Next.js, Viem, and Foundry

In commercial digital audio streaming, game soundtracks, and collaborative AI-generated assets, two dangerous contract anti-patterns are push-loop transfers and floating-point share estimates. Suppose four creators—a composer, arranger, sound designer, and mastering engineer—share the rights to a track. A buyer pays 500 USDC for a commercial license. If the contract distributes funds to all four wallets through token.transfer() calls in a for loop, one multisig wallet without a configured receive hook, or one address on the stablecoin’s sanctions blocklist, can revert the entire transaction. The buyer cannot pay, no creator earns licensing revenue, and the licensing protocol stops working.

A subtler flaw involves rounding dust and dilution of unsettled historical funds. With 6-decimal USDC, splitting 10,000,001 base units (about 10.000001 USDC) at 3333 : 3333 : 3334 basis points inevitably leaves 1 wei orphaned by integer truncation. Unless the ledger state machine explicitly accounts for it, thousands of license purchases will leave the contract’s actual balance out of sync with its recorded liabilities.

To eliminate blocked distributions, precision failures, and malicious reentrancy, Fone MusicFlow implements a production full-stack architecture combining two-stage accrual escrow, creator-initiated pull claims, and offline EIP-712 payout-address authorization. This article examines the contracts, PostgreSQL double-entry ledger, anti-hotlinking media byte streams, and Foundry tests.


Architecture: Separating License and Revenue-Share State

Engineering On-Chain Music Licensing & Automated Contributor Royalty Splits with Next.js, Viem, and Foundry

Fone MusicFlow separates copyright metadata, audio delivery files, and fund flows into four independent engineering layers:

+-----------------------------------------------------------------------------------+
|                         Fone MusicFlow Full-Stack Architecture                    |
+-----------------------------------------------------------------------------------+
|  1. Media Delivery & Streaming                                                    |
|     - Next.js / Node.js gateway (HTTP 206 Partial Content, Range: bytes=0-1048576) |
|     - Preview uses fixed-hash authorization; master uses fixedLicenseAudio (SHA-256)|
+-----------------------------------------------------------------------------------+
                                       |
                                       v
+-----------------------------------------------------------------------------------+
|  2. License Negotiation & Immutable PostgreSQL Double-Entry Accounting             |
|     - Rights reviews: license_rights_reviews (tamper-resistant snapshot trigger)  |
|     - Agreements: license_agreements (multiparty accepted_hash confirmation)      |
|     - Balanced entries: license_journals & license_journal_entries (debits = credits)|
+-----------------------------------------------------------------------------------+
                                       |
                                       v
+-----------------------------------------------------------------------------------+
|  3. Smart-Contract Fund State Machine (LicensePayments.sol)                         |
|     - Funds: Unseen -> Held -> Allocated -> PayoutExecuted (or Frozen/Refund)     |
|     - Quote integrity: keccak256(instanceKey, chainId, policy, work, terms, beneficiaries)|
|     - Precision: OpenZeppelin Math.mulDiv for fees/shares; explicit dust accounting|
+-----------------------------------------------------------------------------------+
                                       |
                                       v
+-----------------------------------------------------------------------------------+
|  4. Secure Creator Settlement & Pull Claim                                         |
|     - Per-order credits: atomic orderCredit[orderKey][beneficiary] increments     |
|     - EIP-712 address changes: PayoutAddressAuthorization + monotonic nonce       |
|     - Contract wallets: SignatureChecker.isValidSignatureNow supports ERC-1271   |
+-----------------------------------------------------------------------------------+

Three Technical Traps in Music Revenue Sharing and Royalty Settlement

Before building an on-chain royalty system, understand the technical weaknesses of traditional Web2 rights agencies and simple Web3 split contracts:

Dimension Traditional Web2 rights agencies (e.g. ASCAP/BMI) Simple Web3 push-loop contract Fone MusicFlow: Accrual + Pull
Settlement cycle Quarterly, T+90 to T+180 days Immediate transfers, but prone to out-of-gas reverts Immediate payment recognition (Held), with batch allocation and withdrawal after a 7-day dispute window
Failure tolerance Manual statement adjustments and expensive cross-border banking One restricted recipient can block the entire transaction Independent withdrawals; one failed transfer does not affect other beneficiaries
Precision Fiat rounded to two decimal places, producing off-chain reconciliation gains/losses Truncated remainders disappear or cause accounting mismatches Math.mulDiv plus explicit orderDust accumulation preserves funds exactly
Address security Paper amendments or backend tickets Bound only to the original key; compromise exposes assets EIP-712 typed authorization + incrementing nonce + ERC-1271 contract wallets
Delivery protection Plaintext CDN links easily captured and hotlinked Raw IPFS CIDs let unpaid users download masters HTTP 206 previews + high-fidelity decrypted delivery gated by on-chain payment evidence

Core Contract: The LicensePayments.sol Fund State Machine

In LicensePayments.sol, every fund movement follows strict state-transition rules. Unverified transfers are prohibited, and reentrancy locks plus before/after token-balance checks (pullExact / transferExact) reject nonstandard fee-charging ERC-20 tokens.

1. Structures and Strict Quote-Hash Validation

To bind payment to the agreed off-chain license terms, work hash, and revenue shares, registerOffer requires a Keccak-256 hash assembled from 13 parameters:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

contract LicensePayments is ReentrancyGuard, EIP712 {
    using SafeERC20 for IERC20;

    enum State { Unseen, Held, Frozen, Refundable, Refunded, Allocated, AllocatedRefunded }

    struct Beneficiary {
        address address_;
        uint16 bps; // Basis points (10000 = 100%)
    }

    struct Offer {
        bytes32 policyHash;
        bytes32 workHash;
        bytes32 termsHash;
        bytes32 agreementHash;
        uint256 amount;
        address platformRecipient;
        uint16 platformBps;
        Beneficiary[] beneficiaries;
        uint64 observationSeconds;
        bool active;
    }

    struct Order {
        bytes32 offerId;
        bytes32 quoteHash;
        address payer;
        uint256 amount;
        uint64 expiresAt;
        uint64 paidAt;
        State state;
    }

    bytes32 public immutable instanceKey;
    IERC20 public immutable token;
    address public immutable treasury;
    address public operator;
    address public pendingOperator;
    bool public salesPaused;

    uint256 public held;
    uint256 public refundable;
    uint256 public credits;
    uint256 public dust;

    mapping(bytes32 => Offer) private offers;
    mapping(bytes32 => Order) private orders;
    mapping(bytes32 => mapping(address => uint256)) public orderCredit;
    mapping(bytes32 => uint256) public orderDust;
    mapping(bytes32 => bool) public payoutExecuted;
    mapping(address => address) private destinations;
    mapping(address => uint256) public payoutNonce;

    bytes32 private constant ADDRESS_TYPEHASH = keccak256(
        "PayoutAddressAuthorization(bytes32 instanceKey,address beneficiary,address destination,uint256 nonce,uint64 deadline)"
    );

    // ... Event definitions ...

    constructor(
        bytes32 instance,
        address asset,
        address initialOperator,
        address initialTreasury
    ) EIP712("Web3MusicPayout", "1") {
        require(instance != bytes32(0) && asset.code.length > 0 && initialOperator != address(0) && initialTreasury != address(0), "invalid setup");
        require(IERC20Metadata(asset).decimals() == 6, "six decimals required");
        instanceKey = instance;
        token = IERC20(asset);
        operator = initialOperator;
        treasury = initialTreasury;
    }

At offer registration, operators cannot arbitrarily alter percentages or amounts because the offer ID must exactly match the digest of all parameters:

    function registerOffer(
        bytes32 id,
        bytes32 policy,
        bytes32 work,
        bytes32 terms,
        bytes32 agreement,
        uint256 amount,
        address recipient,
        uint16 fee,
        Beneficiary[] calldata beneficiaries,
        uint64 observationSeconds
    ) external onlyOperator {
        require(offers[id].amount == 0 && amount > 0 && recipient != address(0) && fee <= 10000 && observationSeconds > 0, "invalid offer");
        require(beneficiaries.length > 0 && beneficiaries.length <= 10, "beneficiaries");

        uint256 sum;
        for (uint256 i; i < beneficiaries.length; i++) {
            require(beneficiaries[i].address_ != address(0) && beneficiaries[i].bps > 0, "beneficiary");
            sum += beneficiaries[i].bps;
            for (uint256 j; j < i; j++) {
                require(beneficiaries[j].address_ != beneficiaries[i].address_, "duplicate beneficiary");
            }
        }
        require(sum == 10000, "shares");

        // Strict hash check locks all static offer commitments
        require(
            id == keccak256(abi.encode(
                uint8(2),
                instanceKey,
                block.chainid,
                address(this),
                policy,
                work,
                terms,
                agreement,
                amount,
                recipient,
                fee,
                keccak256(abi.encode(beneficiaries)),
                observationSeconds
            )),
            "offer hash"
        );

        Offer storage o = offers[id];
        o.policyHash = policy;
        o.workHash = work;
        o.termsHash = terms;
        o.agreementHash = agreement;
        o.amount = amount;
        o.platformRecipient = recipient;
        o.platformBps = fee;
        o.observationSeconds = observationSeconds;
        for (uint256 i; i < beneficiaries.length; i++) {
            o.beneficiaries.push(beneficiaries[i]);
        }
        emit OfferRegistered(id, policy, work, terms, agreement, amount);
    }

2. Payment Accrual and Observation-Period Isolation

When a buyer calls pay, funds enter Held. Until observationSeconds has elapsed—for example, a 7-day dispute window—nobody may allocate or withdraw that order’s funds, preventing bad debt from copyright complaints or fiat chargebacks:

    function pay(bytes32 key, bytes32 id, bytes32 quoteHash, uint64 expiresAt) external nonReentrant {
        Offer storage o = offers[id];
        require(!salesPaused && o.active && key != bytes32(0) && quoteHash != bytes32(0), "not payable");
        require(block.timestamp <= expiresAt && orders[key].state == State.Unseen, "expired or duplicate");

        orders[key] = Order(id, quoteHash, msg.sender, o.amount, expiresAt, uint64(block.timestamp), State.Held);
        held += o.amount;
        pullExact(msg.sender, o.amount);

        emit OrderPaid(key, id, msg.sender, o.amount, quoteHash, expiresAt);
    }

    function pullExact(address from, uint256 amount) private {
        uint256 beforeBalance = token.balanceOf(address(this));
        token.safeTransferFrom(from, address(this), amount);
        require(token.balanceOf(address(this)) == beforeBalance + amount, "nonstandard token");
    }

3. Math.mulDiv Allocation and the Rounding-Dust Invariant

After the observation period, the system calls allocate. Calculation proceeds in two stages:

  1. Take the platform management fee first: platformAmount = Math.mulDiv(amount, platformBps, 10000).
  2. Split the remaining pool by each creator’s bps: part = Math.mulDiv(pool, b.bps, 10000).
  3. Calculate the truncated remainder and add it to global dust:
    function allocate(bytes32 key, bytes32 decisionHash) external onlyOperator {
        Order storage o = orders[key];
        Offer storage f = offers[o.offerId];
        require(
            o.state == State.Held && decisionHash != bytes32(0) && block.timestamp >= uint256(o.paidAt) + f.observationSeconds,
            "not allocatable"
        );

        o.state = State.Allocated;
        held -= o.amount;

        // Calculate the platform fee
        uint256 platformAmount = Math.mulDiv(o.amount, uint256(f.platformBps), 10000);
        uint256 pool = o.amount - platformAmount;
        uint256 distributed = platformAmount;

        orderCredit[key][f.platformRecipient] += platformAmount;

        // Calculate each creator's share
        for (uint256 i; i < f.beneficiaries.length; i++) {
            Beneficiary storage b = f.beneficiaries[i];
            uint256 part = Math.mulDiv(pool, uint256(b.bps), 10000);
            orderCredit[key][b.address_] += part;
            distributed += part;
        }

        // Explicitly account for dust so actual token holdings exactly equal recorded balances
        uint256 remainder = o.amount - distributed;
        orderDust[key] = remainder;
        dust += remainder;
        credits += distributed;

        emit OrderAllocated(key, keccak256(abi.encode(key, o.offerId, o.amount, f.platformBps, f.beneficiaries, decisionHash)));
    }

With this design, the accounting() view always maintains the four-part balance: token.balanceOf(this) = held + refundable + credits + dust + unattributed Any unrecognized tokens sent directly to the contract are recorded as unattributed and cannot contaminate the business ledger.

4. Secure Creator Withdrawals and EIP-712 Payout-Address Authorization

To reduce gas costs, creators need not withdraw each order separately. Operations or creators can initiate batch-order withdrawals (payout). Each withdrawal checks the expected destination and current payout nonce:

    function payout(
        bytes32 key,
        address beneficiary,
        bytes32[] calldata orderKeys,
        address expectedDestination,
        uint256 expectedNonce
    ) external onlyOperator nonReentrant {
        require(key != bytes32(0) && !payoutExecuted[key] && beneficiary != address(0) && orderKeys.length > 0 && orderKeys.length <= 50, "invalid payout");

        address destination = payoutDestination(beneficiary);
        require(expectedDestination == destination && expectedNonce == payoutNonce[beneficiary], "address changed");

        uint256 amount;
        for (uint256 i; i < orderKeys.length; i++) {
            for (uint256 j; j < i; j++) {
                require(orderKeys[i] != orderKeys[j], "duplicate order");
            }
            amount += orderCredit[orderKeys[i]][beneficiary];
            orderCredit[orderKeys[i]][beneficiary] = 0; // Clear order credit after withdrawal
        }
        require(amount > 0, "no credit");

        payoutExecuted[key] = true;
        credits -= amount;
        transferExact(destination, amount);

        emit PayoutExecuted(key, beneficiary, destination, amount);
    }

When a creator changes receiving wallets—for example, moving from a personal hot wallet to a corporate cold wallet or multisig treasury—the system uses offline EIP-712 signatures and SignatureChecker.isValidSignatureNow. It supports ordinary EOA signatures and ERC-1271 isValidSignature verification for smart-contract wallets such as Gnosis Safe:

    function setPayoutAddress(
        address beneficiary,
        address destination,
        uint256 nonce,
        uint64 deadline,
        bytes calldata signature
    ) external {
        require(beneficiary != address(0) && destination != address(0) && nonce == payoutNonce[beneficiary] && block.timestamp <= deadline, "invalid authorization");

        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
            ADDRESS_TYPEHASH,
            instanceKey,
            beneficiary,
            destination,
            nonce,
            deadline
        )));

        require(SignatureChecker.isValidSignatureNow(beneficiary, digest, signature), "signature");

        destinations[beneficiary] = destination;
        payoutNonce[beneficiary] = nonce + 1; // Monotonic increment prevents replay

        emit PayoutAddressChanged(beneficiary, destination, nonce + 1);
    }

Server Settlement Engine and Strict PostgreSQL Ledger Constraints

JavaScript’s native Number has only 53 bits of integer precision, making large base-unit values with 6 or 18 decimals vulnerable to overflow and truncation. Fone MusicFlow uses native BigInt throughout its Node.js/TypeScript orchestration layer and serializes exact strings. Its allocation formula mirrors the Solidity contract:

// Excerpt from web3-ai-music-creator/src/server/economy/settlements.ts
const zero = BigInt(0);
const scale = BigInt(10000);

export function allocationAmounts(x: any) {
  const amount = BigInt(x.amountTokenUnits);
  const platform = (amount * BigInt(x.platformFeeBps)) / scale;
  const pool = amount - platform;
  
  const collaborators = x.beneficiaries.map((b: any) => ({
    address: b.address_,
    bps: b.bps,
    amountTokenUnits: String((pool * BigInt(b.bps)) / scale)
  }));
  
  // Extract the remainder
  const totalAllocated = collaborators.reduce((n: bigint, b: any) => n + BigInt(b.amountTokenUnits), zero);
  const dust = pool - totalAllocated;

  return {
    platformTokenUnits: String(platform),
    collaboratorPoolTokenUnits: String(pool),
    collaborators,
    dustTokenUnits: String(dust)
  };
}

Database Invariants and Trigger Defenses

PostgreSQL double-entry bookkeeping records each change in liabilities caused by an on-chain event. Strict constraint triggers require every journal’s debit-credit difference to be exactly zero:

-- Excerpt from db/migrations/013_license_orders.sql
CREATE TABLE license_journals (
  journal_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  order_id uuid NOT NULL REFERENCES license_orders,
  event_key text NOT NULL REFERENCES license_chain_events,
  reference text NOT NULL UNIQUE,
  asset text NOT NULL,
  snapshot jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE license_journal_entries (
  entry_id bigserial PRIMARY KEY,
  journal_id uuid NOT NULL REFERENCES license_journals,
  account text NOT NULL CHECK(account IN (
    'escrow_token', 'held_liability', 'exception_liability', 'refundable_liability',
    'platform_credit_liability', 'creator_credit_liability', 'dust_liability',
    'operator_refund_funding', 'operator_refund_expense'
  )),
  amount numeric(78,0) NOT NULL CHECK(amount <> 0),
  UNIQUE(journal_id, account)
);

-- Enforce balanced double-entry bookkeeping
CREATE FUNCTION check_license_journal() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE id uuid;
BEGIN
  id := NEW.journal_id;
  IF (SELECT count(*) FROM license_journal_entries WHERE journal_id = id) < 2 
     OR (SELECT coalesce(sum(amount), 1) FROM license_journal_entries WHERE journal_id = id) <> 0 THEN 
    RAISE EXCEPTION 'License journal must balance'; 
  END IF;
  RETURN NULL;
END; $$;

CREATE CONSTRAINT TRIGGER balanced_license_entries 
AFTER INSERT ON license_journal_entries 
DEFERRABLE INITIALLY DEFERRED 
FOR EACH ROW EXECUTE FUNCTION check_license_journal();

Secure Media Delivery: HTTP 206 Preview Streams and Master Verification

A common digital-music vulnerability is “one purchase, unlimited hotlinking.” Expose a complete lossless WAV URL in the DOM and anyone can inspect the page and download it.

MusicFlow separates media delivery into two channels:

  1. Public preview stream: Node.js serves limited-bitrate audio in chunks using HTTP 206 Partial Content, supporting Howler.js seeking while preventing direct static capture of the entire file.
  2. Commercially licensed master delivery: only after on-chain payment and a finalized payment_event in the database can the buyer call fixedLicenseAudio. The server calculates SHA-256 of the original disk file in real time and allows binary attachment download only if it exactly matches the on-chain audioHash:
// Excerpt from web3-ai-music-creator/src/server/media.ts
export async function fixedLicenseAudio(
  pool: Pick<Pool, 'query'>,
  request: Request,
  id: string,
  version: number,
  audioHash: string
) {
  const r = (await pool.query(
    'SELECT r.audio_local_path, r.audio_mime_type, v.audio_hash ' +
    'FROM songs s JOIN song_versions v USING(song_id) ' +
    'JOIN song_generation_results r ON r.job_id=s.source_job_id AND r.audio_hash=v.audio_hash ' +
    'WHERE s.song_id=$1 AND v.version=$2',
    [uuid(id), version]
  )).rows[0];

  if (!r || r.audio_hash !== audioHash) throw new ApiError(404, 'NOT_FOUND', 'Fixed audio not found');

  const root = await realpath(mediaRoot());
  const file = await realpath(path.resolve(root, r.audio_local_path));
  if (!file.startsWith(root + path.sep)) throw new ApiError(404, 'NOT_FOUND', 'Fixed audio not found');

  // Verify the physical file's content hash to prevent unauthorized modification
  const { readFile } = await import('node:fs/promises');
  const bytes = await readFile(file);
  const digest = 'sha256:' + createHash('sha256').update(bytes).digest('hex');
  if (digest !== audioHash) {
    throw new ApiError(503, 'LICENSE_DELIVERY_HASH_MISMATCH', 'Fixed audio verification failed');
  }

  // Build valid response headers with content ranges
  let start = 0, end = bytes.length - 1, status = 200;
  const range = request.headers.get('range');
  const headers = new Headers({
    'content-type': r.audio_mime_type,
    'cache-control': 'private, no-store',
    'x-content-type-options': 'nosniff',
    'accept-ranges': 'bytes',
    'content-disposition': 'attachment; filename="licensed-music.mp3"'
  });

  // Support resumed downloads and partial byte-stream responses
  if (range) {
    const m = range.match(/^bytes=(\d*)-(\d*)$/);
    if (m) {
      start = m[1] ? Number(m[1]) : Math.max(0, bytes.length - Number(m[2]));
      end = m[1] && m[2] ? Math.min(Number(m[2]), bytes.length - 1) : bytes.length - 1;
      status = 206;
      headers.set('content-range', `bytes ${start}-${end}/${bytes.length}`);
    }
  }

  headers.set('content-length', String(end - start + 1));
  return new Response(request.method === 'HEAD' ? null : new Uint8Array(bytes.subarray(start, end + 1)), {
    status,
    headers
  });
}

Foundry Tests: Extreme Conditions and Conservation Regression Checks

To verify the split contract under asymmetric amounts, odd token units, and concurrent withdrawals, MusicFlow provides a rigorous Foundry suite (LicensePayments.t.sol).

1. Exact 10 USDC Split: 15% Platform, 70% Alice, 30% Bob

The test verifies that after taking a 15% platform fee (1,500,000) from 10,000,000 base units (10 USDC), the remaining 8,500,000 is split at 7000 bps : 3000 bps into Alice’s 5,950,000 and Bob’s 2,550,000:

    function testExactSplitAndNoDuplicateAllocation() public {
        pay(K);
        mature();
        escrow.allocate(K, H);

        assertEq(escrow.orderCredit(K, platform), 15e5);      // Platform: 1.5 USDC
        assertEq(escrow.orderCredit(K, alice), 5950000);       // Alice: 5.95 USDC
        assertEq(escrow.orderCredit(K, bob), 2550000);         // Bob: 2.55 USDC

        (uint256 held, , uint256 credits, uint256 dust, ) = escrow.accounting();
        assertEq(held, 0);
        assertEq(credits, 10e6);
        assertEq(dust, 0);

        // Duplicate allocation and duplicate refund must revert
        vm.expectRevert();
        escrow.allocate(K, H);
        vm.expectRevert();
        escrow.approveRefund(K, H);
    }

2. Odd Units and 1-Wei Dust Accumulation

For amounts that do not divide evenly, such as 10,000,001 base units, the test requires the remainder to accumulate accurately in dust, preserving every token unit:

    function testPoolDustStaysRestrictedAndSamePlatformBeneficiaryAddsCredits() public {
        LicensePayments.Beneficiary[] memory bs = shares();
        bs[0].address_ = platform;
        bytes32 odd = offerId(10000001, platform, 1500, bs);

        escrow.registerOffer(odd, H, H, H, H, 10000001, platform, 1500, bs, 7 days);
        escrow.setOfferActive(odd, true);

        vm.prank(payer);
        escrow.pay(K, odd, H, uint64(block.timestamp + 900));
        mature();
        escrow.allocate(K, H);

        assertEq(escrow.orderCredit(K, platform), 7450000);
        (, , uint256 credits, uint256 dust, ) = escrow.accounting();
        assertEq(credits + dust, 10000001);
        assertEq(dust, 1); // Accumulate 1 wei in dust
    }

3. Isolated Operator Funding for Allocated Refunds (refundAllocated)

If an allocated order faces an unavoidable dispute, such as a serious copyright claim requiring a full buyer refund, the operator must inject fresh funds of its own. The system must never take other creators’ recorded orderCredit to cover the deficit:

    function testAllocatedRefundUsesFreshOperatorFundsWithoutTakingCreditsOrAnotherOrder() public {
        pay(K);
        pay(H);
        mature();
        escrow.allocate(K, H);

        // Refunding without fresh operator funding must revert
        vm.expectRevert();
        escrow.refundAllocated(K, H);

        // Operator approves and supplies fresh tokens
        token.mint(address(this), 10e6);
        token.approve(address(escrow), 10e6);
        escrow.refundAllocated(K, H);

        // Buyer receives a full refund; Alice's available credit for this order remains intact
        assertEq(token.balanceOf(payer), 90e6);
        assertEq(escrow.orderCredit(K, alice), 5950000);

        (uint256 held, , uint256 credits, , ) = escrow.accounting();
        assertEq(held, 10e6);
        assertEq(credits, 10e6);
    }

Five Engineering Rules for Digital-Rights Revenue Sharing

When designing on-chain splits for content platforms, AI audio/video marketplaces, or virtual game-item systems, follow these five production requirements:

  1. Prefer pull claims to push loops: never loop through external recipient transfers inside a purchase transaction. Record creator shares in state mappings and let creators or operations initiate controlled batch withdrawals.
  2. Validate the complete quote hash: when calling registerOffer, use keccak256(abi.encode(...)) to fix all static context, including revenue shares, platform fees, and legal terms, preventing runtime changes.
  3. Explicitly accumulate 1-wei dust: integer division truncates. Every remainder must enter a dedicated dust variable, keeping actual contract balances and the accounting total at zero discrepancy.
  4. Support EIP-712 and ERC-1271 address binding: payout-address changes require off-chain typed signatures and incrementing nonces. Administrators cannot freely change recipients, and contract multisig wallets remain supported.
  5. Separate preview streams from delivery masters: serve low-bitrate samples through HTTP 206 chunks. High-bitrate commercial source files require finalized on-chain payment events and real-time server SHA-256 verification to prevent unauthorized mirroring and hotlinking.

Architecture Consulting and Enterprise Delivery

Fone provides full-stack architecture for digital entertainment assets, AIGC pipelines, and compliance-intensive DeFi/RWA systems, spanning smart contracts, double-entry accounting, and high-concurrency frontend/backend delivery. If you are building a decentralized creator platform or IP licensing revenue-share system, or need conservation and security audits for existing contracts, use the following channels: