Iteration 4 of the AI-model-tokens plan: model-token holders can now stake their tokens
and earn a pro-rata share of the vault's revenue (in uclaw) — the "dividend-bearing"
property of a tokenized AI model.
Synthetix-style reward-index accrual (O(1) per stake/unstake/claim, no unbounded staker
iteration):
- Global Dividend { reward_per_token_stored: Uint256 (1e18 SCALE), total_staked }; per
staker Stake { staked, reward_index_snapshot, pending } in STAKES Map<&Addr,Stake>.
- On revenue: delta = amount * SCALE / total_staked. On any stake/unstake/claim: settle
first (pending += staked*(global-snapshot)/SCALE), then advance the snapshot — late
stakers never retroactively earn.
- src/rewards.rs: pure reward_index_delta + earned_since_snapshot, 9 unit tests
(settlement formula, two-staker split, late-staker exclusion, Uint256 precision at
large values, dust floor-rounding, zero guards).
New Execute msgs (exactly-one-coin validation, checked math, BankMsg::Send payouts):
- Stake / Unstake { amount } — model tokens escrowed outside the curve.
- ClaimRewards — pays settled pending in reserve_denom.
- DistributeRevenue — anyone funds the pool; errors NoStakers when total_staked == 0 so
funds are never stranded.
Swap fee (Config.fee_bps, default 30 bps) skimmed from every Buy (off the reserve input,
before the curve) and Sell (off the gross reserve output) and routed into the dividend
pool via the same reward-index bump — stakers earn from the model's usage. When
total_staked == 0 the fee falls back into the curve reserve (documented, never stranded);
curve invariant k = reserve*inventory still holds on the post-fee amounts.
New queries StakeInfo (live-computed claimable) and PoolInfo. INVARIANT (state.rs/README):
reward_per_token_stored monotonic; contract reserve balance covers pool.reserve +
settleable rewards; contract model balance covers pool.inventory + total_staked.
Verified: cargo build, cargo test (15 unit + 20 integration = 35, 0 failures),
cargo build --target wasm32-unknown-unknown --release (model_vault.wasm ~270KB),
clippy + fmt clean. Adversarial verify pass confirmed settle-ordering, pro-rata splits,
stranded-funds guards, no balance double-count, and funds conservation. Existing curve
tests preserved via fee_bps=0 seed helpers. Live deploy still uses cosmwasm/optimizer.
7.8 KiB
ModelVault
A standalone CosmWasm contract that gives an AI model token a bonding-curve market
so it can be traded "like a stock" against a CLAW reserve. This is phase P2 of
docs/plans/2026-06-01-ai-model-tokens.md (ModelVault bonding curve).
The vault trades a native tokenfactory model-token coin (factory/<issuer>/<subdenom>)
against a native reserve coin (uclaw by default) using a constant-product market.
There is no cw20 and no custom message type — only standard cosmwasm-std features, so it
deploys under the chain's wasm capability set (BuiltInCapabilities + token_factory).
Mechanics (constant product)
The pool tracks two amounts in state: reserve (reserve_denom) and inventory
(model_denom). The invariant is k = reserve * inventory. Each trade keeps k constant
(v0 has no swap fee):
- Buy — attach
reserve_denom.tokens_out = inventory - k / (reserve + amount_in); the contract sendstokens_outofmodel_denomto the buyer. Reserve goes up, inventory goes down, so the model-token price (reserve / inventory) rises. - Sell — attach
model_denom.reserve_out = reserve - k / (inventory + amount_in); the contract sendsreserve_outofreserve_denomto the seller. Price falls.
Reserve/inventory are tracked explicitly in state and updated on every trade. They are
NOT read from the live contract balance — during execute, attached funds are already
credited to the contract's bank balance, so a query_balance would double-count the
incoming coins. Tracking state directly avoids that classic gotcha.
Rounding note: an integer constant-product market is not strictly arbitrage-free at the rounding level (a buy-then-sell round trip can drift by a dust amount even before the swap fee). The
round_trip_returns_close_to_principaltest documents and bounds this on a zero-fee vault.
Dividend pool (P2): stake the model token, earn pro-rata revenue
Model-token holders can stake their tokens into a dividend pool and earn a pro-rata
share of revenue (paid in reserve_denom) that flows into the vault. Revenue arrives from
two sources:
- Swap fee — a configurable
fee_bps(default 30 bps = 0.30%) skimmed from everyBuy/Selland routed to stakers. This is the "earn from the model's usage" linkage: the more the model token trades, the more its stakers earn. DistributeRevenue— anyone may pushreserve_denomdirectly into the pool (e.g. the model owner sharing inference revenue).
Reward-index accrual (Synthetix pattern)
Paying every staker on each revenue event would be O(n) and unbounded in gas. Instead we use a single global accumulator and settle each staker lazily, so every operation is O(1) regardless of staker count:
- Global state (
Dividend):reward_per_token_stored(a scaledUint256index) andtotal_staked(Uint128). - Per-staker state (
Map<&Addr, Stake>):{ staked, reward_index_snapshot, pending }. - On revenue of
amountreserve acrosstotal_stakedtokens, the global index rises bydelta = amount * SCALE / total_staked(SCALE = 1e18, fixed-point, computed inUint256to avoid precision loss). - On any stake / unstake / claim, the staker is first settled:
pending += staked * (reward_per_token_stored - reward_index_snapshot) / SCALE, then the snapshot is advanced to the current global index. New tokens therefore never retroactively earn past revenue, and unstaked tokens keep what they already earned.
The pure index math lives in src/rewards.rs with unit tests covering the
settlement formula, two-staker pro-rata split, snapshot-excludes-prior-revenue, large-value
precision via Uint256, and floor-rounding dust.
Reward-index invariant
INVARIANT.
reward_per_token_storedis monotonically non-decreasing. The contract'sreserve_denombalance always coverspool.reserve + Σ(stakers' settleable rewards), and itsmodel_denombalance always coverspool.inventory + total_staked. Staked tokens are escrowed (held by the contract, outside the curve) and never feed the constant-product math; dividends are paid from the contract's reserve balance. Because the index uses floor division, the pool never pays out more than it received — any sub-unit remainder is left as dust until enough revenue accumulates.total_stakedis recomputed from explicit state on every stake/unstake, never inferred from live bank balances.
No-stakers fallback (funds never stranded)
DistributeRevenueerrors (NoStakers) whentotal_staked == 0, so a caller can never push revenue into an empty pool and lose it.- A swap fee that accrues while
total_staked == 0cannot raise the index either, so it is instead left in the curve reserve (added back topool.reserve). The fee is never lost — it simply benefits the curve until there are stakers to receive it.
Messages
InstantiateMsg { model_denom, reserve_denom?, owner?, initial_reserve?, initial_inventory?, fee_bps? }
— reserve_denom defaults to uclaw, owner defaults to the instantiator, fee_bps
defaults to 30 (0.30%) and must be <= 10000. The optional initial amounts seed the curve
state (attach matching funds at instantiate time).
ExecuteMsg:
Fund {}— owner-only. Attachmodel_denomand/orreserve_denom; the matching state amounts increase.Buy {}— attach exactly onereserve_denomcoin. Thefee_bpsportion is skimmed off the input and routed to the dividend pool; the net feeds the curve.Sell {}— attach exactly onemodel_denomcoin. Thefee_bpsportion is skimmed off the gross reserve output; the seller receives the net.Stake {}— attach exactly onemodel_denomcoin to escrow it into the dividend pool.Unstake { amount }— settle, decrease the stake, and returnamountmodel_denom.ClaimRewards {}— settle and pay out accruedreserve_denomdividends, zeroing pending.DistributeRevenue {}— attach exactly onereserve_denomcoin to distribute pro-rata across current stakers (errors iftotal_staked == 0).
QueryMsg:
Config {}->{ model_denom, reserve_denom, owner, fee_bps }Pool {}->{ reserve, inventory }Quote { side, amount }->{ amount_out, denom_in, denom_out }(pure curve math, no state change; reported gross of the swap fee)StakeInfo { address }->{ staked, claimable }(claimableis computed live: settledpending+ accrual since the staker's last settlement)PoolInfo {}->{ total_staked, reward_per_token_stored }
Build & test
# native build + cw-multi-test integration tests + pure-math unit tests
# (curve + reward-index math in src/curve.rs and src/rewards.rs)
cargo build
cargo test
# deployable wasm artifact
cargo build --target wasm32-unknown-unknown --release
# -> target/wasm32-unknown-unknown/release/model_vault.wasm
Demo
scripts/testnet/model-vault-demo.sh (best-effort) stores + instantiates the vault on a
local testnet, issues a model token, funds the vault, buys with CLAW, and sells back,
printing PASS/FAIL. It requires a running local multinode testnet and clawd /
clawchaind on PATH.
Deploying on-chain (wasm packaging)
A raw cargo build --target wasm32-unknown-unknown --release artifact is not
chain-loadable: modern rustc emits post-MVP wasm (bulk-memory/sign-ext) that the
chain's wasmvm rejects (bulk memory support is not enabled / deserialization error).
Produce a chain-loadable, MVP-compatible artifact with the CosmWasm optimizer:
docker run --rm -v "$PWD":/code -w /code/contracts/model-vault cosmwasm/optimizer:0.16.0
# -> contracts/model-vault/artifacts/model_vault.wasm (deploy this)
The contract logic is fully verified offline via cw-multi-test (cargo test); the
optimizer is only a packaging step for on-chain deployment.