Skip to main content
credible-std is the Solidity standard library for writing and testing Credible Layer assertions. It provides the base assertion contract, the ph interface for PhEVM cheatcodes, trigger registration helpers, snapshot-read helpers, typed state-change helpers, and Forge test utilities. For individual cheatcode signatures, see the Cheatcodes API Reference. For local assertion tests, see Testing Assertions.

Package and Configuration

This reference follows source revision fe49de6. Pin your dependency; a Solidity interface in the library does not establish support in your CLI or deployed enforcer. The npm package includes raw ABI arrays under artifacts/, such as artifacts/PhEvm.json and artifacts/protection/safe/SafeTxShapeAssertion.json. Paths mirror src/; additional interfaces in one source file use SourceName.InterfaceName.json. These files contain ABI arrays, not deployment bytecode. Protocol guards live in credible-registry, separately from this assertion library.

Core Contracts

Assertion Helpers

Assertion.sol provides internal helpers for registering when assertion functions run.

Call, Storage, and Balance Helpers

These helpers predate Reshiram. Storage triggers remain useful for configuration policies; the current Safe configuration assertion uses one.

Reshiram Trigger Helpers

Use these helpers for newer trigger types:
The cumulative flow helpers aggregate net flow into per-block buckets over a rolling window. They trigger when the measured flow strictly exceeds the threshold, based on the balance at the window start. See Cumulative Flow Policies for accounting and boundary behavior. registerFnCallTrigger pairs with ph.context() so an assertion can inspect the matched call’s selector and call range.

Anomaly Triggers

watchAnomaly(target, fnSelector, sensitivity) registers a check at a sensitivity level from 1 to 10. Sensitivity.RECOMMENDED is level 7. The trigger decides whether to run the assertion; the assertion’s logic decides whether to reject the transaction. Sensitivity also exposes LEVEL_1 through LEVEL_10, MIN (1), MAX (10), and isValid(uint8). Values outside 1–10 are invalid registration levels. Anomaly dispatch requires runtime support. The released PCL version tested in the anomaly guide does not dispatch these triggers; compiling the interface is insufficient.

Fork and Snapshot Helpers

Reshiram assertions should prefer explicit snapshot IDs over deprecated fork-switching cheatcodes. Construct ForkId values explicitly:
Use ph.loadStateAt to read storage at those snapshots:
For packed storage or mappings, calculate the exact slot before calling loadStateAt. A ForkId identifies a snapshot; constructing one does not switch EVM state. Ordinary getter calls and native .balance reads do not become snapshot reads. Use ph.staticcallAt for protocol getters, or these inherited ForkUtils helpers: The helpers forward 500,000 gas and revert if the snapshot call fails. Override _viewFailureMessage() internal pure virtual returns (string memory) to customize that failure message. Typed helpers also revert if the returned bytes cannot be decoded. When calling ph.staticcallAt directly, check result.ok before decoding result.data.

ERC20 Delta Helpers

ForkUtils.sol also includes ERC20 transfer-delta helpers:
_reducedErc20BalanceDeltasAt forwards to ph.reduceErc20BalanceDeltas. _transferredValueAt sums the returned entries matching both from and to; it returns zero if none match. _consumedBetween returns beforeValue - afterValue for a decrease and zero otherwise. Transfer-derived deltas do not independently establish actual token balances; use snapshot balance reads when the policy needs them.

State Change Helpers

StateChanges.sol converts ph.getStateChanges(...) from bytes32[] into typed arrays:
Each helper also has overloads for mapping keys and mapping keys with slot offsets:
The same overload pattern exists for Address, Bool, and Bytes32. Mapping overloads read keccak256(abi.encodePacked(key, slot)) + slotOffset; they do not automatically resolve nested mappings or dynamic keys. Address conversion keeps the low 160 bits of each word; Boolean conversion treats any nonzero word as true. These helpers do not shift or mask a packed field at an arbitrary byte offset. Read and decode the exact storage word for packed values.

Call Matching Helpers

Assertion.sol includes helpers for querying successful calls through the Reshiram call-matching precompile:
_successOnlyFilter selects successful calls of any call type and depth, including nested calls. _matchingCalls passes that filter to ph.matchingCalls and returns at most limit entries. A bounded result does not prove that no additional matching calls occurred.

Assertion Specifications

The assertion specification selects the PhEVM APIs available to an assertion. It applies to Ethereum builders, L2 sequencers, and local tests; it is independent of which platform UI manages the release.
  • Legacy (V1) uses the original precompile set, including mutable forkPreTx, forkPostTx, and call-level fork switching.
  • Reshiram (V2) uses explicit ForkId values with loadStateAt and staticcallAt. Constructing a ForkId does not change the state used by ordinary Solidity getter calls.
Register the desired specification exactly once in the assertion constructor. A valid assertion must define a specification; if a base constructor already registers it, do not register it again:
Available specs:

Deployment Compatibility

Match the assertion’s specification to the target enforcer and the CLI/runtime used for tests. A library exposing an API or a local test passing does not establish that a deployed enforcer supports it. Confirm the target runtime revision, accepted specification, required precompiles, and trigger support before activation. This requirement applies to both Ethereum and L2 integrations. For a Legacy-to-Reshiram migration, replace every mutable fork switch and the reads that follow it. Use loadStateAt for storage and staticcallAt or the inherited snapshot helpers for getters. Update trigger registration and test transaction, call, and temporary-change boundaries. Adding registerAssertionSpec(AssertionSpec.Reshiram) alone does not migrate the implementation. L2 runtime compatibility covers the requirements to confirm for a sequencer deployment.

Testing Contracts

CredibleTest is the base contract for tests run with pcl test. It exposes cl.assertion(...), which registers an assertion against a target for the next call and selects one assertion function. This does not reproduce production dispatch of every matching assertion. Use the repository’s optimized ci profile for its protection tests; see gas-limit testing.
cl.setAnomalyLevel stages a target’s anomaly verdict for the next cl.assertion call. Stage each target separately. A trigger at level L fires when firesAt != 0 && L >= firesAt; unstaged targets are unscored and do not fire. This interface requires a runtime implementing anomaly staging and dispatch; it does not make those features available in an older PCL release.

Log Utilities

Import LogUtils from credible-std/utils/LogUtils.sol and IERC20LogUtils from credible-std/utils/IERC20LogUtils.sol. Their functions are internal pure: they operate on logs already fetched through ph, without making precompile calls.

LogUtils

Indexed access assumes a non-anonymous event whose first topic is its signature. A hashed indexed dynamic value cannot be recovered by casting its topic.

IERC20LogUtils

The library exposes TRANSFER_EVENT_SIGNATURE and APPROVAL_EVENT_SIGNATURE. Decoders revert on invalid event shape. Matching that shape does not prove the emitter is a standard ERC20 or that the event changed balances or allowances as claimed.

Protection Contracts

The protection/ directory contains reusable assertions, abstract composition bases, protocol adapters, and supporting interfaces. The following map describes the families available at the pinned source revision. Parameters, adapter implementations, and trigger registration determine the actual coverage. Access-control and vault mixins require explicit calls to their _register*Triggers() helpers from triggers(). Inheriting a mixin alone does not activate its check. Define the assertion specification once across the constructor chain, and test each configured check against the actual target implementation. Constructor-time protocol reads are unavailable in the assertion deployment runtime; pass configuration such as the vault asset explicitly and check it at a runtime snapshot. For Safe allowance policies, upstream fix 52f4f87 makes a cumulative increaseAllowance peak of uint256.max require allowUnlimited = true independently of maxAmount. The source pin above predates this fix: a maximum numeric cap can allow that peak even with the flag disabled. Finite peaks remain subject to the numeric cap. Inline compositions are available in Vault Policies and Anomaly-Gated Policies. The latter also describes the current local runtime limitation on anomaly dispatch.

Local Backtesting API

CredibleTestWithBacktesting extends CredibleTest and Forge’s Test with two public entry points. This is the local Solidity replay harness, separate from the automatic backtest attached to a platform release.
Import BacktestingTypes from credible-std/utils/BacktestingTypes.sol. BacktestingResults returns seven uint256 counters: totalTransactions, processedTransactions, successfulValidations, skippedTransactions, assertionFailures, replayFailures, and unknownErrors. The result categories in ValidationResult are Success, Skipped, ReplayFailure, AssertionFailed, and UnknownError. ValidationDetails carries the category, errorMessage, and isProtocolViolation. Those names are API identifiers: the implementation classifies caught errors, so an AssertionFailed result or isProtocolViolation flag needs investigation before treating it as a confirmed policy violation. A skipped transaction did not exercise the selected assertion. The harness requires FFI and the dependency’s scripts/backtesting/transaction_fetcher.sh, which uses Bash, curl, and jq. Without FFI permission, the harness skips the test. The dependency provides a backtesting profile with ffi = true; a consuming project’s profile must grant FFI too. CREDIBLE_STD_PATH can identify the dependency root when script discovery fails; _getScriptSearchPaths() can be overridden for other layouts. Trace-method availability affects transaction selection: the fetcher tries trace APIs and can fall back to direct calls only. Results therefore depend on RPC coverage and replay conditions. The harness returns counters rather than asserting your acceptance criteria; a test that merely calls it can finish without demonstrating successful assertion coverage. Check the counters and failure details explicitly. BacktestingUtils provides the harness’s transaction parsing, hex conversion, revert decoding, and default script search paths. TransactionData records transaction identity, sender/recipient, value/calldata, block/index, and gas/fee fields. These support replay; they are not additional enforcement APIs.

Cheatcodes API Reference

Full PhEVM cheatcode signatures

Testing Assertions

How to test assertions locally

Review Backtesting Results

Review the automatic backtest attached to a platform release

Writing Your Own Policies

Define, implement, and test policies for your protocol.