
Modeling Vesting-Balance Invariants Across Cosmos SDK and EVM State
A vesting account has at least two relevant balances: tokens that are spendable now and tokens that remain locked. Cosmos EVM’s StateDB tracked the spendable balance, while Cosmos SDK staking could delegate locked tokens too. When delegation exceeded the EVM’s spendable-balance view, an unchecked subtraction could wrap; a second balance overflow could then transfer a victim’s apparent balance without changing total supply.
Prevent this class of cross-module accounting failure by making each state transition preserve explicit relationships between spendable, locked, delegated, and total balances. Test the boundary between the Cosmos SDK bank ledger and EVM state—not only whether each module’s local arithmetic succeeds. Solidity examples below are executable models of those invariants, not patches for Cosmos EVM itself.
Environment and baseline specifications
The incident identified in GHSA-7g4w-cg88-2cq2 affected Cosmos EVM versions below v0.6.2 and v0.7.2. This guide uses Solidity ^0.8.24 and Foundry, with the Cancun EVM as a practical baseline for the example harness. Solidity 0.8 checks ordinary arithmetic by default; that is useful for catching analogous mistakes in a model, but it does not repair unchecked arithmetic or inconsistent accounting in a Go implementation.
The reference implementation uses only Solidity’s standard library—no OpenZeppelin dependency. Pin the exact solc version in foundry.toml and use the same Cosmos EVM and Cosmos SDK revisions as the chain under test. For example:
[profile.default]
solc_version = "0.8.24"
evm_version = "cancun"
optimizer = true
optimizer_runs = 200
When reproducing the incident, test the relevant v0.6.x and v0.7.x release branches separately. Their backing-ledger behavior differed: v0.6.x used mint/burn operations; v0.7.x directly set balances in x/bank, subject to a uint256-to-int256 conversion boundary. A passing Solidity test is not evidence that either Go branch is safe.
The invariant that failed
Let:
Sbe the account’s spendable balance as seen by EVMStateDB.Lbe its locked vesting balance.Dbe its delegated balance.Tbe total token supply.
A simplified vesting account has S + L tokens in the bank ledger, but the EVM balance view may expose only S. Staking can nevertheless accept a delegation funded from S + L. If a delegation of d is permitted when d > S, a write-back that computes S - d in an unchecked uint256 context wraps to a value near 2^256.
The safety requirement is not merely “the subtraction does not revert.” It is that every module agrees on the resulting account state and that aggregate balances reconcile with supply. A useful abstract invariant is:
bank balance = spendable + locked + delegated (according to the chain's accounting model)
0 <= spendable
delegated <= amount that the staking transition is authorized to consume
sum(account balances) = total supply
The exact equation depends on whether delegation moves tokens into a staking module account or changes a delegation record while leaving bank balances elsewhere. Define that accounting model from the chain’s actual keeper and module behavior; do not double-count delegated tokens.
Naive pattern: subtracting a balance the caller does not own
This Solidity snippet models the vulnerable write-back. unchecked is essential to the analogy: it recreates wrapping behavior rather than Solidity 0.8’s default checked subtraction.
function afterDelegation(uint256 balance, uint256 delegated) internal pure returns (uint256) {
unchecked {
return balance - delegated;
}
}
If balance is 10 and delegated is 11, the result becomes type(uint256).max. In the Cosmos EVM incident, the relevant mismatch was that the staking precompile and x/staking could use locked vesting funds, but StateDB tracked only spendable funds. The resulting underflow was then usable as an enormous EVM balance.
The second stage matters. The attacker sent a near-maximum amount to a victim account with a high balance. The addition overflowed so the victim’s balance became zero, while the attacker ended up with the victim’s prior balance. The total supply could remain unchanged: this was a redistribution enabled by inconsistent per-account arithmetic, not necessarily a net mint.
Production model: authorize against the same balance domain
A safe transition must determine which balance domain the operation consumes, validate the delegation against that domain, and update all affected representations atomically. The following Solidity model deliberately limits delegation to spendable funds. A chain that supports delegation of locked vesting funds must instead implement an explicit, consistent locked-balance transition; it must not subtract those funds from an EVM spendable-only balance.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract VestingLedgerModel {
error InsufficientSpendable(uint256 available, uint256 requested);
error BalanceInvariant();
struct Account {
uint256 spendable;
uint256 locked;
uint256 delegated;
}
mapping(address => Account) public accounts;
uint256 public totalSupply;
function delegateSpendable(address account, uint256 amount) external {
Account storage a = accounts[account];
if (amount > a.spendable) {
revert InsufficientSpendable(a.spendable, amount);
}
// Effects are applied only after validating the exact source balance.
a.spendable -= amount;
a.delegated += amount;
assert(a.spendable + a.locked + a.delegated <= totalSupply);
}
}
This example’s final assertion is a deliberately weak local bound, not a complete supply proof: total supply covers all accounts, so a per-account sum cannot establish global conservation. A production model should maintain or derive aggregate accounting across all relevant bank and staking module accounts, then assert the chain-specific supply equation. The important repair is the guard and the matched update: funds are debited from the same spendable balance that authorizes the operation.
If protocol requirements allow locked delegation, represent that path separately. For example, track lockedDelegated and reduce locked only under the vesting and staking rules that authorize it. Ensure the SDK bank transition, staking keeper, EVM StateDB write-back, and supply accounting all describe the same movement. A generic “subtract from balance” helper is unsafe when callers have different notions of available funds.
Prevent the follow-on account overflow
Balance addition is another boundary to test. Solidity’s checked arithmetic would revert on overflow, but an EVM-to-SDK bridge can introduce different checks or conversions. Validate recipient credit before changing either side of a transfer:
function credit(Account storage recipient, uint256 amount) internal {
if (amount > type(uint256).max - recipient.spendable) {
revert BalanceInvariant();
}
recipient.spendable += amount;
}
For a real cross-module transfer, both debit and credit must be committed as one transaction or rolled back together. Check the destination balance before mutation, and check every narrowing conversion at the SDK boundary. In particular, v0.7.x behavior described in the post-mortem accepted direct balance changes only if they survived uint256-to-int256 conversion. A value fitting uint256 does not necessarily fit int256; require value <= uint256(type(int256).max) before conversion, and verify how negative values are rejected.
Do not treat supply neutrality as a safety property by itself. The exploit’s combined operations could net to zero supply while stealing a victim’s balance. Per-account conservation and cross-module reconciliation are required in addition to total-supply checks.
Differential verification: test the boundary, not just the helper
Build a reproduction that uses a vesting account whose contract address is precomputed, then created as a vesting account before deploying the malicious contract at that address. This setup is significant: the post-mortem describes chaining the underflow and victim-balance overflow in one transaction through a contract deployed on top of the vesting account. A unit test that calls subtraction directly misses this transaction-level composition.
In Foundry, create a harness with spendable, locked, delegated, victim balance, and total supply. Include tests for:
- Delegating exactly the spendable balance.
- Delegating one unit more than spendable while locked funds exist.
- A credit that would overflow the victim’s balance.
- A transaction that performs delegation then victim credit, asserting rollback or a safe final state.
- The same logical scenario against the actual Cosmos EVM v0.6.x and v0.7.x branches.
For the Solidity model:
forge test -vvv
forge test --match-test testRejectsDelegationAboveSpendable -vvvv
forge test --fuzz-runs 10000
For the chain implementation, run equivalent integration tests against the exact branch and configuration, inspecting StateDB, staking precompile, x/staking, x/bank, and supply after each operation. Compare the v0.6.x Mint/Burn path with the v0.7.x direct-balance-set path; do not assume the same failure mode. The post-mortem notes that v0.6.x could hit a supply overflow and halt, while v0.7.x could accept balance changes within its conversion constraints.
Trade-offs
| Approach | Underflow behavior | Supply/accounting guarantee | Main cost |
|---|---|---|---|
| Unchecked subtraction from EVM spendable balance | Wraps when delegation exceeds spendable | None; subsequent transfer may redistribute victim balance | Cheap, unsafe |
| Solidity checked subtraction only | Reverts on underflow in Solidity 0.8 | Does not prove SDK and EVM state agree | Low, incomplete |
| Explicit source-balance guard plus matched updates | Rejects unauthorized spendable delegation | Requires module-wide reconciliation invariant | Extra checks and tests |
| Cross-version integration and invariant tests | Detects branch-specific behavior | Tests the actual bank, staking, and EVM boundary | Highest test-maintenance cost |
Gas values are intentionally omitted: this guide’s Solidity contract is an invariant model, not a benchmark for Cosmos EVM’s Go execution paths. Measure chain-specific execution costs on the target application and version.
Production pitfalls and edge cases
Locked is not synonymous with unavailable to every module. Staking may permit delegation of vesting funds under SDK rules. The fix is not to blindly forbid all locked delegation; it is to model the authorized source and ensure the EVM’s write-back does not debit a spendable-only balance by a larger amount.
Check ordering and atomicity. A precompile can validate one view, while a keeper or StateDB later writes another. Validate at the authoritative boundary and make intermediate state changes rollback-safe. A partial update followed by a failed conversion or bank operation can create a different mismatch.
Use exact-width conversion rules. uint256 and int256 have different positive ranges. Test values at type(int256).max, one above it, and at the signed minimum bit pattern. Also test zero balances, maximum locked balance, and recipient balances near the maximum.
Model aggregate accounts. The post-mortem mentions victims such as the 0x00 address or a multisignature wallet created at genesis. Tests should not assume ordinary user addresses or zero initial balances. Include module accounts, pre-funded accounts, and unusual but valid account addresses.
Treat deployed versions as an inventory problem. The advisory affected versions below v0.6.2 and v0.7.2, but open, permissionless deployments may be unknown to upstream maintainers. Confirm the deployed binary, backport, chain configuration, and upgrade status rather than relying on a repository’s current main branch.
Do not infer safety from decimal configuration. Initial reproduction efforts reportedly failed on known 18-decimal configurations, contributing to an incorrect assessment. Reproduce with production denomination settings, but also test boundary amounts and vesting states independently of display decimals. Decimal scaling does not remove integer wraparound.
When reviewing adjacent integrations, verify that token transfers and low-level call outcomes are handled correctly; see Preventing ERC-20 Return Value Assumptions in Solidity and Preventing Unchecked Low-Level Call Failures in Solidity. If the transition is exposed through an owner-controlled path, authorization must also avoid caller-identity confusion, as covered in Secure Use of tx.origin in Solidity: Avoiding Phishing-Style Authorization Bugs.
Frequently Asked Questions (FAQ)
Which Cosmos EVM versions were affected by GHSA-7g4w-cg88-2cq2?
The post-mortem identifies production versions below v0.6.2 or v0.7.2 as affected. Chains should verify their actual release branch, backports, and deployed binary rather than infer status from a version label alone.
Why did an 18-decimal configuration not prevent the vesting-balance exploit?
The underlying defect was a mismatch between spendable balance in EVM StateDB and locked funds available to staking, followed by unchecked arithmetic. Decimal configuration did not guarantee that the two modules used the same balance domain or prevent integer wraparound.
Why did Cosmos EVM v0.6.x and v0.7.x have different outcomes?
The post-mortem says v0.6.x used Mint/Burn operations on the backing SDK ledger, where a large mint could trigger a supply overflow and halt the chain. v0.7.x directly set balances in x/bank, accepting changes only when they survived the uint256-to-int256 conversion boundary.