Contract Name:
SecureArbitrageContractV4
Contract Source Code:
<i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol"; <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol"; <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// 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;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// 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());
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
//Router Interface
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
interface I1InchV6 {
function swap(
address executor,
address srcToken,
address dstToken,
uint256 amount,
uint256 minReturn,
bytes calldata data
) external returns (uint256 returnAmount);
}
contract SecureArbitrageContractV4 is
AccessControl,
ReentrancyGuard,
Pausable
{
using SafeERC20 for IERC20;
// ═══════════════════════════════════════════════════════════════════
// ROLES & CONSTANTS
// ═══════════════════════════════════════════════════════════════════
bytes32 public constant BOT_ROLE = keccak256("BOT_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
uint256 public constant MAX_SLIPPAGE = 500; // 5%
uint256 public constant MIN_PROFIT_BASIS_POINTS = 10; // 0.1%
uint256 public constant MAX_TOKENS_PER_ARBITRAGE = 10;
uint256 public constant DEFAULT_MAX_ALLOWANCE_USDC = 10000 * 1e6;
uint256 public constant DEFAULT_MAX_TRADE_AMOUNT_USDC = 5000 * 1e6;
// ═══════════════════════════════════════════════════════════════════
// STRUCTS (OPTIMIZED)
// ═══════════════════════════════════════════════════════════════════
struct Config {
uint256 minProfitThreshold;
uint256 maxSlippage;
uint256 maxGasPrice;
uint256 maxTradeAmountUSDC;
uint256 maxRouterAllowanceUSDC;
bool emergencyMode;
bool strictSelectorValidation; // New: toggle for selector validation
}
struct TradeState {
bool inTrade;
uint256 tradeStartTime;
address initiator;
uint256 nonce;
}
struct AssetInfo {
uint256 maxTradeAmount;
bool isActive;
uint8 decimals;
bytes32 symbolHash;
}
// ═══════════════════════════════════════════════════════════════════
// STATE VARIABLES
// ═══════════════════════════════════════════════════════════════════
Config public config;
TradeState public tradeState;
uint256 public totalProfit;
uint256 public totalTrades;
uint8 public deploymentCount;
// Selector validation
mapping(bytes4 => bool) public validSelectors;
mapping(bytes4 => string) public selectorNames;
bytes4[] public allSelectors;
// Simplified mappings (removed multi-sig related)
mapping(address => bool) public activeBots;
mapping(address => bool) public approvedRouters;
mapping(address => AssetInfo) public assetConfigs;
mapping(address => bool) public approvedTokens;
// Arrays for enumeration
address[] public allBots;
address[] public allRouters;
address[] public allTokens;
// ═══════════════════════════════════════════════════════════════════
// EVENTS
// ═══════════════════════════════════════════════════════════════════
event ArbitrageExecuted(
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 profit,
address indexed routerUsed,
address executor
);
event AssetUpdated(address indexed asset, uint256 maxTrade, bool isActive, string assetType);
event BotUpdated(address indexed bot, bool isActive);
event SelectorUpdated(bytes4 indexed selector, bool isValid, string name);
event Withdrawal(address indexed token, uint256 amount, address indexed recipient);
// ═══════════════════════════════════════════════════════════════════
// MODIFIERS
// ═══════════════════════════════════════════════════════════════════
modifier onlyActiveBot() {
require(hasRole(BOT_ROLE, msg.sender) && activeBots[msg.sender], "Not active bot");
_;
}
modifier validAsset(address asset, bool isToken) {
if (isToken) {
require(approvedTokens[asset] && assetConfigs[asset].isActive, "Invalid token");
} else {
require(approvedRouters[asset] && assetConfigs[asset].isActive, "Invalid router");
}
_;
}
modifier notInTrade() {
require(!tradeState.inTrade, "Trade in progress");
_;
}
modifier gasLimit() {
require(tx.gasprice <= config.maxGasPrice, "Gas price too high");
_;
}
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════════════
constructor(
address _admin,
address _operator,
uint256 _minProfitThreshold,
address[] memory _botAddresses
) {
require(_admin != address(0) && _operator != address(0), "Invalid addresses");
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
_grantRole(OPERATOR_ROLE, _operator);
config = Config({
minProfitThreshold: _minProfitThreshold,
maxSlippage: 300,
maxGasPrice: 100 gwei,
maxTradeAmountUSDC: DEFAULT_MAX_TRADE_AMOUNT_USDC,
maxRouterAllowanceUSDC: DEFAULT_MAX_ALLOWANCE_USDC,
emergencyMode: false,
strictSelectorValidation: true // Enable by default
});
tradeState.nonce = 1;
deploymentCount++;
_initializeDefaults();
_initializeBots(_botAddresses);
_initializeSelectors();
}
// ═══════════════════════════════════════════════════════════════════
// CORE ARBITRAGE FUNCTIONS
// ═══════════════════════════════════════════════════════════════════
function executeArbitrage(
address tokenIn,
address tokenOut,
uint256 amountIn,
address targetRouter,
bytes memory swapData,
uint256 minReturn
)
external
payable
onlyActiveBot
nonReentrant
whenNotPaused
notInTrade
validAsset(targetRouter, false)
validAsset(tokenIn, true)
validAsset(tokenOut, true)
gasLimit
{
require(amountIn > 0 && amountIn <= assetConfigs[tokenIn].maxTradeAmount, "Invalid amount");
require(amountIn <= assetConfigs[targetRouter].maxTradeAmount, "Exceeds router limit");
_startTrade();
// Validate swap data if strict validation is enabled
if (config.strictSelectorValidation) {
_validateSwapData(tokenIn, tokenOut, amountIn, minReturn, targetRouter, swapData);
}
uint256 beforeBal = IERC20(tokenOut).balanceOf(address(this));
_executeSwap(targetRouter, swapData);
uint256 afterBal = IERC20(tokenOut).balanceOf(address(this));
require(afterBal >= minReturn, "Insufficient return");
uint256 profit = afterBal > beforeBal ? afterBal - beforeBal : 0;
if (profit >= config.minProfitThreshold) totalProfit += profit;
totalTrades++;
emit ArbitrageExecuted(tokenIn, tokenOut, amountIn, profit, targetRouter, msg.sender);
_endTrade();
}
function executeMultiArbitrage(
address[] calldata tokens,
uint256 amountIn,
address[] calldata routers,
bytes[] calldata datas,
uint256 minReturn
)
external
payable
onlyActiveBot
nonReentrant
whenNotPaused
notInTrade
gasLimit
{
require(tokens.length >= 3 && tokens.length <= MAX_TOKENS_PER_ARBITRAGE, "Invalid tokens length");
require(routers.length == tokens.length - 1 && datas.length == routers.length, "Mismatched arrays");
require(amountIn <= assetConfigs[tokens[0]].maxTradeAmount, "Amount exceeds limit");
// Validate all assets
for (uint i = 0; i < tokens.length; i++) {
require(approvedTokens[tokens[i]] && assetConfigs[tokens[i]].isActive, "Invalid token");
}
for (uint i = 0; i < routers.length; i++) {
require(approvedRouters[routers[i]] && assetConfigs[routers[i]].isActive, "Invalid router");
}
_startTrade();
uint256 beforeBal = IERC20(tokens[0]).balanceOf(address(this));
uint256 currentAmount = amountIn;
for (uint i = 0; i < routers.length; i++) {
if (i > 0) {
currentAmount = IERC20(tokens[i]).balanceOf(address(this));
}
bytes memory modifiedData = _updateSwapAmount(datas[i], currentAmount);
// Validate if strict validation is enabled
if (config.strictSelectorValidation) {
_validateSwapData(
tokens[i],
tokens[i + 1],
currentAmount,
0,
routers[i],
modifiedData
);
}
_executeSwap(routers[i], modifiedData);
}
uint256 afterBal = IERC20(tokens[0]).balanceOf(address(this));
require(afterBal >= minReturn, "Insufficient return");
uint256 profit = afterBal > beforeBal ? afterBal - beforeBal : 0;
if (profit >= config.minProfitThreshold) totalProfit += profit;
totalTrades++;
emit ArbitrageExecuted(tokens[0], tokens[0], amountIn, profit, address(0), msg.sender);
_endTrade();
}
// ═══════════════════════════════════════════════════════════════════
// INTERNAL HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════════════════
function _validateSwapData(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minReturn,
address router,
bytes memory data
) internal view {
require(data.length >= 4, "Invalid data length");
bytes4 sig;
assembly {
sig := mload(add(data, 32))
}
// Check if selector is valid (if strict validation is enabled)
require(validSelectors[sig], "Invalid function selector");
// Basic validation based on known selectors
if (sig == 0x38ed1739) { // uniswap_swapExactTokensForTokens
(
uint256 inAmt,
uint256 outMin,
address[] memory path,
address to,
uint256 deadline
) = abi.decode(
sliceBytes(data, 4, data.length - 4),
(uint256, uint256, address[], address, uint256)
);
require(path.length >= 2, "Invalid path length");
require(path[0] == tokenIn && path[path.length - 1] == tokenOut, "Invalid path");
require(to == address(this), "Invalid recipient");
require(inAmt == amountIn, "Wrong amountIn");
require(deadline > block.timestamp, "Expired deadline");
if (minReturn > 0) {
require(outMin >= minReturn, "Insufficient minReturn");
}
}
// Add more specific validations for other selectors as needed
}
function sliceBytes(bytes memory data, uint256 start, uint256 length) internal pure returns (bytes memory) {
require(data.length >= start + length, "sliceBytes: out of bounds");
bytes memory result = new bytes(length);
for (uint256 i = 0; i < length; i++) {
result[i] = data[start + i];
}
return result;
}
function _updateSwapAmount(bytes memory data, uint256 newAmountIn) internal pure returns (bytes memory) {
require(data.length >= 4, "Invalid swap data");
bytes4 sig;
assembly {
sig := mload(add(data, 32))
}
// Handle different selectors
if (sig == 0x38ed1739) { // uniswap_swapExactTokensForTokens
(
,
uint256 outMin,
address[] memory path,
address to,
uint256 deadline
) = abi.decode(sliceBytes(data, 4, data.length - 4), (uint256, uint256, address[], address, uint256));
return abi.encodeWithSelector(sig, newAmountIn, outMin, path, to, deadline);
}
else if (sig == 0x12aa3caf || sig == 0x7c025200) { // 1inch swap variants
// Generic handling for 1inch - you may need to adjust based on specific function
(
address executor,
address src,
address dst,
,
uint256 minReturn,
bytes memory swapData
) = abi.decode(sliceBytes(data, 4, data.length - 4), (address, address, address, uint256, uint256, bytes));
return abi.encodeWithSelector(sig, executor, src, dst, newAmountIn, minReturn, swapData);
}
// For unknown selectors, return original data (fallback)
return data;
}
function _executeSwap(address router, bytes memory data) internal {
(bool success, ) = router.call{value: msg.value}(data);
require(success, "Swap failed");
}
function _startTrade() internal {
tradeState = TradeState({
inTrade: true,
tradeStartTime: block.timestamp,
initiator: msg.sender,
nonce: tradeState.nonce + 1
});
}
function _endTrade() internal {
tradeState.inTrade = false;
tradeState.tradeStartTime = 0;
tradeState.initiator = address(0);
}
function _initializeDefaults() internal {
// Default routers
address[3] memory defaultRouters = [
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, // Uniswap V2
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F, // SushiSwap
0x111111125421cA6dc452d289314280a0f8842A65 // 1inch V6
];
for (uint i = 0; i < defaultRouters.length; i++) {
approvedRouters[defaultRouters[i]] = true;
assetConfigs[defaultRouters[i]] = AssetInfo({
maxTradeAmount: DEFAULT_MAX_TRADE_AMOUNT_USDC,
isActive: true,
decimals: 18,
symbolHash: keccak256(abi.encodePacked("ROUTER_", i))
});
allRouters.push(defaultRouters[i]);
}
// Default tokens
address[8] memory defaultTokens = [
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, // USDC
0xdAC17F958D2ee523a2206206994597C13D831ec7, // USDT
0x6B175474E89094C44Da98b954EedeAC495271d0F, // DAI
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, // WETH
0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0, // wstETH
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, // WBTC
0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32, // LDO
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK
];
uint8[8] memory decimals = [6, 6, 18, 18, 18, 8, 18, 18];
uint256[8] memory maxTrades = [
uint256(10000 * 1e6),
uint256(10000 * 1e6),
uint256(10000 * 1e18),
uint256(10 * 1e18),
uint256(10 * 1e18),
uint256(1 * 1e8),
uint256(100000 * 1e18),
uint256(1000 * 1e18)
];
for (uint i = 0; i < defaultTokens.length; i++) {
approvedTokens[defaultTokens[i]] = true;
assetConfigs[defaultTokens[i]] = AssetInfo({
maxTradeAmount: maxTrades[i],
isActive: true,
decimals: decimals[i],
symbolHash: keccak256(abi.encodePacked("TOKEN_", i))
});
allTokens.push(defaultTokens[i]);
}
}
function _initializeBots(address[] memory _botAddresses) internal {
for (uint i = 0; i < _botAddresses.length; i++) {
require(_botAddresses[i] != address(0), "Invalid bot");
_grantRole(BOT_ROLE, _botAddresses[i]);
activeBots[_botAddresses[i]] = true;
allBots.push(_botAddresses[i]);
emit BotUpdated(_botAddresses[i], true);
}
}
function _initializeSelectors() internal {
// Initialize with your provided selectors
bytes4[9] memory selectors = [
bytes4(0x12aa3caf), // 1inch_swap
bytes4(0xe449022e), // 1inch_uniswapV3Swap
bytes4(0x2e95b6c8), // 1inch_unoswap
bytes4(0x84bd6d29), // 1inch_clipperSwap
bytes4(0x7c025200), // 1inch_swap_v2
bytes4(0x0502b1c5), // 1inch_fillOrderRFQ
bytes4(0x38ed1739), // uniswap_swapExactTokensForTokens
bytes4(0x8803dbee), // uniswap_swapTokensForExactTokens
bytes4(0x2195995c) // Additional selector if needed
];
string[9] memory names = [
"1inch_swap",
"1inch_uniswapV3Swap",
"1inch_unoswap",
"1inch_clipperSwap",
"1inch_swap_v2",
"1inch_fillOrderRFQ",
"uniswap_swapExactTokensForTokens",
"uniswap_swapTokensForExactTokens",
"additional_selector"
];
for (uint i = 0; i < selectors.length; i++) {
if (selectors[i] != bytes4(0)) {
validSelectors[selectors[i]] = true;
selectorNames[selectors[i]] = names[i];
allSelectors.push(selectors[i]);
}
}
}
// ═══════════════════════════════════════════════════════════════════
// ADMIN FUNCTIONS (SIMPLIFIED)
// ═══════════════════════════════════════════════════════════════════
// Withdrawal function that works for both ETH and ERC20 tokens
function withdraw(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (token == address(0)) {
// ETH withdrawal
require(address(this).balance >= amount, "Insufficient ETH balance");
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "ETH transfer failed");
} else {
// ERC20 token withdrawal
require(IERC20(token).balanceOf(address(this)) >= amount, "Insufficient token balance");
IERC20(token).safeTransfer(msg.sender, amount);
}
emit Withdrawal(token, amount, msg.sender);
}
// Emergency withdrawal (all balance)
function emergencyWithdraw(address token) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (token == address(0)) {
uint256 balance = address(this).balance;
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "ETH transfer failed");
emit Withdrawal(token, balance, msg.sender);
} else {
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(msg.sender, balance);
emit Withdrawal(token, balance, msg.sender);
}
}
// Selector management functions
function addSelector(bytes4 selector, string memory name) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(!validSelectors[selector], "Selector already exists");
validSelectors[selector] = true;
selectorNames[selector] = name;
allSelectors.push(selector);
emit SelectorUpdated(selector, true, name);
}
function removeSelector(bytes4 selector) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(validSelectors[selector], "Selector doesn't exist");
validSelectors[selector] = false;
selectorNames[selector] = "";
// Remove from array
for (uint i = 0; i < allSelectors.length; i++) {
if (allSelectors[i] == selector) {
allSelectors[i] = allSelectors[allSelectors.length - 1];
allSelectors.pop();
break;
}
}
emit SelectorUpdated(selector, false, "");
}
// Toggle strict selector validation
function toggleSelectorValidation(bool enabled) external onlyRole(DEFAULT_ADMIN_ROLE) {
config.strictSelectorValidation = enabled;
}
// Asset management
function addToken(address token, uint256 maxTradeAmount, uint8 decimals) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(token != address(0), "Invalid token address");
require(!approvedTokens[token], "Token already exists");
approvedTokens[token] = true;
assetConfigs[token] = AssetInfo({
maxTradeAmount: maxTradeAmount,
isActive: true,
decimals: decimals,
symbolHash: keccak256(abi.encodePacked("TOKEN_", allTokens.length))
});
allTokens.push(token);
emit AssetUpdated(token, maxTradeAmount, true, "TOKEN");
}
function addRouter(address router, uint256 maxTradeAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(router != address(0), "Invalid router address");
require(!approvedRouters[router], "Router already exists");
approvedRouters[router] = true;
assetConfigs[router] = AssetInfo({
maxTradeAmount: maxTradeAmount,
isActive: true,
decimals: 18,
symbolHash: keccak256(abi.encodePacked("ROUTER_", allRouters.length))
});
allRouters.push(router);
emit AssetUpdated(router, maxTradeAmount, true, "ROUTER");
}
function updateAsset(address asset, uint256 maxTradeAmount, bool isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(approvedTokens[asset] || approvedRouters[asset], "Asset not found");
assetConfigs[asset].maxTradeAmount = maxTradeAmount;
assetConfigs[asset].isActive = isActive;
emit AssetUpdated(asset, maxTradeAmount, isActive, approvedTokens[asset] ? "TOKEN" : "ROUTER");
}
function updateBot(address bot, bool isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (isActive && !hasRole(BOT_ROLE, bot)) {
_grantRole(BOT_ROLE, bot);
allBots.push(bot);
} else if (!isActive && hasRole(BOT_ROLE, bot)) {
_revokeRole(BOT_ROLE, bot);
}
activeBots[bot] = isActive;
emit BotUpdated(bot, isActive);
}
function approveToken(address token, address spender, uint256 amount) external onlyRole(OPERATOR_ROLE) {
IERC20(token).safeIncreaseAllowance(spender, amount);
}
function pause() external onlyRole(OPERATOR_ROLE) { _pause(); }
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); }
function forceUnlockTrade() external onlyRole(DEFAULT_ADMIN_ROLE) {
tradeState.inTrade = false;
tradeState.tradeStartTime = 0;
tradeState.initiator = address(0);
}
// ═══════════════════════════════════════════════════════════════════
// VIEW FUNCTIONS
// ═══════════════════════════════════════════════════════════════════
function getAllBots() external view returns (address[] memory) { return allBots; }
function getAllRouters() external view returns (address[] memory) { return allRouters; }
function getAllTokens() external view returns (address[] memory) { return allTokens; }
function getAllSelectors() external view returns (bytes4[] memory) { return allSelectors; }
function getSelectorName(bytes4 selector) external view returns (string memory) { return selectorNames[selector]; }
function isValidSelector(bytes4 selector) external view returns (bool) { return validSelectors[selector]; }
// ═══════════════════════════════════════════════════════════════════
// RECEIVE
// ═══════════════════════════════════════════════════════════════════
receive() external payable {}
fallback() external payable {}
}