Verified contractExactMIT
KSIntentInbox
Address0xd055ea582e936e480f780d2704178ef86aac006f
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 44,444,444 runs
- EVM version
- osaka
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,204,533
- Creation transaction
- 0x8c93e9ffb8…4d94cb4c41
27 files
- src/KSIntentInbox.solmain6.29 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/interfaces/IERC1155Receiver.sol213 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/interfaces/IERC721Receiver.sol209 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/proxy/Clones.sol14.52 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol2.6 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol1.34 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol819 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Address.sol6.8 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Create2.sol4.37 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol5.51 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Pausable.sol2.71 KB
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/ks-common-sc/src/base/Common.sol373 B
- lib/ks-common-sc/src/interfaces/ICommon.sol334 B
- lib/ks-common-sc/src/libraries/KSRoles.sol455 B
- src/base/DelegatecallGuard.sol800 B
- src/interfaces/IKSActionExecutor.sol528 B
- src/interfaces/IKSActionValidator.sol1.21 KB
- src/interfaces/IKSIntentInbox.sol3.27 KB
- src/interfaces/IKSIntentInboxFactory.sol2.61 KB
- src/types/ActionParams.sol2.18 KB
- src/types/IntentParams.sol2.95 KB
- src/types/ValidateParams.sol1.34 KB
src/KSIntentInbox.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
import {IKSIntentInbox} from './interfaces/IKSIntentInbox.sol';
import {IKSIntentInboxFactory} from './interfaces/IKSIntentInboxFactory.sol';
import {ActionParams, ActionParamsLibrary} from './types/ActionParams.sol';
import {IntentParams, IntentParamsLibrary} from './types/IntentParams.sol';
import {Clones} from 'openzeppelin-contracts/contracts/proxy/Clones.sol';
import {
ERC1155Holder
} from 'openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol';
import {ERC721Holder} from 'openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol';
import {Address} from 'openzeppelin-contracts/contracts/utils/Address.sol';
import {Pausable} from 'openzeppelin-contracts/contracts/utils/Pausable.sol';
import {Common} from 'ks-common-sc/src/base/Common.sol';
import {KSRoles} from 'ks-common-sc/src/libraries/KSRoles.sol';
import {DelegatecallGuard} from './base/DelegatecallGuard.sol';
/// @notice The KSIntentInbox contract is responsible for receiving tokens and executing intents
contract KSIntentInbox is
IKSIntentInbox,
Pausable,
ERC721Holder,
ERC1155Holder,
Common,
DelegatecallGuard
{
using Address for address;
using ActionParamsLibrary for ActionParams[];
/// @notice Role for the owner
bytes32 internal constant OWNER_ROLE = 0x00;
/// @notice Role for the mainActions operators and fallbackActions operators
bytes32 internal constant OPERATOR_MAIN_ACTION_ROLE = keccak256('OPERATOR_MAIN_ACTION_ROLE');
bytes32 internal constant OPERATOR_FALLBACK_ACTION_ROLE =
keccak256('OPERATOR_FALLBACK_ACTION_ROLE');
/// @notice The address of the KSIntentInboxFactory
IKSIntentInboxFactory internal immutable FACTORY;
constructor() {
FACTORY = IKSIntentInboxFactory(msg.sender);
}
/// @notice Checks if the intent params are valid
modifier checkIntentParams(address owner, IntentParams calldata intentParams) {
if (
Clones.predictDeterministicAddress(
SELF,
IntentParamsLibrary.computeInboxSalt(owner, intentParams.intentHash()),
address(FACTORY)
) != address(this)
) {
revert InvalidIntentParams(owner, intentParams);
}
_;
}
/// @notice Checks if the factory is not paused
/// @dev Kept separate from `whenNotPaused` so guardians can still `pause` an inbox while the
/// factory is paused
modifier whenFactoryNotPaused() {
if (Pausable(address(FACTORY)).paused()) {
revert EnforcedPause();
}
_;
}
/// @notice Checks if the sender is the owner
modifier checkOwner(bytes32 intentHash) {
if (
Clones.predictDeterministicAddress(
SELF, IntentParamsLibrary.computeInboxSalt(msg.sender, intentHash), address(FACTORY)
) != address(this)
) {
revert UnauthorizedAccount(msg.sender, OWNER_ROLE);
}
_;
}
/// @inheritdoc IKSIntentInbox
receive() external payable {}
/// @inheritdoc IKSIntentInbox
function execute(
address owner,
IntentParams calldata intentParams,
bytes[] calldata additionalData,
bool isMainAction
)
external
payable
onlyDelegatecall
whenNotPaused
whenFactoryNotPaused
checkIntentParams(owner, intentParams)
returns (bool[] memory successes, bytes[] memory results, uint256 gasUsed)
{
uint256 gasBefore = gasleft();
if (isMainAction) {
if (block.timestamp > intentParams.deadline) {
revert DeadlinePassed(intentParams.deadline);
}
// mainActions - check mainActionOperators (or allow anyone if empty)
if (intentParams.mainActionOperators.length > 0) {
// Allows to execute the intent from the factory
_checkRole(
OPERATOR_MAIN_ACTION_ROLE,
intentParams.mainActionOperators,
msg.sender == address(FACTORY) ? FACTORY.msgSender() : msg.sender
);
}
(successes, results) =
intentParams.mainActions.executeAll(additionalData, intentParams.mainActionValidateParams);
} else {
if (block.timestamp <= intentParams.deadline) {
revert DeadlineNotPassed(intentParams.deadline);
}
// fallbackActions - check fallbackActionOperators (or allow anyone if empty)
if (intentParams.fallbackActionOperators.length > 0) {
// Allows to execute the intent from the factory
_checkRole(
OPERATOR_FALLBACK_ACTION_ROLE,
intentParams.fallbackActionOperators,
msg.sender == address(FACTORY) ? FACTORY.msgSender() : msg.sender
);
}
(successes, results) = intentParams.fallbackActions
.executeAll(additionalData, intentParams.fallbackActionValidateParams);
}
emit ExecuteIntent(isMainAction, successes);
unchecked {
gasUsed = gasBefore - gasleft();
}
}
/// @inheritdoc IKSIntentInbox
/// @dev Not affected by Pausable
function multicall(
bytes32 intentHash,
address[] calldata targets,
bytes[] calldata data,
bool[] calldata isDelegateCalls
)
external
checkLengths(targets.length, data.length)
checkLengths(targets.length, isDelegateCalls.length)
checkOwner(intentHash)
returns (bytes[] memory results)
{
emit TriggerMulticall();
results = new bytes[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
if (isDelegateCalls[i]) {
results[i] = targets[i].functionDelegateCall(data[i]);
} else {
results[i] = targets[i].functionCall(data[i]);
}
}
}
/// @inheritdoc IKSIntentInbox
function pause(address owner, IntentParams calldata intentParams)
external
checkIntentParams(owner, intentParams)
{
_checkRole(KSRoles.GUARDIAN_ROLE, intentParams.guardians, msg.sender);
_pause();
}
/// @inheritdoc IKSIntentInbox
function unpause(bytes32 intentHash) external checkOwner(intentHash) {
_unpause();
}
/// @notice Checks if the account is in the given role accounts
function _checkRole(bytes32 role, address[] calldata roleAccounts, address account)
internal
view
{
for (uint256 i = 0; i < roleAccounts.length; i++) {
if (account == roleAccounts[i]) {
return;
}
}
revert UnauthorizedAccount(account, role);
}
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/interfaces/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1155Receiver.sol)
pragma solidity >=0.6.2;
import {IERC1155Receiver} from "../token/ERC1155/IERC1155Receiver.sol";
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/interfaces/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC721Receiver.sol)
pragma solidity >=0.5.0;
import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Clones.sol)
pragma solidity ^0.8.20;
import {Create2} from "../utils/Create2.sol";
import {Errors} from "../utils/Errors.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*/
library Clones {
error CloneArgumentsTooLong();
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create opcode, which should never revert.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function clone(address implementation) internal returns (address instance) {
return clone(implementation, 0);
}
/**
* @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
* to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function clone(address implementation, uint256 value) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
assembly ("memory-safe") {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(value, 0x09, 0x37)
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple times will revert, since
* the clones cannot be deployed twice at the same address.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
return cloneDeterministic(implementation, salt, 0);
}
/**
* @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
* a `value` parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneDeterministic(
address implementation,
bytes32 salt,
uint256 value
) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
assembly ("memory-safe") {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(value, 0x09, 0x37, salt)
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
* immutable arguments. These are provided through `args` and cannot be changed after deployment. To
* access the arguments within the implementation, use {fetchCloneArgs}.
*
* This function uses the create opcode, which should never revert.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
return cloneWithImmutableArgs(implementation, args, 0);
}
/**
* @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
* parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneWithImmutableArgs(
address implementation,
bytes memory args,
uint256 value
) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
assembly ("memory-safe") {
instance := create(value, add(bytecode, 0x20), mload(bytecode))
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
* immutable arguments. These are provided through `args` and cannot be changed after deployment. To
* access the arguments within the implementation, use {fetchCloneArgs}.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
* `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
* at the same address.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneDeterministicWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt
) internal returns (address instance) {
return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
}
/**
* @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
* but with a `value` parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneDeterministicWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt,
uint256 value
) internal returns (address instance) {
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
return Create2.deploy(value, salt, bytecode);
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
*/
function predictDeterministicAddressWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
return Create2.computeAddress(salt, keccak256(bytecode), deployer);
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
*/
function predictDeterministicAddressWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
}
/**
* @dev Get the immutable args attached to a clone.
*
* - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
* function will return an empty array.
* - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
* `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
* creation.
* - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
* function should only be used to check addresses that are known to be clones.
*/
function fetchCloneArgs(address instance) internal view returns (bytes memory) {
bytes memory result = new bytes(instance.code.length - 0x2d); // revert if length is too short
assembly ("memory-safe") {
extcodecopy(instance, add(result, 0x20), 0x2d, mload(result))
}
return result;
}
/**
* @dev Helper that prepares the initcode of the proxy with immutable args.
*
* An assembly variant of this function requires copying the `args` array, which can be efficiently done using
* `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
* abi.encodePacked is more expensive but also more portable and easier to review.
*
* NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
* With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
*/
function _cloneCodeWithImmutableArgs(
address implementation,
bytes memory args
) private pure returns (bytes memory) {
if (args.length > 0x5fd3) revert CloneArgumentsTooLong();
return
abi.encodePacked(
hex"61",
uint16(args.length + 0x2d),
hex"3d81600a3d39f3363d3d373d3d3d363d73",
implementation,
hex"5af43d82803e903d91602b57fd5bf3",
args
);
}
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.20;
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
/**
* @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*
* @custom:stateless
*/
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
* {IERC721-setApprovalForAll}.
*
* @custom:stateless
*/
abstract contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
return this.onERC721Received.selector;
}
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bool success = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
bool success = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
bool success = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
lib/ks-common-sc/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/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Create2.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Create2.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.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 (addr == address(0)) {
if (LowLevelCall.returnDataSize() == 0) {
revert Errors.FailedDeployment();
} else {
LowLevelCall.bubbleRevert();
}
}
}
/**
* @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, 0x55) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
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, 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
}
lib/ks-common-sc/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/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
lib/ks-common-sc/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/ks-common-sc/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/ks-common-sc/src/base/Common.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ICommon} from '../interfaces/ICommon.sol';
contract Common is ICommon {
modifier checkAddress(address addr) {
require(addr != address(0), InvalidAddress());
_;
}
modifier checkLengths(uint256 length1, uint256 length2) {
require(length1 == length2, MismatchedArrayLengths());
_;
}
}
lib/ks-common-sc/src/interfaces/ICommon.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title ICommon
/// @notice Common interface for all contracts
interface ICommon {
/// @notice Thrown when trying to update with zero address
error InvalidAddress();
/// @notice Thrown when the lengths of the arrays are mismatched
error MismatchedArrayLengths();
}
lib/ks-common-sc/src/libraries/KSRoles.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for managing roles for KyberSwap
library KSRoles {
/// @notice Role for the operators
bytes32 internal constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE');
/// @notice Role for the guardians
bytes32 internal constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE');
/// @notice Role for the rescuers
bytes32 internal constant RESCUER_ROLE = keccak256('RESCUER_ROLE');
}
src/base/DelegatecallGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Restricts functions to only be invoked via a delegatecall (e.g. from a clone),
/// reverting on direct calls to the deployed implementation.
contract DelegatecallGuard {
/// @notice Thrown when a delegatecall-only function is called directly on the implementation.
error OnlyDelegatecall();
/// @notice The address of this contract as deployed (the implementation), used to detect direct
/// (non-delegatecall) invocations.
address internal immutable SELF;
constructor() {
SELF = address(this);
}
/// @notice Checks that the call arrived via delegatecall, not directly on the implementation
modifier onlyDelegatecall() {
if (address(this) == SELF) {
revert OnlyDelegatecall();
}
_;
}
}
src/interfaces/IKSActionExecutor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the KSActionExecutor
interface IKSActionExecutor {
/**
* @notice Executes an action
* @param intentData The data of the execution, which includes the token and the action-specific data
* @param additionalData The additional data for the action
* @return result The result of the action
*/
function execute(bytes calldata intentData, bytes calldata additionalData)
external
payable
returns (bytes memory result);
}
src/interfaces/IKSActionValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the KSActionValidator
interface IKSActionValidator {
/// @notice Thrown when the validation type is invalid
error InvalidValidateType(bytes32 validateType);
/**
* @notice Returns the state before execution
* @param validateType The type of validation
* @param _beforeExecutionInput The before execution input
* @return _beforeExecutionOutput The output representing the state before execution
*/
function beforeExecution(bytes32 validateType, bytes calldata _beforeExecutionInput)
external
returns (bytes memory _beforeExecutionOutput);
/**
* @notice Validates the current state after execution against the state before execution
* @param validateType The type of validation
* @param _beforeExecutionInput The before execution input
* @param _beforeExecutionOutput The output returned by the beforeExecution function
* @param _afterExecutionInput The after execution input
*/
function afterExecution(
bytes32 validateType,
bytes calldata _beforeExecutionInput,
bytes calldata _beforeExecutionOutput,
bytes calldata _afterExecutionInput
) external;
}
src/interfaces/IKSIntentInbox.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC1155Receiver} from 'openzeppelin-contracts/contracts/interfaces/IERC1155Receiver.sol';
import {IERC721Receiver} from 'openzeppelin-contracts/contracts/interfaces/IERC721Receiver.sol';
import {IntentParams} from '../types/IntentParams.sol';
/// @notice Interface for the KSIntentInbox
interface IKSIntentInbox is IERC721Receiver, IERC1155Receiver {
/// @notice Thrown when the intent params are invalid
error InvalidIntentParams(address owner, IntentParams intentParams);
/// @notice Thrown when the account is missing a role
error UnauthorizedAccount(address account, bytes32 neededRole);
/// @notice Thrown when the main actions are executed after the deadline has passed
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when the fallback actions are executed before the deadline has passed
error DeadlineNotPassed(uint256 deadline);
/// @notice Emitted when the multicall is triggered
event TriggerMulticall();
/**
* @notice Emitted when the intent is executed
* @param isMainAction Whether the main actions were executed (false: the fallback actions)
* @param successes Whether each executed action succeeded, one entry per action
*/
event ExecuteIntent(bool isMainAction, bool[] successes);
/// @notice Receives native currency
receive() external payable;
/**
* @notice Executes an intent
* @param owner The owner of the intent
* @param intentParams The parameters of the intent
* @param additionalData The additional data for each action, one entry per action executed
* @param isMainAction Which batch to execute: true runs `mainActions` (only until the deadline),
* false runs `fallbackActions` (only once the deadline has passed)
* @return successes Whether each executed action succeeded, one entry per action
* @return results The results of each executed action, one entry per action
* @return gasUsed The amount of gas used by this call
*/
function execute(
address owner,
IntentParams calldata intentParams,
bytes[] calldata additionalData,
bool isMainAction
) external payable returns (bool[] memory successes, bytes[] memory results, uint256 gasUsed);
/**
* @notice Calls multiple functions on multiple contracts
* Can only be called by the owner
* @param intentHash The hash of the intent params
* @param targets The targets to call
* @param data The data to call the targets with
* @param isDelegateCalls Whether to call the targets with delegate calls
* @return results The results of the calls
*/
function multicall(
bytes32 intentHash,
address[] calldata targets,
bytes[] calldata data,
bool[] calldata isDelegateCalls
) external returns (bytes[] memory results);
/**
* @notice Pauses the contract
* Can only be called by the guardians
* @param owner The owner of the intent
* @param intentParams The parameters of the intent
*/
function pause(address owner, IntentParams calldata intentParams) external;
/**
* @notice Unpauses the contract
* Can only be called by the owner
* @param intentHash The hash of the intent params
*/
function unpause(bytes32 intentHash) external;
}
src/interfaces/IKSIntentInboxFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IntentParams} from '../types/IntentParams.sol';
/// @notice Interface for the KSIntentInboxFactory
interface IKSIntentInboxFactory {
/// @notice Thrown when the intent inbox already exists
error IntentInboxAlreadyExists(address intentInbox);
/// @notice Emitted when a new KSIntentInbox is created
event CreateIntentInbox(address indexed intentInbox, address indexed owner, bytes32 intentHash);
/**
* @notice Creates a new KSIntentInbox
* @param owner The owner of the intent
* @param intentHash The hash of the intent params
* @return intentInbox The address of the created KSIntentInbox
*/
function create(address owner, bytes32 intentHash) external returns (address intentInbox);
/**
* @notice Creates the KSIntentInbox if it does not exist yet, then executes it
* @param owner The owner of the intent
* @param intentParams The parameters of the intent
* @param additionalData The additional data for each action, one entry per action executed
* @param isMainAction Which batch to execute: true runs `mainActions` (only until the deadline),
* false runs `fallbackActions` (only once the deadline has passed)
* @param allowFailure If true, a failed execution is caught and the call still succeeds (keeping
* the created inbox and refunding `msg.value`); if false, the whole call reverts with the
* execution's revert reason
* @return intentInbox The address of the created KSIntentInbox
* @return createSuccess Whether the creation of the intent inbox was successful
* @return executeSuccess Whether the execution of the intent was successful
* @return successes Whether each executed action succeeded, one entry per action
* @return results The results of each executed action, one entry per action
* @return createGasUsed The amount of gas used to create the KSIntentInbox, 0 if it already existed
* @return executeGasUsed The amount of gas used by the execution of the intent
*/
function createAndExecute(
address owner,
IntentParams calldata intentParams,
bytes[] calldata additionalData,
bool isMainAction,
bool allowFailure
)
external
payable
returns (
address intentInbox,
bool createSuccess,
bool executeSuccess,
bool[] memory successes,
bytes[] memory results,
uint256 createGasUsed,
uint256 executeGasUsed
);
/// @notice Returns the address which called `createAndExecute`
function msgSender() external view returns (address msgSender);
}
src/types/ActionParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IKSActionExecutor} from '../interfaces/IKSActionExecutor.sol';
import {ValidateParams} from './ValidateParams.sol';
import {ICommon} from 'ks-common-sc/src/interfaces/ICommon.sol';
import {LowLevelCall} from 'openzeppelin-contracts/contracts/utils/LowLevelCall.sol';
/// @notice Contains the parameters for an action
/// @param allowFailure If the action's delegatecall fails: true ignores the failure (the action's
/// result is its raw revert data), false reverts the whole batch.
struct ActionParams {
address actionTarget;
bytes actionData;
bool allowFailure;
}
/// @notice Contains functions for processing action params
library ActionParamsLibrary {
/// @notice Executes each action in order and validates the final result against validateParams; an
/// action whose delegatecall fails reverts the whole batch unless its allowFailure is
/// true, in which case its result is its raw revert data and the batch continues
function executeAll(
ActionParams[] calldata self,
bytes[] calldata additionalData,
ValidateParams[] calldata validateParams
) internal returns (bool[] memory successes, bytes[] memory results) {
if (self.length != additionalData.length) {
revert ICommon.MismatchedArrayLengths();
}
bytes[] memory beforeExecutionOutputs = new bytes[](validateParams.length);
for (uint256 i = 0; i < validateParams.length; i++) {
beforeExecutionOutputs[i] = validateParams[i].beforeExecution();
}
successes = new bool[](self.length);
results = new bytes[](self.length);
for (uint256 i = 0; i < self.length; i++) {
successes[i] = LowLevelCall.delegatecallNoReturn(
self[i].actionTarget,
abi.encodeCall(IKSActionExecutor.execute, (self[i].actionData, additionalData[i]))
);
if (!successes[i] && !self[i].allowFailure) {
LowLevelCall.bubbleRevert();
} else {
results[i] = LowLevelCall.returnData();
}
}
for (uint256 i = 0; i < validateParams.length; i++) {
validateParams[i].afterExecution(beforeExecutionOutputs[i]);
}
}
}
src/types/IntentParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ActionParams} from './ActionParams.sol';
import {ValidateParams} from './ValidateParams.sol';
/**
* @notice The full, immutable configuration of an intent
* @dev The whole struct is hashed together with the owner and `block.chainid` into the inbox
* clone's CREATE2 salt at creation time, so every field is part of the inbox identity: two
* intents differing in any field deploy to different addresses, and an inbox only accepts
* the exact params it was created with.
* @param guardians The accounts allowed to `pause` the inbox. Factory GUARDIAN_ROLE holders are not
* included; they pause the factory instead, which blocks `execute` on every inbox
* @param deadline The last timestamp at which `mainActions` are executable; `fallbackActions`
* are executable only after it
* @param mainActionOperators The accounts allowed to run `mainActions`; empty means anyone can
* @param mainActions The actions delegatecalled in order while `block.timestamp <= deadline`
* @param mainActionValidateParams The validators wrapping the whole `mainActions` batch: each runs
* once before the first action and once after the last one
* @param fallbackActionOperators The accounts allowed to run `fallbackActions`; empty means anyone
* can
* @param fallbackActions The actions delegatecalled in order once `block.timestamp > deadline`
* @param fallbackActionValidateParams The validators wrapping the whole `fallbackActions` batch,
* same before/after semantics as `mainActionValidateParams`
* @param salt Caller-chosen value that picks a fresh inbox address for an otherwise identical
* intent.
* @param extraData Arbitrary caller-supplied data. Never read on-chain, but part of the intent
* hash, so it differentiates otherwise identical intents and can carry off-chain metadata.
*/
struct IntentParams {
address[] guardians;
uint256 deadline;
address[] mainActionOperators;
ActionParams[] mainActions;
ValidateParams[] mainActionValidateParams;
address[] fallbackActionOperators;
ActionParams[] fallbackActions;
ValidateParams[] fallbackActionValidateParams;
bytes32 salt;
bytes extraData;
}
using IntentParamsLibrary for IntentParams global;
/// @notice Contains functions for deriving the inbox identity from intent params
library IntentParamsLibrary {
/// @notice Returns the hash of these params
function intentHash(IntentParams calldata self) internal pure returns (bytes32) {
return keccak256(abi.encode(self));
}
/// @notice Returns the CREATE2 salt of the inbox bound to `owner` and `intentHash`
/// @dev Includes `block.chainid`, so the same intent maps to a different inbox on every chain
function computeInboxSalt(address owner, bytes32 intentHash) internal view returns (bytes32) {
return keccak256(abi.encode(owner, intentHash, block.chainid));
}
}
src/types/ValidateParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IKSActionValidator} from '../interfaces/IKSActionValidator.sol';
/**
* @notice Parameters for validation
* @param validator The address of the validator
* @param validateType The type of validation
* @param beforeExecutionInput The input for before execution
* @param afterExecutionInput The input for after execution
*/
struct ValidateParams {
address validator;
bytes32 validateType;
bytes beforeExecutionInput;
bytes afterExecutionInput;
}
using ValidateParamsLibrary for ValidateParams global;
/// @notice Contains functions for processing validate params
library ValidateParamsLibrary {
/// @notice Returns the state before execution
function beforeExecution(ValidateParams calldata self) internal returns (bytes memory) {
return IKSActionValidator(self.validator)
.beforeExecution(self.validateType, self.beforeExecutionInput);
}
/// @notice Validates the current state after execution against the before execution state
function afterExecution(ValidateParams calldata self, bytes memory beforeExecutionOutput)
internal
{
IKSActionValidator(self.validator)
.afterExecution(
self.validateType,
self.beforeExecutionInput,
beforeExecutionOutput,
self.afterExecutionInput
);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 44444444,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"@openzeppelin/contracts/=lib/ks-common-sc/lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/ks-common-sc/lib/forge-std/src/",
"ks-common-sc/=lib/ks-common-sc/",
"openzeppelin-contracts/=lib/ks-common-sc/lib/openzeppelin-contracts/",
"erc4626-tests/=lib/ks-common-sc/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/ks-common-sc/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.