Skip to main content
Status: Draft for Internal Review
Type: Standards Track
Category: Core
Created: 2025-10-03
Updated: 2026-11-03
Relates-to: CIP-43 (access meter and third fee-market track), CIP-40 (transaction verification — §7.3’s mode branch runs after the §2.5 preflight), CIP-41 (multi-signer authorization — consumes §2.5)
Cowboy Cloud and Cowboy Chain. This CIP specifies the Cowboy protocol. Cowboy Cloud runs on this protocol today. Cowboy Chain, a public network on the same protocol, is under consideration for a future release. Where the two differ, this CIP says so.
This specification, as amended by CIP-43, defines Cowboy’s tri-metered gas (Cycles/Accesses/Cells) and independent EIP‑1559 fee markets.
CIP-43 specifies the consensus accesses meter for store I/O, moves flat Storage KV Read/Write work out of Cycles and read bandwidth out of Cells, adds the third EIP-1559 fee track, and defines gas-vectors.v2. CIP-43 owns the Access weight table, capacities, and conformance requirements.
The neocloud fee-payer amendment adds a gated exception to signer-paid top-level gas for an authenticated, single-instruction infrastructure allowlist. It specifies a reservation-price clamp against lane-effective suggested fees, zero tips, bounded pre-payer reads and actor-then-owner reservation. A higher signed maximum is clamped for beneficiary funding; a decayed basefee does not invalidate an older quote. Actual charges must not exceed the clamped hold.C3’s RAS payer selection uses two stages. Pure admission/classification checks the supported commit kind, a signed binding-presence hint where available, and fixed cycles/Cells floors, without scanning refs or deriving a payload-sized access floor. The live selector prepays one Cycle per payload byte before a borrowed shape scan and then compares all three dimensions with the complete base plus C1+C3 allowances. A later shortfall selects signer payment with scan charges retained; failed initial floors perform no scan or C3 work. Finalize’s id-only payload requires one prepaid header read inside C3’s allowance to discover its binding; an unbound Finalize pays that read, while other unbound commit kinds pay no C3 work. Deterministic C3 decode or authority failures select signer payment; local storage/PVM faults escape before a receipt. Estimate advice may compute the complete signing floor, and estimates/final signing include each overhead once. Finalize’s complete access comparison uses the persisted volume/chunk bound after six discovery accesses, reusing live reads; its RPC advice uses a separate metered two-read peek. A signed/live budget from exact native need through native need plus five can finish signer-paid OutOfGas at the gate. Malformed retained stages still fail, with selected funding paying an eligible failure. Optional failed, malformed, incomplete or over-cap payer advice retains all original signer budgets atomically. Valid advice is inclusive and preserves the queued-epoch Cells floor; it never guarantees live funding. Below each C gate, the existing payer and receipt rules remain unchanged.

Cowboy Improvement Proposal (CIP-3): Dual-metered gas calculation and dynamic fee market

Abstract

Background

A single gas unit cannot distinguish computation costs from storage costs. Clients also need identical rules for metering Python execution to reach consensus.

Goal

As amended by CIP-43, this CIP prices resource consumption in three dimensions:
  • The VM meters every computational step in Cycles by instrumenting bytecode.
  • The sealed store gate deterministically charges Accesses for every cold store I/O operation before dispatch (CIP-43 §§3–5).
  • The protocol meters every persisted-data and transaction-data byte in Cells at persistence and payload boundaries.

1. Motivation

The Cowboy Whitepaper separates computation and data fees. Consensus requires clients to calculate the same usage. This CIP defines how Python VM operations consume Cycles and Cells, how the VM enforces cycles_limit and cells_limit, and how on-chain gas differs from off-chain computation fees. It also describes Runner costs for containers and TEEs.

2. Specification

2.1 Core definitions

  • A Cycle (unit: c) measures abstract computational work. Every Python bytecode operation and every host function call has a fixed Cycle cost. This is analogous to an instruction step count.
  • An Access (unit: a) equals one cold StateGet; other store I/O is weighted relative to it and charged before dispatch under CIP-43 §§3–5.
  • A Cell (unit: b) measures persistent data or payload work, where 1 Cell is equivalent to 1 byte. Cells are consumed by transaction payloads, return data, and persisted state; CIP-43 §6 makes transient read bandwidth and memory_cells non-priced on this track.

2.2 On-chain metering: The Actor VM

The Actor’s Python VM MUST implement Cycle, Access, and Cell metering. CIP-43 §§3–5 specify the Access gate; the following describes the existing Cycle and Cell reference strategies. 2.2.1 Cycle Calculation (Instruction-based Metering) Cycles are metered by instrumenting the core bytecode execution loop of the Python VM.
  • Before each Python bytecode instruction, the VM deducts its cost from the call’s remaining cycles_limit. If the cost exceeds the remaining limit, execution MUST halt immediately with an “Out of Cycles” error.
  • A static, consensus-critical cost table (HashMap<Instruction, u64>) maps every Python bytecode instruction to a fixed Cycle cost. This table forms part of the protocol constants. The following table lists some Cycle costs:
Actor deployment and clone (CIP-27 fork()) are host-level operations metered in Cycles, Cells and Accesses. Their costs are anchored to a fixed base plus a per-byte term over the supplied code and route bytes (CIP-15 §6.9), expressed as named protocol constants: Code upgrade (UpgradeActor, and the in-actor upgrade_self host call) is metered by a parallel actor_upgrade_* family with identical initial values (50,000 / 12 / 10,000 / 40). An upgrade also pays the same 10-cycle parse per code byte, charged up front before validation. The two per-byte deploy rates are the Tier-0 governance parameters gas.deploy.cycles_per_byte and gas.deploy.cells_per_byte (CIP-12 SetGovParam, stored at system:gov:param:<path>). Unset, they are the initial values above (12 and 40). Each must be a nonzero u64, checked at proposal submit, at enactment and at genesis, so governance can reprice deploys but never make them free. The upgrade family’s per-byte terms and PublishLibrary (CIP-26 §3.6) use the same two values. The base terms, the 10-Cycle parse and every other constant in this section stay fixed. Execution reads both rates once per block, next to the basefee config, and a change applies from the block after the enacting ExecuteProposal; RPC gas estimation prices with the committed rates, and GET /fees/pricing reports them under deploy. Net, at the initial rates, a code byte costs 22 Cycles + 40 Cells and a route byte costs 12 Cycles + 40 Cells. The JSON calldata Cells every transaction pays (1 Cell per JSON byte, up to 4 JSON bytes per code byte) are on top. CIP-26 §3.6 defines library gas. It distinguishes existing constants from requirements not yet implemented, including the 128-Cell catalog-row charge and the cache-hit code-blob exemption. The clone path defined by CIP-27 fork() MUST charge actor_deploy_base_cycles / actor_deploy_base_cells for the new actor-record write, but MUST NOT charge any per-byte code term. No code is supplied or stored (the parent’s code_hash is reused, and the code blob is already content-addressed on chain). The clone physically copies at most MAX_ACTOR_KV_COUNT storage entries; CIP-30’s O(1) storage-root fork is not consensus-live, so this path MUST charge CIP-43 §5.1’s full R + Copy(n) + Scan(MAX_LIBS_PER_ACTOR) + NestedFrame + W(out-keys) row, plus its host-crossing credit. Copy(n) is the single aggregate out-access charge for the n copied child keys, consumes the structural units specified by CIP-43’s canonical Copy(n) weight, is precharged from the O(1) count, and warms those destination keys; the copied keys MUST NOT also charge W. Here W(out-keys) covers writes outside the copied-key set, including the child actor record, inherited pins, birth slots, endowment and bond legs; the new ABI and residue census use the complete schedule below. When CIP-30 activates child.storage_root := parent.storage_root, CIP-43 MUST be amended so the fork row becomes R(child collision) + W(root) and the per-key copy charge disappears. (Sources: CIP-30 §§3.3–3.4; CIP-43 §5.1.) The address-group release’s existing physical-copy prototype prepays the committed KV bytes before its range walk, then prepays any growth from pending writes before cloning those values. Its copy Cells are max(committed KV bytes, final child KV bytes); pending deletes cannot refund the physical read. The committed byte-counter read uses the ordinary metered point-read Access charge. See CIP-27 §5 for this implementation’s scope. Fork schedule (CIP-27 §3.8, required for its new ABI). CIP-43 owns structural I/O pricing. The old storage-write/delete Cycle constants are not additional charges on this Access-meter release. The table specifies the coordinated implementation; it does not claim the new fork ABI or census is already implemented. R, W, Scan(n) and Copy(n) use CIP-43’s canonical weights and transaction-scoped cold/warm rules. The fork reuses its code blob and pays no code-byte deployment charge. There is no 200-Cycle per-write surcharge or separate census Cycle constant. Scan(1) is charged from the requested one-row bound, even when it finds zero rows; it must never hide an unbounded scan or eager collection. Internal loop steps do not add a second guest-host crossing fee. The non-residue Access components decompose the CIP-43 base row and must not be charged a second time. Residue cursor advances and deletions add variable Scan(1) and W(row) costs beyond that base row; they are not covered by its library-pin scan or output writes. CIP-27 §3.1 gates each prerequisite read/scan before its dependent validation, then reserves the remaining deterministic copy/write work in one checked aggregate. Residue census/deletion reserves incrementally after collision rejection; callback frame/work charges occur before their corresponding dispatch. No read/scan already charged at its gate is charged again by the aggregate. Exhaustion stops before the next bounded read/delete and all fork writes share the rollback savepoint. Conformance vectors cover exact sums, cold/warm overlaps, every conditional row, empty census, many tiny rows, and exhaustion at both positions. An implemented CIP-30 root-sharing release must pin its replacement root-write and Access charges together before removing physical-copy costs. Cycle/cell rates, basefee, and every fee product in this CIP are denominated in native ledger wei, the number the execution layer multiplies directly into u64 balance debits. Source comments calling these rates “attoCBY/attoDBY” are terminology drift; no conversion factor exists anywhere in the fee path, and an absolute-debit vector (N cycles at rate R debit exactly N×R wei) pins the denomination end to end. These constants are part of the fixed protocol gas schedule, except the two per-byte deploy rates above, which are governed (gas.deploy.*). Unlike the dual basefee and lane-fee multipliers (§2.2.3), they are not in the CIP-12 governable parameter set and change only through a node software release. 2.2.1.1 Per-Instruction Metering Requirements The instruction-cost table in §2.2.1 is the required metering model. Enforced metering mode (Enforce) folds interpreter charges into cycles_used, and generated genesis selects that mode. StateSnapshot.pvm_per_instr_gas reports the instruction contribution; it is not an additional charge. The diagnostic ObserveOnly mode excludes that contribution from committed accounting and does not establish conformance to this pricing model. A conforming implementation MUST:
  1. Use the protocol instruction-cost table, with cross-client vectors producing identical totals for the same handler and inputs.
  2. Charge before executing each bytecode, so the instruction stream determines the OutOfCycles halt point. Wall-clock timing and host scheduling do not affect it.
  3. Give nested cross-actor calls their own prepaid budgets and compose their totals in call order.
  4. Calibrate the table and block/lane budgets against representative workloads before treating per-instruction totals as authoritative. Investigate differences from host-boundary measurements. Do not assume the totals are equivalent.
  5. Reject execution on exhaustion without silently falling back to another cost model. Divergent metering is a consensus fault.
Conformance requires checking the enforced cost table and caller paths against these requirements, including nested-call totals and exact exhaustion points. Support for enforced charging alone does not prove that coverage. 2.2.2 Cell Calculation (Event-based Metering) The VM charges Cells at specific data read, write or storage events.
  • The Python VM’s host functions and transaction processing boundary charge Cells by calling meter.consume_cells(byte_count).
  • The protocol charges Cells at these points:
    1. Before Python VM execution begins, the transaction processor charges the transaction’s payload size as Cells.
    2. Host functions that interact with storage or data MUST charge for it.
      • state_set(key, value): charges key.len() + value.len() Cells. Inline blob writes are ordinary stored values, so their bytes are charged here; the per-KiB blob-commit term in §2.2.1 is a Cycles charge, not Cells. Under CIP-30 (Per-Actor Storage Root), state_set (and state_delete) additionally recompute the actor’s storage_root; that update carries a deterministic, bounded storage-trie-update charge on top of the Cell cost above (CIP-30 §3.3). The exact formula is a fixed protocol constant that MUST be pinned before the per-actor-trie scheme goes consensus-live; until then this term is not charged against consensus.
      • emit_event(topic, data): charges topic.len() + data.len() Cells: topic bytes and payload bytes are each billed at 1 cell/byte, with no fixed emission overhead. An explicit schema that first sets or changes the topic declaration is a separate persistent index write and charges the emitter 32 additional Cells for the identifier (CIP-29 §§2.1, 2.3).
    3. After an Actor’s handler successfully returns, the VM charges its return-value byte size as Cells.
2.2.3 Execution Lanes The block cycle budget is partitioned into reserved lanes to prevent any single transaction type from monopolizing block space (see Whitepaper §17.9): Shares are of the 80,000,000-cycle block cap (= 4 × BLOCK_CYCLES_TARGET), which is the sum of the four lanes. Each lane budget is an independent absolute per-block ceiling, not a reserved share of a smaller pool, and unused capacity in one lane does not cascade into another: a transaction is rejected when its own lane’s already-accumulated cycles have reached that lane’s ceiling, checked before the transaction executes. The hard cap on any single workload is therefore the largest lane (System, 32,800,000 = 1.64 × BLOCK_CYCLES_TARGET), not the 80,000,000 sum. A single-lane flood does not reach the aggregate block ceiling or the global basefee adjustment clamp by itself. The four constants are LANE_SYSTEM_CYCLES / LANE_USER_CYCLES / LANE_RUNNER_CYCLES / LANE_TIMER_CYCLES, split 41/28/20/11. WP §13 carries the same four values. Lanes partition cycles only. There is no LANE_*_CELLS constant or per-block cells admission cap. Cells have a basefee target, BLOCK_CELLS_TARGET, but no hard cap. See CIP-33 §2.6.4 reservation-lane erratum. A lane-admission vector set pins the four constants. For ordinary transactions, the Fee Multiplier column scales each global Cycle/Cell/Access basefee: lane_basefee = floor(global_basefee × lane_fee_mult_ppm / 1_000_000). All lanes default to 1.0× at genesis (no subsidy, no surcharge). The four multipliers are governance-tunable via CIP-12 Tier 0 and stored at 0x09 under the single key system:lane_fee_multipliers (a table with one entry per lane). Each multiplier MUST lie in [LANE_FEE_MULT_MIN, LANE_FEE_MULT_MAX] = [1, 1_000_000_000] ppm; 0 is rejected, since a zero multiplier would drive that lane’s effective basefee to 0 and remove the fee floor (a lane-DoS vector). Genesis default is 1_000_000 ppm (1.0×) per lane. Changing a multiplier does not change lane capacity; it scales the applicable live rates. Natural timer fires have a separate cycle basefee. CIP-1 §5 specifies the independent TimerBasefee curve: learning denominator 1, maximum change ±12.5% per block (1/8), and a target of LANE_TIMER_CYCLES / 2 = 4,400,000 cycles; the updated timer basefee is clamped to MIN_BASEFEE ..= MAX_BASEFEE. The Timer multiplier scales that separate cycle rate and the global cell/access rates, with each effective rate floored after division by 1_000_000; CIP-5 §6.3 applies those rates to both maximum and actual cost. Natural-timer usage is excluded from the global basefee update: ordinary transaction usage supplies the global inputs, while timer cycles feed their separate tracker. 2.2.4 Advanced Metering Challenges and Solutions After the rules-v2 regenesis, production actor execution uses the isolated Zygote worker with the Full sandbox from block 0. Frozen imports, deterministic host values, and trusted FSM continuations are unconditional; neither a block-height gate nor a genesis cutover field can disable these execution rules. In-process execution is a test reference only. The genesis-bound pvm_metering_mode controls interpreter compute metering and the unpriced bulk-allocation memory guard: enforce is the default and enables both; observe_only disables both through the existing metering kill switch. Other host-resource charges retain their specified schedules. The guard’s independent memory_cells budget is derived from the Cells limit and is not reduced as priced Cells are consumed. Its allocation counter MUST NOT enter receipt cells_used or fee settlement, consistent with CIP-43 §6; receipt Cells come from the host meter. Retiring the activation height preserves this separation. The current allocation-coverage limitation is recorded in §2.2.4.4 below. This change requires fresh state and a newly generated genesis. The retired pvm_cutover_height input is rejected, including a null value; it must be absent. There is no genesis major-version bump. This requirement does not itself authorize a network reset. Statically pricing high-level bytecode instructions is insufficient. To ensure full determinism, the VM must handle the dynamic nature of the Python language. The following specifications are mandatory:
  1. The cost of a bytecode like BINARY_ADD varies depending on the operand types (integers, strings, lists).
    • The protocol adopts a base cost + dynamic surcharge model. The static cost of a bytecode is its minimum base Cycle cost for execution. The VM must inspect the type and size of the operands at runtime and charge a corresponding surcharge. For example, for string or list concatenation, the surcharge must be proportional to their length.
  2. The cost of built-in functions (e.g., len(), sum(), max()) is directly related to their arguments.
    • All permitted built-in functions must be treated as special host calls and have a well-defined, consensus-critical cost calculation function. For len(), the cost is fixed and low; for sum() or max(), the cost must be proportional to the number of elements iterated over.
  3. Arbitrary C extensions are a major source of non-determinism and security vulnerabilities.
    • The protocol strictly forbids loading and executing arbitrary C extension modules. Any functionality requiring high-performance implementation (e.g., cryptographic operations) must be provided by the VM as deterministic, fully metered host functions. External C libraries are not a permitted source for it.
  4. Standard garbage collection (especially generational GC and cycle detection) is inherently non-deterministic regarding when it triggers and how long it runs.
    • The VM’s garbage collection mechanism must be deterministic. The protocol recommends a combination of the following strategies:
      • Transient allocation memory MUST be deterministically bounded independently of priced Cells. In enforce mode, the unpriced memory_cells guard described above covers instrumented single-operation bulk allocations exceeding MEMORY_LARGE_ALLOC_THRESHOLD_BYTES (4096 bytes). The guard does not cover incremental growth, such as append loops. Allocator-level enforcement remains deferred work; retiring the gate does not establish full allocation-coverage conformance to §2.2.4.4. Extending that coverage MUST preserve CIP-43 §6’s exclusion of memory_cells from fee settlement.
      • The VM primarily manages memory through reference counting. The corresponding bytecode Cycle costs include reference-counting work.
      • During the execution of a single transaction, running a non-deterministic cycle detection algorithm that could cause long pauses is forbidden. Memory management must ensure that all memory is deterministically reclaimed by the end of the transaction.
  5. Floating-point operations can yield minute, inconsistent results across different CPU architectures, operating systems, or compilers, which is fatal for a consensus system.
    • The protocol MUST enforce that all floating-point operations are executed via a deterministic, cross-platform software implementation. Client implementations MUST NOT use their host machine’s native FPU (Floating-Point Unit). All transcendental functions (e.g., trigonometry, logarithms) must come from a network-wide, version-locked deterministic math library.
  6. The operations for throwing and catching exceptions (try…except…finally) involve internal processes whose costs are not fixed and could be exploited for cheap attacks.
    • The cost of exception handling must be explicitly metered. The raise statement, entering a try block, and the jump instructions for executing except / finally blocks must each have their own fixed base Cycle cost.
  7. While JIT compilers can improve performance, their compilation timing, optimization paths, and resulting machine code are highly non-deterministic.
    • To guarantee absolute determinism and predictability, the protocol strictly forbids the use of any form of Just-In-Time compilation technology within the Actor VM. The VM must execute bytecode in a pure interpretation mode.
  8. Python’s import mechanism can load arbitrary modules, including those that depend on the filesystem, network, or system calls. This breaks determinism and security.
    • The protocol MUST maintain a strict “allowed module whitelist”. Only modules on the whitelist can be imported by Actor code.
    • The whitelist should include: core data structure modules (e.g., collections, itertools), math modules (deterministic implementation of math), deterministic hashlib, and protocol-specific host API modules (e.g., cowboy.messaging, cowboy.storage).
    • Attempting to import a module not on the whitelist will result in an ImportError and consume a fixed 50 cycles as a penalty.
    • Module import cost: 100 cycles (first import) + actual execution cost of module initialization. Modules are cached, and repeated imports within the same transaction cost 5 cycles.
  9. Python supports arbitrary precision integer arithmetic. While powerful, malicious code can perform computational DoS attacks by creating astronomically large numbers (e.g., 2**100000000).
    • Integer bit length MUST NOT exceed 4096 bits (approximately 1234 decimal digits).
    • Any operation that produces a result exceeding this limit (e.g., pow(), factorial, large multiplication) will raise an OverflowError.
    • Large integer operation Cycles cost must be proportional to bit length: base cost + max(bitlen(a), bitlen(b)) / 64 cycles.
  10. The encode() and decode() operations on strings may have different handling for certain edge Unicode characters across different Python versions or platforms (e.g., replacement characters, error modes).
    • The protocol only allows UTF-8 encoding for byte string and string conversion.
    • The error handling mode for str.encode() and bytes.decode() must be fixed to errors=‘strict’, which raises a UnicodeError on invalid characters. It cannot silently replace them.
    • The cost is 10 + len(input) cycles.
  11. The whitepaper mentions allowing “cooperative yields via async/await”, but the scheduling order of async code may introduce non-determinism.
    • The protocol prohibits true concurrent execution. All async/await code must execute in a single thread in strictly deterministic order.
    • await operation scheduling follows a FIFO queue. When a coroutine awaits, control passes to the next ready coroutine in the queue.
    • Use of asyncio.gather() or other concurrency operations that may cause non-deterministic execution order is not allowed.
  12. Passing data between Actors via messages and persisting state to storage require serialization of Python objects. If serialization is non-deterministic, the same object may produce different byte streams on different nodes.
    • Actor object storage and continuation state use Canonical CBOR (RFC 8949 §4.2.3 length-first ordering), with shortest integer encoding and no indefinite-length containers, as specified in CIP-6 §11.5. Call/message payloads follow their selected codec. Transaction wire bytes and signing preimages use the separate release-bound cowboy-protocol-codec contract in CIP-11 §10.3; CBOR object rules do not redefine that envelope.
    • CBOR map keys must be sorted by encoded-key length first, then bytewise within equal lengths (CIP-6 §11.5).
    • Floats must be serialized using the exact bit representation according to the IEEE 754 standard.
    • Actor CBOR uses the native codec surcharges below, in addition to ordinary VM instructions and any user callback bytecode. A byte-only 20 + total_bytes formula is not its price. Separate lifecycle/control-plane serialization costs do not configure this actor codec.
    Native CBOR cycle surcharges
    The current schedule applies to cowboy_sdk.codec.encode / decode and the native capture walk. Failed calls retain charges already incurred; the final encode byte remainders are settled only after a successful walk. Each encode/decode walk starts with 20 Cycles, including walks that later fail. Invalid or consumed capture-token metadata and incompatible capture options can be rejected before a walk and its base charge. A non-bytes decode argument instead pays 20 plus its charged class-name diagnostic. Encoding charges 8 per encoded item and another 8 per frozen-key insertion; decoding charges 14 per item, including tags and their inner item. An encoded bignum writes its tag without a second encode-item charge. A value-position dict subclass freezes all its keys. An exact dict begins freezing only at its first non-exact-builtin key and also backfills the preceding keys. Those insertions each pay the additional 8-item charge, even for an exact key; an exact-only dict has no frozen-key dictionary. Maps nested in ordinary keys do not use that dictionary. Freezing a non-exact key pays the 16-Cycle surcharge even when no new data copy is needed. No extra bignum-conversion charge is added merely for hashing an integer map key. Ordinary map keys and their children use the dense write rate, including byte-string payloads. A reducer-produced key is encoded as a value before its bytes are rotated into position, so a reduced byte-string key uses the bulk-payload rate plus its applicable frozen-key hashing/copy costs. For decoding, let D be the accumulated dense bytes read (headers, text, and other non-byte-payload data, plus byte-string key bytes that need hashing), and P the accumulated byte-string payload read beyond the call’s first 4 MiB. The top-ups, beyond the prepaid whole-input charge, are floor(D / 16) - floor(D / 128) and floor(P / 16) - floor(P / 128). They are collected as whole blocks are read, without an encode-style final rounding. Hashing has its own whole-block accumulator. These rounding rules are distinct from the per-copy, bignum, and twin-copy ceilings; rounding every row once per item would produce a different price. The sort’s key-byte term applies at every size; only the per-entry term has the 1,024-entry allowance. For frozen/decoded-key insertion collisions, use the widest encoded key seen so far, not merely the new key’s width. Class-cache entries are cleared when user code may have changed a class, so callback behavior and lookup shape affect the total. These terms are surcharges, not a replacement for the VM instruction schedule or a byte-only client estimate. Prepared capture reuse retains work and the output peak already accounted for by capture. A following encode starts a new walk, then copies the validated matching root ctx bytes without rewalking their items and byte writes; its copy counter continues from the captured encoding. A retained capture does not imply charging those item/byte walks a second time. Allocation accounting and bounds. Where VM memory metering is enabled, the encoder accounts for its output as one growing buffer: free at or below the large-allocation threshold, charged in full on crossing it, then by growth. Its map scratch, entry indexes, frozen twins, and objects built by decoding do not receive decoded-list/dict slot charges from this codec. A rendered capture-error diagnostic separately uses the large-allocation growth hook. This describes allocation bookkeeping; it does not enable or price memory_cells, whose treatment follows CIP-43 §6. Payload/return/persisted-state Cells at other boundaries remain separate. The native codec bounds array/map/tag nesting at 256 levels and reducer-chain normalization at 2; the interpreter’s remaining recursion limit can reject a shallower call. These limits and the prices above describe the current codec, not a proposal to change accepted objects, canonical bytes, or gas.
  13. The following rules bound recursion.
    • Deterministic actor execution MUST start each frame with a recursion limit of 256. The production positive actor policy MUST continue to deny sys.setrecursionlimit(n) with a catchable RuntimeError, leaving the limit unchanged, on both execution engines.
    • As defense in depth, deterministic runtime paths that permit the setter MUST cap a valid requested value at 256; lower valid limits may apply within the frame and MUST reset before the next execution. This runtime bound does not grant production actors access to the setter.
    • Exceeding the limit MUST raise catchable Python RecursionError. Raising the requested limit MUST NOT turn actor recursion into native stack overflow or an infrastructure fault. Already-consumed compute remains charged. Standalone execution with determinism disabled retains Python’s configurable limit.
  14. The following rules govern scalar strings, code validity and native recursion.
    • Deterministic Python MUST refuse unpaired surrogate construction with catchable ValueError or UnicodeError. This includes chr(0xD800..0xDFFF), source literal escapes, %c and integer c formatting (format, format fields and f-strings), JSON escapes yielding lone surrogates, and the surrogatepass/surrogateescape decoding handlers. Valid Unicode scalar strings and JSON surrogate pairs remain accepted. Source constants MUST be checked when evaluated or exposed, including tuple constants, whether emitted by the compiler (for example MATCH_CLASS keyword-name tuples) or supplied through code.replace(co_consts=...).
    • code.replace MUST accept newly constructed scalar strings in allowed filename, name, qualified-name and same-length name-table edits without requiring prior interning, subject to the restrictions below. Standalone profiles that permit raw code construction retain the same string validation and interning rules. Non-string metadata MUST raise TypeError; surrogate metadata MUST raise ValueError("code metadata must not contain surrogates"), including in standalone execution. String subclass conversion MUST NOT invoke guest callbacks. Interning MUST depend only on string content and preserve checkpoint serialization by value. Each explicitly supplied metadata string MUST charge one Cycle per UTF-8 byte before pool lookup, using the per-byte component of the existing str.encode / bytes.decode surcharge; this charge MUST be independent of internedness, pool warmth and checkpoint restoration. Fields omitted from replace() MUST be inherited directly without this surcharge. The charge is additional to ordinary instruction costs, and intentionally changes gas for permitted operations with explicit metadata; it bounds repeated large-name lookup and copying work. Reading a constant index absent from co_consts MUST raise ValueError("code constant index out of range") without panicking. Overflowing line-table varints and line/range arithmetic MUST raise ValueError("invalid code line table") from co_lines/co_positions without panicking.
    • Guest code-object field work MUST be prepaid at one Cycle per byte and one Cycle per logical array slot, derived respectively from the str.encode / bytes.decode byte component and the BUILD_TUPLE / BUILD_LIST element component (2 + size). co_lines() and co_positions() MUST charge the entire line-table byte length on each call before scanning; each emitted line triple MUST prepay six Cycles (2 + 3 for the tuple plus one result-list slot), and each position quadruple MUST prepay seven (2 + 4 + 1) before allocation. Invalid or merged entries do not refund scan charges. Byte getters (co_code, co_linetable, co_exceptiontable) MUST prepay their byte length; tuple getters (co_consts, co_names, co_varnames, co_freevars, co_cellvars) MUST prepay their top-level length. Permitted replacements (and constructors in standalone profiles that expose them) MUST prepay bytecode parsing/copying, line/exception-table copying, each name-array slot, each constant-reference and cached-verdict slot, two coordinates per source-location entry, and each inherited cell-to-argument slot before bulk work. Inherited fields are included in copy charges, but omitted string metadata incurs no string-byte surcharge. Replacement iterable arguments MUST prepay exact tuple/list slots before extraction, or one Cycle before each generic iterator advance (including its terminal advance); length hints MUST NOT authorize speculative allocation. repr(code) MUST prepay the UTF-8 name length plus six times the filename length, bounding debug escaping. These surcharges are additional to ordinary instructions and the explicit metadata-string charges, and intentionally change gas without changing successful field values.
    • Immutable tuple constant classification retains the existing memoized boundary: each tuple is classified at most once, and its first walk is amortized against the work already charged for tuple construction; subsequent code construction and replacement reuse its OnceCell verdict. There is no cache-miss-only Cycle surcharge. Operations that can create large tuples for a flat charge remain a separate p15-fu follow-up. Their price here does not depend on cache state.
    • Arbitrary Python objects remain accepted in co_consts subject to the typed-consumer restrictions below. When code is serialized by marshal or checkpoint machinery, or rendered by native _dis, unsupported literal values MUST raise ValueError("unmarshallable object"). The serialization guard MUST refuse cycles using in-progress identities, visit each distinct constant at most once, allow at most 256 edges from the root code object and at most 1,000,000 expanded values (the root code object and each occurrence of a constant, tuple member or nested code constant), and refuse larger graphs with the same error. These bounds protect the consumers’ native stack and by-value expansion of shared tuples. This grants no new actor import or checkpoint capability.
    • Deterministic actors MUST NOT construct raw code objects (including types.CodeType and type(code)) or supply structural replacement fields co_code, co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals, co_stacksize or co_exceptiontable, even with unchanged values. Integer argument conversion MUST precede the restriction gate: out-of-domain integers MUST raise catchable OverflowError, while every in-domain refusal by these restrictions MUST raise catchable TypeError. For replace(), the integer conversion domains are 0 through 2**32 - 1 for the argument counts, co_nlocals, co_stacksize and co_firstlineno, and 0 through 0xffff for co_flags. Metadata fields co_name, co_qualname, co_filename, co_firstlineno and co_linetable remain editable under the preceding pricing and string rules. co_names, co_varnames, co_cellvars and co_freevars replacements MUST preserve table length and valid scalar-string entries; length changes raise TypeError. co_flags MUST be unchanged or exactly the original flags OR 0x100; any other in-domain value raises TypeError. The allowed transition retains the current masking of that compatibility bit, without changing generator/coroutine flags; the frozen types.coroutine wrapper remains supported in deterministic embeddings. The production positive environment retains its existing refusal of frozen ABC cache writes.
    • A code object containing any typed consumer (MAKE_FUNCTION, SET_FUNCTION_ATTRIBUTE, keyword or expanded-argument calls, class/key matching, string building or format specifications, tuple flattening into tuple/list/set, dictionary update, or list/map/set insertion) MUST preserve every LoadConst-referenced constant slot by object identity on co_consts replacement. A removed or changed protected slot MUST raise TypeError. This conservative linear rule intentionally refuses some safe edits in mixed-use code; no control-flow or per-use proof is attempted. Unreferenced and exclusively ReturnConst slots remain editable, and code without typed consumers retains arbitrary constants. Every explicit constants edit MUST additionally prepay one Cycle per original bytecode byte and original constant slot before scanning, allocating scan facts or checking cached facts. Immutable facts MAY be cached, but cold, warm and restored code MUST pay identical fees. The native scan cache changes code-type __basicsize__ and inherited __sizeof__ observations; it MUST NOT change serialized code formats.
    • Function code assignment and invocation MUST refuse a closure-count mismatch with ValueError. Function construction MUST retain ValueError for an incorrect closure length and TypeError when required closure cells are absent. Function construction, positional-default assignment, code assignment and invocation MUST refuse more positional defaults than positional arguments with ValueError. The compiler establishes argument/local/cell-to-argument layout, and the permitted edits MUST preserve it. __closure__ remains read-only. __kwdefaults__ accepts dict/None; extra keys and subsequent dictionary mutation remain allowed because binding uses bounded lookups for declared parameters. The production positive builtin allowlist continues to exclude exec, eval and compile (unbound-name access raises NameError). Deterministic VM embeddings that expose exec/eval MUST refuse code requiring free variables with TypeError. Actor imports MUST NOT expose raw code factories through marshal or native _dis; checkpoint restoration remains a host-controlled entrance.
    • Node logging MUST NOT execute guest code or touch metering. In particular, enabling DEBUG MUST NOT render an additional Python traceback, invoke exception __str__/__repr__, or perform guest suggestion lookup. Native exception-type logging is allowed. Canonical fault rendering remains metered and MUST be independent of log level, with byte-identical receipt effects, gas and fault detail under DEBUG and INFO.
    • bytes.startswith/endswith and bytearray.startswith/endswith MUST try flat tuple alternatives in order before converting byte values. Integer tuples such as (65, 66) and nested tuple alternatives MUST raise TypeError if reached; an earlier match suppresses subsequent conversion and errors. An empty alternatives tuple MUST return False, including b"x".startswith(()) (previously True). Bytes affix conversion and type validation MUST precede slice-bound matching, so invalid affixes such as b"abc".startswith(1, 100, 0) raise TypeError even with out-of-range bounds. Those bounds cannot return False before affix validation. Bytearray affix conversion, including __iter__, __next__, __length_hint__ and __index__, MUST finish before borrowing the buffer and computing slice bounds.
    • Native recursive hashing, comparison, representation, containment comparisons, iterator chains and recursive length delegation MUST honor the fixed recursion limit with catchable RecursionError. Mutable containers retain their ordinary unhashable TypeError; non-recursive operations such as len do not traverse nested contents. Length-slot and iterator-next guards each consume one recursion level, so even shallow operations can raise RecursionError when the current call depth exhausts the budget.
    • Native recursion errors use the consensus-visible message prefix maximum recursion depth exceeded with an operation-specific suffix (this list is non-exhaustive): while hashing an object, while calling an object, while getting container length, while advancing an iterator, while binding a class method, while getting a method attribute, while getting an attribute, while setting an attribute, in comparison, while getting the repr of an object, in __issubclass__, in __subclasscheck__, in __instancecheck__, or the empty suffix used for ordinary Python-frame recursion; this text is retained in structured errors and receipt commitments.
    • Native callable delegation MUST enter the shared recursion guard at the actual call slot, including cached/direct slot invocation and dynamic __call__ dispatch. Each native delegation slot consumes one level for the duration of delegation. Python functions and bound methods forwarding directly to Python functions MUST use their existing frame-entry level without an additional call-slot level. Bound methods forwarding to native callables or other wrappers retain their native level. The fixed limit is a shared native/Python depth budget: up to 256 Python frames fit when no further guarded operation is needed, while comparisons, repr, getset callbacks, native calls, length and iterator-next operations require remaining budget. Native operations near that budget may raise RecursionError. functools.partial.__setstate__ MUST refuse direct self-reference with RecursionError before changing state; deeper cycles and acyclic chains MUST be bounded at invocation.
    • Native getset getter/setter callbacks MUST enter the shared recursion guard at the descriptor slot, including direct descriptor calls. Static/class method metadata and repr, and property accessor/abstract-flag callbacks, MUST release wrapper locks before invoking guest code. Static/class method __init__ MUST refuse direct self-wrap with RecursionError before changing the wrapped reference. Metadata cycles and deep chains MUST be catchable; wrapper repr MUST propagate Python errors, including recursion refusal, without panicking. Shallow __func__/__wrapped__ access returns the immediate reference without walking the chain.
    • Production-reachable interpreter, container, iterator, metadata, buffer and codec locks MUST be released before guest callbacks or destruction of replaced references. State restoration MUST validate and build replacement dictionaries before publishing them; argument binding MUST release code/locals locks before guest keyword-default lookup. Reentrant callbacks MUST complete or raise a catchable Python exception; iterator callbacks MUST preserve inner exhaustion and advance from the live position after an inner advance. A getset level lasts only while its getter/setter runs; it does not halve the 256-frame allowance. Finalizer reporting at the depth ceiling MUST tolerate import/hook failures without panicking. Rejected collection-setter arguments MUST also be retired after unlocking. Dynamic base changes MUST update each affected descendant MRO after its affected bases, without recursive native traversal or locked finalization.
    • __setstate__ on an active generic sequence iterator MUST reject integers outside the signed native-index range with OverflowError and the message Python int too large to convert to Rust isize, before altering state. In-range negative positions clamp to zero. Advancing an active generic sequence iterator at or above the signed index limit MUST raise OverflowError with the message iter index too large. Iterator position arithmetic MUST NOT panic or wrap.
    • memoryview.cast MUST validate native scalar formats, positive dimensions, the 64-dimension ceiling and the byte-size product before exposing a view. Zero/negative dimensions and overflowing products raise ValueError; a buffer-size mismatch raises TypeError, including scalar casts. An individually unrepresentable dimension retains OverflowError. Slice strides and offsets MUST use checked arithmetic and raise a catchable exception when unrepresentable; empty reverse slices remain valid. Cast views retain the underlying export independently of the source view. Constructing from a released view MUST raise ValueError; get/set MUST recheck release state after guest index conversion before accessing the buffer. Final byte ranges MUST be checked, with invalid offsets raising a catchable Python exception. Exporters MUST preserve backing length until all export handles are released; each cloned handle owns an independent export. Bytearray reinitialization with an active export raises BufferError except for an empty-to-empty no-op; same-length element/slice writes remain allowed. Bulk reads and post-conversion buffer writes MUST check their final ranges and fail catchably on invalid bounds. Zero-dimensional memoryview reads, writes and tolist(), and memoryview comparisons, MUST honor the view start offset (for example, a byte view of ABCD sliced to [1:2] and cast to shape [] reads 66 and writing 90 yields AZCD).
    • Scalar PyStr constants MUST use the cached UTF-8 classification without scanning the string on every load; each immutable tuple MUST cache its recursive member verdict, reused by nested tuples and every code object referring to it (including repeated code.replace() calls with explicit or omitted constants), so constant loads and reuse of an already-classified tuple perform only a constant-time verdict check without changing the publication-time refusal. Deterministic surrogatepass decoding refusal raises UnicodeDecodeError (a UnicodeError). Mutable decode buffers MUST be released before guest codec error handlers run.
    • Direct deterministic surrogateescape encode-error callback invocation raises ValueError, replacing the previous UnicodeEncodeError subtype on that callback. Ordinary ASCII encoding with the surrogateescape error mode retains UnicodeEncodeError.
    • Arbitrarily deep container destruction MUST use bounded native stack. The runtime finalizes objects and clears weak references before deferring payload destruction at native depth 64, then drains those payloads iteratively. Deep descendant destruction may be delayed relative to sibling payloads; ordinary shallow destruction order is unchanged. Cleanup itself does not raise RecursionError.
    • Checkpoint object graphs and CBOR MUST use the same maximum depth on encoding and decoding: root depth zero, accept 256 edges and refuse 257 with RecursionError. Acyclic graph depth is the longest path, including shared tails. For graphs with cycles, depth is measured by a deterministic traversal starting at the root, visiting payload children in canonical child order and then any remaining object-table entries in table order: active back-edges are excluded, and a previously visited node is expanded again only when reached at greater depth. Cyclic outcomes may therefore depend on child order; no order-independence for cycles is promised. A node’s recorded maximum depth can increase at most 257 times. Distinct child IDs MUST be cached in first-occurrence order per node, so repeated payload edges are scanned once, not on each depth re-expansion; traversal work is bounded by O(edges + 256 × (vertices + distinct edges)). Constructor dependencies remain bounded and acyclic; accepted mutable cycles use placeholders. Writer admission MUST apply the completed-table rule once at encoding, after canonical renumbering, using the final table and checkpoint root. Decoder and restoration MUST use the same rule. The writer also bounds native first-discovery recursion. Previously accepted checkpoints exceeding this bound are now refused, even if they did not exhaust the native stack. Accepted checkpoint wire bytes remain unchanged.
    • Unhandled construction or recursion errors MUST produce ordinary transaction faults. They cannot produce worker panics or infrastructure faults. No new production module, native callable, or recursion-setter capability is granted. Standalone execution with determinism disabled retains its WTF-8 string behavior; integer c formatting refuses surrogate values with ValueError in all profiles and does not panic.

2.3 Off-chain fee model: The Runner market

Runners set off-chain job prices. The protocol does not calculate gas for Runner execution.
  • The payment_per_runner specified in CIP-2 is a market-driven price in CBY. Runners are free to ignore jobs they deem underpriced.
  • A Runner may estimate costs before accepting a job and measure usage afterward to calculate profit. The protocol does not enforce a cost model.
    1. The Runner may estimate costs before accepting a job.
      • A Runner uses the result_schema and task_definition from CIP-2 to decide whether to accept a job. The developer-provided expected_execution_ms, identification of the model ID (model_id), and analysis of the input data size are key estimation inputs.
      • Runners should maintain a database of historical jobs. For a previously executed model_id or a similar task, a Runner can query the average or P95 resource consumption (CPU time, peak memory) as a basis for the current estimation.
      • For common public models (e.g., specific LLMs), a Runner can perform advance benchmarks on its standardized hardware to build an internal cost model (e.g., “The cost of generating 100 tokens with Llama3-8B is approximately X”).
    2. The Runner measures usage after execution.
      • A Runner’s orchestration service can obtain resource usage from the container runtime API.
      • The orchestration service records the container’s start and end timestamps to measure execution duration. It can measure CPU time with container monitoring tools or reads from the kernel’s cgroup filesystem.
      • Container monitoring tools report peak memory usage (MAX USAGE) for calculating memory costs.
      • The orchestration service must record inbound traffic from downloading models or data from the network (e.g., IPFS) and outbound traffic from making HTTP requests.
  • When a job request sets tee_required=true, Runners that support TEE will only accept jobs with a significant price premium. This premium accounts for:
    1. TEE execution requires specialized server hardware, such as Intel SGX or AMD SEV.
    2. Memory encryption and enclave transitions increase TEE compute time.
    3. The Runner charges for the guarantee of data confidentiality.

2.4 Dual basefee adjustment mechanism

Cowboy adjusts the Cycles and Cells basefees independently using EIP-1559-style rules. Each rule adjusts the fee according to block usage relative to its target. CIP-43 §8 extends this mechanism with an independent Access track, access_basefee, and target T_a = block_access_target. For that track, x below also includes a; the authoritative common constants are Technical Whitepaper §17.8’s alpha = 96, +/-1/96 clamp, and MIN_BASEFEE = 10 base units for cycles and cells. The access curve clamps to the governed min_access_basefee; MIN_BASEFEE does not set its floor; launch genesis seeds it, and the genesis access basefee, to LAUNCH_MIN_ACCESS_BASEFEE = 35,000 base units per access.
  • The protocol sets an ideal EIP-1559 “target usage” (T_c and T_b) for Cycles and Cells that the basefee tracks. Two distinct capacity bounds, both real and both constitutional (WP §4.2), must be stated together: the per-workload cap = the largest lane = LANE_SYSTEM_CYCLES = 32,800,000 = 1.64 × T_c, the ratified System lane ceiling (the target is approximately 61% of this; the 2× target basefee clamp is not a System-lane capacity invariant), and the whole-block hard cap = the lane sum = 80,000,000 = 4 × T_c, the aggregate admission ceiling across all four lanes (the target is 25% of this). Canonical constants (genesis defaults; the live T_c/T_b are BasefeeConfig fields, CIP-12 Tier-0 governance-mutable): BLOCK_CYCLES_TARGET = 20,000,000, BLOCK_CELLS_TARGET = 4,000,000; BASEFEE_ALPHA = 96; BASEFEE_MAX_CHANGE_DENOM = 96; MIN_BASEFEE = 10 base units (1 CBY = 10^9); MAX_BASEFEE = 10^24. There is no separate “block capacity 32,800,000” constant. LANE_SYSTEM_CYCLES caps a single workload in the largest lane.
    • If the previous block’s actual usage U was higher than the target T, the current block’s basefee will be adjusted upwards to curb demand.
    • If the previous block’s actual usage U was lower than the target T, the current block’s basefee will be adjusted downwards to stimulate demand.
  • Each block calculates the new basefee from the parent block’s usage:
    In this formula:
    • x represents c (Cycle), b (Cell), or, under CIP-43 §8, a (Access).
    • U_x is the total usage of resource x in the parent block.
    • T_x is the target usage for resource x.
    • ALPHA = 96 is the learning-rate denominator (a larger ALPHA means smoother adjustment).
    • The change is clamped to basefee/DENOM (DENOM = 96) per block, and the result to [MIN_BASEFEE, MAX_BASEFEE] = [10, 10^24] for cycles and cells, and [min_access_basefee, MAX_BASEFEE] for access.
  • The following example applies the formula:
    • T_c (cycle target) is 20,000,000.
    • Parent block’s actual usage U_c was 24,000,000 (20% over target).
    • The fee delta is (24M - 20M) / 20M / 96 = 0.2 / 96 ≈ 0.00208, or ≈ +0.21% (well inside the 1/96 ≈ 1.04% per-block clamp).
    • Therefore, the new cycle basefee is ≈0.21% higher than the old one. A canonical vector set pins the update at exact/over/under/clamped boundaries.
  • When submitting a transaction, a user specifies a max_fee_per_* and a tip_per_* for each resource.
    • After a transaction is included, its basefee portion (cycles_used * basefee_cycle + accesses_used * access_basefee + cells_used * basefee_cell) MUST be 100% burned (CIP-43 §8). This exerts a constant deflationary pressure on the native CBY token.
    • The block producer receives the tip. The effective tip paid is min(tip_per_, max_fee_per_ - basefee_*). This provides a direct economic incentive for block producers to include transactions and creates a priority “tip market”.

2.5 Multi-signer transaction admission and metering

A transaction may carry up to MAX_ADDITIONAL_SIGNERS (16) co-signers, each costing one secp256k1 recovery at admission. The block transaction ceiling is MAX_BLOCK_TRANSACTIONS = 5,000. Signature work is bounded by three independent mechanisms, because no single one suffices.
  • The structural math and block budget use three transaction-validity constants alongside MAX_ADDITIONAL_SIGNERS: TX_BASE_CYCLES = 5,000, COSIGNER_VERIFY_CYCLES = 10,000, and MAX_BLOCK_COSIGNERS = 5,000. They are not yet implemented. Admission and billing MUST NOT drift: TX_BASE_CYCLES equals the execution base transaction charge (BASE_CYCLES_SPAM_PENALTY), COSIGNER_VERIFY_CYCLES equals the execution secp256k1 verification price (CRYPTO_SECP256K1_VERIFY_CYCLES), and MAX_BLOCK_COSIGNERS equals MAX_BLOCK_TRANSACTIONS.
  • CIP-40 §7.1 owns algorithm IDs, supported interfaces and exact key/signature lengths; this section owns the corresponding consensus verify_cycles schedule. The transaction recovery row is (algorithm=1, public_key=None, signature_bytes=65, verify_cycles=10,000); both native and EIP-712 modes use this row. The contract row is (algorithm=2, public_key_bytes=32, signature_bytes=64, verify_cycles=5,000) and does not enable Ed25519 transaction slots. A signature cost lookup MUST validate the algorithm and its exact public-key/signature lengths before returning a price; there is no default price for an unknown algorithm or length. COSIGNER_VERIFY_CYCLES names only the current secp256k1 row. It supplies no universal future-algorithm price. TX_BASE_CYCLES pays only the non-cryptographic transaction base. Every caller-signed slot, including the primary, pays its scheduled verification price in addition to that base; sig_cycles is the checked sum over the primary and all additional slots. The primary receives no discount or exemption. This pricing requires coordinated fresh genesis. It does not establish that current execution charges this sum. A future row must specify its sizes, Cycles and block-work weight together. The envelope ceilings are MAX_SIGNATURE_PUBLIC_KEY_BYTES=4,096 and MAX_SIGNATURE_BYTES=65,536, but they never override the exact row lengths. Contract Ed25519 keeps its existing host-boundary charge in addition to the 5,000 crypto Cycles; wrappers must not charge twice. Contract verification looks up the row by (algorithm, public_key_bytes, signature_bytes): Unknown/unsupported algorithms and wrong key/signature lengths raise before any host crossing, with no crypto or host-boundary charge (ordinary Python execution still costs Cycles). Valid shapes cross the existing Ed25519 host once, paying its normal W_HOST_CALL Access; a message exceeding the existing 1,048,576-byte cap fails there before crypto charging. All other valid shapes pay 5,000 crypto Cycles before key decoding/verification, including malformed curve encodings and well-formed invalid signatures. Resource exhaustion is a host error. It does not return False. The wrapper does not add a second crypto charge, and per-byte crypto recalibration remains outside this amendment.
  • For key validation and signed objects (CN-10/CN-17), the codec owns the fixed consensus prices below, indexed by the CIP-40 algorithm ID. Unknown IDs have no price and MUST reject. Structural decoding does not validate a curve key; every consensus key-validation site MUST charge before validation. The P-256/P-384 object values are what the network currently charges; they are not accepted corrected calibration results. The current benchmark record still rejects both measured sets and reserves a replacement pending an accepted quiet-window measurement. That calibration remains open. The key schedule derives from the key-validation benchmark. With median-of-three validation times t = 6732, 4057, 6512, 22073 ns in table order, the derivation is max(100, 100 × ceil(max(10000 × t / 157548, 5000 × t / 35547) / 100)). It yields exactly the four key prices above. Secp256k1 and Ed25519 retain their fixed object-verification anchors of 10,000 and 5,000 Cycles. The prior object-verification benchmark included trusted-key validation in both the algorithm measurements and the reference anchors. The P-256 and P-384 object prices are being re-measured with validation hoisted out of the measured region; their corrected prices and derivation must be pinned before this genesis schedule is complete. Secp256k1 and Ed25519 share one object-verification operation class, but their benchmark anchors imply different work per Cycle: 162630.416344169236 / 10000 and 47465.037751874414 / 5000 ns/Cycle respectively (reported as 16.26 versus 9.49 ns/Cycle). Reconciling these anchor rates is a post-Friday calibration question; their 10,000/5,000-Cycle prices do not change here. This question is separate from the required P-256/P-384 remeasurement above. Every consensus signed-object slot verification MUST immediately precharge KEY_VALIDATION_CYCLES[algorithm] + OBJECT_VERIFY_CYCLES[algorithm] for ObjectSigner::Key, on every call, including when the same key was validated or paid for earlier. For ObjectSigner::Address (secp256k1 recovery), it MUST precharge OBJECT_VERIFY_CYCLES[algorithm] alone. Prior registration validation does not replace this per-call charge. These rules do not add a second fee to the raw contract Ed25519 host row above.
  • signature_bytes(tx) is defined by transaction class: for a caller-signed transaction, it is the checked sum of public-key bytes (zero for None) and signature bytes across all slots, including the primary; for a valid engine-produced deferred transaction, it is exactly zero. The deferred primary’s fixed 65-byte zero placeholder is explicitly excluded from this recovery-work budget, but remains counted in serialized transaction/block size. This exception requires the complete deferred invariants and origin authentication in CIP-40 §7.3; a zero-valued caller signature never earns the exception, and external ingress rejects deferred transactions. Ordinary caller transactions obey MAX_TRANSACTION_BYTES=1,048,576. RestoreActor has a separate admission allowance of that envelope budget plus 8,388,608 + 8 × 10,000 + 4 bytes for the complete storage snapshot (KV quota, per-entry lengths and entry count; CIP-4 §12.3). This byte allowance does not raise gas/access ceilings or waive signature checks. Block admission additionally enforces MAX_BLOCK_SIGNATURE_BYTES=650,000 across transaction slots and volume-write slots. The checked block total is sum(signature_bytes(tx) for tx in block.transactions) + sum(slot.public_key byte length + slot.signature byte length for each VolumeEscrowTransaction in block.volume_writes): each volume write contributes its Ed25519 slot’s 64 signature bytes and any inline public-key bytes. A VolumeEscrowTransaction is not a transaction class, so this is an explicit additional block-budget term; the ingress buckets remain denominated in signature_bytes(tx). Both byte totals and the complete block co-signer budget are computed before scheduling any recovery, including parallel recovery; malformed input or arithmetic overflow rejects with zero recoveries. Local object construction and JSON decoding cannot bypass these checks.
  • In the current coordinated release, the canonical block encoding MUST NOT exceed MAX_BLOCK_BYTES = 15 × 1,048,576, leaving 1 MiB within the 16 MiB P2P message budget for framing and consensus proofs. Block decoding is bounded by this total, and verification MUST enforce both the total and the ordinary/RestoreActor signed-transaction byte limits before signature recovery, including proposals that bypass client ingress. Deferred work retains its separate generation bounds and counts toward the block total. Proposers reserve the actual framing/seed/presence bytes and the maximum inline timer manifest, select a transaction prefix that fits, and return the entire remaining tail to the mempool without skipping nonce predecessors or losing transactions on cancellation. One maximum restore fits; multiple individually legal restores may require separate blocks.
  • Let k = additional_signers.len(). For a caller-signed transaction, sig_cycles = checked_sum(verify_cycles(slot) for slot in every AccountSignature.entries across primary and additional_signers), using the validated CIP-40 descriptors and the cycle schedule above. Unknown or unsupported descriptors reject before recovery. For the genesis secp256k1-only transaction-slot set, this specializes to N_slots × COSIGNER_VERIFY_CYCLES (equal to k + 1 only for one-slot accounts); the multiplication is not an algorithm-independent rule. Admission and precharge MUST use the same checked sum, and the base charge MUST NOT charge primary recovery again.
    • Structural minimum. A non-deferred transaction is rejected unless cycles_limit ≥ TX_BASE_CYCLES + sig_cycles. The check is part of transaction verification and runs before any signature recovery on every path that reaches recovery (RPC admission, the mempool listener, and block verification), so the ordering does not depend on the call site; it runs before either signature mode’s digest computation or recovery (CIP-40 §7.3). The base constant and signature schedule prices are fixed consensus values, never node-local gas-table configuration. Rejection changes no nonce, no fee, and no state. Valid origin-authenticated engine-produced deferred transactions are exempt: no signature recovery occurs, the primary is the required zero placeholder and additional_signers is empty, so sig_cycles = 0. A caller-signed transaction cannot obtain this exemption by zeroing its signature.
    • Precharge. sig_cycles is consumed before tx_base and calldata, so receipts and any deferred child’s origin_remaining_cycles account for it. The structural minimum ensures that the complete signature precharge (including the primary) and base cycle charge fit within the signed cycle limit. The shared outcome path captures base/calldata intrinsic failures; signature precharge must preserve that behavior.
    • Sender-paid intrinsic and execution fees. For every signed (non-deferred) transaction, including top-level ExecuteActor, the sender funds the native fee, including primary and co-signer verification and the selected priority tip, except for the authorized subscriber basefees below. Reserve R = cycles_limit × max_fee_per_cycle + cells_limit × max_fee_per_cell + access_limit × max_fee_per_access with checked arithmetic. For successful or failed execution outcomes that reach the charging tail, settlement computes F for actual metered usage; burn + tip equals F. CIP-7 callback Cycles/Cells basefees W that are authorized against a subscriber are charged to that subscriber. The sender pays S = F − W, including every priority tip and Access fee, and is refunded R − S exactly once for those outcomes, including charged post-admission failures. A StoreError that escapes transaction execution is an exception: the outer transaction savepoint rolls back the transaction, including escrow and nonce changes, and the existing zero-charge escape path produces a zero-charge failed result. Escrow is restored by rollback, not by a charging-tail refund. The signed-tail invariant failures classified below have the same rollback outcome. The callee, its default card and its owner entitlement are not sponsorship tiers. Selecting co-signers cannot debit them. Preserve the structural minimum on cycles_limit and existing separately authorized callback/deferred-work charging rules; see CIP-28 §3.4.
    • Unconditional sender delta settlement. The signed tail re-reads the latest Account[from] and applies only the local sender balance delta, then persists the advanced nonce. It MUST preserve credits and debits already committed during execution; there is no snapshot-overwrite branch or activation gate. Each native effect uses exactly one channel: the local sender delta or a committed account write. Native store/overlay debits of the signer share the gas-escrow and locked-fund reservation across nested frames; the local sender balance already excludes those amounts. A signer callback’s hold is combined with escrow using max(escrow, callback_hold), plus the locked amount, because callback fees are included in the escrow. Actor addresses are rejected as signed wallet identities; the reservation and merge do not authorize actor signers. The additional tail read is included in CIP-43’s nine-access signed envelope.
    • Post-escrow settlement. The following closed category of deterministic intrinsic-meter/arithmetic failures after the escrow deduction, including meter exhaustion (cycles, base cells, calldata cells) and arithmetic failures such as a calldata checked_mul overflow, MUST follow the shared settlement tail (nonce increment, receipt, retention of the complete signature intrinsic charge, refund of unused escrow) identically to OutOfGas. Base/calldata intrinsic failures advance the nonce and route through the shared charged outcome path; per-slot signature metering uses the same path. StoreError handling remains path-specific. A System-arm StoreError, including deterministic committed-state storage-cap rejections (StorageFull, MailboxFull, TimerListFull, and kin), escapes before the charging tail. The System-arm savepoint first rolls back handler writes, then the outer transaction savepoint rolls back the transaction and restores its engine effects; the existing zero-charge escape path produces a zero-charge failed result. An escaping settlement-phase StoreError also triggers that outer rollback. By contrast, an Actor-arm execution StoreError converted to ExecutionStatus::ExecutionError reaches the charging tail and remains charged. This rule does not convert escaping storage faults into charged outcomes. Acceptance, one test per path with exact fee/state outcomes, each on a co-signed transaction: (1) a System-arm StoreError escapes zero-charge through that path, with the transaction rolled back; (2) an Actor-arm execution StoreError converted to ExecutionStatus::ExecutionError settles through the normal charging tail; (3) a settlement-phase StoreError (Watchtower subscriber debit or sender write-back) escapes zero-charge through that path, with the outer transaction savepoint restoring transaction state and engine effects.
    • Signed-tail invariant guards. The guards for inclusive total fee exceeding escrow, callback-fee accumulation/subtraction, checked refund and locked-fund restoration, checked delta merge, and the final locked-balance floor fail closed by escaping the charging tail. They are not the charged intrinsic-meter/arithmetic failures above. The outer transaction savepoint rolls back all transaction state, including nonce, escrow and wallet markers, and restores engine fee/publication effects; the block loop records a zero-gas failed receipt through the existing zero-charge escape path. These guards are unreachable for admitted effects while every signer debit uses exactly one reservation-aware channel and the fee/credit bounds hold.
  • A block’s total additional_signers across all transactions MUST NOT exceed MAX_BLOCK_COSIGNERS (5,000, pinned equal to MAX_BLOCK_TRANSACTIONS), independently of CIP-49’s inner slot count. The 650,000-byte signature budget independently bounds actual secp256k1 recoveries to 10,000 (65 bytes each); account count alone does not bound threshold signatures. The bound is checked in block verification from the decoded transactions before any recovery runs. This is the binding constraint the charge cannot provide: a transaction failing the nonce, basefee, or balance check never reaches metering, yet its signatures were already recovered. A leader could otherwise fill a block with valid-signature stale-nonce transactions and impose 85,000 recoveries (5,000 × 17) on every validator for free. The budget counts additional signers only: a block admits 312 fully loaded 16-co-signer (17 one-slot account) transactions (4,992) and rejects at 313 (5,008). Proposer selection and verification MUST accumulate the count identically; a proposer at the budget skips and requeues the whole candidate.
  • RPC submit, simulation and the mempool listener enforce a per-request signature-byte cap and a per-peer token bucket denominated in signature_bytes(tx), including primaries. Sum the entire request before starting any recovery; charging only additional signers leaves single-signer floods unaccounted for. Count every submitted transaction, including eventual stale-nonce or bad-signature rejections. The peer key is stable across connections: authenticated client identity when available, otherwise the direct source address, with forwarded addresses trusted only from explicitly configured proxies. ONE shared atomic global signature-byte bucket is injected into all recovery entry paths, so opening connections or switching endpoints cannot multiply the budget. A request reserves its whole byte cost atomically before recovery; invalid signatures do not refund consumed work. Finite defaults apply when configuration is absent or malformed; zero/unlimited settings cannot disable the backstop. Numeric rate limits are local admission policy and MUST NOT enter block validity or replay. Protocol block byte/work budgets remain deterministic and separate from these local buckets. Existing raw-body bounds still run before decoding. The Submission wrapper and endpoint body bounds must permit one maximally sized legal transaction without allowing an unbounded batch.
Acceptance (every fee test pins basefee and tip to fixed values and asserts exact deltas, not inequalities): for one-slot accounts at k = 0/1/16, signature precharges are exactly 10,000/20,000/170,000 Cycles and signature-plus-base minima are 15,000/25,000/175,000 Cycles before calldata or instruction work. Each exact minimum passes the structural preflight; each minimum minus one rejects with zero recovery calls. In both native and EIP-712 modes, assert exact cycles, sender-balance, burn, tip, and deferred-child origin_remaining_cycles deltas; the sender funds execution and all signature fees with zero additional sponsorship debit for the callee/card/owner roles; in a no-transfer, no-callback fixture, distinct non-paying callee/card/owner accounts retain unchanged balances, while roles that alias the sender (for example owner == tx.from) incur exactly one sender fee debit; cover locked vesting balances; below-minimum cycles_limit rejected pre-recovery with no nonce increment, no fee, and no state change; stale-nonce, basefee-failed, and underfunded transactions remain zero-charge, bounded by the budget and ingress caps. The charge does not bound these transactions; post-escrow failures (cycle exhaustion, low base cells, calldata-cell exhaustion, and calldata checked_mul overflow) all settle through the shared tail with no zero-charge receipt; per-slot price lookup, byte sum and cost-sum overflow checked; the three constant-equality checks above; callee card caps/policies cannot reject or subsidize a signed top-level call; blocks at exactly 5,000 co-signers verify and 5,001 reject without performing recoveries; a stale-nonce 16-co-signer block at MAX_BLOCK_TRANSACTIONS is bounded by the budget. The charge does not bound that block; proposer requeues over-budget candidates on both selection paths; ingress accepts signature-byte cap C and rejects C + 1 pre-recovery per interface, including primary-only traffic and cross-endpoint requests; under a deterministic clock, per-peer request R within the window is accepted and R + 1 rejected, per interface; the per-peer key survives reconnection and parallel connections; the global bucket saturates under all-compliant requests; a node started with absent or malformed limiter config enforces the defaults. The wallet/actor identity rule in CIP-40 §12.1 also adds state I/O independently of cryptographic Cycles. The current CIP-49 single-signer native envelope is 7R + 2W = 9 structural Accesses; each additional account adds 3R + 1W = 4, including one AccountAuth read per signer. Identity-only pure preflight reserves 3 + 4k structural accesses for k additional accounts and rounds once at maximum governed scalar 1,350,358 ppm, giving floors 5/10/91 for k=0/1/16. Reserve before identity I/O; a below-floor transaction rejects before hashing, recovery, nonce acceptance or fees. Deferred envelopes remain exempt. Deploy and fork() pay for their wallet-marker probes through the ordinary cold/warm state-read schedule. In the wallet-identity release, wallet markers are native transaction bookkeeping, alongside the accepted nonce and fee accounting; they do not pass through the PVM state_set host function. The native intrinsic charges base_cells = 500 as tx_base, plus instruction calldata Cells, before marker persistence. This release adds no separate per-marker or per-byte Cells surcharge; the 86-byte marker key and 3-byte value in CIP-4 do not imply an extra 89-Cell host charge. The fixed native intrinsic and paid out-of-gas settlement rules apply even when the instruction fails. §2.2.2’s per-byte state_set rule specifies actor host writes, not a second debit on native nonce/fee/identity bookkeeping. Identity Accesses are separately charged and included in accesses_used and Access fee settlement under CIP-43. The current maximum signed ordinary-System initial row is 1,116 structural, from staged finalize, with ceiling 1,507 charged. The System lane total is 4,096: ordinary transactions reserve 1,507 and selection owns 2,589. The maximum scalar is 1,350,358, derived as floor(1,507×1,000,000/1,116). These bounds include the complete native + 9 + 4·additional_signers structural row. CIP-43 §8 gives the complete current capacity and governance-recovery bounds; the earlier table-21 PoR sizing derivation is historical. For a single-runner, non-TEE callback result without delegation/offender work, the signed parent’s own work is 77 structural (9+68), and the callback reserve is 311 (149+162). At launch and maximum scalar those independent meters charge 104+420; 10% estimate headroom gives 577. At identity the suggestion is 427. Two suggestions consume 1,154 of the 1,158 Runner lane at launch/maximum, retaining four accesses; the User lane still fits two 1,024 stamps in 2,051. These are isolated lane fits; shared aggregate authority, additional work and the companion CIP-43 per-transaction tail floor still constrain admission.

3. Rationale

On-chain gas accounts for deterministic work. Runners price off-chain costs, including electricity and hardware. Bytecode metering covers loops and recursion; Cell metering charges data at I/O boundaries. Optional TEE pricing lets users choose whether to pay for confidentiality. EIP-1559 adjusts basefees with usage. Under EIP-1559, the protocol burns base fees.

4. Security considerations

  • The bytecode-to-cycle cost table is consensus-critical. Any change requires a coordinated hard fork. All clients MUST implement the exact same table.
  • The cycles_limit per transaction is the primary defense against infinite loops in Actor code, preventing them from halting the chain.
  • The cells_limit per transaction, combined with max_return_bytes defined in CIP-2, prevents Actors or Runners from overwhelming the chain with excessively large data payloads that would incur high processing and storage costs for nodes.
  • Every host function exposed to the VM MUST apply the resource charges specified by this CIP and CIP-43. Persisted and payload bytes consume Cells; the transient allocation guard in §2.2.4.4 is unpriced. Missing required metering or bounds are potential DoS vectors and critical security vulnerabilities.
  • Signature recovery runs across every transaction in a block before execution, and a transaction that fails the nonce, basefee, or balance check returns zero-charge after signature recovery. Pricing alone therefore cannot bound recovery work; the §2.5 block co-signer budget (checked before recovery) is the binding constraint, the intrinsic charge prices only transactions that execute, and the ingress caps bound pre-block work from unauthenticated submitters.

Structured native admission refusals

The shared route-admission and workload-registry refusal contract specifies the height-gated retryable quota code, retry_after, closed-list InvalidData reasons and client treatment of old/new forms. Error code and context are consensus-visible; changing them follows CIP-50, including preservation below the gate.