Verified contractPartialUNLICENSED
AgentSessionPolicyFactory
Address0x6f1b702c2c2923c3f9c8ff63260a7ac2dcc66bd8
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,500,851
- Creation transaction
- 0x31fc2f8c54…9011421af5
7 files
- contracts/session/AgentSessionPolicyFactory.solmain2.33 KB
- contracts/interfaces/ISessionManager.sol10.05 KB
- contracts/session/AgentSessionPolicy.sol12.56 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol653 B
- lib/openzeppelin-contracts/contracts/utils/Create2.sol4.47 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.82 KB
contracts/session/AgentSessionPolicyFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {Create2} from "@openzeppelin/contracts/utils/Create2.sol";
import {AgentSessionPolicy} from "./AgentSessionPolicy.sol";
/// @notice Chain-agnostic deterministic factory for v2 multi-target AgentSessionPolicy delegates.
contract AgentSessionPolicyFactory {
uint256 public constant VERSION = 2;
event PolicyCreated(
address indexed owner,
address indexed policy,
bytes32 indexed sessionId,
address manager,
bytes32 rulesHash
);
error UnsupportedChain();
error InvalidManager();
error TargetNotAllowed(address target);
/// @notice Deploy a grant's policy delegate. The owner still has to register it with SessionManager.
/// @dev Anyone can deploy the exact configuration. Repeating a deployment returns the same delegate.
function deploy(
AgentSessionPolicy.Grant calldata grant,
AgentSessionPolicy.ActionRule[] calldata rules
)
external
returns (AgentSessionPolicy)
{
if (block.chainid != grant.chainId) revert UnsupportedChain();
if (address(grant.manager) == address(0) || address(grant.manager).code.length == 0) {
revert InvalidManager();
}
address predicted = predict(grant, rules);
if (predicted.code.length != 0) return AgentSessionPolicy(predicted);
uint256 len = rules.length;
for (uint256 i = 0; i < len; ++i) {
address target = rules[i].target;
if (!grant.manager.allowedTarget(target)) {
revert TargetNotAllowed(target);
}
}
AgentSessionPolicy policy = new AgentSessionPolicy{salt: grant.salt}(grant, rules);
emit PolicyCreated(
grant.owner, address(policy), policy.sessionId(), address(grant.manager), policy.rulesHash()
);
return policy;
}
function predict(
AgentSessionPolicy.Grant calldata grant,
AgentSessionPolicy.ActionRule[] calldata rules
)
public
view
returns (address)
{
bytes32 initHash = keccak256(
abi.encodePacked(type(AgentSessionPolicy).creationCode, abi.encode(grant, rules))
);
return Create2.computeAddress(grant.salt, initHash);
}
}
contracts/interfaces/ISessionManager.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title ISessionManager
/// @notice On-chain registry + validator for bounded "session keys" delegated by a user.
/// @dev
/// # Third-party integration (target contracts)
/// A "target contract" is a contract that wants to accept delegate-signed calls on behalf of a user.
/// Targets must be explicitly allowlisted by the SessionManager owner.
///
/// Typical integration flow inside a target contract function:
/// 1) Recompute a target-specific `dataHash` from the actual call parameters and require it matches
/// `SessionCall.dataHash`. `SessionManager` does not interpret `dataHash`; it is only signed and replay-protected.
/// 2) Call `validateAndConsume(spendToken, spendAmount, call, delegateSignature, msg.sender)`:
/// - `msg.sender` (in the target) is treated as the `executor` (relayer/bundler) and must equal `call.executor`.
/// - One unordered nonce is consumed and `nonces[sessionId]` increments as a call counter.
/// - `spendToken`/`spendAmount` are accounted against `tokenAllowance` (decremented per call).
/// 3) Use the returned `(owner_, delegate, maxFeeBps)` to determine the payer (`owner_`) and to bound relayer fees.
///
/// IMPORTANT: `spendToken` / `spendAmount` are provided by the target and are not part of `SessionCall`.
/// Targets should pass the actual token/amount spent on behalf of `owner_` and should include those values in their
/// `dataHash` scheme so the delegate signature binds them.
///
/// # Offchain signing notes
/// - `sessionId = keccak256(abi.encode(owner, delegate, salt))` (see `computeSessionId`).
/// - Delegates sign EIP-712 typed data for `SessionCall` where `target` is the target contract address.
/// - `SessionCall.nonce` is unordered; nonce N+1 can be consumed before nonce N.
/// - `nonces(sessionId)` is a consumed-call counter used to enforce `maxCalls`, not the next required nonce.
///
/// ## EIP-712 details (reference `SessionManager` implementation)
/// - Domain: name = "FT SessionManager", version = "1".
/// - Types (exact strings):
/// - "AssetLimit(address token,uint256 limit)"
/// - "Session(address owner,address delegate,uint48 validAfter,uint48 validUntil,uint32 maxCalls,uint16 maxFeeBps,AssetLimit[] limits,bytes32 salt)"
/// - "SessionCall(bytes32 sessionId,address target,bytes32 dataHash,uint256 nonce,uint256 deadline,address executor,uint256 feeAmount)"
/// - "RevokeSession(bytes32 sessionId,uint256 deadline)"
/// - "InvalidateNonce(bytes32 sessionId,uint256 nonce,uint256 deadline,address executor)"
/// - `limits` is order-sensitive and is encoded as `keccak256(abi.encodePacked(keccak256(AssetLimit[0]), ...))`.
/// - `target` is the target contract address (validated on-chain as `msg.sender` in `validateAndConsume`).
interface ISessionManager {
// ===== Types =====
struct AssetLimit {
address token;
uint256 limit;
}
struct SessionConfig {
address owner;
address delegate;
uint48 validAfter;
uint48 validUntil; // 0 = no expiry
uint32 maxCalls; // 0 = unlimited (requires validUntil != 0)
uint16 maxFeeBps; // max relayer fee vs amount out (0 = no fee)
}
struct SessionCall {
bytes32 sessionId;
bytes32 dataHash; // target-specific hash of call parameters (incl selector)
uint256 nonce; // unordered nonce; can be consumed in any order
uint256 deadline; // 0 = no per-call deadline
address executor; // relayer/bundler that must submit this call
uint256 feeAmount; // relayer fee amount (token defined by target)
}
// ===== Events =====
event SessionCreated(
bytes32 indexed sessionId,
address indexed owner,
address indexed delegate,
uint48 validAfter,
uint48 validUntil,
uint32 maxCalls,
uint16 maxFeeBps
);
event SessionRevoked(bytes32 indexed sessionId, address indexed owner);
event SessionConsumed(
bytes32 indexed sessionId,
address indexed owner,
address indexed target,
address executor,
uint256 nonce,
bytes32 dataHash,
address spendToken,
uint256 spendAmount,
uint256 feeAmount
);
event AllowedTargetUpdated(address indexed target, bool allowed);
event NonceInvalidated(
bytes32 indexed sessionId, address indexed delegate, uint256 invalidatedNonce
);
// ===== Errors =====
error ZeroAddress();
error InvalidSessionWindow(uint48 validAfter, uint48 validUntil);
error SessionExpiryTooSoon(uint48 validUntil, uint48 minValidUntil);
error SessionMustHaveExpiryOrCallLimit();
error SessionAlreadyExists(bytes32 sessionId);
error SessionNotFound(bytes32 sessionId);
error SessionIsRevoked(bytes32 sessionId);
error SessionNotYetValid(bytes32 sessionId, uint48 validAfter);
error SessionExpired(bytes32 sessionId, uint48 validUntil);
error SessionCallsExceeded(bytes32 sessionId, uint32 maxCalls);
error DeadlineExpired(uint256 deadline, uint256 currentTime);
error InvalidNonce(uint256 expected, uint256 provided);
error InvalidSignature();
error NotSessionOwner(bytes32 sessionId, address caller);
error TargetNotAllowed(address target);
error DuplicateAsset(address token);
error AssetNotAllowed(address token);
error AssetLimitExceeded(address token, uint256 requested, uint256 remaining);
error ExecutorMismatch(address expected, address actual);
error ExecutorCannotBeDelegate(address delegate);
error InvalidMaxFeeBps(uint16 maxFeeBps);
error NonceMismatch(uint256 expected, uint256 provided);
// ===== Constants (as getters) =====
function BPS() external pure returns (uint256);
function MIN_SESSION_DURATION() external pure returns (uint48);
// ===== View =====
function sessions(bytes32 sessionId)
external
view
returns (
address owner,
address delegate,
uint48 validAfter,
uint48 validUntil,
uint32 maxCalls,
uint16 maxFeeBps
);
function revoked(bytes32 sessionId) external view returns (bool);
function nonces(bytes32 sessionId) external view returns (uint256);
function allowedTarget(address target) external view returns (bool);
/// @notice Returns the number of delegate calls consumed for a session.
/// @dev This is the value used to enforce `maxCalls`; unordered nonce values may be sparse.
function usedCallCount(bytes32 sessionId) external view returns (uint256 count);
/// @notice Returns whether an unordered nonce has already been consumed or invalidated.
function isNonceUsed(bytes32 sessionId, uint256 nonce) external view returns (bool used);
/// @notice Returns the raw 256-bit unordered nonce bitmap word for relayer/UI batching.
function nonceBitmapWord(
bytes32 sessionId,
uint248 wordPos
)
external
view
returns (uint256 bitmap);
/// @notice Remaining per-session per-asset allowance.
/// @dev `type(uint256).max` matches ERC-20 allowance semantics: "infinite" allowance (no decrement).
function tokenAllowance(bytes32 sessionId, address token) external view returns (uint256);
// ===== Mutations =====
function computeSessionId(
address owner_,
address delegate,
bytes32 salt
)
external
pure
returns (bytes32 sessionId);
function createSession(
address delegate,
uint48 validAfter,
uint48 validUntil,
uint32 maxCalls,
uint16 maxFeeBps,
AssetLimit[] calldata limits,
bytes32 salt
)
external
returns (bytes32 sessionId);
function createSessionBySig(
address owner_,
address delegate,
uint48 validAfter,
uint48 validUntil,
uint32 maxCalls,
uint16 maxFeeBps,
AssetLimit[] calldata limits,
bytes32 salt,
bytes calldata ownerSignature
)
external
returns (bytes32 sessionId);
function revokeSession(bytes32 sessionId) external;
function revokeSessionBySig(
bytes32 sessionId,
uint256 deadline,
bytes calldata ownerSignature
)
external;
function setAllowedTarget(address target, bool allowed) external;
function setAllowedTargets(address[] calldata targets, bool allowed) external;
/// @notice Invalidate an unordered session nonce without revoking the entire session.
/// @param sessionId The session to invalidate the nonce for.
/// @param nonce The unordered nonce to invalidate.
/// @param deadline Signature expiry (0 = no deadline).
/// @param executor The address authorized to submit this invalidation (must be msg.sender).
/// @param delegateSignature EIP-712 signature from the session delegate.
function invalidateNonceBySig(
bytes32 sessionId,
uint256 nonce,
uint256 deadline,
address executor,
bytes calldata delegateSignature
)
external;
/// @notice Validate a delegate-signed call and consume one session nonce.
/// @dev Can only be called by the target contract that will execute the action.
/// @param spendToken Token being spent from the session owner (0 if none).
/// @param spendAmount Amount being spent (0 if none).
/// @param call Session call intent signed by the delegate.
/// @param delegateSignature Signature from the session delegate over `call`.
/// @param executor The relayer/bundler address that submitted the target tx (target should pass `msg.sender`).
function validateAndConsume(
address spendToken,
uint256 spendAmount,
SessionCall calldata call,
bytes calldata delegateSignature,
address executor
)
external
returns (address owner_, address delegate, uint16 maxFeeBps);
}
contracts/session/AgentSessionPolicy.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {ISessionManager} from "../interfaces/ISessionManager.sol";
/// @notice Immutable ERC-1271 delegate enforcing owner-bound multi-target SessionManager policies.
contract AgentSessionPolicy is IERC1271 {
/// @notice Owner-bound session identity, lifetime, call budget, and relayer constraints.
struct Grant {
uint256 chainId;
ISessionManager manager;
address owner;
address signer;
address executor;
bytes32 salt;
uint48 validAfter;
uint48 validUntil;
uint32 maxCalls;
uint16 maxFeeBps;
}
/// @notice Per-(target, actionTypeHash) authorization rule with optional token, amount, fee, and cumulative bounds.
/// @dev Action dataHash is reconstructed as keccak256(bytes.concat(actionTypeHash, params)), where params has
/// exact length expectedWords * 32. Set amountWordIndex, tokenWordIndex, or feeWordIndex to NO_WORD (255)
/// when unused.
struct ActionRule {
address target;
uint8 expectedWords;
uint8 amountWordIndex;
uint8 tokenWordIndex;
uint8 feeWordIndex;
bytes32 actionTypeHash;
address allowedToken;
address spendToken;
uint128 maxAmount;
uint128 totalSpendLimit;
uint128 maxFee;
}
/// @dev The signature envelope is:
/// abi.encode(Authorization) [160 bytes] || params [expectedWords * 32 bytes] || sig [65 bytes (r || s || v)].
struct Authorization {
uint256 version;
uint256 ruleIndex;
uint256 nonce;
uint256 deadline;
uint256 fee;
}
uint256 public constant VERSION = 2;
uint256 public constant MAX_CALL_LIFETIME = 2 minutes;
uint256 public constant MAX_RULES = 32;
uint8 public constant MAX_PAYLOAD_WORDS = 16;
uint8 public constant NO_WORD = type(uint8).max;
uint256 private constant _HEADER_LENGTH = 5 * 32;
uint256 private constant _BPS = 10_000;
bytes4 private constant _INVALID = 0xffffffff;
bytes32 private constant _DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant _CALL_TYPEHASH = keccak256(
"SessionCall(bytes32 sessionId,address target,bytes32 dataHash,uint256 nonce,uint256 deadline,address executor,uint256 feeAmount)"
);
uint256 public immutable chainId;
ISessionManager public immutable manager;
address public immutable owner;
address public immutable signer;
address public immutable executor;
bytes32 public immutable salt;
uint48 public immutable validAfter;
uint48 public immutable validUntil;
uint32 public immutable maxCalls;
uint16 public immutable maxFeeBps;
bytes32 public immutable sessionId;
bytes32 public immutable domainSeparator;
bytes32 public immutable rulesHash;
uint256 public immutable ruleCount;
ActionRule[] private _rules;
error InvalidGrant();
error InvalidRules();
error InvalidRule(uint256 index);
error TargetNotAllowed(address target);
constructor(Grant memory grant, ActionRule[] memory rules) {
if (
block.chainid != grant.chainId || address(grant.manager) == address(0)
|| address(grant.manager).code.length == 0 || grant.owner == address(0)
|| grant.signer == address(0) || grant.executor == address(0)
|| grant.signer == grant.executor || grant.validUntil <= block.timestamp
|| grant.validUntil <= grant.validAfter || grant.maxCalls == 0
|| grant.maxFeeBps >= _BPS
) revert InvalidGrant();
uint256 len = rules.length;
if (len == 0 || len > MAX_RULES) revert InvalidRules();
for (uint256 i = 0; i < len; ++i) {
ActionRule memory rule = rules[i];
if (
rule.target == address(0) || rule.actionTypeHash == bytes32(0)
|| rule.expectedWords > MAX_PAYLOAD_WORDS
) revert InvalidRule(i);
if (!grant.manager.allowedTarget(rule.target)) {
revert TargetNotAllowed(rule.target);
}
if (rule.amountWordIndex != NO_WORD) {
if (rule.amountWordIndex >= rule.expectedWords || rule.maxAmount == 0) {
revert InvalidRule(i);
}
} else if (rule.maxAmount != 0) {
revert InvalidRule(i);
}
if (rule.tokenWordIndex != NO_WORD) {
if (rule.tokenWordIndex >= rule.expectedWords || rule.allowedToken == address(0)) {
revert InvalidRule(i);
}
} else if (rule.allowedToken != address(0)) {
revert InvalidRule(i);
}
if (rule.feeWordIndex != NO_WORD && rule.feeWordIndex >= rule.expectedWords) {
revert InvalidRule(i);
}
if (
(rule.tokenWordIndex != NO_WORD && rule.tokenWordIndex == rule.amountWordIndex)
|| (rule.tokenWordIndex != NO_WORD && rule.tokenWordIndex == rule.feeWordIndex)
|| (rule.amountWordIndex != NO_WORD
&& rule.amountWordIndex == rule.feeWordIndex)
) {
revert InvalidRule(i);
}
if (rule.spendToken != address(0)) {
if (
rule.totalSpendLimit == 0
|| (rule.amountWordIndex != NO_WORD && rule.maxAmount > rule.totalSpendLimit)
) revert InvalidRule(i);
} else if (rule.totalSpendLimit != 0) {
revert InvalidRule(i);
}
if (rule.maxFee != 0 && grant.maxFeeBps == 0) {
revert InvalidRule(i);
}
for (uint256 j = 0; j < i; ++j) {
ActionRule memory prev = rules[j];
if (rule.target == prev.target && rule.actionTypeHash == prev.actionTypeHash) {
if (
rule.expectedWords != prev.expectedWords
|| rule.tokenWordIndex != prev.tokenWordIndex
|| rule.amountWordIndex != prev.amountWordIndex
|| rule.feeWordIndex != prev.feeWordIndex
|| rule.tokenWordIndex == NO_WORD
|| rule.allowedToken == prev.allowedToken
) {
revert InvalidRule(i);
}
}
}
_rules.push(rule);
}
chainId = grant.chainId;
manager = grant.manager;
owner = grant.owner;
signer = grant.signer;
executor = grant.executor;
salt = grant.salt;
validAfter = grant.validAfter;
validUntil = grant.validUntil;
maxCalls = grant.maxCalls;
maxFeeBps = grant.maxFeeBps;
sessionId = keccak256(abi.encode(grant.owner, address(this), grant.salt));
domainSeparator = keccak256(
abi.encode(
_DOMAIN_TYPEHASH,
keccak256("FT SessionManager"),
keccak256("1"),
grant.chainId,
grant.manager
)
);
rulesHash = keccak256(abi.encode(rules));
ruleCount = len;
}
/// @notice Returns the immutable authorization rule at `index`.
function getRule(uint256 index) external view returns (ActionRule memory) {
return _rules[index];
}
/// @inheritdoc IERC1271
/// @dev Enforces policy rules, revocation, nonce freshness, call count, and manager session invariants directly.
function isValidSignature(
bytes32 digest,
bytes calldata envelope
)
external
view
returns (bytes4)
{
if (block.chainid != chainId || envelope.length < _HEADER_LENGTH + 65) {
return _INVALID;
}
Authorization memory auth = abi.decode(envelope[:_HEADER_LENGTH], (Authorization));
if (
auth.version != VERSION || auth.ruleIndex >= ruleCount || block.timestamp < validAfter
|| block.timestamp >= validUntil || auth.deadline == 0
|| auth.deadline < block.timestamp || auth.deadline > validUntil
|| auth.deadline - block.timestamp > MAX_CALL_LIFETIME
) return _INVALID;
ActionRule memory rule = _rules[auth.ruleIndex];
uint256 paramsLen = uint256(rule.expectedWords) * 32;
if (envelope.length != _HEADER_LENGTH + paramsLen + 65) {
return _INVALID;
}
if (auth.fee > rule.maxFee || (auth.fee != 0 && maxFeeBps == 0)) {
return _INVALID;
}
if (!manager.allowedTarget(rule.target)) {
return _INVALID;
}
bytes calldata params = envelope[_HEADER_LENGTH:_HEADER_LENGTH + paramsLen];
if (rule.tokenWordIndex != NO_WORD) {
uint256 tokenOffset = uint256(rule.tokenWordIndex) * 32;
bytes32 tokenWord = bytes32(params[tokenOffset:tokenOffset + 32]);
if (tokenWord != bytes32(uint256(uint160(rule.allowedToken)))) {
return _INVALID;
}
}
uint256 amount;
if (rule.amountWordIndex != NO_WORD) {
uint256 amountOffset = uint256(rule.amountWordIndex) * 32;
amount = uint256(bytes32(params[amountOffset:amountOffset + 32]));
if (amount == 0 || amount > rule.maxAmount) {
return _INVALID;
}
}
if (rule.feeWordIndex != NO_WORD) {
uint256 feeOffset = uint256(rule.feeWordIndex) * 32;
uint256 payloadFee = uint256(bytes32(params[feeOffset:feeOffset + 32]));
if (payloadFee > rule.maxFee || (payloadFee != 0 && maxFeeBps == 0)) {
return _INVALID;
}
}
bytes32 dataHash = keccak256(bytes.concat(rule.actionTypeHash, params));
bytes32 callHash = keccak256(
abi.encode(
_CALL_TYPEHASH,
sessionId,
rule.target,
dataHash,
auth.nonce,
auth.deadline,
executor,
auth.fee
)
);
if (digest != keccak256(abi.encodePacked(hex"1901", domainSeparator, callHash))) {
return _INVALID;
}
bytes calldata sig = envelope[_HEADER_LENGTH + paramsLen:];
uint8 v = uint8(sig[64]);
if (v != 27 && v != 28) return _INVALID;
(address recovered, ECDSA.RecoverError err,) =
ECDSA.tryRecover(digest, v, bytes32(sig[:32]), bytes32(sig[32:64]));
if (err != ECDSA.RecoverError.NoError || recovered != signer) return _INVALID;
if (!_matchesGrant(rule, amount, auth.nonce)) return _INVALID;
return IERC1271.isValidSignature.selector;
}
function _matchesGrant(
ActionRule memory rule,
uint256 amount,
uint256 nonce
)
private
view
returns (bool)
{
if (
manager.revoked(sessionId) || manager.usedCallCount(sessionId) >= maxCalls
|| manager.isNonceUsed(sessionId, nonce)
) return false;
(
address registeredOwner,
address delegate,
uint48 start,
uint48 end,
uint32 calls,
uint16 feeBps
) = manager.sessions(sessionId);
if (
registeredOwner != owner || delegate != address(this) || start != validAfter
|| end != validUntil || calls != maxCalls || feeBps != maxFeeBps
|| block.timestamp < start
) return false;
if (rule.spendToken != address(0)) {
uint256 remaining = manager.tokenAllowance(sessionId, rule.spendToken);
if (remaining == type(uint256).max || remaining > rule.totalSpendLimit) {
return false;
}
if (rule.amountWordIndex != NO_WORD) {
if (amount > remaining) return false;
} else if (remaining == 0) {
return false;
}
}
return true;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @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 _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
lib/openzeppelin-contracts/contracts/utils/Create2.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev There's no code to deploy.
*/
error Create2EmptyBytecode();
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (bytecode.length == 0) {
revert Create2EmptyBytecode();
}
assembly ("memory-safe") {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
// if no address was created, and returndata is not empty, bubble revert
if and(iszero(addr), not(iszero(returndatasize()))) {
let p := mload(0x40)
returndatacopy(p, 0, returndatasize())
revert(p, returndatasize())
}
}
if (addr == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
assembly ("memory-safe") {
let ptr := mload(0x40) // Get free memory pointer
// | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
// |-------------------|---------------------------------------------------------------------------|
// | bytecodeHash | CCCCCCCCCCCCC...CC |
// | salt | BBBBBBBBBBBBB...BB |
// | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
// | 0xFF | FF |
// |-------------------|---------------------------------------------------------------------------|
// | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
// | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
mstore8(start, 0xff)
addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 derives the `address(0)`.
*/
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.
*
* 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 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.
*
* 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 error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, 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 error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, 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 error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"forge-std/=lib/forge-std/src/",
"@ft-common/=contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.