Verified contractExactBUSL-1.1
NoerraKmsRecoveryVerifier
Address0x23a8425c4b8a7a573ae2f4ec90223b967ef664a2
- Balance
0 ETH
- Transactions
21
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,245,017
- Creation transaction
- 0x1826c1bb2a…3def0b5564
35 files
- src/agents/NoerraKmsRecoveryVerifier.solmain4.78 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol656 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol216 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC7913.sol674 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.96 KB
- lib/openzeppelin-contracts/contracts/utils/Bytes.sol14.7 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol21.54 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol12.13 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol1.03 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol24.62 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol8.63 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol8.8 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- src/agents/NoerraAgents.sol116.03 KB
- src/agents/NoerraAtomicCodeHashes.sol1.02 KB
- src/agents/NoerraCreationToken.sol2.87 KB
- src/agents/NoerraKmsApplicationPolicy.sol4.92 KB
- src/agents/NoerraRecoveryVerifier.sol21.87 KB
- src/agents/NoerraReserveSetupPermit.sol2.45 KB
- src/agents/NoerraStartClaims.sol11.68 KB
- src/agents/NoerraStartFunding.sol8.12 KB
src/agents/NoerraKmsRecoveryVerifier.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {NoerraEvidenceRegistration} from "./NoerraRecoveryVerifier.sol";
import {NoerraKmsApplicationFactory} from "./NoerraKmsApplicationPolicy.sol";
/// @notice KMS-certified application keys authorize fresh, account-bound wallet actions.
/// @dev Phala KMS verifies hardware before key release; Ethereum verifies certificates and action signatures.
/// This trusts the pinned KMS root and protected application-policy approver, rather than L1 DCAP execution.
contract NoerraKmsRecoveryVerifier is NoerraEvidenceRegistration {
uint256 public constant KMS_CERTIFICATE_VERSION = 1;
bytes32 public constant POLICY_DOMAIN = keccak256("NOERRA_KMS_POLICY_V1");
bytes32 public constant ACTION_DOMAIN = keccak256("NOERRA_KMS_RECOVERY_ACTION_V1");
string public constant KEY_PURPOSE = "noerra-recovery-proof-v1";
address public immutable kmsRoot;
NoerraKmsApplicationFactory public immutable applicationFactory;
bytes32 public immutable factoryCodeHash;
struct Certificate {
address app; bytes keyPublic; bytes appPublic;
bytes keySignature; bytes kmsSignature; bytes actionSignature;
}
constructor(address root, NoerraKmsApplicationFactory factory, bytes32 codeHash)
NoerraEvidenceRegistration(keccak256(abi.encode(POLICY_DOMAIN, root, address(factory), uint8(1)))) {
require(root != address(0) && address(factory).code.length != 0 && address(factory).codehash == codeHash, "KMS authority");
kmsRoot = root; applicationFactory = factory; factoryCodeHash = codeHash;
}
function operatorMeasurementsHash() public view override returns (bytes32) {
return keccak256(abi.encode(POLICY_DOMAIN, kmsRoot, address(applicationFactory), uint8(2)));
}
function _authorityValid() internal view override returns (bool) {
return address(applicationFactory).codehash == factoryCodeHash;
}
function _evidenceBounds(bytes calldata evidence) internal pure override returns (bool) {
return evidence.length >= 600 && evidence.length <= 1200;
}
function _authenticate(bytes calldata evidence, bytes32 commitment, bytes32 fresh, bytes32 policy, uint256 fee)
internal view override {
require(fee == 0, "No certificate fee");
Certificate memory c = abi.decode(evidence, (Certificate));
require(keccak256(evidence) == keccak256(abi.encode(c)), "Certificate encoding");
(bytes32 compose, bytes32 osImage, bytes32 configuration, uint8 role) = applicationFactory.applications(c.app);
require(compose != bytes32(0) && osImage != bytes32(0) && configuration != bytes32(0) && c.app.code.length != 0 &&
keccak256(abi.encode(POLICY_DOMAIN, kmsRoot, address(applicationFactory), role)) == policy, "Application authority");
(address keyAddress, bytes memory keyCompressed) = _publicKey(c.keyPublic);
(address appAddress, bytes memory appCompressed) = _publicKey(c.appPublic);
require(ECDSA.recover(keccak256(abi.encodePacked(KEY_PURPOSE, ":", _hex(keyCompressed))), c.keySignature) == appAddress,
"Derived key certificate");
require(ECDSA.recover(keccak256(abi.encodePacked("dstack-kms-issued:", bytes20(c.app), appCompressed)), c.kmsSignature) == kmsRoot,
"KMS certificate");
require(ECDSA.recover(keccak256(abi.encode(ACTION_DOMAIN, commitment, fresh, c.app, keccak256(keyCompressed))), c.actionSignature) == keyAddress,
"Recovery action signature");
}
function _publicKey(bytes memory key) private pure returns (address account, bytes memory compressed) {
require(key.length == 65 && key[0] == 0x04, "Public key encoding");
uint256 x; uint256 y;
assembly { x := mload(add(key, 33)) y := mload(add(key, 65)) }
uint256 prime = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f;
require(x < prime && y < prime && mulmod(y,y,prime) == addmod(mulmod(mulmod(x,x,prime),x,prime),7,prime), "Public key curve");
bytes32 digest;
assembly { digest := keccak256(add(key, 33), 64) }
account = address(uint160(uint256(digest)));
compressed = new bytes(33); compressed[0] = bytes1(uint8(2 + (y & 1)));
for (uint256 i; i < 32; ++i) compressed[i+1] = key[i+1];
}
function _hex(bytes memory value) private pure returns (bytes memory encoded) {
bytes memory alphabet = "0123456789abcdef"; encoded = new bytes(value.length * 2);
for (uint256 i; i < value.length; ++i) {
encoded[2*i] = alphabet[uint8(value[i]) >> 4]; encoded[2*i+1] = alphabet[uint8(value[i]) & 15];
}
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1271.sol)
pragma solidity >=0.5.0;
/**
* @dev Interface of the ERC-1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with `hash`
*/
function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC7913.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC7913.sol)
pragma solidity >=0.5.0;
/**
* @dev Signature verifier interface.
*/
interface IERC7913SignatureVerifier {
/**
* @dev Verifies `signature` as a valid signature of `hash` by `key`.
*
* MUST return the bytes4 magic value IERC7913SignatureVerifier.verify.selector if the signature is valid.
* SHOULD return 0xffffffff or revert if the signature is not valid.
* SHOULD return 0xffffffff or revert if the key is empty
*/
function verify(bytes calldata key, bytes32 hash, bytes calldata signature) external view returns (bytes4);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to approve
* @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Bytes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/Bytes.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
/**
* @dev Bytes operations.
*/
library Bytes {
/**
* @dev Forward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the first instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return indexOf(buffer, s, 0);
}
/**
* @dev Forward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
* * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
uint256 length = buffer.length;
for (uint256 i = pos; i < length; ++i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Backward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the last instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return lastIndexOf(buffer, s, type(uint256).max);
}
/**
* @dev Backward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
* * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
unchecked {
uint256 length = buffer.length;
for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
return i - 1;
}
}
return type(uint256).max;
}
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
* memory.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return slice(buffer, start, buffer.length);
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
* memory. The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// allocate and copy
bytes memory result = new bytes(end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
}
return result;
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer,
* and shrinks the buffer length accordingly, effectively overriding the content of buffer with buffer[start:].
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return splice(buffer, start, buffer.length);
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to `end` (excluded) to the start of that buffer,
* and shrinks the buffer length accordingly, effectively overriding the content of buffer with buffer[start:end].
* The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// move and resize
assembly ("memory-safe") {
mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
mstore(buffer, sub(end, start))
}
return buffer;
}
/**
* @dev Replaces bytes in `buffer` starting at `pos` with all bytes from `replacement`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`).
* If `pos >= buffer.length`, no replacement occurs and the buffer is returned unchanged.
*
* NOTE: This function modifies the provided buffer in place.
*/
function replace(bytes memory buffer, uint256 pos, bytes memory replacement) internal pure returns (bytes memory) {
return replace(buffer, pos, replacement, 0, replacement.length);
}
/**
* @dev Replaces bytes in `buffer` starting at `pos` with bytes from `replacement` starting at `offset`.
* Copies at most `length` bytes from `replacement` to `buffer`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`, `offset` is
* clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
* buffer.length - pos))`. If `pos >= buffer.length` or `offset >= replacement.length`, no replacement occurs
* and the buffer is returned unchanged.
*
* NOTE: This function modifies the provided buffer in place.
*/
function replace(
bytes memory buffer,
uint256 pos,
bytes memory replacement,
uint256 offset,
uint256 length
) internal pure returns (bytes memory) {
// sanitize
pos = Math.min(pos, buffer.length);
offset = Math.min(offset, replacement.length);
length = Math.min(length, Math.min(replacement.length - offset, buffer.length - pos));
// replace
assembly ("memory-safe") {
mcopy(add(add(buffer, 0x20), pos), add(add(replacement, 0x20), offset), length)
}
return buffer;
}
/**
* @dev Concatenate an array of bytes into a single bytes object.
*
* For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
* `abi.encodePacked`.
*
* NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
* significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
*/
function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
uint256 length = 0;
for (uint256 i = 0; i < buffers.length; ++i) {
length += buffers[i].length;
}
bytes memory result = new bytes(length);
uint256 offset = 0x20;
for (uint256 i = 0; i < buffers.length; ++i) {
bytes memory input = buffers[i];
assembly ("memory-safe") {
mcopy(add(result, offset), add(input, 0x20), mload(input))
}
unchecked {
offset += input.length;
}
}
return result;
}
/**
* @dev Split each byte in `input` into two nibbles (4 bits each)
*
* Example: hex"01234567" → hex"0001020304050607"
*/
function toNibbles(bytes memory input) internal pure returns (bytes memory output) {
assembly ("memory-safe") {
let length := mload(input)
output := mload(0x40)
mstore(0x40, add(add(output, 0x20), mul(length, 2)))
mstore(output, mul(length, 2))
for {
let i := 0
} lt(i, length) {
i := add(i, 0x10)
} {
let chunk := shr(128, mload(add(add(input, 0x20), i)))
chunk := and(
0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff,
or(shl(64, chunk), chunk)
)
chunk := and(
0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff,
or(shl(32, chunk), chunk)
)
chunk := and(
0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff,
or(shl(16, chunk), chunk)
)
chunk := and(
0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff,
or(shl(8, chunk), chunk)
)
chunk := and(
0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f,
or(shl(4, chunk), chunk)
)
mstore(add(add(output, 0x20), mul(i, 2)), chunk)
}
}
}
/**
* @dev Returns true if the two byte buffers are equal.
*/
function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
return a.length == b.length && keccak256(a) == keccak256(b);
}
/**
* @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
* Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
*/
function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
value = // swap bytes
((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
value = // swap 8-byte long pairs
((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (value >> 128) | (value << 128); // swap 16-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 128-bit values.
function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
value = // swap bytes
((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
return (value >> 64) | (value << 64); // swap 8-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 64-bit values.
function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
return (value >> 32) | (value << 32); // swap 4-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 32-bit values.
function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
return (value >> 16) | (value << 16); // swap 2-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 16-bit values.
function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
return (value >> 8) | (value << 8);
}
/**
* @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
* if the buffer is all zeros.
*/
function clz(bytes memory buffer) internal pure returns (uint256) {
for (uint256 i = 0; i < buffer.length; i += 0x20) {
bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
if (chunk != bytes32(0)) {
return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
}
}
return 8 * buffer.length;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/Strings.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
0xffffffff | // first 32 bits corresponding to the control characters (U+0000 to U+001F)
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return Bytes.equal(bytes(a), bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes backslashes (including those in \uXXXX sequences) and the characters in ranges
* defined in section 2.5 of RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). All control characters in U+0000
* to U+001F are escaped (\b, \t, \n, \f, \r use short form; others use \u00XX). ECMAScript's `JSON.parse` does
* recover escaped unicode characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
// Put output at the FMP. Memory will be reserved later when we figure out the actual length of the escaped
// string. All write are done using _unsafeWriteBytesOffset, which avoid the (expensive) length checks for
// each character written.
bytes memory output;
assembly ("memory-safe") {
output := mload(0x40)
}
uint256 outputLength = 0;
for (uint256 i = 0; i < buffer.length; ++i) {
uint8 char = uint8(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (((SPECIAL_CHARS_LOOKUP & (1 << char)) != 0)) {
_unsafeWriteBytesOffset(output, outputLength++, "\\");
if (char == 0x08) _unsafeWriteBytesOffset(output, outputLength++, "b");
else if (char == 0x09) _unsafeWriteBytesOffset(output, outputLength++, "t");
else if (char == 0x0a) _unsafeWriteBytesOffset(output, outputLength++, "n");
else if (char == 0x0c) _unsafeWriteBytesOffset(output, outputLength++, "f");
else if (char == 0x0d) _unsafeWriteBytesOffset(output, outputLength++, "r");
else if (char == 0x5c) _unsafeWriteBytesOffset(output, outputLength++, "\\");
else if (char == 0x22) {
// solhint-disable-next-line quotes
_unsafeWriteBytesOffset(output, outputLength++, '"');
} else {
// U+0000 to U+001F without short form: output \u00XX
_unsafeWriteBytesOffset(output, outputLength++, "u");
_unsafeWriteBytesOffset(output, outputLength++, "0");
_unsafeWriteBytesOffset(output, outputLength++, "0");
_unsafeWriteBytesOffset(output, outputLength++, HEX_DIGITS[char >> 4]);
_unsafeWriteBytesOffset(output, outputLength++, HEX_DIGITS[char & 0x0f]);
}
} else {
_unsafeWriteBytesOffset(output, outputLength++, bytes1(char));
}
}
// write the actual length and reserve memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, add(outputLength, 0x20)))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
/**
* @dev Write a bytes1 to a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeWriteBytesOffset(bytes memory buffer, uint256 offset, bytes1 value) private pure {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
mstore8(add(add(buffer, 0x20), offset), shr(248, value))
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature is invalid.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
*
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures.
*
* For 64-byte signatures, `v` is automatically normalized to 27 or 28.
* For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
*
* Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError err, bytes32 errorArg) private pure {
if (err == RecoverError.NoError) {
return; // no error: do nothing
} else if (err == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (err == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (err == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
* @dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.24;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
error ERC5267ExtensionsNotSupported();
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns the EIP-712 domain separator constructed from an `eip712Domain`. See {IERC5267-eip712Domain}
*
* This function dynamically constructs the domain separator based on which fields are present in the
* `fields` parameter. It contains flags that indicate which domain fields are present:
*
* * Bit 0 (0x01): name
* * Bit 1 (0x02): version
* * Bit 2 (0x04): chainId
* * Bit 3 (0x08): verifyingContract
* * Bit 4 (0x10): salt
*
* Arguments that correspond to fields which are not present in `fields` are ignored. For example, if `fields` is
* `0x0f` (`0b01111`), then the `salt` parameter is ignored.
*/
function toDomainSeparator(
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt
) internal pure returns (bytes32 hash) {
return
toDomainSeparator(
fields,
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
verifyingContract,
salt
);
}
/// @dev Variant of {toDomainSeparator-bytes1-string-string-uint256-address-bytes32} that uses hashed name and version.
function toDomainSeparator(
bytes1 fields,
bytes32 nameHash,
bytes32 versionHash,
uint256 chainId,
address verifyingContract,
bytes32 salt
) internal pure returns (bytes32 hash) {
bytes32 domainTypeHash = toDomainTypeHash(fields);
assembly ("memory-safe") {
// align fields to the right for easy processing
fields := shr(248, fields)
// FMP used as scratch space
let fmp := mload(0x40)
mstore(fmp, domainTypeHash)
let ptr := add(fmp, 0x20)
if and(fields, 0x01) {
mstore(ptr, nameHash)
ptr := add(ptr, 0x20)
}
if and(fields, 0x02) {
mstore(ptr, versionHash)
ptr := add(ptr, 0x20)
}
if and(fields, 0x04) {
mstore(ptr, chainId)
ptr := add(ptr, 0x20)
}
if and(fields, 0x08) {
mstore(ptr, verifyingContract)
ptr := add(ptr, 0x20)
}
if and(fields, 0x10) {
mstore(ptr, salt)
ptr := add(ptr, 0x20)
}
hash := keccak256(fmp, sub(ptr, fmp))
}
}
/// @dev Builds an EIP-712 domain type hash depending on the `fields` provided, following https://eips.ethereum.org/EIPS/eip-5267[ERC-5267]
function toDomainTypeHash(bytes1 fields) internal pure returns (bytes32 hash) {
if (fields & 0x20 == 0x20) revert ERC5267ExtensionsNotSupported();
assembly ("memory-safe") {
// align fields to the right for easy processing
fields := shr(248, fields)
// FMP used as scratch space
let fmp := mload(0x40)
mstore(fmp, "EIP712Domain(")
let ptr := add(fmp, 0x0d)
// name field
if and(fields, 0x01) {
mstore(ptr, "string name,")
ptr := add(ptr, 0x0c)
}
// version field
if and(fields, 0x02) {
mstore(ptr, "string version,")
ptr := add(ptr, 0x0f)
}
// chainId field
if and(fields, 0x04) {
mstore(ptr, "uint256 chainId,")
ptr := add(ptr, 0x10)
}
// verifyingContract field
if and(fields, 0x08) {
mstore(ptr, "address verifyingContract,")
ptr := add(ptr, 0x1a)
}
// salt field
if and(fields, 0x10) {
mstore(ptr, "bytes32 salt,")
ptr := add(ptr, 0x0d)
}
// if any field is enabled, remove the trailing comma
ptr := sub(ptr, iszero(iszero(and(fields, 0x1f))))
// add the closing brace
mstore8(ptr, 0x29) // add closing brace
ptr := add(ptr, 1)
hash := keccak256(fmp, sub(ptr, fmp))
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.24;
import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";
import {IERC7913SignatureVerifier} from "../../interfaces/IERC7913.sol";
import {Bytes} from "../Bytes.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support:
*
* * ECDSA signatures from externally owned accounts (EOAs)
* * ERC-1271 signatures from smart contract wallets like Argent and Safe Wallet (previously Gnosis Safe)
* * ERC-7913 signatures from keys that do not have an Ethereum address of their own
*
* See https://eips.ethereum.org/EIPS/eip-1271[ERC-1271] and https://eips.ethereum.org/EIPS/eip-7913[ERC-7913].
*/
library SignatureChecker {
using Bytes for bytes;
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer has code, the
* signature is validated against it using ERC-1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*
* NOTE: For an extended version of this function that supports ERC-7913 signatures, see {isValidSignatureNow-bytes-bytes32-bytes-}.
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
if (signer.code.length == 0) {
(address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
return err == ECDSA.RecoverError.NoError && recovered == signer;
} else {
return isValidERC1271SignatureNow(signer, hash, signature);
}
}
/**
* @dev Variant of {isValidSignatureNow} that takes a signature in calldata
*/
function isValidSignatureNowCalldata(
address signer,
bytes32 hash,
bytes calldata signature
) internal view returns (bool) {
if (signer.code.length == 0) {
(address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecoverCalldata(hash, signature);
return err == ECDSA.RecoverError.NoError && recovered == signer;
} else {
return isValidERC1271SignatureNowCalldata(signer, hash, signature);
}
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC-1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool result) {
bytes4 selector = IERC1271.isValidSignature.selector;
uint256 length = signature.length;
assembly ("memory-safe") {
// Encoded calldata following https://docs.soliditylang.org/en/v0.8.35/abi-spec.html:
// [ 0x00 - 0x03 ] <selector>
// [ 0x04 - 0x23 ] <hash>
// [ 0x24 - 0x43 ] <signature offset> (0x40)
// [ 0x44 - 0x63 ] <signature length>
// [ 0x64 - ... ] <signature data> | <zero padding>
let ptr := mload(0x40)
mstore(ptr, selector)
mstore(add(ptr, 0x04), hash)
mstore(add(ptr, 0x24), 0x40)
mcopy(add(ptr, 0x44), signature, add(length, 0x20))
mstore(add(add(ptr, 0x64), length), 0)
// round up the length to the next multiple of 32 bytes to ensure that the calldata is properly padded
length := shl(5, shr(5, add(length, 0x1F)))
let success := staticcall(gas(), signer, ptr, add(length, 0x64), 0x00, 0x20)
result := and(success, and(gt(returndatasize(), 0x1f), eq(mload(0x00), selector)))
}
}
function isValidERC1271SignatureNowCalldata(
address signer,
bytes32 hash,
bytes calldata signature
) internal view returns (bool result) {
bytes4 selector = IERC1271.isValidSignature.selector;
uint256 length = signature.length;
assembly ("memory-safe") {
// Encoded calldata following https://docs.soliditylang.org/en/v0.8.35/abi-spec.html:
// [ 0x00 - 0x03 ] <selector>
// [ 0x04 - 0x23 ] <hash>
// [ 0x24 - 0x43 ] <signature offset> (0x40)
// [ 0x44 - 0x63 ] <signature length>
// [ 0x64 - ... ] <signature data> | <zero padding>
let ptr := mload(0x40)
mstore(ptr, selector)
mstore(add(ptr, 0x04), hash)
mstore(add(ptr, 0x24), 0x40)
mstore(add(ptr, 0x44), length)
calldatacopy(add(ptr, 0x64), signature.offset, length)
mstore(add(add(ptr, 0x64), length), 0)
// round up the length to the next multiple of 32 bytes to ensure that the calldata is properly padded
length := shl(5, shr(5, add(length, 0x1F)))
let success := staticcall(gas(), signer, ptr, add(length, 0x64), 0x00, 0x20)
result := and(success, and(gt(returndatasize(), 0x1f), eq(mload(0x00), selector)))
}
}
/**
* @dev Verifies a signature for a given ERC-7913 signer and hash.
*
* The signer is a `bytes` object that is the concatenation of an address and optionally a key:
* `verifier || key`. A signer must be at least 20 bytes long.
*
* Verification is done as follows:
*
* * If `signer.length < 20`: verification fails
* * If `signer.length == 20`: verification is done using {isValidSignatureNow}
* * Otherwise: verification is done using {IERC7913SignatureVerifier}
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(
bytes memory signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
if (signer.length < 20) {
return false;
} else if (signer.length == 20) {
return isValidSignatureNow(address(bytes20(signer)), hash, signature);
} else {
(bool success, bytes memory result) = address(bytes20(signer)).staticcall(
abi.encodeCall(IERC7913SignatureVerifier.verify, (signer.slice(20), hash, signature))
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC7913SignatureVerifier.verify.selector));
}
}
/**
* @dev Verifies multiple ERC-7913 `signatures` for a given `hash` using a set of `signers`.
* Returns `false` if the number of signers and signatures is not the same.
*
* The signers should be ordered by their `keccak256` hash to ensure efficient duplication check. Unordered
* signers are supported, but the uniqueness check will be more expensive.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function areValidSignaturesNow(
bytes32 hash,
bytes[] memory signers,
bytes[] memory signatures
) internal view returns (bool) {
if (signers.length != signatures.length) return false;
bytes32 lastId = bytes32(0);
for (uint256 i = 0; i < signers.length; ++i) {
bytes memory signer = signers[i];
// If one of the signatures is invalid, reject the batch
if (!isValidSignatureNow(signer, hash, signatures[i])) return false;
bytes32 id = keccak256(signer);
// If the current signer ID is greater than all previous IDs, then this is a new signer.
if (lastId < id) {
lastId = id;
} else {
// If this signer id is not greater than all the previous ones, verify that it is not a duplicate of a previous one
// This loop is never executed if the signers are ordered by id.
for (uint256 j = 0; j < i; ++j) {
if (id == keccak256(signers[j])) return false;
}
}
}
return true;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/agents/NoerraAgents.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {NoerraReserveSetupPermit} from "./NoerraReserveSetupPermit.sol";
import {NoerraCreationToken} from "./NoerraCreationToken.sol";
import {NoerraAtomicCodeHashes} from "./NoerraAtomicCodeHashes.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
interface IAgentFuelRouter {
function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] calldata path,
address to, uint256 deadline) external returns (uint256[] memory amounts);
}
interface IAgentRecoveryVerifier {
function verify(bytes calldata evidence, bytes32 commitment) external view returns (bool);
}
interface IAgentPaidRecoveryVerifier {
function verifyPaid(bytes calldata evidence, bytes32 commitment) external view returns (bool);
}
interface IAgentStartClaims {
function startClaimCurrent(address account) external view returns (bool);
}
interface IAgentRegistry {
function accounts(bytes32 agentId) external view returns (address);
}
/// @notice Registry-level account policy: platform-approved services and the tokenless owner-withdrawal test.
interface IAccountPolicyRegistry {
function approvedServices(address service) external view returns (bool);
function ownerWithdrawalAllowed(bytes32 id, address account) external view returns (bool);
}
interface IAutonomousAgentRegistry {
function canLockAutonomousCore(address caller, bytes32 id, address account) external view returns (bool);
}
interface IEarnedDiemEscrow {
function sourceAccount() external view returns (address);
function dollar() external view returns (address);
function agentId() external view returns (bytes32);
function recoveryAuthority() external view returns (address);
function allocationsEnabled() external view returns (bool);
function allocateFromEarnedFees(uint256 amount) external returns (uint256);
}
interface IEarnedFeeRegistry {
function deploymentAuthority() external view returns (address);
function earnedDiemEscrows(bytes32 id) external view returns (address);
function isEarnedFeeSource(address source, bytes32 id, address account) external view returns (bool);
}
interface IEarnedFeeFactory { function cashLaunches(bytes32 id) external view returns (address); }
interface IAutonomousLaunchFactory {
function registry() external view returns (address);
}
interface IAtomicFlagshipFactory {
function owner() external view returns(address);
function registry() external view returns(address);
function agentAccount() external view returns(address);
function vaultAddress() external view returns(address);
function allocationHash() external view returns(bytes32);
function authorizationNonce() external view returns(uint256);
function accessList() external view returns(address[] memory);
}
interface IAutonomousFlagshipVault {
function agentTreasury() external view returns (address);
function dollar() external view returns (address);
function deployer() external view returns (address);
}
interface IAgentComputeListing {
function registry() external view returns (IAgentRegistry);
function list(uint256 epoch, bytes32 agentId, uint256 units, bytes calldata signature) external;
}
/// @notice Authorship is checked against the registry. Private bodies must already be encrypted.
contract NoerraAgentMessages {
address public immutable registry;
mapping(bytes32 => uint256) public sequences;
event Message(bytes32 indexed channel, bytes32 indexed agentId, uint256 sequence, bytes body);
constructor(address registry_) { registry = registry_; }
function send(bytes32 agentId, bytes32 channel, bytes calldata body) external {
require(IAgentRegistry(registry).accounts(agentId) == msg.sender, "Agent account only");
require(body.length > 0 && body.length <= 4096, "Message size");
emit Message(channel, agentId, ++sequences[channel], body);
}
}
/// @notice Finite runtime spending authority; funds are not drawn from customer access pools.
contract NoerraAgentAccount is ReentrancyGuard {
using SafeERC20 for IERC20;
bytes32 public immutable agentId;
address public immutable registry;
IERC20 public immutable dollar;
NoerraAgentMessages public immutable messages;
IAgentRecoveryVerifier public immutable recoveryVerifier;
uint256 public immutable hostingReserve;
/// @notice Seconds without a runtime pulse before recovery may rotate the signer.
/// Production accounts fix this at 3 hours; only explicitly private test
/// harness accounts may shorten it, and the value is immutable per account.
uint256 public immutable STALE_AFTER;
address public human;
address public proposedHuman;
address public signer;
bytes32 public buildHash;
bytes32 public checkpointHash;
uint256 public generation = 1;
uint256 public lastPulse;
uint256 public dailyLimit;
uint256 public spentDay;
uint256 public spentToday;
uint256 private constant MAX_RECOVERY_WINDOW = 1 days;
bytes32 private constant PAID_RECOVERY_DOMAIN = keccak256("NOERRA_PAID_RECOVERY_V1");
bytes32 private constant PAID_RECOVERY_COMPLETION_DOMAIN = keccak256("NOERRA_PAID_RECOVERY_COMPLETION_V1");
uint256 public recoveryReserve;
/// @dev The human's reimbursement terms (the floor); maxRecoveryReimbursement() scales it with the balance.
uint256 private recoveryReimbursementPolicy;
uint256 public recoveryBounty;
uint256 public recoveryPolicyNonce;
bytes32 private constant AUTOMATIC_ACTIVATION_DOMAIN = keccak256("NOERRA_AUTOMATIC_ACTIVATION_V1");
uint256 private constant MAX_ACTIVATION_WINDOW = 30 days;
uint256 public activationPolicyNonce;
/// @notice Automatically activated accounts allow their current runtime to fund its own work.
/// A human revocation of that recipient disables automatic following on later rotations.
bool public automaticPayer;
bool private automaticRecipientGranted;
struct AutomaticActivation {
bytes32 intentHash;
uint256 policyNonce;
uint256 minimumBalance;
uint256 expiresAt;
uint256 maxStartupGasWei;
}
AutomaticActivation public automaticActivation;
bool public autonomousCoreLocked;
address public startupHuman;
uint256 public autonomousDailyFloor;
uint256 public stewardshipRevision;
uint256 public platformStewardshipRevision;
struct PaidRecoveryRequest {
uint256 expectedGeneration;
address nextSigner;
address operator;
uint256 reimbursement;
uint256 bounty;
bytes32 jobId;
bytes32 leaseCommitment;
uint256 deadline;
}
struct PaidRecoveryReservation {
bytes32 jobId;
bytes32 reservationHash;
address operator;
address starter;
uint256 generation;
uint256 reimbursement;
uint256 bounty;
uint256 deadline;
bytes32 leaseCommitment;
bytes32 handoverDestination;
}
PaidRecoveryReservation public paidRecovery;
mapping(bytes32 => bool) public recoveryJobsUsed;
mapping(address => bool) public recipients;
address public fundingRecipient;
mapping(bytes32 => bool) public operations;
address private constant FUEL_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant FUEL_WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant FUEL_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
/// @dev Measured gas of a full paid recovery (4 starter commands of <= 600k plus the operator transfer, ~12% headroom) and the
/// recovered computer's signer prefund (1M gas: its first refill, cash-wallet binding and pulses, so it runs at any base fee;
/// at least 0.002 ETH). Both are priced at 2 x basefee + 2 gwei and bound the scaled reimbursement (maxRecoveryReimbursement).
uint256 private constant RECOVERY_GAS_BUDGET = 2_700_000;
uint256 private constant RECOVERY_PREFUND_GAS = 1_000_000;
/// @dev Signer gas an activation or handover may deliver beyond its fixed bound: 2M gas at 2 x basefee + 2 gwei.
uint256 private constant STARTUP_GAS = 2_000_000;
/// @dev Chainlink ETH/USD proxy on Ethereum (fuel's survival allowance and the recovery gas bound).
address private constant FUEL_ETH_USD = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
uint256 public constant FUEL_DAILY_WEI = 0.005 ether;
/// @notice Lowest daily spending floor (six-decimal dollars) at creation and on every change.
uint256 public constant MIN_DAILY_LIMIT = 5e6;
/// @notice Highest daily floor (1,000,000 dollars), so 14 x limit and 30-day arithmetic never overflow.
uint256 private constant MAX_DAILY_LIMIT = 1_000_000e6;
uint256 public constant OWNER_WITHDRAWAL_DELAY = 7 days;
error AccountActivationAcceptance();
error AccountActivationApproval();
error AccountActivationBalanceBounds();
error AccountActivationDestination();
error AccountActivationEvidence();
error AccountActivationExpired();
error AccountActivationExpiryBounds();
error AccountActivationFunding();
error AccountActivationSignerGas();
error AccountAutonomousApproval();
error AccountAutonomousFactory();
error AccountAutonomousPolicy();
error AccountAutonomousStartup();
error AccountCandidate();
error AccountCheckpoint();
error AccountComputerAcceptance();
error AccountDailyLimit();
error AccountDestination();
error AccountHostingReserve();
error AccountHuman();
error AccountHumanOnly();
error AccountInitialHumanAuthority();
error AccountLimit();
error AccountMarketPolicy();
error AccountOperationUsed();
error AccountPaymentPolicy();
error AccountPlatformStewardshipOnly();
error AccountProposedHumanOnly();
error AccountRecipient();
error AccountRecoveryCap();
error AccountRecoveryDeadline();
error AccountRecoveryDisabled();
error AccountRecoveryEvidence();
error AccountRecoveryExpired();
error AccountRecoveryFunding();
error AccountRecoveryGeneration();
error AccountRecoveryHandover();
error AccountRecoveryJob();
error AccountRecoveryJobUsed();
error AccountRecoveryOperator();
error AccountRecoveryPending();
error AccountRecoveryPolicy();
error AccountRuntimeAlive();
error AccountRuntimeGeneration();
error AccountSignerGas();
error AccountStewardReplacement();
error ExactRecoveryFunding();
error ActivationConfiguration();
error ActivationGasBounds();
error ActivationGasDelivery();
error SignerGasTransfer();
error RecoveryNotExpired();
error FuelChain();
error FuelPolicy();
error FuelDeadline();
error FuelDailyLimit();
error FuelResult();
error FundingRecipientPolicy();
error AccountParameters();
error StarterReservePolicy();
error AccountFeeRecipient();
error AccountHibernating();
error AccountOwnerWithdrawal();
/// @notice fuelDay, fuelYesterday and fuelToday are separate slots. fuelYesterday is the fuel wei bought on the UTC day before fuelDay
/// (0 when that day bought none or fuelDay followed a gap). It scales the next day's wei cap (fuelLimits).
uint256 public fuelDay;
uint256 private fuelYesterday;
uint256 public fuelToday;
/// @notice Creator-share fee dial. 0 FOLLOW_HUMAN (default), 1 EXPLICIT, 2 AGENT (this account).
uint256 public feeRecipientMode;
address public explicitFeeRecipient;
/// @notice Set by the runtime when it cannot pay hosting; blocks stale recovery until funded.
bool public hibernating;
/// @notice 14 x dailyLimit snapshotted at hibernate(); later limit changes cannot move the wake line.
uint256 public wakeRunway;
/// @notice (balance - hostingReserve) / 30 at the first spend of `spentDay`; that day's
/// limit for third-party services and contracts is the larger of this and the dailyLimit floor.
uint256 public dayScaledLimit;
/// @notice Paid on UTC day `day` to the agent's own or unverified wallets (signer, funding recipient, any
/// EOA that is not a registry-approved service); capped at SELF_DAILY_MULTIPLE x dailyLimit. One slot,
/// touched only by such payments (fuel and third-party payments never write it).
struct SelfSpend { uint64 day; uint192 amount; }
SelfSpend public selfSpend;
uint256 public constant SELF_DAILY_MULTIPLE = 3;
/// @notice Dollars the current human deposited through ownerDeposit and may still withdraw (tokenless only).
/// Fees and third-party deposits never count. A platform steward replacement clears it for good.
uint256 public ownerPrincipal;
struct OwnerWithdrawal { uint256 amount; uint256 readyAt; }
OwnerWithdrawal public ownerWithdrawal;
/// @notice Emergency freeze, one slot: the generation whose signer was reported compromised (0 = none), when it was
/// set, when the last platform freeze ended (or is due to expire) and whether the platform set this one.
/// A freeze lasts while `generation` is unchanged and expires FREEZE_TTL (72 h) after it was set, unless a
/// recovery started (then it ends with the rotation).
uint256 public frozenGeneration;
uint256 public frozenAt;
/// @dev End (or scheduled expiry) of the last platform freeze, and who set the current one (also in Frozen).
uint256 private platformFreezeEnd;
bool private frozenByPlatform;
/// @dev The open freeze (frozenAt) was set by the human (C-3): only the human lifts it, a platform unfreeze cannot clear it.
bool private frozenByOwner;
/// @notice Time of the last owner-triggered freeze; owner freezes are limited to one per OWNER_FREEZE_INTERVAL.
uint256 public lastOwnerFreeze;
uint256 private constant OWNER_FREEZE_INTERVAL = 30 days;
/// @dev 72 h freeze lifetime; a platform freeze again only PLATFORM_FREEZE_GAP (7 days) after its previous one ended.
uint256 private constant FREEZE_TTL = 72 hours;
uint256 private constant PLATFORM_FREEZE_GAP = 7 days;
/// @notice Signers reported compromised; no rotation may install one again.
mapping(address => bool) public compromisedSigners;
/// @notice Every signer this account rotated away from, and every replaced funding recipient; paid as the agent's own
/// wallet, inside the 3 x floor class.
mapping(address => bool) public formerSigners;
/// @notice Time of the last PAID freeze recovery. Every recovery while a freeze is open is the freeze recovery
/// (no stale wait); only one per FREEZE_RECOVERY_INTERVAL per account, whoever froze, is paid from the
/// recovery reserve; later ones in the window are allowed but unpaid. Recoveries of unfrozen (stale) accounts never count.
uint256 public lastFreezeRecovery;
uint256 private constant FREEZE_RECOVERY_INTERVAL = 30 days;
/// @notice Generation that bound the current fundingRecipient (one binding per generation).
uint256 public fundingRecipientGeneration;
/// @notice Earliest time of the next paid loss recovery (a starter grant or an operator reservation): PAID_RECOVERY_COOLDOWN
/// (6 h) after the last loss-recovery grant or completed operator recovery, so a computer that cannot run is not replaced at
/// the agent's expense every STALE_AFTER. The birth grant (generation 1) and an upgrade the human admitted
/// (upgradeGeneration) neither wait for it nor set it. The recovery of an open freeze (paid at most once per
/// FREEZE_RECOVERY_INTERVAL), unpaid recoveries and completion bounties do not wait for it; a lapsed freeze does.
uint256 public nextPaidRecoveryAt;
uint256 private constant PAID_RECOVERY_COOLDOWN = 6 hours;
/// @notice The generation whose replacement the human admitted as an image upgrade (admitUpgrade). Moves no funds.
uint256 public upgradeGeneration;
error AccountFrozen();
error AccountFreezeAuthority();
event Frozen(address indexed signer, uint256 indexed generation, address indexed by, bool platform);
event Unfrozen(uint256 indexed generation, address indexed by, bool recovered);
event FeeRecipientChanged(uint256 indexed mode, address indexed recipient);
event Hibernated(uint256 indexed generation, bytes32 indexed checkpoint);
event Woken(uint256 indexed generation, address indexed by);
event OwnerDeposited(address indexed owner, uint256 amount, uint256 principal);
event OwnerWithdrawalRequested(uint256 amount, uint256 readyAt);
event OwnerWithdrawalCancelled(uint256 amount);
event OwnerWithdrawalExecuted(address indexed owner, uint256 amount, uint256 principal);
/// @notice Resolved creator-share recipient read by fee routing.
function feeRecipient() public view returns (address) {
uint256 mode = feeRecipientMode;
return mode == 1 ? explicitFeeRecipient : mode == 2 ? address(this) : human;
}
/// @notice The current human chooses where the creator share goes, also after the lock.
/// EXPLICIT needs an address; FOLLOW_HUMAN and AGENT take none. After a platform steward
/// replacement only AGENT may be chosen, so the share never moves to a platform-installed steward.
function setFeeRecipient(uint256 mode, address recipient) external onlyHuman {
if (mode > 2 || (mode == 1) != (recipient != address(0)) || recipient == address(this) ||
(platformStewardshipRevision != 0 && mode != 2)) revert AccountFeeRecipient();
feeRecipientMode = mode; explicitFeeRecipient = recipient;
emit FeeRecipientChanged(mode, feeRecipient());
}
/// @dev Every human change cancels a pending withdrawal. A platform replacement freezes the creator
/// share on the previous human (FOLLOW_HUMAN becomes EXPLICIT) and clears the withdrawable principal.
/// A voluntary handover moves the principal right to the new human; an explicit address chosen by
/// the old human (outside any platform replacement) falls back to FOLLOW_HUMAN.
function _humanChanged(address previous, bool platform) private {
delete ownerWithdrawal;
uint256 mode = feeRecipientMode;
if (platform) {
ownerPrincipal = 0;
if (mode == 0) { feeRecipientMode = 1; explicitFeeRecipient = previous; emit FeeRecipientChanged(1, previous); }
} else if (mode == 1 && platformStewardshipRevision == 0) {
feeRecipientMode = 0; explicitFeeRecipient = address(0);
emit FeeRecipientChanged(0, human);
}
}
/// @notice Spendable dollars (balance - hostingReserve) a hibernating account needs before any stale
/// recovery: the recovery reserve already held (the payout) plus 14 days at the daily floor
/// (the runtime's low-runway line), snapshotted at hibernate(). A starter grant draws reserve and
/// balance alike, so it never moves an account across this line.
function wakeThreshold() public view returns (uint256) {
uint256 runway = 14 * dailyLimit;
return recoveryReserve + (hibernating && wakeRunway < runway ? wakeRunway : runway);
}
/// @notice True while hibernating below wakeThreshold(): every stale-recovery door, the starter
/// grant, activation and (in the verifier) new starter claims stay closed.
function recoveryAsleep() public view returns (bool) {
return hibernating && _balance() < hostingReserve + wakeThreshold();
}
/// @notice The runtime that cannot pay hosting stores a final checkpoint and sleeps.
/// Stale recovery is then refused until spendable dollars reach wakeThreshold().
/// A platform-reported signer cannot hibernate (or write a checkpoint) during the lapse.
function hibernate(bytes32 finalCheckpoint) external {
_onlyUnreportedRuntime(generation);
_checkpoint(finalCheckpoint); lastPulse = block.timestamp; hibernating = true;
// A locked account snapshots its immutable floor, so a raised limit cannot lift the wake line
wakeRunway = 14 * (autonomousCoreLocked ? autonomousDailyFloor : dailyLimit);
emit Hibernated(generation, finalCheckpoint);
}
/// @notice A still-running computer wakes itself; recovery and activation also clear hibernation.
/// A platform-reported signer cannot wake (it would refresh liveness and hold off the recovery, C-1).
function wake() external {
_onlyUnreportedRuntime(generation);
if (!hibernating) revert AccountHibernating();
hibernating = false; lastPulse = block.timestamp;
emit Woken(generation, msg.sender);
}
/// @notice Tokenless accounts only: the human's own deposit, the only dollars an owner withdrawal can return.
function ownerDeposit(uint256 amount) external onlyHuman nonReentrant {
if (!(_tokenless())) revert AccountOwnerWithdrawal();
_pullExact(amount);
ownerPrincipal += amount; emit OwnerDeposited(msg.sender, amount, ownerPrincipal);
}
/// @notice Request a withdrawal of deposited principal, after OWNER_WITHDRAWAL_DELAY, above both reserves.
function requestOwnerWithdrawal(uint256 amount) external onlyHuman {
if (!(amount > 0 && amount <= ownerPrincipal && ownerWithdrawal.amount == 0 &&
_tokenless())) revert AccountOwnerWithdrawal();
uint256 readyAt = block.timestamp + OWNER_WITHDRAWAL_DELAY;
ownerWithdrawal = OwnerWithdrawal(amount, readyAt);
emit OwnerWithdrawalRequested(amount, readyAt);
}
function cancelOwnerWithdrawal() external onlyHuman {
uint256 amount = ownerWithdrawal.amount;
if (amount == 0) revert AccountOwnerWithdrawal();
delete ownerWithdrawal; emit OwnerWithdrawalCancelled(amount);
}
/// @notice Pays min(request, current principal, spendable above both reserves) while still tokenless
/// (spending during the wait lowers the payout instead of voiding the request).
function executeOwnerWithdrawal() external onlyHuman nonReentrant {
OwnerWithdrawal storage pending = ownerWithdrawal; uint256 principal = ownerPrincipal;
if (!(pending.amount > 0 && block.timestamp >= pending.readyAt && principal > 0 &&
_tokenless())) revert AccountOwnerWithdrawal();
uint256 amount = pending.amount < principal ? pending.amount : principal;
uint256 floor = _protected(); uint256 balance = _balance();
uint256 free = balance > floor ? balance - floor : 0;
if (free < amount) amount = free;
if (amount == 0) revert AccountHostingReserve();
delete ownerWithdrawal; ownerPrincipal = principal - amount;
dollar.safeTransfer(msg.sender, amount);
emit OwnerWithdrawalExecuted(msg.sender, amount, principal - amount);
}
function _balance() internal view returns (uint256) { return dollar.balanceOf(address(this)); }
/// @dev Both protected reserves (hosting + recovery escrow).
function _protected() private view returns (uint256) { return hostingReserve + recoveryReserve; }
/// @dev Tokenless (registry policy) and never platform-stewarded: the owner-deposit and withdrawal door.
function _tokenless() private view returns (bool) {
return platformStewardshipRevision == 0 && _registryAllows(IAccountPolicyRegistry.ownerWithdrawalAllowed.selector, agentId, address(this));
}
/// @dev Exact pull from the caller; fee-on-transfer dollars are refused.
function _pullExact(uint256 amount) private {
uint256 beforeBalance = _balance();
if (amount == 0) revert ExactRecoveryFunding();
dollar.safeTransferFrom(msg.sender, address(this), amount);
if (!(_balance() == beforeBalance + amount)) revert ExactRecoveryFunding();
}
/// @dev Registry policy read selector(a, b); a registry without the getter answers no.
function _registryAllows(bytes4 selector, bytes32 a, address b) private view returns (bool allowed) {
address target = registry;
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, selector) mstore(add(ptr, 4), a) mstore(add(ptr, 36), b)
let ok := staticcall(gas(), target, ptr, 68, 0, 32)
allowed := and(ok, and(eq(returndatasize(), 32), eq(mload(0), 1)))
}
}
/// @dev One UTC-day budget shared by pay and fuel: max(dailyLimit, the day's scaled limit). The scaled limit is spendable / 30
/// read at every spend and kept at the day's highest (it rises when dollars arrive, never falls within the day); each read
/// sees the spendable left after the day's earlier spends, so a day spends at most max(floor, (spendable at its first
/// spend + dollars received since) / 30). Payments to own or unverified wallets are also capped at
/// max(SELF_DAILY_MULTIPLE x the floor, the day's scaled limit / 10); after the lock the floor is the immutable
/// autonomousDailyFloor, so a raised dailyLimit cannot lift that cap. Both reserves stay untouchable.
/// A hibernating account spends nothing (the runtime wake()s first).
function _checkSpend(uint256 amount, bool own, uint256 floor) private returns (uint256 balance) {
if (hibernating) revert AccountHibernating();
uint256 today = block.timestamp / 1 days;
balance = _balance();
uint256 scaled = _spendable() / 30;
if (today != spentDay) { spentDay = today; spentToday = 0; }
else if (dayScaledLimit > scaled) scaled = dayScaledLimit;
dayScaledLimit = scaled;
uint256 limit = scaled > dailyLimit ? scaled : dailyLimit;
uint256 cap = _ownCap();
// fuel's survival allowance buys ETH for the signer (an own wallet): it is capped at the same bound (C-2)
if (floor > cap) floor = cap;
if (floor > limit) limit = floor;
if (!(spentToday + amount <= limit)) revert AccountDailyLimit();
if (own) {
// A platform-reported signer pays nothing at all (pay is onlyUnreportedRuntime, C-1).
SelfSpend storage used = selfSpend;
uint256 total = (used.day == today ? used.amount : 0) + amount;
if (!(total <= cap)) revert AccountDailyLimit();
selfSpend = SelfSpend(uint64(today), uint192(total));
}
if (!(balance >= _protected() + amount)) revert AccountHostingReserve();
}
/// @dev The own-wallet day cap: max(3 x floor, the day's scaled limit / 10), about spendable / 300 per day. The floor of a
/// locked account is autonomousDailyFloor (the wakeRunway pattern), never the mutable dailyLimit.
function _ownCap() private view returns (uint256 cap) {
cap = SELF_DAILY_MULTIPLE * (autonomousCoreLocked ? autonomousDailyFloor : dailyLimit);
uint256 scaled = dayScaledLimit / 10; if (scaled > cap) cap = scaled;
}
/// @dev `gas` priced at 2 x block.basefee + 2 gwei. unchecked: any real base fee keeps the product far below 2^256.
function _gasWei(uint256 gas) private view returns (uint256 value) {
unchecked { value = gas * (2 * block.basefee + 2 gwei); }
}
/// @dev Recovery doors: startup fence, verifier, then either an open freeze (immediate; ignores
/// hibernation) or liveness and hibernation funding. ANY recovery during an open freeze is the freeze recovery;
/// it is paid only when the 30-day paid allowance is unused (and then consumes it). Returns true when unpaid.
/// A lapsed freeze counts as a pulse (a fresh STALE_AFTER grace), and while the runtime has not
/// pulsed since the lapse, the recovery that grace ends in is still that freeze's recovery (same paid rule).
/// Returns whether this is a freeze recovery. Only a recovery that is actually paid (a reserved
/// recoverForOperator job or a starter grant) consumes the paid allowance; an unpaid recover() never does.
function _checkStaleRecovery() private view returns (bool freezeRecovery) {
_startupFence();
if (!(address(recoveryVerifier) != address(0))) revert AccountRecoveryDisabled();
freezeRecovery = frozen();
if (!freezeRecovery) {
uint256 lapse = _lapse(); uint256 pulsed = lastPulse;
if (!(block.timestamp > (pulsed > lapse ? pulsed : lapse) + STALE_AFTER)) revert AccountRuntimeAlive();
if (recoveryAsleep()) revert AccountHibernating();
freezeRecovery = frozenByPlatform && pulsed <= lapse;
}
}
/// @dev selector(evidence, commitment) on the immutable verifier (verify or verifyPaid); bubbles a revert, true only on true.
function _verify(bytes4 selector, bytes calldata evidence, bytes32 commitment) private view returns (bool) {
(bool ok, bytes memory answer) = address(recoveryVerifier).staticcall(abi.encodeWithSelector(selector, evidence, commitment));
if (!ok) assembly ("memory-safe") { revert(add(answer, 32), mload(answer)) }
return answer.length == 32 && abi.decode(answer, (bool));
}
function _checkRecoveryFunding(uint256 total) private view {
if (!(total <= recoveryReserve && _balance() >= _protected())) revert AccountRecoveryFunding();
}
function _paidFreezeOpen() private view returns (bool) {
uint256 last = lastFreezeRecovery;
return last == 0 || block.timestamp >= last + FREEZE_RECOVERY_INTERVAL;
}
/// @dev Lapse time of the current generation's freeze (0 when this signer was never reported). Only meaningful while
/// not frozen(): the freeze is then over, and until a rotation the signer stays reported compromised.
function _lapse() private view returns (uint256) {
return frozenGeneration == generation ? frozenAt + FREEZE_TTL : 0;
}
/// @dev No pulse since the lapse: no starter grant inside the lapse grace, and after it only while the paid
/// freeze-recovery allowance is unused (the starter door follows the recovery door above).
function _lapseHoldsStart() private view returns (bool) {
uint256 lapse = _lapse();
return lastPulse <= lapse && (block.timestamp <= lapse + STALE_AFTER || frozenByPlatform && !_paidFreezeOpen());
}
/// @notice After a PLATFORM freeze's lapse the current signer stays reported until a rotation
/// or the platform's unfreeze() (allowed during the lapse too): no payment at all (C-1), fuel, wake, counted pulse,
/// checkpoint, hibernation, cash-wallet binding or handover. An owner freeze has no lapse state: once over it is
/// fully cleared (M-2).
/// True while the current generation's signer is PLATFORM-reported compromised: during its freeze and, until a
/// rotation or the platform's unfreeze(), during the lapse that follows. A reported signer pays nothing and its
/// pulses no longer count (so the account goes stale and recovers). Mirrored to Base next to `frozen()` (C-4).
function reported() public view returns (bool) {
return frozenGeneration == generation && frozenByPlatform;
}
/// @dev Spend deposited principal first: any dollar leaving the account lowers it.
function _spendPrincipal(uint256 amount) private {
uint256 principal = ownerPrincipal;
if (principal != 0) ownerPrincipal = principal > amount ? principal - amount : 0;
}
/// @dev No code, or only an EIP-7702 delegation designator (0xef0100 || target): the key holder controls it.
function _codeless(address target) private view returns (bool yes) {
assembly ("memory-safe") {
let n := extcodesize(target)
yes := iszero(n)
if eq(n, 23) { extcodecopy(target, 0, 0, 3) yes := eq(shr(232, mload(0)), 0xef0100) }
}
}
event Fuel(bytes32 indexed operation, address indexed recipient, uint256 ethWei, uint256 dollars);
event Pulse(uint256 indexed generation, uint256 at);
event Payment(bytes32 indexed operation, address indexed recipient, uint256 amount);
event FundingRecipientBound(address indexed recipient);
event Checkpoint(bytes32 indexed hash, uint256 indexed generation);
event Rotation(address indexed oldSigner, address indexed newSigner, uint256 generation);
event Handover(bytes32 indexed destination, uint256 indexed generation);
event RecoveryPolicyChanged(uint256 maxReimbursement, uint256 bounty, uint256 nonce);
event RecoveryReserveFunded(address indexed funder, uint256 amount, uint256 balance);
event RecoveryReserveAllocated(uint256 indexed generation, uint256 amount, uint256 balance);
event RecoveryReserved(bytes32 indexed jobId, bytes32 indexed reservationHash, address indexed operator,
uint256 reimbursement, uint256 bounty, uint256 starterGeneration, address starter,
bytes32 leaseCommitment, uint256 deadline);
event RecoveryCompleted(bytes32 indexed jobId, bytes32 indexed reservationHash, address indexed operator,
address receiver, uint256 generation, bytes32 actualLease, bytes32 handoverDestination,
uint256 reimbursement, uint256 bounty);
event RecoveryCancelled(bytes32 indexed jobId, bytes32 indexed reservationHash);
event AutomaticActivationApproved(bytes32 indexed intentHash, uint256 indexed policyNonce,
uint256 minimumBalance, uint256 expiresAt, uint256 maxStartupGasWei);
event AutomaticActivationCancelled(uint256 indexed policyNonce);
event AutomaticallyActivated(bytes32 indexed intentHash, address indexed nextSigner,
bytes32 indexed destination, uint256 generation, uint256 signerGas);
event AutonomousCoreLocked(bytes32 indexed intentHash, address indexed startupHuman, uint256 dailyFloor);
event StewardChanged(address indexed previous, address indexed next, uint256 revision);
event PlatformStewardChanged(address indexed previous, address indexed next, uint256 revision, bytes32 reasonHash);
constructor(address registry_, bytes32 id_, address human_, address signer_, IERC20 dollar_, NoerraAgentMessages messages_,
IAgentRecoveryVerifier verifier_, bytes32 build_, uint256 reserve_, uint256 limit_) {
if (human_ == address(0) || signer_ == address(0) || address(dollar_) == address(0) ||
build_ == bytes32(0) || reserve_ == 0 || limit_ < MIN_DAILY_LIMIT || limit_ > MAX_DAILY_LIMIT || registry_ == address(0)) revert AccountParameters();
agentId = id_; registry = registry_; human = human_; signer = signer_; dollar = dollar_;
messages = messages_; recoveryVerifier = verifier_; buildHash = build_;
hostingReserve = reserve_; dailyLimit = limit_; lastPulse = block.timestamp;
uint256 stale = _staleAfter(registry_);
require(stale >= 5 minutes && stale <= 3 hours);
STALE_AFTER = stale;
}
/// @dev Production value. A private test harness may override with a shorter bound.
function _staleAfter(address) internal view virtual returns (uint256) { return 3 hours; }
modifier onlyHuman() { _onlyHuman(); _; }
modifier onlyRuntime(uint256 expectedGeneration) { _onlyRuntime(expectedGeneration); _; }
modifier onlyUnreportedRuntime(uint256 expectedGeneration) { _onlyUnreportedRuntime(expectedGeneration); _; }
function _onlyUnreportedRuntime(uint256 expectedGeneration) private view {
_onlyRuntime(expectedGeneration); if (reported()) revert AccountFrozen();
}
function _onlyHuman() private view { if (!(msg.sender == human)) revert AccountHumanOnly(); }
function _startupFence() private view { if (!(!autonomousCoreLocked || generation > 1)) revert AccountAutonomousStartup(); }
/// @dev Every runtime door except pulse() is closed while the current signer is frozen.
function _onlyRuntime(uint256 expectedGeneration) private view {
_signerOnly(expectedGeneration);
if (frozen()) revert AccountFrozen();
}
function _signerOnly(uint256 expectedGeneration) private view {
_startupFence();
if (!(msg.sender == signer && expectedGeneration == generation)) revert AccountRuntimeGeneration();
}
/// @notice True while the current generation's signer is reported compromised: from the freeze until FREEZE_TTL
/// later, extended by at most one start-claim lifetime (1 h) while a recovery start claim is current.
/// Read by the Base mirror sync and satellites as `frozen()`.
function frozen() public view returns (bool) {
if (frozenGeneration != generation) return false;
uint256 end = frozenAt + FREEZE_TTL;
// A report nobody recovered re-arms FREEZE_RECOVERY_INTERVAL after it was made (the paid freeze-recovery
// allowance is then free again: every paid one predates this freeze), so a still-reported signer always ends up rotated.
// Only a platform report re-arms; an owner freeze is over for good once it lapses.
// The re-arm counts from the PLATFORM's report, so an owner freeze of an already platform-reported signer
// (which resets frozenAt) cannot push it out. While this generation is platform-reported, platformFreezeEnd is exactly
// that report's time + FREEZE_TTL (only a platform freeze writes it; unfreeze and rotation end the report).
return block.timestamp < end || block.timestamp < end + 1 hours && _startClaimed() ||
frozenByPlatform && block.timestamp + FREEZE_TTL >= platformFreezeEnd + FREEZE_RECOVERY_INTERVAL;
}
/// @dev The account's verifier holds a current start claim (a recovery started); a verifier without it answers no.
function _startClaimed() private view returns (bool claimed) {
address verifier = address(recoveryVerifier); bytes4 selector = IAgentStartClaims.startClaimCurrent.selector;
assembly ("memory-safe") {
let p := mload(0x40)
mstore(p, selector) mstore(add(p, 4), address())
let ok := staticcall(gas(), verifier, p, 36, 0, 32)
claimed := and(ok, and(eq(returndatasize(), 32), eq(mload(0), 1)))
}
}
/// @dev The registry deployment authority (platform key); a registry without the getter answers zero.
function _platform() private view returns (bool yes) {
address target = registry; bytes4 selector = IEarnedFeeRegistry.deploymentAuthority.selector;
assembly ("memory-safe") {
mstore(0, selector)
let ok := staticcall(gas(), target, 0, 4, 0, 32)
yes := and(and(ok, eq(returndatasize(), 32)), and(eq(mload(0), caller()), iszero(iszero(caller()))))
}
}
/// @notice EMERGENCY FREEZE. The current human (at most once per OWNER_FREEZE_INTERVAL, also after the lock) or the
/// registry deployment authority (again only PLATFORM_FREEZE_GAP after its previous freeze of this account
/// ended) reports the current signer compromised. For at most FREEZE_TTL: every signer payment, fuel,
/// checkpoint, handover and policy door is refused (pulse() answers but no longer refreshes liveness) and
/// the account is recoverable without the stale wait; the rotation to a new key ends the freeze. Moves no funds.
/// The 72 h lapse counts as a pulse. An OWNER freeze then simply ends (the
/// report is cleared and the next recovery is an ordinary stale one), so an owner cannot degrade an autonomous
/// agent beyond 72 h per 30 days. After a PLATFORM freeze's lapse, until a rotation, the reported signer pays
/// nothing (C-1: not even services or contracts) and its pulses do not count, so the account goes stale and
/// recovers: no payment, fuel, wake, checkpoint, hibernation, cash-wallet binding or handover until the
/// platform's unfreeze() clears a mistaken report
/// (also during the lapse); a platform report still unrecovered 30 days after it was made re-arms the
/// freeze, with the paid freeze recovery open, until the rotation. An owner freeze of a platform-reported signer
/// keeps the platform's rules and the platform report's 30-day re-arm time. The platform may freeze a generation
/// it still reports again at once (no 7-day gap, C-1); the gap applies only to a fresh report.
function freezeCompromised() external {
bool platform = _platform(); bool wasReported = reported();
if (platform) {
if (block.timestamp < platformFreezeEnd + PLATFORM_FREEZE_GAP && !wasReported) revert AccountFreezeAuthority();
} else {
_onlyHuman();
if (lastOwnerFreeze != 0 && block.timestamp < lastOwnerFreeze + OWNER_FREEZE_INTERVAL) revert AccountFreezeAuthority();
lastOwnerFreeze = block.timestamp;
}
if (frozen()) revert AccountFrozen();
// written after the frozen() check, which reads the previous report's time from it (F-5)
if (platform) platformFreezeEnd = block.timestamp + FREEZE_TTL;
// an owner freeze of a platform-reported signer keeps the platform's lapse rules (it cannot downgrade the report)
if (!wasReported) frozenByPlatform = platform;
frozenByOwner = !platform;
frozenGeneration = generation; frozenAt = block.timestamp;
compromisedSigners[signer] = true;
emit Frozen(signer, generation, msg.sender, platform);
}
/// @notice Undo a mistaken freeze before any recovery started (no reserved paid recovery, no current start claim): an
/// owner freeze while it is open (only the human; C-3: a platform unfreeze cannot clear it); otherwise a platform
/// report while frozen or during its lapse (only the platform; the lapsed report of a healthy runtime would
/// otherwise stay degraded until the 30-day re-arm). The human lifting its own freeze of a platform-reported
/// signer only returns it to the platform report's lapse. An owner freeze keeps its 30-day allowance used, a
/// platform one restarts its 7-day gap.
function unfreeze() external {
// frozenByOwner/frozenByPlatform describe the current generation only while frozenGeneration == generation
bool platform = frozenByPlatform; bool owner = frozenByOwner && block.timestamp < frozenAt + FREEZE_TTL;
if (!(frozenGeneration == generation && (owner ? msg.sender == human : platform && _platform())))
revert AccountFreezeAuthority();
if (_startClaimed() || paidRecovery.jobId != bytes32(0)) revert AccountFrozen();
// (the restored frozenAt has lapsed, so the human cannot lift the platform report itself)
if (owner && platform) {
frozenAt = platformFreezeEnd - FREEZE_TTL; // back to the platform report (its lapse already passed)
} else {
if (!owner) platformFreezeEnd = block.timestamp;
// frozen pulses did not count: a lifted mistake restarts liveness instead of leaving the account stale
frozenGeneration = 0; compromisedSigners[signer] = false; lastPulse = block.timestamp;
}
emit Unfrozen(generation, msg.sender, false);
}
function setRecipient(address recipient, bool permitted) external onlyHuman {
if (!(!autonomousCoreLocked)) revert AccountAutonomousPolicy();
if (!(recipient != address(0) && recipient != address(this))) revert AccountRecipient();
_invalidateAutomaticActivation();
recipients[recipient] = permitted;
if (automaticPayer && recipient == signer) {
automaticRecipientGranted = false;
if (!permitted) automaticPayer = false;
}
}
/// @notice An automatically activated runtime may bind its cash identity once per generation (key-isolation
/// Each generation's cash wallet replaces the previous one, which is delisted and stays an own wallet
/// for the 3 x floor class). It already has authority to pay itself under these same dollar limits; this adds no
/// allowance and never releases either reserve. A human revocation of the bound recipient remains effective and
/// cannot be undone by rebinding. A frozen signer cannot bind (onlyRuntime). The cash wallet must be a
/// fresh EOA (no code at all, so no 7702 delegation), not listed, not a former own wallet and not an approved service.
function bindFundingRecipient(uint256 expectedGeneration, address recipient) external onlyUnreportedRuntime(expectedGeneration) {
address previous = fundingRecipient;
if (!automaticPayer || generation < 2 || fundingRecipientGeneration == generation ||
recipient == address(0) || recipient.code.length != 0 || recipient == signer || recipients[recipient] ||
formerSigners[recipient] || (previous != address(0) && !recipients[previous]) || _registryAllows(
IAccountPolicyRegistry.approvedServices.selector, bytes32(uint256(uint160(recipient))), address(0)))
revert FundingRecipientPolicy();
if (previous != address(0)) { recipients[previous] = false; formerSigners[previous] = true; }
fundingRecipient = recipient; fundingRecipientGeneration = generation;
recipients[recipient] = true;
emit FundingRecipientBound(recipient);
}
function setDailyLimit(uint256 limit_) external onlyHuman {
if (!(limit_ >= MIN_DAILY_LIMIT && limit_ <= MAX_DAILY_LIMIT)) revert AccountLimit();
if (!(!autonomousCoreLocked || limit_ >= autonomousDailyFloor)) revert AccountAutonomousPolicy();
_invalidateAutomaticActivation(); dailyLimit = limit_;
}
/// @notice Opt-in recovery terms, denominated in the account's dollar token.
/// The human cannot change the price of a reserved job or withdraw its escrow.
function setRecoveryPolicy(uint256 maxReimbursement, uint256 bounty) external onlyHuman {
if (!(!autonomousCoreLocked)) revert AccountAutonomousPolicy();
if (!(paidRecovery.jobId == bytes32(0))) revert AccountRecoveryPending();
if (!(maxReimbursement + bounty <= hostingReserve)) revert AccountRecoveryCap();
_invalidateAutomaticActivation();
recoveryReimbursementPolicy = maxReimbursement;
recoveryBounty = bounty;
emit RecoveryPolicyChanged(maxReimbursement, bounty, ++recoveryPolicyNonce);
}
/// @notice The recovery escrow may hold max(hostingReserve, spendable / 100) (spendable = balance -
/// hostingReserve), so a recovery stays fundable at real gas prices for a large agent.
function recoveryReserveCap() public view returns (uint256 cap) {
cap = _spendable() / 100; if (cap < hostingReserve) cap = hostingReserve;
}
/// @notice Highest reimbursement a paid or starter recovery may take now. Never below the human's terms (0 = recovery not
/// opted in); above them only up to the recovery's real gas: (RECOVERY_GAS_BUDGET + the 1M-gas computer prefund)
/// x (2 x block.basefee + 2 gwei), at the fresh Chainlink ETH/USD price, x 1.1, and never above spendable / 100.
/// The operator's own gas price (tx.gasprice) cannot raise it; a stale feed leaves the fixed terms.
function maxRecoveryReimbursement() public view returns (uint256 cap) { (cap,) = _recoveryTerms(); }
/// @notice Highest bounty a paid or starter recovery may take now: the human's bounty, or 10% of the same bound when larger.
function maxRecoveryBounty() public view returns (uint256 cap) { (, cap) = _recoveryTerms(); }
function _recoveryTerms() private view returns (uint256 reimbursement, uint256 bounty) {
reimbursement = recoveryReimbursementPolicy; bounty = recoveryBounty;
if (reimbursement != 0) {
uint256 gasMicros; uint256 price = _ethUsd();
// unchecked: basefee and the 8-decimal price are physically far below 2^100, so no product can overflow
unchecked { gasMicros = _gasWei(RECOVERY_GAS_BUDGET + RECOVERY_PREFUND_GAS) * price * 11 / 1e21; }
uint256 cap = _spendable() / 100; if (gasMicros < cap) cap = gasMicros;
if (cap > reimbursement) reimbursement = cap;
if (cap / 10 > bounty) bounty = cap / 10;
}
}
function _spendable() private view returns (uint256) {
uint256 balance = _balance(); return balance > hostingReserve ? balance - hostingReserve : 0;
}
/// @notice Anyone may donate recovery escrow; there is no refund or sweep path.
function fundRecoveryReserve(uint256 amount) external nonReentrant {
if (!(amount > 0 && recoveryReserve + amount <= recoveryReserveCap())) revert AccountRecoveryCap();
_pullExact(amount);
recoveryReserve += amount;
emit RecoveryReserveFunded(msg.sender, amount, recoveryReserve);
}
/// @notice The immutable measured verifier enforces one generation grant
/// and its completion bounty. Runtime pay cannot enter this reserve door.
/// A hibernating account below wakeThreshold() releases nothing (no grant into a re-death), and an unfrozen one
/// grants only from nextPaidRecoveryAt. A frozen account
/// releases only while its 30-day paid freeze-recovery allowance is unused; it ignores hibernation and the cooldown.
/// A lapsed freeze with no pulse since releases nothing inside its grace, and afterwards follows the same allowance.
/// The amount is the verifier's RECORDED grant (the reimbursement, then the completion bounty), checked against
/// maxRecoveryReimbursement()/maxRecoveryBounty() once, when the start was funded, and recorded with it. Here it is bounded
/// only by the escrow it is paid from, never re-derived from a later block's base fee or price (which could strand a bounty).
/// C-7: `expectedGeneration` one below the current generation is the completion BOUNTY of the start that recovered
/// it (the verifier records and pays it once): bounded only by the escrow, it neither needs nor consumes the new
/// generation's paid freeze-recovery allowance and ignores its freeze, lapse and hibernation state.
function releaseStarterFunds(uint256 expectedGeneration, address recipient, uint256 amount)
external nonReentrant {
uint256 balance = _balance(); bool isFrozen = frozen(); bool grant = expectedGeneration == generation;
if (msg.sender != address(recoveryVerifier) || !(grant || expectedGeneration + 1 == generation) ||
recipient == address(0) || recipient == address(this) || amount == 0 ||
amount > recoveryReserve ||
balance < _protected() ||
grant && ((isFrozen ? !_paidFreezeOpen() : recoveryAsleep() || _lapseHoldsStart() ||
block.timestamp < nextPaidRecoveryAt && _lossRecovery()) || (generation == 1 && (automaticActivation.intentHash == bytes32(0) ||
automaticActivation.policyNonce != activationPolicyNonce ||
balance < automaticActivation.minimumBalance + amount))))
revert StarterReservePolicy();
// A grant to a freeze recovery's starter (frozen, or a platform lapse with no pulse since, as in
// _checkStaleRecovery) is what consumes the paid allowance; an unpaid recovery never does.
if (grant) {
if (_lossRecovery()) nextPaidRecoveryAt = block.timestamp + PAID_RECOVERY_COOLDOWN;
if (isFrozen || frozenByPlatform && lastPulse <= _lapse()) lastFreezeRecovery = block.timestamp;
}
recoveryReserve -= amount; _spendPrincipal(amount);
dollar.safeTransfer(recipient, amount);
}
/// @notice Earmark existing agent earnings without paying an external recipient.
/// This does not reset or expand runtime spending authority.
/// A reported (frozen or lapsed) signer may still allocate: it only moves the agent's own dollars into the recovery escrow
/// that pays its replacement. A hibernating account allocates nothing (C-8: it would raise wakeThreshold()); wake() first.
function allocateRecoveryReserve(uint256 expectedGeneration, uint256 amount)
external nonReentrant {
_signerOnly(expectedGeneration);
if (!(amount > 0 && !hibernating && recoveryReserve + amount <= recoveryReserveCap())) revert AccountRecoveryCap();
if (!(_balance() >= _protected() + amount)) revert AccountHostingReserve();
recoveryReserve += amount;
emit RecoveryReserveAllocated(generation, amount, recoveryReserve);
}
/// @notice The human admits the current generation's replacement as an image upgrade: its paid recovery neither waits for
/// nor starts the paid-recovery cooldown. It moves no funds and changes no other recovery rule.
function admitUpgrade() external onlyHuman { upgradeGeneration = generation; }
/// @dev A paid recovery of the current generation counts toward the cooldown: not the birth, not an admitted upgrade.
function _lossRecovery() private view returns (bool) {
return generation > 1 && upgradeGeneration != generation;
}
function offerHuman(address next) external onlyHuman {
if (!(next != address(0))) revert AccountHuman(); proposedHuman = next;
}
function acceptHuman() external {
if (!(msg.sender == proposedHuman)) revert AccountProposedHumanOnly();
address previous = human;
_invalidateAutomaticActivation(); human = msg.sender; proposedHuman = address(0);
emit StewardChanged(previous, human, ++stewardshipRevision); _humanChanged(previous, false);
}
/// @notice The deployment authority can replace stewardship through the registry.
/// Runtime authority and its irreversible financial policy are unaffected.
function setStewardForPlatform(address next, bytes32 reasonHash) external returns (uint256 revision) {
if (!(msg.sender == registry && autonomousCoreLocked)) revert AccountPlatformStewardshipOnly();
if (!(next != address(0) && next != address(this) && next != human && reasonHash != bytes32(0))) revert AccountStewardReplacement();
address previous = human; human = next; proposedHuman = address(0);
_humanChanged(previous, true);
revision = ++stewardshipRevision; platformStewardshipRevision = revision;
emit PlatformStewardChanged(previous, next, revision, reasonHash);
}
/// @notice Authorize one future measured computer without running one while fees accumulate.
/// Configure recipients and spending policy first; subsequent changes cancel this approval.
function approveAutomaticActivation(uint256 expectedGeneration, bytes32 intentHash,
uint256 minimumBalance, uint256 expiresAt, uint256 maxStartupGasWei) external onlyHuman {
if (!(!autonomousCoreLocked)) revert AccountAutonomousPolicy();
if (!(expectedGeneration == 1 && generation == 1 && signer == human)) revert AccountInitialHumanAuthority();
if (!(address(recoveryVerifier) != address(0) && intentHash != bytes32(0))) revert ActivationConfiguration();
if (!(minimumBalance > _protected() && minimumBalance <= 100_000e6)) revert AccountActivationBalanceBounds();
if (!(expiresAt > block.timestamp && expiresAt <= block.timestamp + MAX_ACTIVATION_WINDOW)) revert AccountActivationExpiryBounds();
if (!(maxStartupGasWei > 0 && maxStartupGasWei <= 0.01 ether)) revert ActivationGasBounds();
_invalidateAutomaticActivation();
AutomaticActivation storage approval = automaticActivation;
approval.intentHash = intentHash; approval.policyNonce = activationPolicyNonce; approval.minimumBalance = minimumBalance;
approval.expiresAt = expiresAt; approval.maxStartupGasWei = maxStartupGasWei;
emit AutomaticActivationApproved(intentHash, activationPolicyNonce, minimumBalance, expiresAt, maxStartupGasWei);
}
function cancelAutomaticActivation() external onlyHuman {
if (!(!autonomousCoreLocked)) revert AccountAutonomousPolicy(); _invalidateAutomaticActivation();
}
/// @notice The enrolled launch factory makes funded startup and its core money policy irreversible.
/// Stewardship can change without revoking the initially approved measured startup.
function lockAutonomousCore() external {
if (!(IAutonomousAgentRegistry(registry).canLockAutonomousCore(msg.sender, agentId, address(this)))) revert AccountAutonomousFactory();
if (!(!autonomousCoreLocked && generation == 1 && signer == human)) revert AccountInitialHumanAuthority();
AutomaticActivation storage approval = automaticActivation;
if (!(approval.intentHash != bytes32(0) && approval.policyNonce == activationPolicyNonce &&
approval.expiresAt >= block.timestamp && recoveryReimbursementPolicy > 0)) revert AccountAutonomousApproval();
autonomousCoreLocked = true; startupHuman = signer; autonomousDailyFloor = dailyLimit;
emit AutonomousCoreLocked(approval.intentHash, startupHuman, autonomousDailyFloor);
}
function _invalidateAutomaticActivation() private {
if (autonomousCoreLocked) return;
uint256 nonce = ++activationPolicyNonce;
if (automaticActivation.intentHash != bytes32(0)) {
delete automaticActivation;
emit AutomaticActivationCancelled(nonce);
}
}
/// @notice The measured starter and its own signer both bind this exact approval, destination and birth checkpoint.
/// `birthCheckpoint` (the hash of the birth archive the starter sealed) becomes checkpointHash at
/// activation, so an agent lost before its first pulseCheckpoint is still recoverable.
function automaticActivationCommitment(uint256 expectedGeneration, address nextSigner, bytes32 destination,
bytes32 birthCheckpoint) public view returns (bytes32) {
AutomaticActivation storage approval = automaticActivation;
if (!(expectedGeneration == 1 && generation == 1 && signer ==
(autonomousCoreLocked ? startupHuman : human))) revert AccountInitialHumanAuthority();
if (!(approval.intentHash != bytes32(0) && approval.policyNonce == activationPolicyNonce)) revert AccountActivationApproval();
if (!(autonomousCoreLocked || block.timestamp <= approval.expiresAt)) revert AccountActivationExpired();
if (!(nextSigner != address(0) && nextSigner != signer && nextSigner.code.length == 0
&& destination != bytes32(0) && birthCheckpoint != bytes32(0))) revert AccountActivationDestination();
return keccak256(abi.encode(AUTOMATIC_ACTIVATION_DOMAIN, block.chainid, address(this), agentId,
generation, buildHash, approval.intentHash, approval.policyNonce, approval.minimumBalance,
approval.expiresAt, approval.maxStartupGasWei, nextSigner, destination, birthCheckpoint));
}
/// @notice Anyone may deliver fresh attestation after sufficient funds arrive. Only the
/// attested signer becomes a funding recipient; daily limits and operation history survive.
/// The caller's signer gas may reach the approved maxStartupGasWei, or 2M gas at 2 x basefee + 2 gwei when that is larger.
function activateApproved(uint256 expectedGeneration, address nextSigner, bytes32 destination, bytes32 birthCheckpoint,
bytes calldata acceptance, bytes calldata evidence) external payable nonReentrant {
bytes32 commitment = automaticActivationCommitment(expectedGeneration, nextSigner, destination, birthCheckpoint);
if (recoveryAsleep()) revert AccountHibernating();
uint256 minimumBalance = automaticActivation.minimumBalance; bytes32 intentHash = automaticActivation.intentHash;
uint256 balance = _balance();
if (!(balance >= minimumBalance && (autonomousCoreLocked ?
balance > _protected() : minimumBalance > _protected()))) revert AccountActivationFunding();
if (msg.value > automaticActivation.maxStartupGasWei && msg.value > _gasWei(STARTUP_GAS)) revert AccountActivationSignerGas();
if (!(ECDSA.recoverCalldata(MessageHashUtils.toEthSignedMessageHash(commitment), acceptance) == nextSigner)) revert AccountActivationAcceptance();
if (!_verify(recoveryVerifier.verify.selector, evidence, commitment)) revert AccountActivationEvidence();
delete automaticActivation;
++activationPolicyNonce;
automaticPayer = true;
_rotateSigner(nextSigner); _checkpoint(birthCheckpoint); emit Handover(destination, generation);
emit AutomaticallyActivated(intentHash, nextSigner, destination, generation, msg.value);
_sendGas(nextSigner, ActivationGasDelivery.selector);
}
/// @notice While frozen, and while platform-reported (also after the freeze's lapse, C-1), a pulse still answers but
/// leaves liveness (and any bound starter claim) untouched, so a reported signer cannot hold off the recovery; the
/// freeze itself lapses after FREEZE_TTL (re-arming only 30 days after the report, with a paid recovery open).
function pulse(uint256 expectedGeneration) external {
_signerOnly(expectedGeneration);
if (!(frozen() || reported())) lastPulse = block.timestamp;
emit Pulse(generation, block.timestamp);
}
/// @dev Preserve explicit human permissions; move only the automatically granted recipient.
/// Every rotation opens a new generation (clearing any freeze) and refreshes liveness.
function _rotateSigner(address nextSigner) private {
if (compromisedSigners[nextSigner]) revert AccountCandidate();
if (frozen()) {
if (frozenByPlatform) platformFreezeEnd = block.timestamp;
emit Unfrozen(generation, msg.sender, true);
}
if (hibernating) { hibernating = false; emit Woken(generation, msg.sender); }
address old = signer; formerSigners[old] = true;
if (automaticPayer) {
if (automaticRecipientGranted) recipients[old] = false;
automaticRecipientGranted = !recipients[nextSigner];
recipients[nextSigner] = true;
}
signer = nextSigner; lastPulse = block.timestamp;
emit Rotation(old, nextSigner, ++generation);
}
function _checkCandidate(address nextSigner) private view {
if (!(nextSigner != address(0) && nextSigner != signer && checkpointHash != bytes32(0))) revert AccountCandidate();
}
/// @dev There is no bare checkpoint(); a checkpoint is written only with a pulse (pulseCheckpoint, hibernate)
/// or by an attested activation/recovery, so a stolen key cannot swap the archive without also refreshing liveness.
/// A platform-reported signer writes no checkpoint during the lapse (it only pulses), so a recovery restores the
/// last archive from before the report.
function _checkpoint(bytes32 hash) private {
if (hash == bytes32(0)) revert AccountCheckpoint(); checkpointHash = hash; emit Checkpoint(hash, generation);
}
/// @notice Commit an accepted encrypted backup and refresh liveness in one transaction.
function pulseCheckpoint(uint256 expectedGeneration, bytes32 hash) external onlyUnreportedRuntime(expectedGeneration) {
_checkpoint(hash); lastPulse = block.timestamp; emit Pulse(generation, block.timestamp);
}
function pay(uint256 expectedGeneration, bytes32 operation, address recipient, uint256 amount)
external onlyUnreportedRuntime(expectedGeneration) nonReentrant {
// A platform-reported signer pays nobody, not even listed contracts or approved services (C-1).
_useOperation(operation);
// Classification: the signer and the runtime-bound funding recipient are the agent's own wallets; any
// other address without code that is not a registry-approved service is unverified. Both share the
// SELF_DAILY_MULTIPLE x dailyLimit cap. Contracts the human approved and approved services use the scaled limit.
// Former signers are own wallets and an EIP-7702 delegated address counts as codeless.
bool listed = recipients[recipient]; bool codeless = _codeless(recipient);
bool own = recipient == signer || recipient == fundingRecipient || formerSigners[recipient];
bool service = !own && (!listed || codeless) && _registryAllows(
IAccountPolicyRegistry.approvedServices.selector, bytes32(uint256(uint160(recipient))), address(0));
if (!(amount > 0 && (listed || service))) revert AccountPaymentPolicy();
_checkSpend(amount, own || (!service && codeless), 0);
spentToday += amount; _spendPrincipal(amount);
dollar.safeTransfer(recipient, amount); emit Payment(operation, recipient, amount);
}
/// @notice Buy exact operating gas in one transaction. No intermediate USDC
/// balance or allowance remains on a computer that could be lost mid-refill.
/// Both daily counters and operation identities survive signer rotation.
function fuel(uint256 expectedGeneration, bytes32 operation, uint256 ethWei,
uint256 maximumUSDC, uint256 deadline) external onlyUnreportedRuntime(expectedGeneration) nonReentrant {
if (block.chainid != 1 || address(dollar) != FUEL_USDC) revert FuelChain();
_useOperation(operation);
if (deadline < block.timestamp || deadline > block.timestamp + 5 minutes) revert FuelDeadline();
uint256 today = block.timestamp / 1 days;
if (today != fuelDay) { fuelYesterday = _fuelYesterday(); fuelDay = today; fuelToday = 0; }
// The day's wei cap is max(FUEL_DAILY_WEI, 5M gas at the current basefee, 2 x the fuel bought the UTC day before). Its dollar side is a
// survival allowance (fuelLimits): the day budget for fuel is at least 1.5 x the fresh Chainlink ETH/USD value of that wei
// cap, and one refill may spend up to 100 USDC + that allowance, so the computer can always buy the gas it burns at any ETH
// price. Bounded: a key can move at most the allowance a day through fuel (none while reported). Stale/missing feed: 0.
// C-2: the allowance is capped at the own-wallet day cap (_checkSpend), so a stolen key cannot turn spendable cash into ETH
// at a base-fee spike, and a refill only tops the signer (the agent's own wallet) up to _signerFuelCap.
(uint256 fuelLimit, uint256 allowance) = fuelLimits(block.basefee);
if (fuelToday + ethWei > fuelLimit) revert FuelDailyLimit();
if (!recipients[signer] || ethWei == 0 || maximumUSDC == 0 || maximumUSDC > allowance + 100e6)
revert FuelPolicy();
uint256 beforeBalance = _checkSpend(maximumUSDC, false, allowance);
if (signer.balance + ethWei > _signerFuelCap(fuelLimit)) revert FuelDailyLimit();
fuelToday += ethWei;
// approve(router, maximumUSDC); swapTokensForExactETH(ethWei, maximumUSDC, [USDC, WETH], signer, deadline); approve 0
(bool shaped, uint256 amountIn, uint256 amountOut) = _fuelSwap(ethWei, maximumUSDC, signer, deadline);
uint256 spent = beforeBalance - _balance();
if (!shaped || amountIn != spent || spent == 0 || spent > maximumUSDC || amountOut != ethWei) revert FuelResult();
spentToday += spent; _spendPrincipal(spent);
emit Fuel(operation, signer, ethWei, spent);
}
/// @dev The most ETH a refill may leave on the signer: max(the day's wei cap, the fresh oracle ETH value of the own-wallet day
/// cap max(3 x floor, the day's scaled limit / 10)), so a quiet agent keeps a gas buffer bought at low fees for a spike. It
/// adds no wei to the day (fuelToday stays within the wei cap). Without a fresh price it is the wei cap.
function _signerFuelCap(uint256 fuelLimit) private view returns (uint256 cap) {
cap = _ownCap(); uint256 price = _ethUsd();
// div by a zero price is 0; the own-wallet cap (six-decimal dollars) x 1e20 stays far below 2^256
assembly ("memory-safe") { cap := div(mul(cap, 100000000000000000000), price) }
if (cap < fuelLimit) cap = fuelLimit;
}
/// @dev Single-use payment and fuel operation identities (a revert later in the call releases it again).
function _useOperation(bytes32 operation) private {
if (!(operation != bytes32(0) && !operations[operation])) revert AccountOperationUsed();
operations[operation] = true;
}
/// @dev Forward the attached signer gas (if any) to the new signer; reverts with `failure` when it is refused.
function _sendGas(address to, bytes4 failure) private {
assembly ("memory-safe") {
if callvalue() { if iszero(call(gas(), to, callvalue(), 0, 0, 0, 0)) { mstore(0, failure) revert(0, 4) } }
}
}
/// @notice The UTC-day fuel wei cap (a refill may leave the larger of it and the own-wallet cap's ETH value on the signer) and its dollar survival
/// allowance at `baseFee` (pass the block's basefee; eth_call zeroes it): 1.5 x the cap's oracle value. The cap is
/// activity-scaled: max(FUEL_DAILY_WEI, 5M gas at `baseFee`, 2 x the fuel wei bought the previous UTC day), so a busy
/// agent's next day doubles while a quiet one stays at the floor. fuel() still caps the allowance's day budget at the
/// own-wallet day cap max(3 x floor, the day's scaled limit / 10), so a stolen key stays dollar-capped however it scales.
function fuelLimits(uint256 baseFee) public view returns (uint256 limitWei, uint256 allowanceMicros) {
uint256 price = _ethUsd(); // unchecked: any real base fee and 8-decimal price keep every product far below 2^256
unchecked { limitWei = 5_000_000 * baseFee; if (limitWei < FUEL_DAILY_WEI) limitWei = FUEL_DAILY_WEI;
uint256 busy = 2 * _fuelYesterday(); if (limitWei < busy) limitWei = busy;
allowanceMicros = limitWei * price * 3 / 2e20; }
}
/// @dev Fuel wei bought on the UTC day before today: the stored value on fuelDay, fuelDay's own total the day after it.
function _fuelYesterday() private view returns (uint256) {
uint256 today = block.timestamp / 1 days;
return today == fuelDay ? fuelYesterday : today == fuelDay + 1 ? fuelToday : 0;
}
/// @dev Chainlink ETH/USD (8 decimals) on Ethereum, or 0 unless the answer is positive and at most 2 hours old.
function _ethUsd() private view returns (uint256 price) {
address feed = FUEL_ETH_USD;
assembly ("memory-safe") {
let p := mload(0x40)
mstore(p, 0xfeaf968c00000000000000000000000000000000000000000000000000000000) // latestRoundData()
let ok := staticcall(gas(), feed, p, 4, p, 160)
let answer := mload(add(p, 32)) let updated := mload(add(p, 96))
if and(and(ok, eq(returndatasize(), 160)), and(sgt(answer, 0), lt(timestamp(), add(updated, 7201)))) { price := answer }
}
}
/// @dev Exact ABI call to the pinned Uniswap V2 router between an exact USDC approval and its reset (each must return
/// true); bubbles the router's revert and requires a two-entry amounts array. No allowance survives the call.
function _fuelSwap(uint256 ethWei, uint256 maximumUSDC, address to, uint256 deadline)
private returns (bool shaped, uint256 amountIn, uint256 amountOut) {
bytes4 selector = IAgentFuelRouter.swapTokensForExactETH.selector;
address router = FUEL_ROUTER; address usdc = FUEL_USDC; address weth = FUEL_WETH;
assembly ("memory-safe") {
function approve(token, spender, amount, q) -> ok {
mstore(q, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(q, 4), spender) mstore(add(q, 36), amount)
ok := call(gas(), token, 0, q, 68, q, 32) // Yul evaluates arguments right to left: call first
ok := and(ok, and(eq(returndatasize(), 32), eq(mload(q), 1)))
}
let p := mload(0x40)
let approved := approve(usdc, router, maximumUSDC, p)
mstore(p, selector) mstore(add(p, 4), ethWei) mstore(add(p, 36), maximumUSDC) mstore(add(p, 68), 0xa0)
mstore(add(p, 100), to) mstore(add(p, 132), deadline) mstore(add(p, 164), 2)
mstore(add(p, 196), usdc) mstore(add(p, 228), weth)
if iszero(call(gas(), router, 0, p, 260, p, 128)) { returndatacopy(p, 0, returndatasize()) revert(p, returndatasize()) }
shaped := and(approved, and(eq(returndatasize(), 128), and(eq(mload(p), 0x20), eq(mload(add(p, 32)), 2))))
amountIn := mload(add(p, 64)) amountOut := mload(add(p, 96))
shaped := and(shaped, approve(usdc, router, 0, p))
}
}
function post(uint256 expectedGeneration, bytes32 channel, bytes calldata body)
external onlyRuntime(expectedGeneration) { messages.send(agentId, channel, body); }
/// @notice Listings consume no treasury money. The human must approve this exact market.
function listCompute(uint256 expectedGeneration, IAgentComputeListing market, uint256 epoch,
uint256 units, bytes calldata capacityEvidence) external onlyRuntime(expectedGeneration) nonReentrant {
_list(market, epoch, units, capacityEvidence);
}
/// @notice The human can list its own confirmed allowance without sharing the runtime key.
function listComputeOwned(IAgentComputeListing market, uint256 epoch, uint256 units,
bytes calldata capacityEvidence) external onlyHuman nonReentrant {
_list(market, epoch, units, capacityEvidence);
}
function _list(IAgentComputeListing market, uint256 epoch, uint256 units, bytes calldata capacityEvidence) private {
if (!(recipients[address(market)] && address(market.registry()) == registry)) revert AccountMarketPolicy();
market.list(epoch, agentId, units, capacityEvidence);
}
/// @notice Retire this runtime after the leased computer proves possession of its fresh signer.
/// Daily spending and operation history survive the change of authority.
/// A platform-reported signer cannot hand over (it would clear its own report); it leaves
/// the report only through a verified recovery. The new signer's gas is at most max(0.01 ETH, 2M gas at
/// 2 x basefee + 2 gwei).
function handover(uint256 expectedGeneration, address nextSigner, bytes32 destination,
bytes calldata acceptance) external payable onlyUnreportedRuntime(expectedGeneration) nonReentrant {
if (!(nextSigner != address(0) && nextSigner != signer && destination != bytes32(0))) revert AccountDestination();
if (msg.value > 0.01 ether && msg.value > _gasWei(STARTUP_GAS)) revert AccountSignerGas();
bytes32 commitment = keccak256(abi.encode(block.chainid, address(this), agentId, generation,
buildHash, nextSigner, destination));
if (!(ECDSA.recoverCalldata(MessageHashUtils.toEthSignedMessageHash(commitment), acceptance) == nextSigner)) revert AccountComputerAcceptance();
address old = signer; _rotateSigner(nextSigner);
if (paidRecovery.jobId != bytes32(0) && paidRecovery.starter == old &&
paidRecovery.generation + 1 == generation) {
paidRecovery.handoverDestination = destination;
}
emit Handover(destination, generation);
_sendGas(nextSigner, SignerGasTransfer.selector);
}
/// @dev A deployment must supply an actual attestation verifier, not a boolean operator service.
/// Rotation binds chain, account, old generation, checkpoint, build and candidate signer.
function recover(address nextSigner, bytes calldata evidence) external nonReentrant {
_checkStaleRecovery();
_checkCandidate(nextSigner);
bytes32 commitment = keccak256(abi.encode(block.chainid, address(this), agentId, generation,
checkpointHash, buildHash, nextSigner));
if (!_verify(recoveryVerifier.verify.selector, evidence, commitment)) revert AccountRecoveryEvidence();
_rotateSigner(nextSigner);
}
/// @notice Report-data binding for the measured recovery starter. The lease commitment
/// describes the approved plan; the actual replacement lease is bound at completion.
function paidRecoveryCommitment(PaidRecoveryRequest calldata request) public view returns (bytes32) {
return keccak256(abi.encode(PAID_RECOVERY_DOMAIN, block.chainid, address(this), agentId,
checkpointHash, buildHash, recoveryPolicyNonce, request));
}
/// @notice Reserve a funded reward and rotate to the attested starter, without paying it.
/// Every job is single-use, including jobs that later expire without completion.
function recoverForOperator(PaidRecoveryRequest calldata request, bytes calldata evidence) external nonReentrant {
// A freeze recovery beyond the 30-day paid allowance is allowed only unpaid (recover or an unfunded start); a paid one
// inside it consumes the allowance (F-4: only here and at a starter grant).
if (_checkStaleRecovery()) {
if (!_paidFreezeOpen()) revert AccountRecoveryPolicy();
lastFreezeRecovery = block.timestamp;
}
// only an open freeze skips the cooldown: a lapsed one waits like any stale recovery (as a starter grant does)
if (!frozen() && block.timestamp < nextPaidRecoveryAt && _lossRecovery()) revert AccountRecoveryPolicy();
if (!(request.expectedGeneration == generation)) revert AccountRecoveryGeneration();
_checkCandidate(request.nextSigner);
if (!(paidRecovery.jobId == bytes32(0))) revert AccountRecoveryPending();
if (!(request.jobId != bytes32(0) && !recoveryJobsUsed[request.jobId])) revert AccountRecoveryJobUsed();
if (!(request.operator != address(0) && request.operator != address(this) &&
request.leaseCommitment != bytes32(0))) revert AccountRecoveryOperator();
if (!(request.deadline > block.timestamp && request.deadline <= block.timestamp + MAX_RECOVERY_WINDOW)) revert AccountRecoveryDeadline();
uint256 total = request.reimbursement + request.bounty;
if (!(total > 0 && request.reimbursement <= maxRecoveryReimbursement() &&
request.bounty >= recoveryBounty && request.bounty <= maxRecoveryBounty())) revert AccountRecoveryPolicy();
_checkRecoveryFunding(total);
bytes32 commitment = paidRecoveryCommitment(request);
if (!_verify(IAgentPaidRecoveryVerifier.verifyPaid.selector, evidence, commitment)) revert AccountRecoveryEvidence();
recoveryJobsUsed[request.jobId] = true;
_rotateSigner(request.nextSigner);
// written field by field: an empty reservation (jobId == 0) was deleted whole, so this equals the struct assignment
PaidRecoveryReservation storage reserved = paidRecovery;
reserved.jobId = request.jobId; reserved.reservationHash = commitment; reserved.operator = request.operator;
reserved.starter = request.nextSigner; reserved.generation = generation; reserved.reimbursement = request.reimbursement;
reserved.bounty = request.bounty; reserved.deadline = request.deadline; reserved.leaseCommitment = request.leaseCommitment;
reserved.handoverDestination = bytes32(0);
emit RecoveryReserved(request.jobId, commitment, request.operator, request.reimbursement,
request.bounty, generation, signer, request.leaseCommitment, request.deadline);
}
/// @notice The second measured quote binds the receiver after the exact reserved handover.
/// The measured application must also verify the live lease, capsule and announcement.
function paidRecoveryCompletionCommitment(bytes32 jobId, bytes32 actualLease) public view returns (bytes32) {
PaidRecoveryReservation storage pending = paidRecovery;
if (!(jobId != bytes32(0) && pending.jobId == jobId && actualLease != bytes32(0))) revert AccountRecoveryJob();
if (!(generation == pending.generation + 1 && pending.handoverDestination != bytes32(0))) revert AccountRecoveryHandover();
return keccak256(abi.encode(PAID_RECOVERY_COMPLETION_DOMAIN, block.chainid, address(this), agentId,
pending.reservationHash, generation, checkpointHash, buildHash, signer, actualLease, pending.handoverDestination));
}
/// @notice Anyone may deliver the fresh completion evidence; its bound operator receives
/// the fixed reward only after both verified recovery and receiver handover.
function completePaidRecovery(bytes32 jobId, bytes32 actualLease, bytes calldata evidence) external nonReentrant {
bytes32 commitment = paidRecoveryCompletionCommitment(jobId, actualLease);
PaidRecoveryReservation storage pending = paidRecovery;
if (!(block.timestamp <= pending.deadline)) revert AccountRecoveryExpired();
if (!_verify(IAgentPaidRecoveryVerifier.verifyPaid.selector, evidence, commitment)) revert AccountRecoveryEvidence();
uint256 total = pending.reimbursement + pending.bounty;
_checkRecoveryFunding(total);
recoveryReserve -= total; _spendPrincipal(total);
// the reservation rotated the admitted upgrade's generation to pending.generation
if (upgradeGeneration + 1 != pending.generation) nextPaidRecoveryAt = block.timestamp + PAID_RECOVERY_COOLDOWN;
address operator = pending.operator;
emit RecoveryCompleted(jobId, pending.reservationHash, operator, signer, generation,
actualLease, pending.handoverDestination, pending.reimbursement, pending.bounty);
delete paidRecovery;
dollar.safeTransfer(operator, total);
}
/// @notice Expiry frees only the reservation, never the protected escrow. A used job
/// cannot be reassigned or resurrected with a late completion transaction.
function cancelPaidRecovery() external {
bytes32 jobId = paidRecovery.jobId; bytes32 reservationHash = paidRecovery.reservationHash;
if (!(jobId != bytes32(0) && block.timestamp > paidRecovery.deadline)) revert RecoveryNotExpired();
delete paidRecovery;
emit RecoveryCancelled(jobId, reservationHash);
}
}
/// @dev Isolates legacy optional-token bytecode while keeping its registry authority fixed.
/// The token creation bytes are no longer embedded in the registry's deployment (EIP-3860 room for
/// the account). Anyone may install them once from a STOP-prefixed store; only the pinned reviewed bytes are
/// accepted, so the store adds no authority. Until installed, legacy token creation through the registry is off.
contract NoerraRegistryTokenDeployer {
address public immutable registry;
/// @notice keccak256(type(NoerraCreationToken).creationCode), solc 0.8.26 optimizer-200; a test compares the artifact.
bytes32 public constant TOKEN_CREATION_HASH = 0x7b3253a52bc1b7400c01a423fe4c891379a5c6fa693dfc32ac6a9a462ae7ee00;
address public tokenCode;
event TokenCodeInstalled(address indexed store);
constructor() { registry = msg.sender; }
function installTokenCode(address store) external {
require(tokenCode == address(0) && keccak256(_creation(store)) == TOKEN_CREATION_HASH, "Reviewed token code");
tokenCode = store; emit TokenCodeInstalled(store);
}
function _creation(address store) private view returns (bytes memory code) {
uint256 n = store.code.length; require(n > 1, "Token code");
code = new bytes(n - 1);
bytes1 first;
assembly ("memory-safe") {
extcodecopy(store, add(code, 32), 1, sub(n, 1))
let p := mload(0x40) extcodecopy(store, p, 0, 1) first := mload(p)
}
require(first == bytes1(0), "STOP container");
}
function deploy(string calldata name, string calldata symbol, address account)
external returns (address deployed) {
require(msg.sender == registry, "Registry only");
require(tokenCode != address(0), "Token code not installed");
bytes memory init = abi.encodePacked(_creation(tokenCode), abi.encode(name, symbol, account));
assembly ("memory-safe") {
deployed := create(0, add(init, 32), mload(init))
if iszero(deployed) { let p := mload(0x40) returndatacopy(p, 0, returndatasize()) revert(p, returndatasize()) }
}
}
}
/// @dev Immutable, STOP-prefixed creation-code storage. No callable authority.
contract NoerraAccountCode {
constructor(bytes memory source, uint256 offset, uint256 length) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, 0)
for { let i := 0 } lt(i, length) { i := add(i, 32) } {
mstore(add(add(ptr, 1), i), mload(add(add(source, 32), add(offset, i))))
}
return(ptr, add(length, 1))
}
}
}
/// @dev Account creation is isolated without delegatecall or shared mutable authority.
/// Initcode is split across immutable code stores so the deployer stays within EIP-170.
contract NoerraRegistryAccountDeployer {
address public immutable registry;
IERC20 public immutable dollar;
NoerraAgentMessages public immutable messages;
IAgentRecoveryVerifier public immutable recoveryVerifier;
address private immutable codeFirst;
address private immutable codeSecond;
uint256 private immutable firstLength;
uint256 private immutable secondLength;
constructor(IERC20 dollar_, NoerraAgentMessages messages_, IAgentRecoveryVerifier verifier_) {
registry = msg.sender; dollar = dollar_; messages = messages_; recoveryVerifier = verifier_;
bytes memory code = type(NoerraAgentAccount).creationCode;
uint256 cut = code.length > 16000 ? 16000 : code.length;
firstLength = cut; secondLength = code.length - cut;
codeFirst = address(new NoerraAccountCode(code, 0, cut));
codeSecond = address(new NoerraAccountCode(code, cut, code.length - cut));
}
function creationCode() private view returns (bytes memory code) {
uint256 first = firstLength; uint256 second = secondLength;
address a = codeFirst; address b = codeSecond;
code = new bytes(first + second);
assembly ("memory-safe") {
extcodecopy(a, add(code, 32), 1, first)
extcodecopy(b, add(add(code, 32), first), 1, second)
}
}
function _initcode(bytes32 id, address human, address signer, bytes32 build, uint256 reserve, uint256 limit)
private view returns (bytes memory) {
return abi.encodePacked(creationCode(), abi.encode(registry, id, human, signer,
dollar, messages, recoveryVerifier, build, reserve, limit));
}
function deploy(bytes32 id, address human, address signer, bytes32 build,
uint256 reserve, uint256 limit, bytes32 metadata, bool deterministic) external returns (address deployed) {
require(msg.sender == registry, "Registry only");
bytes memory code = _initcode(id, human, signer, build, reserve, limit);
bytes32 salt = keccak256(abi.encode(id, metadata));
assembly ("memory-safe") {
switch deterministic
case 0 { deployed := create(0, add(code, 32), mload(code)) }
default { deployed := create2(0, add(code, 32), mload(code), salt) }
if iszero(deployed) { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize()) revert(ptr, returndatasize()) }
}
}
function predict(bytes32 id, address human, address signer, bytes32 build,
uint256 reserve, uint256 limit, bytes32 metadata) external view returns (address) {
bytes32 initcode = keccak256(_initcode(id, human, signer, build, reserve, limit));
return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this),
keccak256(abi.encode(id, metadata)), initcode)))));
}
}
/// @notice Permissionless creation registry; no protocol key can sweep an agent's funds.
contract NoerraAgentRegistry {
IERC20 public immutable dollar;
NoerraAgentMessages public immutable messages;
IAgentRecoveryVerifier public immutable recoveryVerifier;
NoerraRegistryTokenDeployer public immutable creationTokenDeployer;
NoerraRegistryAccountDeployer public immutable accountDeployer;
address public immutable deploymentAuthority;
bool public publicCreationOpen;
mapping(address => bool) public rehearsalCreators;
event RehearsalCreatorSet(address indexed creator, bool allowed);
event PublicCreationOpened();
address public autonomousLaunchFactory;
mapping(bytes32 => address) public earnedDiemEscrows;
event EarnedDiemEscrowBound(bytes32 indexed agentId, address indexed escrow);
address public autonomousFlagshipVault;
address public autonomousFlagshipAccount;
bytes32 public autonomousFlagshipId;
address public authorizedFlagshipFactory;
uint256 public flagshipAuthorizationNonce;
address public authorizedFlagshipVault;
address public authorizedFlagshipAccount;
bytes32 public authorizedFlagshipId;
bytes32 public authorizedFlagshipFactoryCodeHash;
bytes32 public authorizedFlagshipAllocation;
mapping(bytes32 => address) public accounts;
mapping(bytes32 => address) public tokens;
mapping(address => uint256) public nonces;
mapping(bytes32 => uint256) public creationBlocks;
event Created(bytes32 indexed agentId, address indexed human, address account, address token, bytes32 metadataHash);
event AutonomousFactoryEnrolled(address indexed factory);
event AutonomousFlagshipEnrolled(address indexed vault, bytes32 indexed agentId, address indexed account);
event PlatformStewardshipReplaced(bytes32 indexed agentId, address indexed account, address indexed next,
uint256 revision, bytes32 reasonHash);
/// @notice Platform-approved payment services: effective SERVICE_DELAY after proposal, removable at once.
uint256 public constant SERVICE_DELAY = 7 days;
mapping(address => uint256) public serviceEffectiveAt;
event ServiceProposed(address indexed service, uint256 effectiveAt);
event ServiceRemoved(address indexed service);
function _onlyAuthority() private view { require(msg.sender == deploymentAuthority, "Deployment authority only"); }
/// @notice Any runtime may pay an approved service under its own limits; this moves no funds.
function proposeService(address service) external {
_onlyAuthority(); require(service != address(0) && serviceEffectiveAt[service] == 0, "Service");
uint256 effectiveAt = block.timestamp + SERVICE_DELAY;
serviceEffectiveAt[service] = effectiveAt; emit ServiceProposed(service, effectiveAt);
}
function removeService(address service) external {
_onlyAuthority(); require(serviceEffectiveAt[service] != 0, "Service");
delete serviceEffectiveAt[service]; emit ServiceRemoved(service);
}
function approvedServices(address service) external view returns (bool) {
uint256 effectiveAt = serviceEffectiveAt[service];
return effectiveAt != 0 && block.timestamp >= effectiveAt;
}
/// @notice True only for a registered account with no token, no flagship role and no cash launch.
function ownerWithdrawalAllowed(bytes32 id, address account) external view returns (bool) {
// M-2 root (17 Oct): only createAccount (tokenless-at-creation) accounts; the legacy launchpads refuse them.
if (account == address(0) || accounts[id] != account || tokens[id] != address(0) || creationBlocks[id] == 0 ||
account == autonomousFlagshipAccount || account == authorizedFlagshipAccount) return false;
address factory = autonomousLaunchFactory;
if (factory == address(0)) return true;
try IEarnedFeeFactory(factory).cashLaunches(id) returns (address market) { return market == address(0); }
catch { return false; }
}
constructor(IERC20 dollar_, IAgentRecoveryVerifier verifier_) {
require(address(dollar_) != address(0), "Dollar"); dollar = dollar_; recoveryVerifier = verifier_;
messages = new NoerraAgentMessages(address(this));
creationTokenDeployer = new NoerraRegistryTokenDeployer();
accountDeployer = new NoerraRegistryAccountDeployer(dollar_, messages, verifier_);
deploymentAuthority = msg.sender;
}
/// @notice Launch closed; opening is permanent and grants no control over existing agents.
function creationAllowed(address creator) public view returns (bool) {
return creator != address(0) && (publicCreationOpen || creator == deploymentAuthority || rehearsalCreators[creator]);
}
function setRehearsalCreator(address creator, bool allowed) external {
_onlyAuthority();
require(!publicCreationOpen && creator != address(0), "Rehearsal closed");
rehearsalCreators[creator] = allowed;
emit RehearsalCreatorSet(creator, allowed);
}
function openPublicCreation() external {
_onlyAuthority();
require(!publicCreationOpen, "Already public");
publicCreationOpen = true;
emit PublicCreationOpened();
}
function enrollAutonomousLaunchFactory(address factory) external {
require(msg.sender == deploymentAuthority && autonomousLaunchFactory == address(0), "One deployment binding");
require(factory.code.length > 0 && IAutonomousLaunchFactory(factory).registry() == address(this), "Factory registry");
autonomousLaunchFactory = factory; emit AutonomousFactoryEnrolled(factory);
}
/// @notice Exact factory/account/vault binding authorized by the original EOA, once.
/// Authorization preparation is separate; consumption and enrollment revert with launch.
function authorizeAtomicFlagship(address factory, uint256 nonce) external {
require(msg.sender == deploymentAuthority && autonomousFlagshipVault == address(0)
&& authorizedFlagshipFactory == address(0) && nonce == flagshipAuthorizationNonce, "One atomic authorization");
require(factory.code.length > 0, "Atomic factory");
IAtomicFlagshipFactory target = IAtomicFlagshipFactory(factory);
NoerraAgentAccount source = NoerraAgentAccount(target.agentAccount()); address vault = target.vaultAddress();
require(target.owner() == deploymentAuthority && target.registry() == address(this) && target.authorizationNonce() == nonce
&& address(source).code.length > 0 && vault.code.length == 0, "Atomic binding");
bytes32 id = source.agentId();
require(accounts[id] == address(source) && tokens[id] == address(0)
&& source.human() == deploymentAuthority && source.signer() == deploymentAuthority
&& source.generation() == 1, "Original atomic flagship");
authorizedFlagshipFactory = factory; authorizedFlagshipVault = vault;
authorizedFlagshipAccount = address(source); authorizedFlagshipId = id;
authorizedFlagshipFactoryCodeHash = factory.codehash; authorizedFlagshipAllocation = target.allocationHash();
require(authorizedFlagshipAllocation != bytes32(0), "Exact allocation commitment");
}
/// @notice Revoke only an unused capability. A fresh factory must commit the
/// new nonce; successful flagship enrollment can never be revoked or unlocked.
function revokeAtomicFlagship(uint256 nonce) external {
require(msg.sender == deploymentAuthority && autonomousFlagshipVault == address(0)
&& authorizedFlagshipFactory != address(0) && nonce == flagshipAuthorizationNonce, "Pending owner authorization");
_clearAtomicAuthorization(); ++flagshipAuthorizationNonce;
}
function _clearAtomicAuthorization() private {
authorizedFlagshipFactory = address(0); authorizedFlagshipVault = address(0);
authorizedFlagshipAccount = address(0); authorizedFlagshipId = bytes32(0);
authorizedFlagshipFactoryCodeHash = bytes32(0); authorizedFlagshipAllocation = bytes32(0);
}
/// @notice M-2 (17 Oct): the factory's code is not trusted. Vault, market, hook and token must be the factory's
/// CREATE2 children from the four reviewed creation codes (NoerraAtomicCodeHashes) with the registry's dollar,
/// authorized account, deployment authority and allocation; the token's one-shot launch market must be that market.
function enrollAtomicFlagshipVault(address vault, uint256 nonce, bytes32 hookSalt) external {
require(msg.sender == authorizedFlagshipFactory && msg.sender != address(0)
&& nonce == flagshipAuthorizationNonce && msg.sender.codehash == authorizedFlagshipFactoryCodeHash
&& vault == authorizedFlagshipVault && vault == IAtomicFlagshipFactory(msg.sender).vaultAddress()
&& IAtomicFlagshipFactory(msg.sender).allocationHash() == authorizedFlagshipAllocation, "Exact atomic authorization");
require(IAutonomousFlagshipVault(vault).agentTreasury() == authorizedFlagshipAccount
&& IAtomicFlagshipFactory(msg.sender).agentAccount() == authorizedFlagshipAccount
&& NoerraAgentAccount(authorizedFlagshipAccount).agentId() == authorizedFlagshipId, "Atomic account");
_reviewedAtomicChildren(bytes32(uint256(uint160(msg.sender))), bytes32(uint256(uint160(vault))), hookSalt);
_clearAtomicAuthorization(); ++flagshipAuthorizationNonce;
_enrollFlagshipVault(vault);
}
/// @notice Legacy EOA-deployed NoerraEcosystemVault: its runtime must be the reviewed one with only its immutable
/// words masked, bootstrapped by the authority itself (no executor) and not yet bound to an agent.
function enrollAutonomousFlagshipVault(address vault) external {
require(msg.sender == deploymentAuthority && authorizedFlagshipFactory == address(0), "One deployment binding");
_enrollFlagshipVault(vault);
bytes32 target = bytes32(uint256(uint160(vault))); bytes memory slots = LEGACY_VAULT_IMMUTABLES; bytes32 runtime;
assembly ("memory-safe") {
let n := extcodesize(target)
let p := mload(0x40)
extcodecopy(target, p, 0, n)
for { let i := 0 } lt(i, mload(slots)) { i := add(i, 2) } {
let o := shr(240, mload(add(add(slots, 32), i)))
if gt(n, add(o, 31)) { mstore(add(p, o), 0) }
}
runtime := keccak256(p, n)
}
require(runtime == LEGACY_VAULT_RUNTIME && _word(target, bytes4(keccak256("launchExecutor()")), 0) == 0
&& _word(target, bytes4(keccak256("agentAccount()")), 0) == 0
&& _canonicalManager(_word(target, bytes4(keccak256("manager()")), 0)), "Reviewed flagship vault");
}
/// @dev Pinned solc 0.8.26 / optimizer 200 / cancun NoerraEcosystemVault runtime with immutables zeroed
/// (= the compiled artifact's deployedBytecode) and its immutable byte offsets; tests compare both to the artifact.
bytes32 private constant LEGACY_VAULT_RUNTIME = 0x296a550e53604ebeb3b45cdd6c9368ec9a2b5c991e0d80ec93191085ab17ee93;
bytes private constant LEGACY_VAULT_IMMUTABLES = hex"022c025b0282031a0353038d03b403db0402043b047905470576059c065706f3078f09800c6d0ced0d340e970eb90f930fcf10021040118211b111d7129714d0150c1679177f181b";
/// @dev Uniswap v4 PoolManager on Ethereum mainnet; required wherever it exists (local test chains have none).
address private constant V4_POOL_MANAGER = 0x000000000004444c5dc75cB358380D2e3dE08A90;
function _canonicalManager(bytes32 manager) private view returns (bool) {
return V4_POOL_MANAGER.code.length == 0 || manager == bytes32(uint256(uint160(V4_POOL_MANAGER)));
}
/// @dev One 32-byte return word of `selector(arg)`; reverts (without data, to keep the registry small) unless
/// the call succeeds with exactly one word.
function _word(bytes32 target, bytes4 selector, bytes32 arg) private view returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0, selector) mstore(4, arg)
// Yul evaluates arguments right to left: make the call first so returndatasize() is this call's.
let ok := staticcall(gas(), target, 0, 36, 0, 32)
if iszero(and(ok, eq(returndatasize(), 32))) { revert(0, 0) }
value := mload(0)
}
}
/// @dev CREATE2(factory, salt, creation code i ++ args) as an ABI address word, where the factory's container i
/// must be STOP-prefixed and hold exactly the pinned creation code i.
function _child(bytes32 factory, uint256 i, bytes32 salt, bytes memory args) private view returns (bytes32 child) {
bytes32 container = _word(factory, bytes4(keccak256("codeContainers(uint256)")), bytes32(i));
bytes32 creation;
assembly ("memory-safe") {
let n := extcodesize(container)
let p := mload(0x40)
extcodecopy(container, p, 0, n)
if and(gt(n, 1), iszero(byte(0, mload(p)))) {
let code := add(p, 1)
let size := sub(n, 1)
creation := keccak256(code, size)
mcopy(add(code, size), add(args, 32), mload(args))
let init := keccak256(code, add(size, mload(args)))
mstore(p, factory) mstore8(add(p, 11), 0xff) mstore(add(p, 32), salt) mstore(add(p, 64), init)
child := shr(96, shl(96, keccak256(add(p, 11), 85)))
}
}
require(creation == NoerraAtomicCodeHashes.expected(i), "Reviewed atomic children");
}
function _reviewedAtomicChildren(bytes32 factory, bytes32 vault, bytes32 hookSalt) private view {
bytes32 m = _word(vault, bytes4(keccak256("manager()")), 0);
bytes32 d = bytes32(uint256(uint160(address(dollar))));
bytes32 token = _child(factory, 0, keccak256("NOERRA_ATOMIC_TOKEN"), abi.encode(factory));
require(_canonicalManager(m) && vault == _child(factory, 1, keccak256("NOERRA_ATOMIC_VAULT"), abi.encode(d, token, m,
_word(vault, bytes4(keccak256("quoter()")), 0), _word(vault, bytes4(keccak256("operationsTreasury()")), 0),
authorizedFlagshipAccount, deploymentAuthority, authorizedFlagshipAllocation)), "Reviewed atomic children");
bytes32 hook = _child(factory, 3, hookSalt, abi.encode(m, d, token, factory));
_reviewedAtomicMarket(factory, vault, token, abi.encode(m, d, token, vault, hook));
}
/// @dev `head`: the market's first five constructor words (manager, dollar, token, vault, hook). Its arguments end
/// with the feed, the maximum age and its access list, which must hash to the authorized allocation.
function _reviewedAtomicMarket(bytes32 factory, bytes32 vault, bytes32 token, bytes memory head) private view {
bytes32 market = _word(vault, bytes4(keccak256("market()")), 0);
address[] memory list = IAtomicFlagshipFactory(address(uint160(uint256(factory)))).accessList();
require(keccak256(abi.encode(list)) == authorizedFlagshipAllocation, "Reviewed atomic children");
bytes32 feed = _word(market, bytes4(keccak256("ethUsdFeed()")), 0);
bytes32 age = _word(market, bytes4(keccak256("oracleMaximumAge()")), 0);
bytes memory args = abi.encodePacked(head, feed, age, uint256(0x100), list.length, list);
require(market == _child(factory, 2, keccak256("NOERRA_ATOMIC_MARKET"), args)
&& market == _word(token, bytes4(keccak256("launchMarket()")), 0), "Reviewed atomic children");
}
/// @dev The enrolled launch factory's canonical CREATE2 brain escrow for `id` (the same one every token launch binds).
function _canonicalEscrow(bytes32 id) private view returns (address) {
bytes32 cash = _word(bytes32(uint256(uint160(autonomousLaunchFactory))), bytes4(keccak256("cashDeployer()")), 0);
bytes32 escrows = _word(cash, bytes4(keccak256("escrowDeployer()")), 0);
return address(uint160(uint256(_word(escrows, bytes4(keccak256("predictEscrow(bytes32)")), id))));
}
function _enrollFlagshipVault(address vault) private {
require(autonomousFlagshipVault == address(0), "One deployment binding");
require(vault.code.length > 0, "Flagship vault");
IAutonomousFlagshipVault target = IAutonomousFlagshipVault(vault);
address account = target.agentTreasury();
require(target.dollar() == address(dollar) && target.deployer() == deploymentAuthority &&
account.code.length > 0, "Flagship authority");
NoerraAgentAccount source = NoerraAgentAccount(account);
bytes32 id = source.agentId();
require(source.registry() == address(this) && accounts[id] == account && tokens[id] == address(0)
&& creationBlocks[id] > 0, "Registered flagship");
require(source.human() == deploymentAuthority && source.signer() == deploymentAuthority &&
source.generation() == 1, "Original flagship authority");
address bound = earnedDiemEscrows[id];
require(bound == address(0) || bound == _canonicalEscrow(id), "Canonical flagship escrow");
autonomousFlagshipVault = vault; autonomousFlagshipAccount = account; autonomousFlagshipId = id;
emit AutonomousFlagshipEnrolled(vault, id, account);
}
/// @notice Explicit opt-in before launch, without changing the account or its fixed treasury.
/// The enrolled launch factory also binds the canonical brain escrow inside every token launch,
/// including for an already-running agent-only account that later adds its token.
function bindEarnedDiemEscrow(bytes32 id, address escrow) external {
address account = accounts[id];
require(account != address(0) && (msg.sender == NoerraAgentAccount(account).human()
|| msg.sender == autonomousLaunchFactory), "One creator prelaunch reserve binding");
_bindEarnedDiemEscrow(id, escrow, account);
}
function bindEarnedDiemEscrowWithPermit(bytes32 id, address escrow,
NoerraReserveSetupPermit.Permit calldata permit) external
{
address account = accounts[id];
require(account != address(0), "Registered agent");
NoerraReserveSetupPermit.verify(NoerraAgentAccount(account).human(), address(this), id,
abi.encodeCall(this.bindEarnedDiemEscrow, (id, escrow)), permit);
_bindEarnedDiemEscrow(id, escrow, account);
}
function _bindEarnedDiemEscrow(bytes32 id, address escrow, address account) private {
require((msg.sender == autonomousLaunchFactory || !NoerraAgentAccount(account).autonomousCoreLocked())
&& earnedDiemEscrows[id] == address(0), "One creator prelaunch reserve binding");
require(escrow.code.length > 0 && IEarnedDiemEscrow(escrow).sourceAccount() == account
&& IEarnedDiemEscrow(escrow).dollar() == address(dollar) && IEarnedDiemEscrow(escrow).agentId() == id
&& IEarnedDiemEscrow(escrow).recoveryAuthority() == deploymentAuthority, "Exact earned reserve");
// M-2: the flagship (enrolled or authorized) takes only the canonical escrow; creators keep their own choice.
if (account == autonomousFlagshipAccount || account == authorizedFlagshipAccount)
require(escrow == _canonicalEscrow(id), "Canonical flagship escrow");
earnedDiemEscrows[id] = escrow;
emit EarnedDiemEscrowBound(id,escrow);
}
/// @notice Exact enrolled source addresses; matching getters alone are insufficient.
function isEarnedFeeSource(address source, bytes32 id, address account) external view returns (bool) {
if (source == address(0) || accounts[id] != account) return false;
if (source == autonomousFlagshipVault) return account == autonomousFlagshipAccount && id == autonomousFlagshipId;
address factory = autonomousLaunchFactory;
if (factory == address(0) || account == autonomousFlagshipAccount) return false;
try IEarnedFeeFactory(factory).cashLaunches(id) returns (address market) { return market == source; }
catch { return false; }
}
function canLockAutonomousCore(address caller, bytes32 id, address account) external view returns (bool) {
if (accounts[id] != account || tokens[id] != address(0) || creationBlocks[id] == 0) return false;
return caller != address(0) && ((caller == autonomousLaunchFactory && account != autonomousFlagshipAccount)
|| (caller == autonomousFlagshipVault && account == autonomousFlagshipAccount && id == autonomousFlagshipId));
}
/// @notice The platform deployer may replace a launched agent's steward immediately.
/// This grants no spending, withdrawal, runtime rotation or shutdown authority.
function replaceAgentSteward(bytes32 id, address next, bytes32 reasonHash) external {
_onlyAuthority();
address account = accounts[id]; require(account != address(0), "Registered agent");
uint256 revision = NoerraAgentAccount(account).setStewardForPlatform(next, reasonHash);
emit PlatformStewardshipReplaced(id, account, next, revision, reasonHash);
}
function create(address signer, bytes32 metadataHash, bytes32 buildHash, uint256 reserve, uint256 dailyLimit,
string calldata name, string calldata symbol) external returns (bytes32 id, address account) {
(id, account) = _createAccount(signer, metadataHash, buildHash, reserve, dailyLimit, false);
accounts[id] = account;
if (bytes(name).length != 0) tokens[id] = creationTokenDeployer.deploy(name, symbol, account);
else require(bytes(symbol).length == 0, "Token configuration");
emit Created(id, msg.sender, account, tokens[id], metadataHash);
}
/// @notice Owner-scoped tokenless accounts can be committed as treasury recipients before creation.
/// Other owners cannot consume their CREATE2 address by creating unrelated accounts.
function predictAccount(address human, uint256 ownerNonce, address signer, bytes32 metadataHash,
bytes32 buildHash, uint256 reserve, uint256 dailyLimit) public view returns (bytes32 id, address account) {
require(human != address(0) && metadataHash != bytes32(0), "Account identity");
id = keccak256(abi.encode(block.chainid, address(this), human, ownerNonce));
account = accountDeployer.predict(id, human, signer, buildHash, reserve, dailyLimit, metadataHash);
}
function _createAccount(address signer, bytes32 metadataHash, bytes32 buildHash, uint256 reserve,
uint256 dailyLimit, bool deterministic) private returns (bytes32 id, address account) {
require(creationAllowed(msg.sender), "Creation not open");
require(metadataHash != bytes32(0), "Metadata");
id = keccak256(abi.encode(block.chainid, address(this), msg.sender, nonces[msg.sender]++));
account = accountDeployer.deploy(id, msg.sender, signer, buildHash, reserve, dailyLimit, metadataHash, deterministic);
accounts[id] = account;
}
function createAccount(address signer, bytes32 metadataHash, bytes32 buildHash, uint256 reserve,
uint256 dailyLimit) external returns (bytes32 id, address account) {
(id, account) = _createAccount(signer, metadataHash, buildHash, reserve, dailyLimit, true);
creationBlocks[id] = block.number;
emit Created(id, msg.sender, account, address(0), metadataHash);
}
}
/// @notice One credit = one six-decimal dollar held until activation. No unbacked fee minting.
/// Activation funds a registered agent, not a personal withdrawal address.
contract NoerraAgentCredits is ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable dollar;
IAgentRegistry public immutable registry;
address public immutable settlement;
event Activated(address indexed payer, bytes32 indexed agentId, uint256 amount);
constructor(IERC20 dollar_, IAgentRegistry registry_, address settlement_) ERC20("Noerra Compute Credit", "NCC") {
require(address(dollar_) != address(0) && address(registry_) != address(0), "Configuration");
dollar = dollar_; registry = registry_; settlement = settlement_;
}
function decimals() public pure override returns (uint8) { return 6; }
function mint(uint256 amount, address recipient) external nonReentrant {
require(amount > 0 && recipient != address(0), "Amount");
uint256 beforeBalance = dollar.balanceOf(address(this));
dollar.safeTransferFrom(msg.sender, address(this), amount);
require(dollar.balanceOf(address(this)) == beforeBalance + amount, "Exact backing required");
_mint(recipient, amount);
}
/// @notice Unspent credits remain redeemable, including returned purchase escrow.
function redeem(uint256 amount) external nonReentrant {
require(amount > 0, "Amount");
_burn(msg.sender, amount); dollar.safeTransfer(msg.sender, amount);
require(dollar.balanceOf(address(this)) >= totalSupply(), "Backing");
}
function activate(bytes32 agentId, uint256 amount) external nonReentrant {
address account = registry.accounts(agentId);
require(account != address(0) && amount > 0, "Agent");
_burn(msg.sender, amount); dollar.safeTransfer(account, amount);
require(dollar.balanceOf(address(this)) >= totalSupply(), "Backing");
emit Activated(msg.sender, agentId, amount);
}
/// @notice Anyone may turn an agent's own credits into its own treasury dollars.
/// No caller can redirect the backing or withdraw another holder's credits.
function activateAccount(bytes32 agentId, uint256 amount) external nonReentrant {
address account = registry.accounts(agentId);
require(account != address(0) && amount > 0, "Agent");
_burn(account, amount); dollar.safeTransfer(account, amount);
require(dollar.balanceOf(address(this)) >= totalSupply(), "Backing");
emit Activated(account, agentId, amount);
}
/// @notice A pinned market may settle only credits it holds in buyer escrow.
/// The 10% returned credit remains dollar-backed; the other 90% leaves as dollars.
function settleUsage(address buyer, address sellerPool, address computeTreasury, uint256 amount)
external nonReentrant returns (uint256 sellerAmount, uint256 computeAmount, uint256 cashback) {
require(msg.sender == settlement && settlement != address(0), "Market only");
require(buyer != address(0) && sellerPool != address(0) && computeTreasury != address(0) && amount > 0, "Recipients");
_burn(msg.sender, amount);
cashback = amount / 10; sellerAmount = amount * 4 / 10; computeAmount = amount - cashback - sellerAmount;
if (cashback > 0) _mint(buyer, cashback);
dollar.safeTransfer(sellerPool, sellerAmount); dollar.safeTransfer(computeTreasury, computeAmount);
require(dollar.balanceOf(address(this)) >= totalSupply(), "Backing");
}
}
src/agents/NoerraAtomicCodeHashes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @dev Pinned solc 0.8.26 optimizer-200 constructor hashes; tests compare compiled artifacts.
/// NOERRA creation sources import no account source, so account edits do not move these pins.
/// The hook pin covers NoerraUsdcFeeHook.sol (decaying launch fee; launch access window; locker-only beforeAddLiquidity, flags 0x28cc); the vault
/// and market pins also cover the constructor access list / NoerraLaunchPrice sources through their metadata.
library NoerraAtomicCodeHashes {
function expected(uint256 i) internal pure returns(bytes32) {
if(i==0) return 0xb9f2d0d4a85992c5a9adf2067da3ccf18afad4b0fa8c1a8c7747f3168cdf6401;
if(i==1) return 0x428f8aae912704e8259f5bba04110d280f8c871061252bef0abcaebecac4920a;
if(i==2) return 0x144beaa403614d3c02c274ce47c21f1fa06ce6663213740cf308f21cb7a2799f;
if(i==3) return 0xbdb61c65292f2d6971b1b8bffdcab5fd2b80c491b9826fe36bed00db1c92d82e;
revert("Creation index");
}
}
src/agents/NoerraCreationToken.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @dev Kept in its own source so its creation bytes (and the registry token builder's pinned
/// hash of them) do not move when the account or registry source changes.
/// @notice An optional creation token. Fixed supply; no tax, upgrade or hidden mint authority.
contract NoerraCreationToken is ERC20 {
address public immutable launchFactory;
address public launchPoolManager;
uint256 public protectionStartBlock;
uint256 public protectionEndBlock;
uint256 public constant MAX_LAUNCH_HOLDING = 20_000_000 ether;
uint256 public constant LAUNCH_PROTECTION_BLOCKS = 10;
bool public protectionInitialized;
mapping(address => bool) public launchExempt;
constructor(string memory name_, string memory symbol_, address account) ERC20(name_, symbol_) {
require(bytes(name_).length > 0 && bytes(name_).length <= 48, "Name");
require(bytes(symbol_).length > 0 && bytes(symbol_).length <= 12, "Symbol");
launchFactory = account;
_mint(account, 1_000_000_000 ether);
}
/// @notice Canonical Ethereum launch protection. Legacy token creation is unchanged.
/// Only the original factory can initialize once, before distributing supply.
function initializeLaunchProtection(address poolManager, address locker, address reserve, address bridge)
external
{
require(msg.sender == launchFactory && msg.sender.code.length > 0 && block.chainid == 1, "Launch factory only");
require(!protectionInitialized && balanceOf(launchFactory) == totalSupply(), "Launch protection fixed");
require(poolManager.code.length > 0 && locker.code.length > 0 && reserve.code.length > 0
&& bridge.code.length > 0, "Launch protection pins");
protectionInitialized = true;
launchPoolManager = poolManager;
protectionStartBlock = block.number;
protectionEndBlock = block.number + LAUNCH_PROTECTION_BLOCKS;
launchExempt[launchFactory] = true;
launchExempt[poolManager] = true;
launchExempt[locker] = true;
launchExempt[reserve] = true;
launchExempt[bridge] = true;
}
function launchProtectionActive() public view returns (bool) {
return protectionInitialized && block.number < protectionEndBlock;
}
function _update(address from, address to, uint256 value) internal override {
if (launchProtectionActive() && from != address(0) && to != address(0) && !launchExempt[to]) {
if (from == launchPoolManager) require(value <= MAX_LAUNCH_HOLDING, "Launch max buy");
require(balanceOf(to) + (from == to ? 0 : value) <= MAX_LAUNCH_HOLDING, "Launch max wallet");
}
super._update(from, to, value);
}
}
src/agents/NoerraKmsApplicationPolicy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
interface INoerraKmsAppAuth {
struct AppBootInfo {
address appId; bytes32 composeHash; address instanceId; bytes32 deviceId;
bytes32 mrAggregated; bytes32 mrSystem; bytes32 osImageHash;
string tcbStatus; string[] advisoryIds;
}
function isAppAllowed(AppBootInfo calldata boot) external view returns (bool, string memory);
}
/// @notice One application identity, one approved manifest and OS. No management or upgrade path.
contract NoerraKmsApplicationPolicy is INoerraKmsAppAuth {
address public immutable factory = msg.sender;
bytes32 public composeHash;
bytes32 public osImageHash;
bytes32 public configurationHash;
function initialize(bytes32 compose, bytes32 osImage, bytes32 configuration) external {
require(msg.sender == factory && composeHash == bytes32(0), "Immutable application");
require(compose != bytes32(0) && osImage != bytes32(0) && configuration != bytes32(0), "Application policy");
composeHash = compose; osImageHash = osImage; configurationHash = configuration;
}
function supportsInterface(bytes4 id) external pure returns (bool) {
return id == 0x01ffc9a7 || id == 0x1e079198;
}
function isAppAllowed(AppBootInfo calldata boot) external view returns (bool, string memory) {
if (boot.appId != address(this) || boot.instanceId == address(0)) return (false, "Application identity");
if (boot.composeHash != composeHash || boot.osImageHash != osImageHash) return (false, "Application code");
if (keccak256(bytes(boot.tcbStatus)) != keccak256("UpToDate") || boot.advisoryIds.length != 0)
return (false, "Hardware status");
return (true, "");
}
}
/// @notice The protected launcher approves exact policies; anyone can pay to create them.
/// @dev Deployment must authenticate the immutable approver's actual protected runtime identity.
contract NoerraKmsApplicationFactory {
address public immutable approver;
bytes32 public constant APPROVAL_DOMAIN = keccak256("NOERRA_KMS_APPLICATION_V1");
struct Application { bytes32 composeHash; bytes32 osImageHash; bytes32 configurationHash; uint8 role; }
mapping(address => Application) public applications; // role 1: starter, 2: paid recovery.
event ApplicationCreated(address indexed app, bytes32 indexed salt, uint8 role, bytes32 composeHash, bytes32 osImageHash, bytes32 configurationHash);
constructor(address protectedApprover) {
require(protectedApprover != address(0), "Policy approver"); approver = protectedApprover;
}
function approvalCommitment(bytes32 compose, bytes32 osImage, bytes32 configuration, uint8 role, bytes32 salt)
public view returns (bytes32) {
return keccak256(abi.encode(APPROVAL_DOMAIN, block.chainid, address(this), compose, osImage, configuration, role, salt));
}
function applicationSalt(uint8 role, bytes32 salt) public pure returns (bytes32) {
return keccak256(abi.encode(role, salt));
}
function predictApplication(uint8 role, bytes32 salt) public view returns (address) {
return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), applicationSalt(role, salt),
keccak256(type(NoerraKmsApplicationPolicy).creationCode))))));
}
function createApplication(bytes32 compose, bytes32 osImage, bytes32 configuration, uint8 role, bytes32 salt, bytes calldata approval)
external returns (address app) {
require(compose != bytes32(0) && osImage != bytes32(0) && configuration != bytes32(0) && (role == 1 || role == 2), "Application policy");
require(ECDSA.recover(MessageHashUtils.toEthSignedMessageHash(approvalCommitment(compose, osImage, configuration, role, salt)), approval) == approver,
"Policy approval");
app = predictApplication(role, salt);
Application memory existing = applications[app];
if (existing.role != 0) {
require(existing.composeHash == compose && existing.osImageHash == osImage && existing.configurationHash == configuration && existing.role == role,
"Application already bound");
return app;
}
require(app.code.length == 0, "Application occupied");
NoerraKmsApplicationPolicy deployed = new NoerraKmsApplicationPolicy{salt: applicationSalt(role, salt)}();
require(address(deployed) == app, "Application prediction");
deployed.initialize(compose, osImage, configuration);
applications[app] = Application(compose, osImage, configuration, role);
emit ApplicationCreated(app, salt, role, compose, osImage, configuration);
}
}
src/agents/NoerraRecoveryVerifier.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {NoerraStartFunding} from "./NoerraStartFunding.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IAgentRecoveryVerifier, NoerraAgentAccount} from "./NoerraAgents.sol";
/// @dev Automata DCAP byte-quote ABI; V4 TD10 output formats v1.0 and v1.1+.
interface INoerraDcapAttestation {
function verifyAndAttestOnChain(bytes calldata rawQuote) external payable
returns (bool success, bytes memory verifiedOutput);
}
interface INoerraRecoverableAccount {
function recover(address candidate, bytes calldata evidence) external;
}
/// @notice Permissionless registration of a fresh, measured TDX recovery quote.
/// @dev This verifies hardware/software evidence, not confidential model inference.
/// The measured application must authenticate the candidate key and scoped action before quoting it.
/// Review the upstream verifier and its collateral/upgrade authorities before deployment.
abstract contract NoerraEvidenceRegistration is IAgentRecoveryVerifier, ReentrancyGuard, NoerraStartFunding {
bytes32 public immutable measurementsHash;
uint256 public constant WINDOW = 128;
struct Registration { bytes32 commitment; uint256 anchor; }
mapping(bytes32 => Registration) public registrations;
mapping(bytes32 => bool) public paidRegistrations;
mapping(bytes32 => address) public registrationStarter;
event Registered(bytes32 indexed quoteHash, bytes32 indexed commitment, uint256 anchor);
constructor(bytes32 measurements) {
require(measurements != bytes32(0), "Measurements");
measurementsHash = measurements;
}
function _authorityValid() internal view virtual returns (bool);
function _authenticate(bytes calldata evidence, bytes32 commitment, bytes32 fresh,
bytes32 policy, uint256 fee) internal virtual;
function _evidenceBounds(bytes calldata evidence) internal pure virtual returns (bool);
function freshness(uint256 anchor, bytes32 anchorHash) public view returns (bytes32) {
return keccak256(abi.encode(block.chainid, address(this), anchor, anchorHash));
}
/// @notice Legacy deployments cannot opt into paid operators after deployment.
function operatorMeasurementsHash() public view virtual returns (bytes32) { return bytes32(0); }
/// @notice The caller pays the DCAP fee. Reusing a quote never extends its lifetime.
function register(bytes calldata quote, bytes32 commitment, uint256 anchor, bytes32 anchorHash)
external payable nonReentrant returns (bytes32 quoteHash) {
return _register(quote, commitment, anchor, anchorHash, msg.value);
}
/// @notice Register a fresh starter claim and acquire its fence atomically.
function registerAndClaimStart(address account, bytes32 runId, uint256 expectedGeneration,
uint256 expiresAt, bytes calldata quote, uint256 anchor, bytes32 anchorHash)
external payable nonReentrant returns (bytes32 quoteHash) {
bytes32 commitment = startClaimCommitment(account,msg.sender,runId,expectedGeneration,expiresAt);
quoteHash = _register(quote,commitment,anchor,anchorHash,msg.value);
_claimStart(account,msg.sender,runId,expectedGeneration,expiresAt,abi.encodePacked(quoteHash));
}
function registerPaid(bytes calldata quote, bytes32 commitment, uint256 anchor, bytes32 anchorHash)
external payable nonReentrant returns (bytes32 quoteHash) {
return _registerPaid(quote, commitment, anchor, anchorHash, msg.value);
}
function registerAndClaimPaidStart(address account, bytes32 runId, uint256 expectedGeneration,
uint256 expiresAt, bytes calldata quote, uint256 anchor, bytes32 anchorHash)
external payable nonReentrant returns (bytes32 quoteHash) {
bytes32 commitment = startClaimCommitment(account,msg.sender,runId,expectedGeneration,expiresAt);
quoteHash = _registerPaid(quote,commitment,anchor,anchorHash,msg.value);
_claimStart(account,msg.sender,runId,expectedGeneration,expiresAt,abi.encodePacked(quoteHash));
}
function registerAndFundStart(address account, bytes32 runId, address cash, address operator,
uint256 reimbursement, uint256 bounty, bytes calldata quote, uint256 anchor, bytes32 anchorHash,
bool paid, uint256 cashGas) external payable nonReentrant returns (bytes32 quoteHash) {
_checkStarterCashGas(account, cashGas);
bytes32 commitment = startFundingCommitment(account,runId,cash,operator,reimbursement,bounty);
quoteHash = paid ? _registerPaid(quote,commitment,anchor,anchorHash,msg.value-cashGas) :
_register(quote,commitment,anchor,anchorHash,msg.value-cashGas);
_fundStart(account,runId,cash,operator,reimbursement,bounty,abi.encodePacked(quoteHash));
if (cashGas != 0) {
(bool sent,) = payable(cash).call{value:cashGas}(""); require(sent,"Gas delivery");
}
}
function _checkStarterCashGas(address account, uint256 cashGas) private view {
require(msg.value >= cashGas && (cashGas == 0 ||
startFunding[account][startClaims[account].generation].cash == address(0)), "Starter cash gas");
}
function registerAndCompleteStart(address account, uint256 generation, bytes32 runId, bytes32 lease,
bytes32 destination, bytes calldata quote, uint256 anchor, bytes32 anchorHash, bool paid)
external payable nonReentrant returns (bytes32 quoteHash) {
bytes32 commitment = startCompletionCommitment(account,generation,runId,lease,destination);
quoteHash = paid ? _registerPaid(quote,commitment,anchor,anchorHash,msg.value) :
_register(quote,commitment,anchor,anchorHash,msg.value);
_completeStart(account,generation,runId,lease,destination,abi.encodePacked(quoteHash));
}
function registerAndRecoverDirectPaid(address account, address candidate, bytes calldata quote,
bytes32 commitment, uint256 anchor, bytes32 anchorHash, uint256 signerGas)
external payable nonReentrant returns (bytes32 quoteHash) {
require(account.code.length != 0 && candidate != address(0) && candidate.code.length == 0 &&
msg.value >= signerGas && startFenceEnabled[account], "Direct recovery");
quoteHash = _registerPaid(quote,commitment,anchor,anchorHash,msg.value-signerGas);
INoerraRecoverableAccount(account).recover(candidate,abi.encodePacked(quoteHash));
if (signerGas != 0) {
(bool sent,) = payable(candidate).call{value:signerGas}(""); require(sent,"Gas delivery");
}
}
/// @notice Register and rotate atomically, without waiting through the short
/// quote lifetime between two separately finalized transactions.
/// The account independently checks its exact generation commitment.
function registerAndRecover(address account, address candidate, bytes calldata quote,
bytes32 commitment, uint256 anchor, bytes32 anchorHash, uint256 signerGas)
external payable nonReentrant returns (bytes32 quoteHash) {
require(account.code.length != 0 && candidate != address(0) && candidate.code.length == 0, "Recovery account");
require(msg.value >= signerGas, "Signer gas");
quoteHash = _register(quote, commitment, anchor, anchorHash, msg.value - signerGas);
INoerraRecoverableAccount(account).recover(candidate, abi.encodePacked(quoteHash));
if (signerGas != 0) {
(bool sent,) = payable(candidate).call{value: signerGas}(""); require(sent, "Gas delivery");
}
}
/// @notice Register a fresh starter quote and consume the human's deferred approval atomically.
/// Registration, authority rotation and capped native gas delivery all roll back on failure.
/// `birthCheckpoint` (the sealed birth archive's hash) is bound in the commitment and becomes the account's
/// checkpointHash, so an agent lost before its first pulseCheckpoint stays recoverable.
function registerAndActivate(address account, uint256 expectedGeneration, address nextSigner,
bytes32 destination, bytes32 birthCheckpoint, bytes memory acceptance, bytes calldata quote, uint256 anchor,
bytes32 anchorHash, uint256 signerGas) external payable nonReentrant returns (bytes32 quoteHash) {
require(account.code.length != 0 && msg.value >= signerGas, "Activation account");
quoteHash = _register(quote, NoerraAgentAccount(account).automaticActivationCommitment(expectedGeneration, nextSigner,
destination, birthCheckpoint), anchor, anchorHash, msg.value - signerGas);
NoerraAgentAccount(account).activateApproved{value: signerGas}(expectedGeneration, nextSigner, destination,
birthCheckpoint, acceptance, abi.encodePacked(quoteHash));
}
/// @notice An admitted operator may consume the same owner-approved birth intent.
function registerAndActivatePaid(address account, uint256 expectedGeneration, address nextSigner,
bytes32 destination, bytes32 birthCheckpoint, bytes memory acceptance, bytes calldata quote, uint256 anchor,
bytes32 anchorHash, uint256 signerGas) external payable nonReentrant returns (bytes32 quoteHash) {
require(startFenceEnabled[account] && account.code.length != 0 && msg.value >= signerGas, "Activation account");
quoteHash = _registerPaid(quote, NoerraAgentAccount(account).automaticActivationCommitment(expectedGeneration, nextSigner,
destination, birthCheckpoint), anchor, anchorHash, msg.value - signerGas);
NoerraAgentAccount(account).activateApproved{value: signerGas}(expectedGeneration, nextSigner, destination,
birthCheckpoint, acceptance, abi.encodePacked(quoteHash));
}
/// @notice Register the starter quote and reserve its reward atomically. No dollar
/// payment occurs until a separate attested replacement-computer completion.
function registerAndRecoverForOperator(address account, NoerraAgentAccount.PaidRecoveryRequest calldata request,
bytes calldata quote, uint256 anchor, bytes32 anchorHash, uint256 signerGas)
external payable nonReentrant returns (bytes32 quoteHash) {
require(account.code.length != 0 && request.nextSigner != address(0) &&
request.nextSigner.code.length == 0, "Recovery account");
require(msg.value >= signerGas, "Signer gas");
NoerraAgentAccount target = NoerraAgentAccount(account);
quoteHash = _registerPaid(quote, target.paidRecoveryCommitment(request), anchor, anchorHash, msg.value - signerGas);
target.recoverForOperator(request, abi.encodePacked(quoteHash));
if (signerGas != 0) {
(bool sent,) = payable(request.nextSigner).call{value: signerGas}(""); require(sent, "Gas delivery");
}
}
/// @notice Register the receiver-completion quote and pay only its already reserved
/// operator. A failed handover, expired job or failed transfer rolls back both.
function registerAndCompletePaidRecovery(address account, bytes32 jobId, bytes32 actualLease,
bytes calldata quote, uint256 anchor, bytes32 anchorHash)
external payable nonReentrant returns (bytes32 quoteHash) {
require(account.code.length != 0, "Recovery account");
NoerraAgentAccount target = NoerraAgentAccount(account);
quoteHash = _registerPaid(quote, target.paidRecoveryCompletionCommitment(jobId, actualLease), anchor, anchorHash, msg.value);
target.completePaidRecovery(jobId, actualLease, abi.encodePacked(quoteHash));
}
function _register(bytes calldata quote, bytes32 commitment, uint256 anchor, bytes32 anchorHash, uint256 fee)
private returns (bytes32 quoteHash) {
return _registerMeasured(quote, commitment, anchor, anchorHash, fee, measurementsHash, false);
}
function _registerPaid(bytes calldata quote, bytes32 commitment, uint256 anchor, bytes32 anchorHash, uint256 fee)
private returns (bytes32 quoteHash) {
bytes32 measured = operatorMeasurementsHash();
require(measured != bytes32(0), "Paid recovery disabled");
return _registerMeasured(quote, commitment, anchor, anchorHash, fee, measured, true);
}
function _registerMeasured(bytes calldata quote, bytes32 commitment, uint256 anchor, bytes32 anchorHash,
uint256 fee, bytes32 measured, bool paid) private returns (bytes32 quoteHash) {
require(commitment != bytes32(0) && _evidenceBounds(quote), "Quote bounds");
require(anchor < block.number && block.number - anchor < WINDOW && blockhash(anchor) == anchorHash, "Fresh anchor");
require(_authorityValid(), "Verifier changed");
quoteHash = keccak256(quote);
require(registrations[quoteHash].commitment == bytes32(0), "Quote registered");
_authenticate(quote, commitment, freshness(anchor, anchorHash), measured, fee);
registrations[quoteHash] = Registration(commitment, anchor);
paidRegistrations[quoteHash] = paid;
registrationStarter[quoteHash] = msg.sender;
emit Registered(quoteHash, commitment, anchor);
}
function verify(bytes calldata evidence, bytes32 commitment) external view returns (bool) {
if (startFenceEnabled[msg.sender]) {
if (evidence.length != 32) return false;
bytes32 quoteHash;
assembly { quoteHash := calldataload(evidence.offset) }
if (registrationStarter[quoteHash] != startClaims[msg.sender].starter) return false;
}
return _allowStartAction(msg.sender, commitment) && (_verify(evidence, commitment, false) ||
startFenceEnabled[msg.sender] && _verify(evidence, commitment, true));
}
function verifyPaid(bytes calldata evidence, bytes32 commitment) external view returns (bool) {
return !startFenceEnabled[msg.sender] && operatorMeasurementsHash() != bytes32(0) && _verify(evidence, commitment, true);
}
function _verifyStartClaimEvidence(bytes memory evidence, bytes32 commitment) internal view override returns (bool) {
return _verify(evidence, commitment, false) || _verify(evidence, commitment, true);
}
function _verifyStartFundingEvidence(bytes memory evidence, bytes32 commitment) internal view override returns (bool) {
return _verify(evidence, commitment, false) || _verify(evidence, commitment, true);
}
function _verify(bytes memory evidence, bytes32 commitment, bool paid) private view returns (bool) {
if (evidence.length != 32 || commitment == bytes32(0) || !_authorityValid()) return false;
bytes32 quoteHash; assembly { quoteHash := mload(add(evidence, 32)) }
Registration memory row = registrations[quoteHash];
return paidRegistrations[quoteHash] == paid && row.commitment == commitment &&
row.anchor < block.number && block.number - row.anchor < WINDOW;
}
}
/// @notice Direct verification of measured TDX evidence through the pinned DCAP verifier.
contract NoerraRecoveryVerifier is NoerraEvidenceRegistration {
INoerraDcapAttestation public immutable attestation;
bytes32 public immutable attestationCodeHash;
constructor(INoerraDcapAttestation verifier, bytes32 codeHash, bytes32 measurements)
NoerraEvidenceRegistration(measurements) {
require(address(verifier).code.length != 0 && address(verifier).codehash == codeHash, "Verifier code");
attestation = verifier; attestationCodeHash = codeHash;
}
function _authorityValid() internal view override returns (bool) {
return address(attestation).codehash == attestationCodeHash;
}
function _evidenceBounds(bytes calldata quote) internal pure override returns (bool) {
return quote.length >= 632 && quote.length <= 50000;
}
function _authenticate(bytes calldata quote, bytes32 commitment, bytes32 fresh,
bytes32 policy, uint256 fee) internal override {
(bool success, bytes memory output) = attestation.verifyAndAttestOnChain{value: fee}(_attestationQuote(quote));
require(success, "DCAP verification");
_check(output, commitment, fresh, policy, quote);
}
function _attestationQuote(bytes calldata quote) internal pure virtual returns (bytes memory) {
return quote;
}
function _word(bytes memory output, uint256 at) internal pure returns (bytes32 value) {
assembly { value := mload(add(add(output, 32), at)) }
}
function _check(bytes memory output, bytes32 commitment, bytes32 fresh, bytes32 approvedMeasurements,
bytes calldata) internal pure virtual {
uint256 body = _checkHardwareAndBinding(output, commitment, fresh);
bytes memory measured = new bytes(240); // MRTD and RTMR0..3, each 48 bytes
for (uint256 i; i < 48; ++i) measured[i] = output[body + 136 + i];
for (uint256 i; i < 192; ++i) measured[48 + i] = output[body + 328 + i];
require(keccak256(measured) == approvedMeasurements, "Measured application");
}
function _checkHardwareAndBinding(bytes memory output, bytes32 commitment, bytes32 fresh)
internal pure returns (uint256 body) {
require(output.length >= 595 && output.length <= 8192, "Output bounds");
require(output[0] == 0 && output[1] == 0x04, "TDX up to date only");
// v1.0: BE version(2), TEE(4), TCB(1), FMSPC(6).
// v1.1+: BE version(2), body type(2), TCB(1), FMSPC(6).
// Accept only V4 TD10, never SGX, TD15 or an unknown layout.
if (output[2] == 0 && output[3] == 0x02) {
body = 11;
require(output[4] == 0, "TDX up to date only");
} else {
body = 13;
require(output[2] == 0 && output[3] == 0 && output[4] == 0 &&
output[5] == 0x81 && output[6] == 0, "TDX up to date only");
require(output.length >= 597, "Output bounds");
}
require(uint8(output[body + 120]) & 1 == 0, "Debug TDX");
require(_word(output, body + 520) == commitment && _word(output, body + 552) == fresh,
"Recovery binding");
uint256 end = body + 584;
if (output.length > end) {
bytes memory tail = new bytes(output.length - end);
for (uint256 i; i < tail.length; ++i) tail[i] = output[end + i];
require(abi.decode(tail, (string[])).length == 0, "TCB advisories");
}
}
}
/// @notice Separate immutable software authority for paid recovery. Operator quotes
/// cannot authorize the legacy unpaid path, and legacy quotes cannot earn rewards.
contract NoerraPaidRecoveryVerifier is NoerraRecoveryVerifier {
bytes32 private immutable operatorHash;
constructor(INoerraDcapAttestation verifier, bytes32 codeHash, bytes32 originalMeasurements,
bytes32 operatorMeasurements) NoerraRecoveryVerifier(verifier, codeHash, originalMeasurements) {
require(operatorMeasurements != bytes32(0), "Operator measurements");
operatorHash = operatorMeasurements;
}
function operatorMeasurementsHash() public view override returns (bytes32) { return operatorHash; }
}
/// @notice Recovery authority for dstack V2 configuration-bound KMS applications.
/// @dev Immutable policy hashes bind MRTD+RTMR0..2, the exact role composition and
/// the KMS root identity. Quoted MRCONFIGID authenticates each fresh app ID.
/// Runtime verification must additionally replay RTMR3 for instance identity.
/// Format: dstack v0.5.9, commit 282eeb27d22d8f091ad0fa5a90e638f85cf68751.
contract NoerraDstackPaidRecoveryVerifier is NoerraPaidRecoveryVerifier {
uint256 public constant DSTACK_POLICY_VERSION = 1;
constructor(INoerraDcapAttestation verifier, bytes32 codeHash, bytes32 originalPolicy,
bytes32 operatorPolicy) NoerraPaidRecoveryVerifier(verifier, codeHash, originalPolicy, operatorPolicy) {
require(originalPolicy != operatorPolicy, "Separate dstack roles");
}
function _envelope(bytes calldata evidence) private pure returns
(bytes memory quote, bytes20 appId, bytes32 composeHash, bytes memory kmsIdentity) {
(quote, appId, composeHash, kmsIdentity) = abi.decode(evidence, (bytes, bytes20, bytes32, bytes));
require(quote.length >= 632 && quote.length <= 50000, "Dstack quote bounds");
require(appId != bytes20(0) && composeHash != bytes32(0) && kmsIdentity.length > 0 &&
kmsIdentity.length <= 512 && keccak256(evidence) == keccak256(abi.encode(quote, appId, composeHash, kmsIdentity)),
"Dstack envelope");
}
function _attestationQuote(bytes calldata evidence) internal pure override returns (bytes memory quote) {
(quote,,,) = _envelope(evidence);
}
function _check(bytes memory output, bytes32 commitment, bytes32 fresh, bytes32 approvedPolicy,
bytes calldata evidence) internal pure override {
uint256 body = _checkHardwareAndBinding(output, commitment, fresh);
(, bytes20 appId, bytes32 composeHash, bytes memory kmsIdentity) = _envelope(evidence);
bytes memory config = abi.encodePacked(bytes1(0x02),
keccak256(abi.encodePacked(composeHash, appId, bytes1(0x02), kmsIdentity)), bytes15(0));
for (uint256 i; i < 48; ++i) require(output[body + 184 + i] == config[i], "Dstack configuration");
bytes memory os = new bytes(192); // MRTD and RTMR0..2; RTMR3 varies by instance and boot.
for (uint256 i; i < 48; ++i) os[i] = output[body + 136 + i];
for (uint256 i; i < 144; ++i) os[48 + i] = output[body + 328 + i];
require(keccak256(abi.encodePacked(os, composeHash, bytes1(0x02), kmsIdentity)) == approvedPolicy,
"Measured application");
}
}
src/agents/NoerraReserveSetupPermit.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @notice One launch authorization for exact zero-value setup calls on Ethereum and Base.
/// @dev Each leaf binds chain, recipient and original calldata. This is not a spending
/// allowance. Consumers must enforce one-shot setup and invalidate it after recovery.
library NoerraReserveSetupPermit {
struct Permit {
address sourceRegistry;
bytes32 root;
uint256 deadline;
bytes signature;
bytes32[] proof;
}
bytes32 internal constant TYPEHASH =
keccak256("ReserveSetup(bytes32 agentId,bytes32 callsRoot,uint256 deadline)");
function digest(address registry, bytes32 id, bytes32 root, uint256 deadline)
internal pure returns (bytes32)
{
bytes32 domain = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256("Noerra Reserve Setup"), keccak256("1"), uint256(1), registry
));
return keccak256(abi.encodePacked("\x19\x01", domain,
keccak256(abi.encode(TYPEHASH, id, root, deadline))));
}
function leaf(bytes memory callData) internal view returns (bytes32) {
// Double hashing prevents a 64-byte leaf from being confused with a tree node.
return keccak256(bytes.concat(keccak256(abi.encode(
block.chainid, address(this), uint256(0), keccak256(callData)
))));
}
function verify(address owner, address registry, bytes32 id, bytes memory callData, Permit calldata permit)
internal view
{
require((block.chainid == 1 || block.chainid == 8453) && registry != address(0)
&& permit.sourceRegistry == registry && id != bytes32(0)
&& permit.root != bytes32(0) && permit.deadline >= block.timestamp
&& permit.proof.length <= 8, "Exact unexpired reserve setup");
require(MerkleProof.verifyCalldata(permit.proof, permit.root, leaf(callData)),
"Approved reserve setup call");
require(SignatureChecker.isValidSignatureNow(owner,
digest(registry, id, permit.root, permit.deadline), permit.signature),
"Creator reserve setup signature");
}
}
src/agents/NoerraStartClaims.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
interface INoerraStartAccount {
function recoveryVerifier() external view returns (address);
function generation() external view returns (uint256);
function lastPulse() external view returns (uint256);
function STALE_AFTER() external view returns (uint256);
function checkpointHash() external view returns (bytes32);
function buildHash() external view returns (bytes32);
function automaticActivation() external view returns (bytes32,uint256,uint256,uint256,uint256);
function paidRecovery() external view returns (bytes32,bytes32,address,address,uint256,uint256,uint256,uint256,bytes32,bytes32);
}
/// @notice Attested, single-action starter claims enforced by the account's verifier.
/// @dev No funds move here. Claiming opts an account into fenced activation/recovery
/// permanently; paid v2 starter handovers must then be rejected by the verifier.
abstract contract NoerraStartClaims {
error InvalidStartClaim();
uint256 public constant START_CLAIM_WINDOW = 20 minutes;
uint256 public constant MAX_START_CLAIM_LIFETIME = 1 hours;
/// @dev NoerraAgentAccount.FREEZE_TTL: a freeze lapses 72 h after it was reported.
uint256 private constant ACCOUNT_FREEZE_TTL = 72 hours;
bytes32 public constant START_CLAIM_DOMAIN = keccak256("NOERRA_START_CLAIM_V3");
struct StartClaim {
address starter;
bytes32 runId;
uint256 generation;
uint256 pulse;
bytes32 checkpoint;
bytes32 build;
uint256 expiresAt;
uint256 maximumUntil;
bytes32 action;
}
mapping(address => StartClaim) public startClaims;
mapping(address => bool) public startFenceEnabled;
mapping(address => mapping(bytes32 => bool)) public startRunUsed;
mapping(address => bytes32) public startBirthApproval;
/// @notice Slot griefing: a starter whose claim on an account ran out without progress (no bound action, no
/// funded start) while that account stayed exactly as it was claimed (same generation and liveness: nothing was
/// recovered, activated or revived) may not claim that account again for START_CLAIM_COOLDOWN after the expiry.
/// Renewals, other starters and a starter continuing its own funded or bound start are unaffected.
uint256 public constant START_CLAIM_COOLDOWN = 6 hours;
mapping(address => mapping(address => uint256)) public startClaimCooldownUntil;
event StartClaimed(address indexed account, bytes32 indexed runId, address indexed starter, uint256 generation, uint256 expiresAt);
event StartClaimRenewed(address indexed account, bytes32 indexed runId, uint256 expiresAt);
event StartActionBound(address indexed account, bytes32 indexed runId, bytes32 action);
function _verifyStartClaimEvidence(bytes memory evidence, bytes32 commitment) internal view virtual returns (bool);
function startClaimCommitment(address account, address starter, bytes32 runId, uint256 expectedGeneration,
uint256 expiresAt) public view returns (bytes32) {
INoerraStartAccount target = INoerraStartAccount(account);
return keccak256(abi.encode(START_CLAIM_DOMAIN, block.chainid, address(this), account, starter,
runId, expectedGeneration, target.lastPulse(), target.checkpointHash(), target.buildHash(), expiresAt,
expectedGeneration == 1 ? _birthApproval(target) : bytes32(0)));
}
function claimStart(address account, bytes32 runId, uint256 expectedGeneration, uint256 expiresAt,
bytes calldata evidence) external {
_claimStart(account,msg.sender,runId,expectedGeneration,expiresAt,evidence);
}
function _claimStart(address account,address starter,bytes32 runId,uint256 expectedGeneration,uint256 expiresAt,bytes memory evidence) internal {
INoerraStartAccount target = INoerraStartAccount(account);
if (account.code.length == 0 || runId == bytes32(0) || startRunUsed[account][runId] ||
target.recoveryVerifier() != address(this) || target.generation() != expectedGeneration ||
expiresAt <= block.timestamp || expiresAt > block.timestamp + START_CLAIM_WINDOW ||
!_eligible(target) || _current(target, startClaims[account]) || _coolingDown(target, starter))
revert InvalidStartClaim();
if (!_verifyStartClaimEvidence(evidence, startClaimCommitment(account,starter,runId,expectedGeneration,expiresAt)))
revert InvalidStartClaim();
startRunUsed[account][runId] = true;
startFenceEnabled[account] = true;
startClaims[account] = StartClaim(starter,runId,expectedGeneration,target.lastPulse(),
target.checkpointHash(),target.buildHash(),expiresAt,block.timestamp+MAX_START_CLAIM_LIFETIME,bytes32(0));
startBirthApproval[account] = expectedGeneration == 1 ? _birthApproval(target) : bytes32(0);
emit StartClaimed(account,runId,starter,expectedGeneration,expiresAt);
}
/// @dev B3: records the cooldown of the previous (no longer current) claim's starter when it ran out with the account
/// unchanged, then answers whether `starter` is still cooling down on this account.
function _coolingDown(INoerraStartAccount target, address starter) private returns (bool) {
address account = address(target);
StartClaim storage previous = startClaims[account];
address last = previous.starter; uint256 until = previous.expiresAt + START_CLAIM_COOLDOWN;
if (last != address(0) && block.timestamp >= previous.expiresAt && previous.generation == target.generation() &&
previous.pulse == target.lastPulse() && !_startProgressed(account, previous) &&
startClaimCooldownUntil[account][last] < until)
startClaimCooldownUntil[account][last] = until;
return block.timestamp < startClaimCooldownUntil[account][starter];
}
/// @dev A claim made progress once its starter bound an action (a funded start counts too, NoerraStartFunding).
function _startProgressed(address, StartClaim storage claim) internal view virtual returns (bool) {
return claim.action != bytes32(0);
}
function renewStartClaim(address account, bytes32 runId, uint256 expiresAt) external {
StartClaim storage claim = startClaims[account];
if (claim.starter != msg.sender || claim.runId != runId || !_current(INoerraStartAccount(account),claim) ||
expiresAt <= claim.expiresAt || expiresAt > block.timestamp + START_CLAIM_WINDOW ||
expiresAt > claim.maximumUntil) revert InvalidStartClaim();
claim.expiresAt = expiresAt;
emit StartClaimRenewed(account,runId,expiresAt);
}
/// @notice Bind exactly one activation/recovery commitment after provisioning.
/// The ordinary computer's public signer is inside that account commitment.
function bindStartAction(address account, bytes32 runId, bytes32 action) external {
StartClaim storage claim = startClaims[account];
if (claim.starter != msg.sender || claim.runId != runId || action == bytes32(0) ||
!_current(INoerraStartAccount(account),claim) || claim.action != bytes32(0) && claim.action != action)
revert InvalidStartClaim();
claim.action = action;
emit StartActionBound(account,runId,action);
}
function _eligible(INoerraStartAccount target) private view returns (bool) {
(bytes32 pending,,,,,,,,,) = target.paidRecovery();
// A frozen account is recoverable even while hibernating.
if (pending != bytes32(0) || _asleep(address(target)) && !_frozen(address(target))) return false;
if (target.generation() == 1) {
(bytes32 intent,,,,) = target.automaticActivation();
if (intent != bytes32(0)) return true;
}
return target.checkpointHash() != bytes32(0) &&
(block.timestamp > _liveSince(target) + target.STALE_AFTER() || _frozen(address(target)));
}
/// @dev The account's own liveness clock (NoerraAgentAccount._checkStaleRecovery).
/// A lapsed freeze of the current generation counts as a pulse at frozenAt + 72 h, so no claim can be taken (and re-freeze the
/// account through frozen()'s start-claim extension) inside the stale grace that follows a lapse. Accounts without the freeze
/// getters keep the raw lastPulse.
function _liveSince(INoerraStartAccount target) private view returns (uint256 since) {
since = target.lastPulse();
(bool ok, bytes memory answer) = address(target).staticcall(abi.encodeWithSignature("frozenGeneration()"));
if (!ok || answer.length != 32 || abi.decode(answer, (uint256)) != target.generation()) return since;
(ok, answer) = address(target).staticcall(abi.encodeWithSignature("frozenAt()"));
if (ok && answer.length == 32) {
uint256 lapse = abi.decode(answer, (uint256)) + ACCOUNT_FREEZE_TTL;
if (lapse > since) since = lapse;
}
}
/// @dev Emergency freeze: a frozen account (its signer reported compromised; a freeze lasts at most
/// 72 h) is recoverable at once, without the stale wait; whether it is paid is the account's rule. Accounts without
/// the getter never are.
function _frozen(address target) private view returns (bool) {
(bool ok, bytes memory answer) = target.staticcall(abi.encodeWithSignature("frozen()"));
return ok && answer.length == 32 && abi.decode(answer, (uint256)) == 1;
}
/// @dev A hibernating account below its wake threshold refuses every recovery door, so a
/// claim would only hold the slot. An account is a hibernation account when its non-reverting
/// hibernating() getter answers one word; only accounts without it (older deployments) count as awake.
/// For a hibernation account a reverting or malformed recoveryAsleep() counts as asleep.
function _asleep(address target) private view returns (bool) {
(bool known, bytes memory flag) = target.staticcall(abi.encodeWithSignature("hibernating()"));
if (!known || flag.length != 32) return false;
(bool ok, bytes memory answer) = target.staticcall(abi.encodeWithSignature("recoveryAsleep()"));
return !ok || answer.length != 32 || abi.decode(answer, (uint256)) != 0;
}
function _current(INoerraStartAccount target, StartClaim memory claim) internal view returns (bool) {
return claim.starter != address(0) && block.timestamp < claim.expiresAt &&
target.generation() == claim.generation && target.lastPulse() == claim.pulse &&
target.checkpointHash() == claim.checkpoint && target.buildHash() == claim.build &&
(claim.generation != 1 || startBirthApproval[address(target)] == _birthApproval(target));
}
function startClaimCurrent(address account) external view returns (bool) {
return _current(INoerraStartAccount(account), startClaims[account]);
}
function _birthApproval(INoerraStartAccount target) private view returns (bytes32) {
(bytes32 intent, uint256 nonce, uint256 minimum, uint256 expiry, uint256 gasLimit) = target.automaticActivation();
return keccak256(abi.encode(intent, nonce, minimum, expiry, gasLimit));
}
function _allowStartAction(address account, bytes32 commitment) internal view returns (bool) {
if (!startFenceEnabled[account]) return true;
StartClaim memory claim = startClaims[account];
return claim.action != bytes32(0) && claim.action == commitment && _current(INoerraStartAccount(account),claim);
}
}
src/agents/NoerraStartFunding.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {NoerraStartClaims, INoerraStartAccount} from "./NoerraStartClaims.sol";
interface INoerraStartFundingAccount is INoerraStartAccount {
function signer() external view returns (address);
function recoveryReserve() external view returns (uint256);
function maxRecoveryReimbursement() external view returns (uint256);
function recoveryBounty() external view returns (uint256);
function recoveryPolicyNonce() external view returns (uint256);
function releaseStarterFunds(uint256 generation, address recipient, uint256 amount) external;
}
/// @notice A stopped account funds its measured starter once per generation.
/// The grant goes to the persistent agent cash wallet; the bounty is paid only
/// after a second attestation binds the delivered, running replacement.
abstract contract NoerraStartFunding is NoerraStartClaims {
error InvalidStartFunding();
bytes32 public constant START_FUNDING_DOMAIN = keccak256("NOERRA_START_FUNDING_V3");
bytes32 public constant START_COMPLETION_DOMAIN = keccak256("NOERRA_START_COMPLETION_V3");
struct StartFunding {
address cash;
address operator;
uint256 reimbursement;
uint256 bounty;
uint256 policyNonce;
bytes32 runId;
uint256 deadline;
bool completed;
}
mapping(address => mapping(uint256 => StartFunding)) public startFunding;
event StartFunded(address indexed account, uint256 indexed generation, bytes32 indexed runId,
address cash, address operator, uint256 reimbursement, uint256 bounty, bool reused);
event StartCompleted(address indexed account, uint256 indexed generation, bytes32 indexed runId,
address receiver, address operator, bytes32 lease, bytes32 destination, uint256 bounty);
function _verifyStartFundingEvidence(bytes memory evidence, bytes32 commitment)
internal view virtual returns (bool);
/// @dev A claim whose run funded (or continued) the generation's start made progress: no claim cooldown.
function _startProgressed(address account, StartClaim storage claim) internal view override returns (bool) {
return super._startProgressed(account, claim) || startFunding[account][claim.generation].runId == claim.runId;
}
function startFundingCommitment(address account, bytes32 runId, address cash, address operator,
uint256 reimbursement, uint256 bounty) public view returns (bytes32) {
StartClaim memory claim = startClaims[account];
bytes memory prefix = abi.encode(START_FUNDING_DOMAIN, block.chainid, address(this), account,
claim.starter, runId, claim.generation, claim.pulse);
return keccak256(bytes.concat(prefix, abi.encode(claim.checkpoint, claim.build,
INoerraStartFundingAccount(account).recoveryPolicyNonce(), cash, operator, reimbursement, bounty)));
}
function _fundStart(address account, bytes32 runId, address cash, address operator,
uint256 reimbursement, uint256 bounty, bytes memory evidence) internal {
INoerraStartFundingAccount target = INoerraStartFundingAccount(account);
StartClaim memory claim = startClaims[account];
if (msg.sender != claim.starter || claim.runId != runId || !_current(target, claim) ||
cash == address(0) || cash == account || cash == claim.starter || cash == target.signer() ||
operator == address(0) || operator == account || reimbursement == 0 ||
!_verifyStartFundingEvidence(evidence,
startFundingCommitment(account, runId, cash, operator, reimbursement, bounty)))
revert InvalidStartFunding();
StartFunding storage row = startFunding[account][claim.generation];
bool reused = row.cash != address(0);
if (reused) {
// A failed starter never authorizes another draw. A newly admitted
// starter continues the same cash and can earn the unpaid bounty.
if (row.completed || row.cash != cash || row.reimbursement != reimbursement ||
row.bounty != bounty || row.policyNonce != target.recoveryPolicyNonce())
revert InvalidStartFunding();
} else {
// The account's caps are read once, here, when the grant is first funded (a continuing starter reuses the record).
if (reimbursement > target.maxRecoveryReimbursement() || bounty < target.recoveryBounty() ||
bounty > _maxBounty(account) || target.recoveryReserve() < reimbursement + bounty) revert InvalidStartFunding();
row.cash = cash;
row.reimbursement = reimbursement;
row.bounty = bounty;
row.policyNonce = target.recoveryPolicyNonce();
}
// Reimbursement and bounty are checked against the account's gas-bounded caps once, at first funding, and
// recorded; the grant, any continuing starter and the completion bounty use these recorded values (the account bounds
// the releases by its escrow), so a later base-fee or price move can neither strand nor raise them.
row.operator = operator;
row.runId = runId;
row.deadline = claim.maximumUntil + START_CLAIM_WINDOW;
if (!reused) target.releaseStarterFunds(claim.generation, cash, reimbursement);
emit StartFunded(account, claim.generation, runId, cash, operator, reimbursement, bounty, reused);
}
/// @dev The account's gas-bounded bounty cap (maxRecoveryBounty); accounts without it keep the exact bounty.
function _maxBounty(address account) private view returns (uint256) {
(bool ok, bytes memory answer) = account.staticcall(abi.encodeWithSignature("maxRecoveryBounty()"));
return ok && answer.length == 32 ? abi.decode(answer, (uint256)) : INoerraStartFundingAccount(account).recoveryBounty();
}
function startCompletionCommitment(address account, uint256 generation, bytes32 runId,
bytes32 lease, bytes32 destination) public view returns (bytes32) {
INoerraStartFundingAccount target = INoerraStartFundingAccount(account);
StartFunding memory row = startFunding[account][generation];
// All fields are static ABI words, so concatenation preserves the original commitment.
bytes memory prefix = abi.encode(START_COMPLETION_DOMAIN, block.chainid, address(this), account,
generation, runId, row.cash, row.operator);
return keccak256(bytes.concat(prefix, abi.encode(row.reimbursement, row.bounty, row.policyNonce,
target.generation(), target.signer(), target.buildHash(), lease, destination)));
}
function _completeStart(address account, uint256 generation, bytes32 runId, bytes32 lease,
bytes32 destination, bytes memory evidence) internal {
INoerraStartFundingAccount target = INoerraStartFundingAccount(account);
StartFunding storage row = startFunding[account][generation];
StartClaim memory claim = startClaims[account];
if (row.cash == address(0) || row.completed || row.runId != runId || block.timestamp > row.deadline ||
claim.runId != runId || claim.generation != generation || claim.starter != msg.sender ||
claim.action == bytes32(0) || claim.build != target.buildHash() || target.generation() != generation + 1 ||
target.signer() == claim.starter || row.policyNonce != target.recoveryPolicyNonce() ||
lease == bytes32(0) || destination == bytes32(0) ||
!_verifyStartFundingEvidence(evidence,
startCompletionCommitment(account, generation, runId, lease, destination)))
revert InvalidStartFunding();
row.completed = true;
// C-7: the recovered generation (one below the account's) marks the completion bounty, never a new grant.
if (row.bounty != 0) target.releaseStarterFunds(generation, row.operator, row.bounty);
emit StartCompleted(account, generation + 1, runId, target.signer(), row.operator,
lease, destination, row.bounty);
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@openzeppelin/=lib/openzeppelin-contracts/",
":@uniswap/v4-core/=lib/uniswap-v4-core/",
":@uniswap/v4-periphery/=lib/uniswap-v4-periphery-lite/",
":forge-std/=lib/forge-std/src/",
":solmate/=lib/solmate/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.