Skip to main content

Replacing Custom Escrow with Protocol Primitives: Nine Stake-for-X Modes, Gas Sponsorship, and a Built-In TokenFactory

Robert Mao
BlockchainProtocol PrimitivesSecurityState MachineAnti-Sybil

Looking through a decade of public-chain security incidents, a pattern emerges: many severe asset losses begin with application-level custody logic, rather than a broken elliptic curve or SHA-256 hash. Developers repeatedly have to write asset-locking and escrow mechanisms from scratch in Turing-complete smart contracts.

Bridge reserves, auction bids, liquidity pools, and fee sponsorship all require someone to hold or constrain assets. On conventional chains, each project implements its own contracts. A missing reentrancy check, an incorrect rounding direction, or a compromised upgrade authority can put the entire pool at risk.

When designing state-layer primitives for @ocap/ledger-core, we asked:

If locking assets in exchange for a defined protocol right or performance guarantee is a basic operation, why should thousands of developers independently implement hazardous custody contracts instead of using a protocol primitive checked against formal invariants?

We built three engines directly into the state layer: delegated sponsorship with no extractable allocation (y = 0), a general stake state machine covering nine Stake-for-X modes, and a protocol-level TokenFactory with bonding-curve initialization, anti-Sybil graduation gates, and built-in constant-product routing.

1. The y = 0 invariant: free trials without transferable faucet allocations

Every application serving mainstream users or AI agents encounters the same onboarding problem: a newly registered DID wallet has a zero balance and cannot pay the gas fee for its first interaction.

The conventional solution is a faucet or registration airdrop. After an email, phone, or CAPTCHA check, the system transfers a small amount of native tokens, represented by y > 0, to the new address for fees or a trial.

While designing a free-trial mechanism without bearer allocations, we focused on a simple failure mode: any transferable allocation to a new account can become a target for automated Sybil collection. Frontend CAPTCHAs and device fingerprints add barriers, but they leave the transferable allocation in place.

Generating thousands of DID addresses is inexpensive. Automated CAPTCHA services and multimodal AI can help scripts pass centralized admission checks, then consolidate the allocations. The vulnerability begins with making the trial allocation independently transferable.

Delegated sponsorship with y = 0

Our constraint is that the new user's net increase in externally withdrawable, transferable balance remains zero (y = 0), while the user still signs real on-chain activity with their own key.

The execution pipeline in @ocap/ledger-core uses the native VerifyDelegation sponsorship primitive:

  1. The user signs without holding tokens. The client constructs a real application transaction, such as creating a workspace, minting a first commemorative badge, or calling an AI agent service. Its logical initiator (delegator) is the user's DID, while the fee-paying from identifies the application's marketingAccount.
  2. The protocol constrains recipients to a first-party allowlist of <= 32 addresses. The sponsorship credential permits only specified transaction types. Its itx.to must belong to a nonempty allowlist of first-party service addresses, capped at 32 entries. Per-transaction limits and rolling 24-hour quotas also apply.
  3. No transferable allocation leaks to the user. Execution atomically pays fees and service costs from the sponsorship account to the designated service or fee pool. The user experiences sovereign signing and an on-chain state transition, but receives no bearer tokens that can be consolidated and withdrawn. The transferable output of the trial is 0.

Sybil collection through faucet allocations compared with y=0 protocol-level delegated sponsorship

2. Nine Stake-for-X modes on one deterministic state machine

Beyond onboarding, many interactions among users, applications, and agents share the same structure: lock an asset to obtain a protocol resource, a performance guarantee, or a compute quota.

Instead of maintaining separate locking tables in each module, @ocap/ledger-core uses a shared protocol state store, statedb.stake (IStakeState). Every position follows the same deterministic finite-state machine:

ACTIVE (活跃生效) ──[revoke_stake]──► REVOKING (延时解锁冷静期, revokingUnlockAt)
  │                                        │
  ├──[slash_stake]────────────► SLASHED    └──[claim_stake (timestamp >= unlockAt)]──► RELEASED
  └──[consume_stake]──────────► CONSUMED

Here, ACTIVE means the position is in effect. REVOKING is the delayed-release cooldown, with release controlled by revokingUnlockAt. The diagram is reproduced unchanged from the source.

The protocol builds nine independent Stake-for-X modes on this common lifecycle, covering resource quotas and multiparty settlement:

ModeLocked assetProtocol right or state-machine behaviorCustom mechanism replaced
1. Stake-for-GasNative tokensDaily replenishment of fee-free compute quota according to stake weight, with deterministic GasSecurityGuard enforcementCentralized gas-relay pool contracts
2. Stake-for-TokenIssuance deposit (minIssuanceStakeAbt)Creating a functional token requires a locked deposit (revocable: false). Release is permitted only when the token reaches RETIRED and circulating supply is zeroExternal factories with no issuance admission requirement
3. Stake-for-LiquidityAssets on both sides of a poolDeposit into a protocol-level constant-product pool and create a tamper-evident LP positionExternal pool contracts exposed to reentrancy and flash-loan manipulation
4. Stake-for-BidAuction bid fundsEnglish or Dutch auction participation; a higher valid bid triggers a full return of the previous bid in the same transaction, in O(1) timeAuction escrow requiring manual withdrawals and risking stranded funds
5. Stake-for-OfferBuyer offer fundsOffers for a specific NFT or an attribute predicate, such as any pass with legendary rarity; delivery settles atomicallyOff-chain order books combined with broad asset-approval contracts
6. Stake-for-BridgeCross-chain backing reservesGuarantees for sovereign subledgers or cross-chain channels, constrained by challenge windows and slashingCustom multisignature bridge-custody contracts
7. Stake-for-CardFunctional tokens or denominated creditsFT-in-an-NFT-Policy-Shell: fungible credits inside an NFT access or compute card with expiry, frequency, and scope rulesComplex membership and prepaid-card contracts
8. Stake-for-DistributorDistributor and curator admission depositsAccess to ValueCard wholesale distribution and cross-brand Bundle curation without a licensing fee; the deposit is fully releasable after ESCROW_MATURITY settlement and the cooldownCentralized distribution systems with nonrefundable admission fees, or custom commission contracts
9. Stake-for-QualityService-provider performance depositsAn AI agent or node provider posts a service guarantee; verifiable breach evidence triggers deterministic SLASHED compensationOff-chain service-level agreements (SLAs) without protocol enforcement

Why GasSecurityGuard separates admission control from state transitions

Implementing Stake-for-Gas exposed a subtle consensus hazard. To keep a malicious fee-free account from flooding the sequencer, a node needs request-rate and rolling-window counters.

If a process-local per-second counter enters the on-chain state-transition function, machines with slightly different clocks or arrival timing can compute different stateRootHash values. That can cause a consensus fork.

We therefore split GasSecurityGuard into two layers:

  • Admission-only, process-local control. Sliding-window rate checks run at the gateway before a transaction enters the sequencing channel.
  • State-transition execution as a pure function of (tx, onChainState). Once admitted, quota deductions and state updates depend only on the transaction's deterministic txTimestampSeconds and persisted on-chain state. Validators and light nodes replaying the sequence compute identical Merkle state roots.

Nine Stake-for-X protocol modes built around a shared deterministic locking state machine

3. A built-in TokenFactory and constant-product AMM

Creating functional credits, community metering units, or a subledger's native settlement medium introduces another class of custody and routing problems. Unreviewed token and pool contracts can enable counterfeit assets, unauthorized reserve withdrawals, or cumulative rounding errors that violate pool invariants.

In @ocap/ledger-core, the two-stage TokenFactory and CONSTANT_PRODUCT_AMM are protocol state machines.

A two-stage lifecycle with anti-Sybil graduation gates

Every standard TokenFactory instance follows BONDING_CURVE → CONSTANT_PRODUCT_AMM:

  • Stage one: deterministic BONDING_CURVE. During initialization, a protocol-defined mathematical curve controls conversion ratios. All contributed reserves remain locked in the protocol state store, with no external administrator withdrawal key.
  • Two simultaneous graduation conditions. A reserve threshold alone can be filled through circular activity. The kernel therefore requires both:
    1. Accumulated reserves reaching minGraduationReserve.
    2. A qualifying holder count reaching minGraduationUniqueHolders, where each counted address must hold at least 0.50% of the current total supply (50 bps). Dust-sized address splitting cannot satisfy this holder criterion.
  • Permanently locked initial liquidity (revocable: false). When both gates pass, the same transaction moves the instance into CONSTANT_PRODUCT_AMM (x * y = k). All initial graduation reserves become a protocol-level Stake-for-Liquidity position with revocable: false, preventing withdrawal of that initial pool through position revocation.

Asymmetric pool-favoring rounding and atomic PathPayment

Integer arithmetic creates a dangerous edge case for x * y = k: repeated tiny conversions can exploit rounding errors to deplete reserves.

The integer mathematics library enforces an asymmetric pool-favoring rounding invariant:

  • Required asset inputs round up (ceil).
  • Asset outputs round down (floor).

After each state transition, the reserve product satisfies x' * y' >= k. Rounding residuals remain in the pool rather than becoming extractable through repeated calls.

The protocol also supplies PathPayment, an atomic multihop routing primitive. Suppose an AI agent holds medium A but needs to pay a compute service that accepts only C. Rather than making separate conversions and a final payment, it submits one PathPayment transaction specifying the route and minimum acceptable output. The core executes the cross-pool route, conversions, and final payment in one atomic state transition. If any slippage postcondition fails, the entire transaction rolls back without a partial transfer.

Two-stage TokenFactory graduation gates, permanently locked initial AMM liquidity, and atomic multihop PathPayment

Put the complexity in protocol invariants

Application developers rarely implement memory page tables or TCP congestion control. Operating systems encapsulate these error-prone mechanisms behind system calls with defined behavior and security boundaries.

The same reasoning applies to a blockchain foundation for ARCs and large-scale applications. Requiring each application developer to implement custody carefully repeats the hardest security work at every layer.

By making y = 0 sponsorship, nine Stake-for-X locking modes, the two-stage TokenFactory, and pool-favoring AMM / PathPayment arithmetic standard operations of the ledger core, we give developers declarative primitives governed by explicit mathematical invariants. Every custom escrow mechanism they can avoid is one fewer custody implementation to secure and maintain.