chore(verification): add Chain 138 verification sources and audit output
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
{"id":"c99cd462-7d3d-477e-bcff-0903bd33ef68","ts":"2026-07-05T23:51:49.003Z","category":"reconcile","action":"triple_state_reconcile","traceId":"0xfefb7411285a639b00be06bbffe897eb802ee817983aa57facf5bde6a1b52ff4","status":"error","metadata":{"breakCount":3,"aligned":false}}
|
||||
{"id":"33510913-6f91-4c3b-a672-3b5eee875c73","ts":"2026-07-05T23:53:58.873Z","category":"reconcile","action":"triple_state_reconcile","traceId":"0xfefb7411285a639b00be06bbffe897eb802ee817983aa57facf5bde6a1b52ff4","status":"error","metadata":{"breakCount":3,"aligned":false}}
|
||||
{"id":"717a6667-2cff-4cdc-b2f6-aaf59761b9b3","ts":"2026-07-06T00:07:39.756Z","category":"reconcile","action":"triple_state_reconcile","traceId":"0xfefb7411285a639b00be06bbffe897eb802ee817983aa57facf5bde6a1b52ff4","status":"error","metadata":{"breakCount":3,"aligned":false}}
|
||||
{"id":"4d21094d-56fd-4324-a75b-1075f9a5dd59","ts":"2026-07-06T00:23:58.822Z","category":"reconcile","action":"triple_state_reconcile","traceId":"0xfefb7411285a639b00be06bbffe897eb802ee817983aa57facf5bde6a1b52ff4","status":"error","metadata":{"breakCount":3,"aligned":false}}
|
||||
{"id":"9b28b030-b396-4e07-9aa8-47854797096c","ts":"2026-07-06T00:28:58.771Z","category":"reconcile","action":"triple_state_reconcile","traceId":"0xfefb7411285a639b00be06bbffe897eb802ee817983aa57facf5bde6a1b52ff4","status":"error","metadata":{"breakCount":3,"aligned":false}}
|
||||
{"id":"d7ea5f0c-5827-4795-ae98-23f958b92646","ts":"2026-07-06T00:29:30.710Z","category":"reconcile","action":"triple_state_reconcile","traceId":"0xfefb7411285a639b00be06bbffe897eb802ee817983aa57facf5bde6a1b52ff4","status":"error","metadata":{"breakCount":3,"aligned":false}}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
|
||||
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
|
||||
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
|
||||
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
|
||||
import {Initializable} from "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
|
||||
struct RoleData {
|
||||
mapping(address account => bool) hasRole;
|
||||
bytes32 adminRole;
|
||||
}
|
||||
|
||||
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
|
||||
|
||||
|
||||
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
|
||||
struct AccessControlStorage {
|
||||
mapping(bytes32 role => RoleData) _roles;
|
||||
}
|
||||
|
||||
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
|
||||
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
|
||||
|
||||
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
|
||||
assembly {
|
||||
$.slot := AccessControlStorageLocation
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
_;
|
||||
}
|
||||
|
||||
function __AccessControl_init() internal onlyInitializing {
|
||||
}
|
||||
|
||||
function __AccessControl_init_unchained() internal onlyInitializing {
|
||||
}
|
||||
/// @inheritdoc IERC165
|
||||
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) {
|
||||
AccessControlStorage storage $ = _getAccessControlStorage();
|
||||
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) {
|
||||
AccessControlStorage storage $ = _getAccessControlStorage();
|
||||
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 {
|
||||
AccessControlStorage storage $ = _getAccessControlStorage();
|
||||
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) {
|
||||
AccessControlStorage storage $ = _getAccessControlStorage();
|
||||
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) {
|
||||
AccessControlStorage storage $ = _getAccessControlStorage();
|
||||
if (hasRole(role, account)) {
|
||||
$._roles[role].hasRole[account] = false;
|
||||
emit RoleRevoked(role, account, _msgSender());
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
|
||||
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
|
||||
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
|
||||
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
|
||||
*
|
||||
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
|
||||
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
|
||||
* case an upgrade adds a module that needs to be initialized.
|
||||
*
|
||||
* For example:
|
||||
*
|
||||
* [.hljs-theme-light.nopadding]
|
||||
* ```solidity
|
||||
* contract MyToken is ERC20Upgradeable {
|
||||
* function initialize() initializer public {
|
||||
* __ERC20_init("MyToken", "MTK");
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
|
||||
* function initializeV2() reinitializer(2) public {
|
||||
* __ERC20Permit_init("MyToken");
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
|
||||
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
|
||||
*
|
||||
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
|
||||
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
|
||||
*
|
||||
* [CAUTION]
|
||||
* ====
|
||||
* Avoid leaving a contract uninitialized.
|
||||
*
|
||||
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
|
||||
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
|
||||
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
|
||||
*
|
||||
* [.hljs-theme-light.nopadding]
|
||||
* ```
|
||||
* /// @custom:oz-upgrades-unsafe-allow constructor
|
||||
* constructor() {
|
||||
* _disableInitializers();
|
||||
* }
|
||||
* ```
|
||||
* ====
|
||||
*/
|
||||
abstract contract Initializable {
|
||||
/**
|
||||
* @dev Storage of the initializable contract.
|
||||
*
|
||||
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
|
||||
* when using with upgradeable contracts.
|
||||
*
|
||||
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
|
||||
*/
|
||||
struct InitializableStorage {
|
||||
/**
|
||||
* @dev Indicates that the contract has been initialized.
|
||||
*/
|
||||
uint64 _initialized;
|
||||
/**
|
||||
* @dev Indicates that the contract is in the process of being initialized.
|
||||
*/
|
||||
bool _initializing;
|
||||
}
|
||||
|
||||
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
|
||||
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
|
||||
|
||||
/**
|
||||
* @dev The contract is already initialized.
|
||||
*/
|
||||
error InvalidInitialization();
|
||||
|
||||
/**
|
||||
* @dev The contract is not initializing.
|
||||
*/
|
||||
error NotInitializing();
|
||||
|
||||
/**
|
||||
* @dev Triggered when the contract has been initialized or reinitialized.
|
||||
*/
|
||||
event Initialized(uint64 version);
|
||||
|
||||
/**
|
||||
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
|
||||
* `onlyInitializing` functions can be used to initialize parent contracts.
|
||||
*
|
||||
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
|
||||
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
|
||||
* production.
|
||||
*
|
||||
* Emits an {Initialized} event.
|
||||
*/
|
||||
modifier initializer() {
|
||||
// solhint-disable-next-line var-name-mixedcase
|
||||
InitializableStorage storage $ = _getInitializableStorage();
|
||||
|
||||
// Cache values to avoid duplicated sloads
|
||||
bool isTopLevelCall = !$._initializing;
|
||||
uint64 initialized = $._initialized;
|
||||
|
||||
// Allowed calls:
|
||||
// - initialSetup: the contract is not in the initializing state and no previous version was
|
||||
// initialized
|
||||
// - construction: the contract is initialized at version 1 (no reinitialization) and the
|
||||
// current contract is just being deployed
|
||||
bool initialSetup = initialized == 0 && isTopLevelCall;
|
||||
bool construction = initialized == 1 && address(this).code.length == 0;
|
||||
|
||||
if (!initialSetup && !construction) {
|
||||
revert InvalidInitialization();
|
||||
}
|
||||
$._initialized = 1;
|
||||
if (isTopLevelCall) {
|
||||
$._initializing = true;
|
||||
}
|
||||
_;
|
||||
if (isTopLevelCall) {
|
||||
$._initializing = false;
|
||||
emit Initialized(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
|
||||
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
|
||||
* used to initialize parent contracts.
|
||||
*
|
||||
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
|
||||
* are added through upgrades and that require initialization.
|
||||
*
|
||||
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
|
||||
* cannot be nested. If one is invoked in the context of another, execution will revert.
|
||||
*
|
||||
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
|
||||
* a contract, executing them in the right order is up to the developer or operator.
|
||||
*
|
||||
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
|
||||
*
|
||||
* Emits an {Initialized} event.
|
||||
*/
|
||||
modifier reinitializer(uint64 version) {
|
||||
// solhint-disable-next-line var-name-mixedcase
|
||||
InitializableStorage storage $ = _getInitializableStorage();
|
||||
|
||||
if ($._initializing || $._initialized >= version) {
|
||||
revert InvalidInitialization();
|
||||
}
|
||||
$._initialized = version;
|
||||
$._initializing = true;
|
||||
_;
|
||||
$._initializing = false;
|
||||
emit Initialized(version);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
|
||||
* {initializer} and {reinitializer} modifiers, directly or indirectly.
|
||||
*/
|
||||
modifier onlyInitializing() {
|
||||
_checkInitializing();
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
|
||||
*/
|
||||
function _checkInitializing() internal view virtual {
|
||||
if (!_isInitializing()) {
|
||||
revert NotInitializing();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
|
||||
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
|
||||
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
|
||||
* through proxies.
|
||||
*
|
||||
* Emits an {Initialized} event the first time it is successfully executed.
|
||||
*/
|
||||
function _disableInitializers() internal virtual {
|
||||
// solhint-disable-next-line var-name-mixedcase
|
||||
InitializableStorage storage $ = _getInitializableStorage();
|
||||
|
||||
if ($._initializing) {
|
||||
revert InvalidInitialization();
|
||||
}
|
||||
if ($._initialized != type(uint64).max) {
|
||||
$._initialized = type(uint64).max;
|
||||
emit Initialized(type(uint64).max);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the highest version that has been initialized. See {reinitializer}.
|
||||
*/
|
||||
function _getInitializedVersion() internal view returns (uint64) {
|
||||
return _getInitializableStorage()._initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
|
||||
*/
|
||||
function _isInitializing() internal view returns (bool) {
|
||||
return _getInitializableStorage()._initializing;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
|
||||
*
|
||||
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
|
||||
*/
|
||||
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
|
||||
return INITIALIZABLE_STORAGE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns a pointer to the storage namespace.
|
||||
*/
|
||||
// solhint-disable-next-line var-name-mixedcase
|
||||
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
|
||||
bytes32 slot = _initializableStorageSlot();
|
||||
assembly {
|
||||
$.slot := slot
|
||||
}
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
|
||||
|
||||
pragma solidity ^0.8.22;
|
||||
|
||||
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
|
||||
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
|
||||
import {Initializable} from "./Initializable.sol";
|
||||
|
||||
/**
|
||||
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
|
||||
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
|
||||
*
|
||||
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
|
||||
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
|
||||
* `UUPSUpgradeable` with a custom implementation of upgrades.
|
||||
*
|
||||
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
|
||||
*/
|
||||
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
|
||||
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
|
||||
address private immutable __self = address(this);
|
||||
|
||||
/**
|
||||
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
|
||||
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
|
||||
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
|
||||
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
|
||||
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
|
||||
* during an upgrade.
|
||||
*/
|
||||
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
|
||||
|
||||
/**
|
||||
* @dev The call is from an unauthorized context.
|
||||
*/
|
||||
error UUPSUnauthorizedCallContext();
|
||||
|
||||
/**
|
||||
* @dev The storage `slot` is unsupported as a UUID.
|
||||
*/
|
||||
error UUPSUnsupportedProxiableUUID(bytes32 slot);
|
||||
|
||||
/**
|
||||
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
|
||||
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
|
||||
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
|
||||
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
|
||||
* fail.
|
||||
*/
|
||||
modifier onlyProxy() {
|
||||
_checkProxy();
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
|
||||
* callable on the implementing contract but not through proxies.
|
||||
*/
|
||||
modifier notDelegated() {
|
||||
_checkNotDelegated();
|
||||
_;
|
||||
}
|
||||
|
||||
function __UUPSUpgradeable_init() internal onlyInitializing {
|
||||
}
|
||||
|
||||
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
|
||||
}
|
||||
/**
|
||||
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
|
||||
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
|
||||
*
|
||||
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
|
||||
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
|
||||
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
|
||||
*/
|
||||
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
|
||||
return ERC1967Utils.IMPLEMENTATION_SLOT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
|
||||
* encoded in `data`.
|
||||
*
|
||||
* Calls {_authorizeUpgrade}.
|
||||
*
|
||||
* Emits an {Upgraded} event.
|
||||
*
|
||||
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
|
||||
*/
|
||||
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
|
||||
_authorizeUpgrade(newImplementation);
|
||||
_upgradeToAndCallUUPS(newImplementation, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the execution is not performed via delegatecall or the execution
|
||||
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
|
||||
*/
|
||||
function _checkProxy() internal view virtual {
|
||||
if (
|
||||
address(this) == __self || // Must be called through delegatecall
|
||||
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
|
||||
) {
|
||||
revert UUPSUnauthorizedCallContext();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the execution is performed via delegatecall.
|
||||
* See {notDelegated}.
|
||||
*/
|
||||
function _checkNotDelegated() internal view virtual {
|
||||
if (address(this) != __self) {
|
||||
// Must not be called through delegatecall
|
||||
revert UUPSUnauthorizedCallContext();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
|
||||
* {upgradeToAndCall}.
|
||||
*
|
||||
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
|
||||
*
|
||||
* ```solidity
|
||||
* function _authorizeUpgrade(address) internal onlyOwner {}
|
||||
* ```
|
||||
*/
|
||||
function _authorizeUpgrade(address newImplementation) internal virtual;
|
||||
|
||||
/**
|
||||
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
|
||||
*
|
||||
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
|
||||
* is expected to be the implementation slot in ERC-1967.
|
||||
*
|
||||
* Emits an {IERC1967-Upgraded} event.
|
||||
*/
|
||||
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
|
||||
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
|
||||
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
|
||||
revert UUPSUnsupportedProxiableUUID(slot);
|
||||
}
|
||||
ERC1967Utils.upgradeToAndCall(newImplementation, data);
|
||||
} catch {
|
||||
// The implementation is not UUPS
|
||||
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
|
||||
}
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
|
||||
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
|
||||
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
|
||||
import {Initializable} from "../../proxy/utils/Initializable.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the {IERC20} interface.
|
||||
*
|
||||
* This implementation is agnostic to the way tokens are created. This means
|
||||
* that a supply mechanism has to be added in a derived contract using {_mint}.
|
||||
*
|
||||
* TIP: For a detailed writeup see our guide
|
||||
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
|
||||
* to implement supply mechanisms].
|
||||
*
|
||||
* The default value of {decimals} is 18. To change this, you should override
|
||||
* this function so it returns a different value.
|
||||
*
|
||||
* We have followed general OpenZeppelin Contracts guidelines: functions revert
|
||||
* instead returning `false` on failure. This behavior is nonetheless
|
||||
* conventional and does not conflict with the expectations of ERC-20
|
||||
* applications.
|
||||
*/
|
||||
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
|
||||
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
|
||||
struct ERC20Storage {
|
||||
mapping(address account => uint256) _balances;
|
||||
|
||||
mapping(address account => mapping(address spender => uint256)) _allowances;
|
||||
|
||||
uint256 _totalSupply;
|
||||
|
||||
string _name;
|
||||
string _symbol;
|
||||
}
|
||||
|
||||
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
|
||||
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
|
||||
|
||||
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
|
||||
assembly {
|
||||
$.slot := ERC20StorageLocation
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the values for {name} and {symbol}.
|
||||
*
|
||||
* Both values are immutable: they can only be set once during construction.
|
||||
*/
|
||||
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
|
||||
__ERC20_init_unchained(name_, symbol_);
|
||||
}
|
||||
|
||||
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
$._name = name_;
|
||||
$._symbol = symbol_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() public view virtual returns (string memory) {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
return $._name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token, usually a shorter version of the
|
||||
* name.
|
||||
*/
|
||||
function symbol() public view virtual returns (string memory) {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
return $._symbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of decimals used to get its user representation.
|
||||
* For example, if `decimals` equals `2`, a balance of `505` tokens should
|
||||
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
|
||||
*
|
||||
* Tokens usually opt for a value of 18, imitating the relationship between
|
||||
* Ether and Wei. This is the default value returned by this function, unless
|
||||
* it's overridden.
|
||||
*
|
||||
* NOTE: This information is only used for _display_ purposes: it in
|
||||
* no way affects any of the arithmetic of the contract, including
|
||||
* {IERC20-balanceOf} and {IERC20-transfer}.
|
||||
*/
|
||||
function decimals() public view virtual returns (uint8) {
|
||||
return 18;
|
||||
}
|
||||
|
||||
/// @inheritdoc IERC20
|
||||
function totalSupply() public view virtual returns (uint256) {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
return $._totalSupply;
|
||||
}
|
||||
|
||||
/// @inheritdoc IERC20
|
||||
function balanceOf(address account) public view virtual returns (uint256) {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
return $._balances[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transfer}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - the caller must have a balance of at least `value`.
|
||||
*/
|
||||
function transfer(address to, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_transfer(owner, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @inheritdoc IERC20
|
||||
function allowance(address owner, address spender) public view virtual returns (uint256) {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
return $._allowances[owner][spender];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-approve}.
|
||||
*
|
||||
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
|
||||
* `transferFrom`. This is semantically equivalent to an infinite approval.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `spender` cannot be the zero address.
|
||||
*/
|
||||
function approve(address spender, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_approve(owner, spender, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transferFrom}.
|
||||
*
|
||||
* Skips emitting an {Approval} event indicating an allowance update. This is not
|
||||
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
|
||||
*
|
||||
* NOTE: Does not update the allowance if the current allowance
|
||||
* is the maximum `uint256`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` and `to` cannot be the zero address.
|
||||
* - `from` must have a balance of at least `value`.
|
||||
* - the caller must have allowance for ``from``'s tokens of at least
|
||||
* `value`.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
|
||||
address spender = _msgSender();
|
||||
_spendAllowance(from, spender, value);
|
||||
_transfer(from, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to`.
|
||||
*
|
||||
* This internal function is equivalent to {transfer}, and can be used to
|
||||
* e.g. implement automatic token fees, slashing mechanisms, etc.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _transfer(address from, address to, uint256 value) internal {
|
||||
if (from == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
if (to == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
|
||||
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
|
||||
* this function.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
if (from == address(0)) {
|
||||
// Overflow check required: The rest of the code assumes that totalSupply never overflows
|
||||
$._totalSupply += value;
|
||||
} else {
|
||||
uint256 fromBalance = $._balances[from];
|
||||
if (fromBalance < value) {
|
||||
revert ERC20InsufficientBalance(from, fromBalance, value);
|
||||
}
|
||||
unchecked {
|
||||
// Overflow not possible: value <= fromBalance <= totalSupply.
|
||||
$._balances[from] = fromBalance - value;
|
||||
}
|
||||
}
|
||||
|
||||
if (to == address(0)) {
|
||||
unchecked {
|
||||
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
|
||||
$._totalSupply -= value;
|
||||
}
|
||||
} else {
|
||||
unchecked {
|
||||
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
|
||||
$._balances[to] += value;
|
||||
}
|
||||
}
|
||||
|
||||
emit Transfer(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
|
||||
* Relies on the `_update` mechanism
|
||||
*
|
||||
* Emits a {Transfer} event with `from` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _mint(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(address(0), account, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
|
||||
* Relies on the `_update` mechanism.
|
||||
*
|
||||
* Emits a {Transfer} event with `to` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead
|
||||
*/
|
||||
function _burn(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
_update(account, address(0), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
|
||||
*
|
||||
* This internal function is equivalent to `approve`, and can be used to
|
||||
* e.g. set automatic allowances for certain subsystems, etc.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `owner` cannot be the zero address.
|
||||
* - `spender` cannot be the zero address.
|
||||
*
|
||||
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value) internal {
|
||||
_approve(owner, spender, value, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
|
||||
*
|
||||
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
|
||||
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
|
||||
* `Approval` event during `transferFrom` operations.
|
||||
*
|
||||
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
|
||||
* true using the following override:
|
||||
*
|
||||
* ```solidity
|
||||
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
|
||||
* super._approve(owner, spender, value, true);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Requirements are the same as {_approve}.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
|
||||
ERC20Storage storage $ = _getERC20Storage();
|
||||
if (owner == address(0)) {
|
||||
revert ERC20InvalidApprover(address(0));
|
||||
}
|
||||
if (spender == address(0)) {
|
||||
revert ERC20InvalidSpender(address(0));
|
||||
}
|
||||
$._allowances[owner][spender] = value;
|
||||
if (emitEvent) {
|
||||
emit Approval(owner, spender, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
|
||||
*
|
||||
* Does not update the allowance value in case of infinite allowance.
|
||||
* Revert if not enough allowance is available.
|
||||
*
|
||||
* Does not emit an {Approval} event.
|
||||
*/
|
||||
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
|
||||
uint256 currentAllowance = allowance(owner, spender);
|
||||
if (currentAllowance < type(uint256).max) {
|
||||
if (currentAllowance < value) {
|
||||
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
|
||||
}
|
||||
unchecked {
|
||||
_approve(owner, spender, currentAllowance - value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
import {Initializable} from "../proxy/utils/Initializable.sol";
|
||||
|
||||
/**
|
||||
* @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 ContextUpgradeable is Initializable {
|
||||
function __Context_init() internal onlyInitializing {
|
||||
}
|
||||
|
||||
function __Context_init_unchained() internal onlyInitializing {
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
import {Initializable} from "../proxy/utils/Initializable.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module that helps prevent reentrant calls to a function.
|
||||
*
|
||||
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
|
||||
* available, which can be applied to functions to make sure there are no nested
|
||||
* (reentrant) calls to them.
|
||||
*
|
||||
* Note that because there is a single `nonReentrant` guard, functions marked as
|
||||
* `nonReentrant` may not call one another. This can be worked around by making
|
||||
* those functions `private`, and then adding `external` `nonReentrant` entry
|
||||
* points to them.
|
||||
*
|
||||
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
|
||||
* consider using {ReentrancyGuardTransient} instead.
|
||||
*
|
||||
* TIP: If you would like to learn more about reentrancy and alternative ways
|
||||
* to protect against it, check out our blog post
|
||||
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
|
||||
*/
|
||||
abstract contract ReentrancyGuardUpgradeable is Initializable {
|
||||
// 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;
|
||||
|
||||
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
|
||||
struct ReentrancyGuardStorage {
|
||||
uint256 _status;
|
||||
}
|
||||
|
||||
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
|
||||
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
|
||||
|
||||
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
|
||||
assembly {
|
||||
$.slot := ReentrancyGuardStorageLocation
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Unauthorized reentrant call.
|
||||
*/
|
||||
error ReentrancyGuardReentrantCall();
|
||||
|
||||
function __ReentrancyGuard_init() internal onlyInitializing {
|
||||
__ReentrancyGuard_init_unchained();
|
||||
}
|
||||
|
||||
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
|
||||
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
|
||||
$._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 {
|
||||
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
|
||||
// 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 {
|
||||
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
|
||||
// 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) {
|
||||
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
|
||||
return $._status == ENTERED;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
|
||||
import {Initializable} from "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165 {
|
||||
function __ERC165_init() internal onlyInitializing {
|
||||
}
|
||||
|
||||
function __ERC165_init_unchained() internal onlyInitializing {
|
||||
}
|
||||
/// @inheritdoc IERC165
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
|
||||
return interfaceId == type(IERC165).interfaceId;
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.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` to `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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev External interface of AccessControl declared to support ERC165 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 signaling 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, an admin role
|
||||
* bearer except when using {AccessControl-_setupRole}.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Context} from "../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module which provides a basic access control mechanism, where
|
||||
* there is an account (an owner) that can be granted exclusive access to
|
||||
* specific functions.
|
||||
*
|
||||
* The initial owner is set to the address provided by the deployer. This can
|
||||
* later be changed with {transferOwnership}.
|
||||
*
|
||||
* This module is used through inheritance. It will make available the modifier
|
||||
* `onlyOwner`, which can be applied to your functions to restrict their use to
|
||||
* the owner.
|
||||
*/
|
||||
abstract contract Ownable is Context {
|
||||
address private _owner;
|
||||
|
||||
/**
|
||||
* @dev The caller account is not authorized to perform an operation.
|
||||
*/
|
||||
error OwnableUnauthorizedAccount(address account);
|
||||
|
||||
/**
|
||||
* @dev The owner is not a valid owner account. (eg. `address(0)`)
|
||||
*/
|
||||
error OwnableInvalidOwner(address owner);
|
||||
|
||||
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
|
||||
*/
|
||||
constructor(address initialOwner) {
|
||||
if (initialOwner == address(0)) {
|
||||
revert OwnableInvalidOwner(address(0));
|
||||
}
|
||||
_transferOwnership(initialOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Throws if called by any account other than the owner.
|
||||
*/
|
||||
modifier onlyOwner() {
|
||||
_checkOwner();
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the current owner.
|
||||
*/
|
||||
function owner() public view virtual returns (address) {
|
||||
return _owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Throws if the sender is not the owner.
|
||||
*/
|
||||
function _checkOwner() internal view virtual {
|
||||
if (owner() != _msgSender()) {
|
||||
revert OwnableUnauthorizedAccount(_msgSender());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Leaves the contract without owner. It will not be possible to call
|
||||
* `onlyOwner` functions. Can only be called by the current owner.
|
||||
*
|
||||
* NOTE: Renouncing ownership will leave the contract without an owner,
|
||||
* thereby disabling any functionality that is only available to the owner.
|
||||
*/
|
||||
function renounceOwnership() public virtual onlyOwner {
|
||||
_transferOwnership(address(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers ownership of the contract to a new account (`newOwner`).
|
||||
* Can only be called by the current owner.
|
||||
*/
|
||||
function transferOwnership(address newOwner) public virtual onlyOwner {
|
||||
if (newOwner == address(0)) {
|
||||
revert OwnableInvalidOwner(address(0));
|
||||
}
|
||||
_transferOwnership(newOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers ownership of the contract to a new account (`newOwner`).
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _transferOwnership(address newOwner) internal virtual {
|
||||
address oldOwner = _owner;
|
||||
_owner = newOwner;
|
||||
emit OwnershipTransferred(oldOwner, newOwner);
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// 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";
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4906.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "./IERC165.sol";
|
||||
import {IERC721} from "./IERC721.sol";
|
||||
|
||||
/// @title EIP-721 Metadata Update Extension
|
||||
interface IERC4906 is IERC165, IERC721 {
|
||||
/// @dev This event emits when the metadata of a token is changed.
|
||||
/// So that the third-party platforms such as NFT market could
|
||||
/// timely update the images and related attributes of the NFT.
|
||||
event MetadataUpdate(uint256 _tokenId);
|
||||
|
||||
/// @dev This event emits when the metadata of a range of tokens is changed.
|
||||
/// So that the third-party platforms such as NFT market could
|
||||
/// timely update the images and related attributes of the NFTs.
|
||||
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
interface IERC5267 {
|
||||
/**
|
||||
* @dev MAY be emitted to signal that the domain could have changed.
|
||||
*/
|
||||
event EIP712DomainChanged();
|
||||
|
||||
/**
|
||||
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
|
||||
* signature.
|
||||
*/
|
||||
function eip712Domain()
|
||||
external
|
||||
view
|
||||
returns (
|
||||
bytes1 fields,
|
||||
string memory name,
|
||||
string memory version,
|
||||
uint256 chainId,
|
||||
address verifyingContract,
|
||||
bytes32 salt,
|
||||
uint256[] memory extensions
|
||||
);
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "../token/ERC721/IERC721.sol";
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
|
||||
* proxy whose upgrades are fully controlled by the current implementation.
|
||||
*/
|
||||
interface IERC1822Proxiable {
|
||||
/**
|
||||
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
|
||||
* address.
|
||||
*
|
||||
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
|
||||
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
|
||||
* function revert if invoked through a proxy.
|
||||
*/
|
||||
function proxiableUUID() external view returns (bytes32);
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Standard ERC20 Errors
|
||||
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
|
||||
*/
|
||||
interface IERC20Errors {
|
||||
/**
|
||||
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
* @param balance Current balance for the interacting account.
|
||||
* @param needed Minimum amount required to perform a transfer.
|
||||
*/
|
||||
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
*/
|
||||
error ERC20InvalidSender(address sender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC20InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
|
||||
* @param spender Address that may be allowed to operate on tokens without being their owner.
|
||||
* @param allowance Amount of tokens a `spender` is allowed to operate with.
|
||||
* @param needed Minimum amount required to perform a transfer.
|
||||
*/
|
||||
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
|
||||
* @param approver Address initiating an approval operation.
|
||||
*/
|
||||
error ERC20InvalidApprover(address approver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
|
||||
* @param spender Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC20InvalidSpender(address spender);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Standard ERC721 Errors
|
||||
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
|
||||
*/
|
||||
interface IERC721Errors {
|
||||
/**
|
||||
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
|
||||
* Used in balance queries.
|
||||
* @param owner Address of the current owner of a token.
|
||||
*/
|
||||
error ERC721InvalidOwner(address owner);
|
||||
|
||||
/**
|
||||
* @dev Indicates a `tokenId` whose `owner` is the zero address.
|
||||
* @param tokenId Identifier number of a token.
|
||||
*/
|
||||
error ERC721NonexistentToken(uint256 tokenId);
|
||||
|
||||
/**
|
||||
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
* @param tokenId Identifier number of a token.
|
||||
* @param owner Address of the current owner of a token.
|
||||
*/
|
||||
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
*/
|
||||
error ERC721InvalidSender(address sender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC721InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
* @param tokenId Identifier number of a token.
|
||||
*/
|
||||
error ERC721InsufficientApproval(address operator, uint256 tokenId);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
|
||||
* @param approver Address initiating an approval operation.
|
||||
*/
|
||||
error ERC721InvalidApprover(address approver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC721InvalidOperator(address operator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Standard ERC1155 Errors
|
||||
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
|
||||
*/
|
||||
interface IERC1155Errors {
|
||||
/**
|
||||
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
* @param balance Current balance for the interacting account.
|
||||
* @param needed Minimum amount required to perform a transfer.
|
||||
* @param tokenId Identifier number of a token.
|
||||
*/
|
||||
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
*/
|
||||
error ERC1155InvalidSender(address sender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC1155InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
* @param owner Address of the current owner of a token.
|
||||
*/
|
||||
error ERC1155MissingApprovalForAll(address operator, address owner);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
|
||||
* @param approver Address initiating an approval operation.
|
||||
*/
|
||||
error ERC1155InvalidApprover(address approver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC1155InvalidOperator(address operator);
|
||||
|
||||
/**
|
||||
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
|
||||
* Used in batch transfers.
|
||||
* @param idsLength Length of the array of token identifiers
|
||||
* @param valuesLength Length of the array of token amounts
|
||||
*/
|
||||
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Proxy} from "../Proxy.sol";
|
||||
import {ERC1967Utils} from "./ERC1967Utils.sol";
|
||||
|
||||
/**
|
||||
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
|
||||
* implementation address that can be changed. This address is stored in storage in the location specified by
|
||||
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
|
||||
* implementation behind the proxy.
|
||||
*/
|
||||
contract ERC1967Proxy is Proxy {
|
||||
/**
|
||||
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
|
||||
*
|
||||
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
|
||||
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - If `data` is empty, `msg.value` must be zero.
|
||||
*/
|
||||
constructor(address implementation, bytes memory _data) payable {
|
||||
ERC1967Utils.upgradeToAndCall(implementation, _data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current implementation address.
|
||||
*
|
||||
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
|
||||
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
|
||||
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
|
||||
*/
|
||||
function _implementation() internal view virtual override returns (address) {
|
||||
return ERC1967Utils.getImplementation();
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IBeacon} from "../beacon/IBeacon.sol";
|
||||
import {Address} from "../../utils/Address.sol";
|
||||
import {StorageSlot} from "../../utils/StorageSlot.sol";
|
||||
|
||||
/**
|
||||
* @dev This abstract contract provides getters and event emitting update functions for
|
||||
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
|
||||
*/
|
||||
library ERC1967Utils {
|
||||
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
|
||||
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
|
||||
/**
|
||||
* @dev Emitted when the implementation is upgraded.
|
||||
*/
|
||||
event Upgraded(address indexed implementation);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the admin account has changed.
|
||||
*/
|
||||
event AdminChanged(address previousAdmin, address newAdmin);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the beacon is changed.
|
||||
*/
|
||||
event BeaconUpgraded(address indexed beacon);
|
||||
|
||||
/**
|
||||
* @dev Storage slot with the address of the current implementation.
|
||||
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
|
||||
*/
|
||||
// solhint-disable-next-line private-vars-leading-underscore
|
||||
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
|
||||
|
||||
/**
|
||||
* @dev The `implementation` of the proxy is invalid.
|
||||
*/
|
||||
error ERC1967InvalidImplementation(address implementation);
|
||||
|
||||
/**
|
||||
* @dev The `admin` of the proxy is invalid.
|
||||
*/
|
||||
error ERC1967InvalidAdmin(address admin);
|
||||
|
||||
/**
|
||||
* @dev The `beacon` of the proxy is invalid.
|
||||
*/
|
||||
error ERC1967InvalidBeacon(address beacon);
|
||||
|
||||
/**
|
||||
* @dev An upgrade function sees `msg.value > 0` that may be lost.
|
||||
*/
|
||||
error ERC1967NonPayable();
|
||||
|
||||
/**
|
||||
* @dev Returns the current implementation address.
|
||||
*/
|
||||
function getImplementation() internal view returns (address) {
|
||||
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Stores a new address in the EIP1967 implementation slot.
|
||||
*/
|
||||
function _setImplementation(address newImplementation) private {
|
||||
if (newImplementation.code.length == 0) {
|
||||
revert ERC1967InvalidImplementation(newImplementation);
|
||||
}
|
||||
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
|
||||
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
|
||||
* to avoid stuck value in the contract.
|
||||
*
|
||||
* Emits an {IERC1967-Upgraded} event.
|
||||
*/
|
||||
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
|
||||
_setImplementation(newImplementation);
|
||||
emit Upgraded(newImplementation);
|
||||
|
||||
if (data.length > 0) {
|
||||
Address.functionDelegateCall(newImplementation, data);
|
||||
} else {
|
||||
_checkNonPayable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Storage slot with the admin of the contract.
|
||||
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
|
||||
*/
|
||||
// solhint-disable-next-line private-vars-leading-underscore
|
||||
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
|
||||
|
||||
/**
|
||||
* @dev Returns the current admin.
|
||||
*
|
||||
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
|
||||
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
|
||||
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
|
||||
*/
|
||||
function getAdmin() internal view returns (address) {
|
||||
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Stores a new address in the EIP1967 admin slot.
|
||||
*/
|
||||
function _setAdmin(address newAdmin) private {
|
||||
if (newAdmin == address(0)) {
|
||||
revert ERC1967InvalidAdmin(address(0));
|
||||
}
|
||||
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the admin of the proxy.
|
||||
*
|
||||
* Emits an {IERC1967-AdminChanged} event.
|
||||
*/
|
||||
function changeAdmin(address newAdmin) internal {
|
||||
emit AdminChanged(getAdmin(), newAdmin);
|
||||
_setAdmin(newAdmin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
|
||||
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
|
||||
*/
|
||||
// solhint-disable-next-line private-vars-leading-underscore
|
||||
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
|
||||
|
||||
/**
|
||||
* @dev Returns the current beacon.
|
||||
*/
|
||||
function getBeacon() internal view returns (address) {
|
||||
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Stores a new beacon in the EIP1967 beacon slot.
|
||||
*/
|
||||
function _setBeacon(address newBeacon) private {
|
||||
if (newBeacon.code.length == 0) {
|
||||
revert ERC1967InvalidBeacon(newBeacon);
|
||||
}
|
||||
|
||||
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
|
||||
|
||||
address beaconImplementation = IBeacon(newBeacon).implementation();
|
||||
if (beaconImplementation.code.length == 0) {
|
||||
revert ERC1967InvalidImplementation(beaconImplementation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Change the beacon and trigger a setup call if data is nonempty.
|
||||
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
|
||||
* to avoid stuck value in the contract.
|
||||
*
|
||||
* Emits an {IERC1967-BeaconUpgraded} event.
|
||||
*
|
||||
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
|
||||
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
|
||||
* efficiency.
|
||||
*/
|
||||
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
|
||||
_setBeacon(newBeacon);
|
||||
emit BeaconUpgraded(newBeacon);
|
||||
|
||||
if (data.length > 0) {
|
||||
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
|
||||
} else {
|
||||
_checkNonPayable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
|
||||
* if an upgrade doesn't perform an initialization call.
|
||||
*/
|
||||
function _checkNonPayable() private {
|
||||
if (msg.value > 0) {
|
||||
revert ERC1967NonPayable();
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
|
||||
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
|
||||
* be specified by overriding the virtual {_implementation} function.
|
||||
*
|
||||
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
|
||||
* different contract through the {_delegate} function.
|
||||
*
|
||||
* The success and return data of the delegated call will be returned back to the caller of the proxy.
|
||||
*/
|
||||
abstract contract Proxy {
|
||||
/**
|
||||
* @dev Delegates the current call to `implementation`.
|
||||
*
|
||||
* This function does not return to its internal call site, it will return directly to the external caller.
|
||||
*/
|
||||
function _delegate(address implementation) internal virtual {
|
||||
assembly {
|
||||
// Copy msg.data. We take full control of memory in this inline assembly
|
||||
// block because it will not return to Solidity code. We overwrite the
|
||||
// Solidity scratch pad at memory position 0.
|
||||
calldatacopy(0, 0, calldatasize())
|
||||
|
||||
// Call the implementation.
|
||||
// out and outsize are 0 because we don't know the size yet.
|
||||
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
|
||||
|
||||
// Copy the returned data.
|
||||
returndatacopy(0, 0, returndatasize())
|
||||
|
||||
switch result
|
||||
// delegatecall returns 0 on error.
|
||||
case 0 {
|
||||
revert(0, returndatasize())
|
||||
}
|
||||
default {
|
||||
return(0, returndatasize())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
|
||||
* function and {_fallback} should delegate.
|
||||
*/
|
||||
function _implementation() internal view virtual returns (address);
|
||||
|
||||
/**
|
||||
* @dev Delegates the current call to the address returned by `_implementation()`.
|
||||
*
|
||||
* This function does not return to its internal call site, it will return directly to the external caller.
|
||||
*/
|
||||
function _fallback() internal virtual {
|
||||
_delegate(_implementation());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
|
||||
* function in the contract matches the call data.
|
||||
*/
|
||||
fallback() external payable virtual {
|
||||
_fallback();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/BeaconProxy.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IBeacon} from "./IBeacon.sol";
|
||||
import {Proxy} from "../Proxy.sol";
|
||||
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
|
||||
|
||||
/**
|
||||
* @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.
|
||||
*
|
||||
* The beacon address can only be set once during construction, and cannot be changed afterwards. It is stored in an
|
||||
* immutable variable to avoid unnecessary storage reads, and also in the beacon storage slot specified by
|
||||
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] so that it can be accessed externally.
|
||||
*
|
||||
* CAUTION: Since the beacon address can never be changed, you must ensure that you either control the beacon, or trust
|
||||
* the beacon to not upgrade the implementation maliciously.
|
||||
*
|
||||
* IMPORTANT: Do not use the implementation logic to modify the beacon storage slot. Doing so would leave the proxy in
|
||||
* an inconsistent state where the beacon storage slot does not match the beacon address.
|
||||
*/
|
||||
contract BeaconProxy is Proxy {
|
||||
// An immutable address for the beacon to avoid unnecessary SLOADs before each delegate call.
|
||||
address private immutable _beacon;
|
||||
|
||||
/**
|
||||
* @dev Initializes the proxy with `beacon`.
|
||||
*
|
||||
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
|
||||
* will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity
|
||||
* constructor.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `beacon` must be a contract with the interface {IBeacon}.
|
||||
* - If `data` is empty, `msg.value` must be zero.
|
||||
*/
|
||||
constructor(address beacon, bytes memory data) payable {
|
||||
ERC1967Utils.upgradeBeaconToAndCall(beacon, data);
|
||||
_beacon = beacon;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current implementation address of the associated beacon.
|
||||
*/
|
||||
function _implementation() internal view virtual override returns (address) {
|
||||
return IBeacon(_getBeacon()).implementation();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the beacon.
|
||||
*/
|
||||
function _getBeacon() internal view virtual returns (address) {
|
||||
return _beacon;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev This is the interface that {BeaconProxy} expects of its beacon.
|
||||
*/
|
||||
interface IBeacon {
|
||||
/**
|
||||
* @dev Must return an address that can be used as a delegate call target.
|
||||
*
|
||||
* {UpgradeableBeacon} will check that this address is a contract.
|
||||
*/
|
||||
function implementation() external view returns (address);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/UpgradeableBeacon.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IBeacon} from "./IBeacon.sol";
|
||||
import {Ownable} from "../../access/Ownable.sol";
|
||||
|
||||
/**
|
||||
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
|
||||
* implementation contract, which is where they will delegate all function calls.
|
||||
*
|
||||
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
|
||||
*/
|
||||
contract UpgradeableBeacon is IBeacon, Ownable {
|
||||
address private _implementation;
|
||||
|
||||
/**
|
||||
* @dev The `implementation` of the beacon is invalid.
|
||||
*/
|
||||
error BeaconInvalidImplementation(address implementation);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the implementation returned by the beacon is changed.
|
||||
*/
|
||||
event Upgraded(address indexed implementation);
|
||||
|
||||
/**
|
||||
* @dev Sets the address of the initial implementation, and the initial owner who can upgrade the beacon.
|
||||
*/
|
||||
constructor(address implementation_, address initialOwner) Ownable(initialOwner) {
|
||||
_setImplementation(implementation_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current implementation address.
|
||||
*/
|
||||
function implementation() public view virtual returns (address) {
|
||||
return _implementation;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Upgrades the beacon to a new implementation.
|
||||
*
|
||||
* Emits an {Upgraded} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - msg.sender must be the owner of the contract.
|
||||
* - `newImplementation` must be a contract.
|
||||
*/
|
||||
function upgradeTo(address newImplementation) public virtual onlyOwner {
|
||||
_setImplementation(newImplementation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the implementation contract address for this beacon
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `newImplementation` must be a contract.
|
||||
*/
|
||||
function _setImplementation(address newImplementation) private {
|
||||
if (newImplementation.code.length == 0) {
|
||||
revert BeaconInvalidImplementation(newImplementation);
|
||||
}
|
||||
_implementation = newImplementation;
|
||||
emit Upgraded(newImplementation);
|
||||
}
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "./IERC20.sol";
|
||||
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the {IERC20} interface.
|
||||
*
|
||||
* This implementation is agnostic to the way tokens are created. This means
|
||||
* that a supply mechanism has to be added in a derived contract using {_mint}.
|
||||
*
|
||||
* TIP: For a detailed writeup see our guide
|
||||
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
|
||||
* to implement supply mechanisms].
|
||||
*
|
||||
* The default value of {decimals} is 18. To change this, you should override
|
||||
* this function so it returns a different value.
|
||||
*
|
||||
* We have followed general OpenZeppelin Contracts guidelines: functions revert
|
||||
* instead returning `false` on failure. This behavior is nonetheless
|
||||
* conventional and does not conflict with the expectations of ERC20
|
||||
* applications.
|
||||
*
|
||||
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
|
||||
* This allows applications to reconstruct the allowance for all accounts just
|
||||
* by listening to said events. Other implementations of the EIP may not emit
|
||||
* these events, as it isn't required by the specification.
|
||||
*/
|
||||
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
|
||||
mapping(address account => uint256) private _balances;
|
||||
|
||||
mapping(address account => mapping(address spender => uint256)) private _allowances;
|
||||
|
||||
uint256 private _totalSupply;
|
||||
|
||||
string private _name;
|
||||
string private _symbol;
|
||||
|
||||
/**
|
||||
* @dev Sets the values for {name} and {symbol}.
|
||||
*
|
||||
* All two of these values are immutable: they can only be set once during
|
||||
* construction.
|
||||
*/
|
||||
constructor(string memory name_, string memory symbol_) {
|
||||
_name = name_;
|
||||
_symbol = symbol_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() public view virtual returns (string memory) {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token, usually a shorter version of the
|
||||
* name.
|
||||
*/
|
||||
function symbol() public view virtual returns (string memory) {
|
||||
return _symbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of decimals used to get its user representation.
|
||||
* For example, if `decimals` equals `2`, a balance of `505` tokens should
|
||||
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
|
||||
*
|
||||
* Tokens usually opt for a value of 18, imitating the relationship between
|
||||
* Ether and Wei. This is the default value returned by this function, unless
|
||||
* it's overridden.
|
||||
*
|
||||
* NOTE: This information is only used for _display_ purposes: it in
|
||||
* no way affects any of the arithmetic of the contract, including
|
||||
* {IERC20-balanceOf} and {IERC20-transfer}.
|
||||
*/
|
||||
function decimals() public view virtual returns (uint8) {
|
||||
return 18;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-totalSupply}.
|
||||
*/
|
||||
function totalSupply() public view virtual returns (uint256) {
|
||||
return _totalSupply;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-balanceOf}.
|
||||
*/
|
||||
function balanceOf(address account) public view virtual returns (uint256) {
|
||||
return _balances[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transfer}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - the caller must have a balance of at least `value`.
|
||||
*/
|
||||
function transfer(address to, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_transfer(owner, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-allowance}.
|
||||
*/
|
||||
function allowance(address owner, address spender) public view virtual returns (uint256) {
|
||||
return _allowances[owner][spender];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-approve}.
|
||||
*
|
||||
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
|
||||
* `transferFrom`. This is semantically equivalent to an infinite approval.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `spender` cannot be the zero address.
|
||||
*/
|
||||
function approve(address spender, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_approve(owner, spender, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transferFrom}.
|
||||
*
|
||||
* Emits an {Approval} event indicating the updated allowance. This is not
|
||||
* required by the EIP. See the note at the beginning of {ERC20}.
|
||||
*
|
||||
* NOTE: Does not update the allowance if the current allowance
|
||||
* is the maximum `uint256`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` and `to` cannot be the zero address.
|
||||
* - `from` must have a balance of at least `value`.
|
||||
* - the caller must have allowance for ``from``'s tokens of at least
|
||||
* `value`.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
|
||||
address spender = _msgSender();
|
||||
_spendAllowance(from, spender, value);
|
||||
_transfer(from, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to`.
|
||||
*
|
||||
* This internal function is equivalent to {transfer}, and can be used to
|
||||
* e.g. implement automatic token fees, slashing mechanisms, etc.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _transfer(address from, address to, uint256 value) internal {
|
||||
if (from == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
if (to == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
|
||||
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
|
||||
* this function.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual {
|
||||
if (from == address(0)) {
|
||||
// Overflow check required: The rest of the code assumes that totalSupply never overflows
|
||||
_totalSupply += value;
|
||||
} else {
|
||||
uint256 fromBalance = _balances[from];
|
||||
if (fromBalance < value) {
|
||||
revert ERC20InsufficientBalance(from, fromBalance, value);
|
||||
}
|
||||
unchecked {
|
||||
// Overflow not possible: value <= fromBalance <= totalSupply.
|
||||
_balances[from] = fromBalance - value;
|
||||
}
|
||||
}
|
||||
|
||||
if (to == address(0)) {
|
||||
unchecked {
|
||||
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
|
||||
_totalSupply -= value;
|
||||
}
|
||||
} else {
|
||||
unchecked {
|
||||
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
|
||||
_balances[to] += value;
|
||||
}
|
||||
}
|
||||
|
||||
emit Transfer(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
|
||||
* Relies on the `_update` mechanism
|
||||
*
|
||||
* Emits a {Transfer} event with `from` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _mint(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(address(0), account, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
|
||||
* Relies on the `_update` mechanism.
|
||||
*
|
||||
* Emits a {Transfer} event with `to` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead
|
||||
*/
|
||||
function _burn(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
_update(account, address(0), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
|
||||
*
|
||||
* This internal function is equivalent to `approve`, and can be used to
|
||||
* e.g. set automatic allowances for certain subsystems, etc.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `owner` cannot be the zero address.
|
||||
* - `spender` cannot be the zero address.
|
||||
*
|
||||
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value) internal {
|
||||
_approve(owner, spender, value, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
|
||||
*
|
||||
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
|
||||
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
|
||||
* `Approval` event during `transferFrom` operations.
|
||||
*
|
||||
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
|
||||
* true using the following override:
|
||||
* ```
|
||||
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
|
||||
* super._approve(owner, spender, value, true);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Requirements are the same as {_approve}.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
|
||||
if (owner == address(0)) {
|
||||
revert ERC20InvalidApprover(address(0));
|
||||
}
|
||||
if (spender == address(0)) {
|
||||
revert ERC20InvalidSpender(address(0));
|
||||
}
|
||||
_allowances[owner][spender] = value;
|
||||
if (emitEvent) {
|
||||
emit Approval(owner, spender, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
|
||||
*
|
||||
* Does not update the allowance value in case of infinite allowance.
|
||||
* Revert if not enough allowance is available.
|
||||
*
|
||||
* Does not emit an {Approval} event.
|
||||
*/
|
||||
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
|
||||
uint256 currentAllowance = allowance(owner, spender);
|
||||
if (currentAllowance != type(uint256).max) {
|
||||
if (currentAllowance < value) {
|
||||
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
|
||||
}
|
||||
unchecked {
|
||||
_approve(owner, spender, currentAllowance - value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC20 standard as defined in the EIP.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Context} from "../../../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {ERC20} that allows token holders to destroy both their own
|
||||
* tokens and those that they have an allowance for, in a way that can be
|
||||
* recognized off-chain (via event analysis).
|
||||
*/
|
||||
abstract contract ERC20Burnable is Context, ERC20 {
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from the caller.
|
||||
*
|
||||
* See {ERC20-_burn}.
|
||||
*/
|
||||
function burn(uint256 value) public virtual {
|
||||
_burn(_msgSender(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from `account`, deducting from
|
||||
* the caller's allowance.
|
||||
*
|
||||
* See {ERC20-_burn} and {ERC20-allowance}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have allowance for ``accounts``'s tokens of at least
|
||||
* `value`.
|
||||
*/
|
||||
function burnFrom(address account, uint256 value) public virtual {
|
||||
_spendAllowance(account, _msgSender(), value);
|
||||
_burn(account, value);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../IERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface for the optional metadata functions from the ERC20 standard.
|
||||
*/
|
||||
interface IERC20Metadata is IERC20 {
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token.
|
||||
*/
|
||||
function symbol() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the decimals places of the token.
|
||||
*/
|
||||
function decimals() external view returns (uint8);
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
|
||||
*
|
||||
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
|
||||
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
|
||||
* need to send a transaction, and thus is not required to hold Ether at all.
|
||||
*
|
||||
* ==== Security Considerations
|
||||
*
|
||||
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
|
||||
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
|
||||
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
|
||||
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
|
||||
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
|
||||
* generally recommended is:
|
||||
*
|
||||
* ```solidity
|
||||
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
|
||||
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
|
||||
* doThing(..., value);
|
||||
* }
|
||||
*
|
||||
* function doThing(..., uint256 value) public {
|
||||
* token.safeTransferFrom(msg.sender, address(this), value);
|
||||
* ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
|
||||
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
|
||||
* {SafeERC20-safeTransferFrom}).
|
||||
*
|
||||
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
|
||||
* contracts should have entry points that don't rely on permit.
|
||||
*/
|
||||
interface IERC20Permit {
|
||||
/**
|
||||
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
|
||||
* given ``owner``'s signed approval.
|
||||
*
|
||||
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
|
||||
* ordering also apply here.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `spender` cannot be the zero address.
|
||||
* - `deadline` must be a timestamp in the future.
|
||||
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
|
||||
* over the EIP712-formatted function arguments.
|
||||
* - the signature must use ``owner``'s current nonce (see {nonces}).
|
||||
*
|
||||
* For more information on the signature format, see the
|
||||
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
|
||||
* section].
|
||||
*
|
||||
* CAUTION: See Security Considerations above.
|
||||
*/
|
||||
function permit(
|
||||
address owner,
|
||||
address spender,
|
||||
uint256 value,
|
||||
uint256 deadline,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the current nonce for `owner`. This value must be
|
||||
* included whenever a signature is generated for {permit}.
|
||||
*
|
||||
* Every successful call to {permit} increases ``owner``'s nonce by one. This
|
||||
* prevents a signature from being used multiple times.
|
||||
*/
|
||||
function nonces(address owner) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function DOMAIN_SEPARATOR() external view returns (bytes32);
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../IERC20.sol";
|
||||
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
|
||||
import {Address} from "../../../utils/Address.sol";
|
||||
|
||||
/**
|
||||
* @title SafeERC20
|
||||
* @dev Wrappers around ERC20 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 {
|
||||
using Address for address;
|
||||
|
||||
/**
|
||||
* @dev An operation with an ERC20 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 Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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 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).
|
||||
*/
|
||||
function _callOptionalReturn(IERC20 token, bytes memory data) private {
|
||||
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
|
||||
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
|
||||
// the target address contains contract code and also asserts for success in the low-level call.
|
||||
|
||||
bytes memory returndata = address(token).functionCall(data);
|
||||
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
|
||||
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 silents catches all reverts and returns a bool instead.
|
||||
*/
|
||||
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
|
||||
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
|
||||
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
|
||||
// and not revert is the subcall reverts.
|
||||
|
||||
(bool success, bytes memory returndata) = address(token).call(data);
|
||||
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
|
||||
}
|
||||
}
|
||||
+483
@@ -0,0 +1,483 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "./IERC721.sol";
|
||||
import {IERC721Receiver} from "./IERC721Receiver.sol";
|
||||
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {Strings} from "../../utils/Strings.sol";
|
||||
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
|
||||
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
|
||||
* the Metadata extension, but not including the Enumerable extension, which is available separately as
|
||||
* {ERC721Enumerable}.
|
||||
*/
|
||||
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
|
||||
using Strings for uint256;
|
||||
|
||||
// Token name
|
||||
string private _name;
|
||||
|
||||
// Token symbol
|
||||
string private _symbol;
|
||||
|
||||
mapping(uint256 tokenId => address) private _owners;
|
||||
|
||||
mapping(address owner => uint256) private _balances;
|
||||
|
||||
mapping(uint256 tokenId => address) private _tokenApprovals;
|
||||
|
||||
mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
|
||||
*/
|
||||
constructor(string memory name_, string memory symbol_) {
|
||||
_name = name_;
|
||||
_symbol = symbol_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
|
||||
return
|
||||
interfaceId == type(IERC721).interfaceId ||
|
||||
interfaceId == type(IERC721Metadata).interfaceId ||
|
||||
super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-balanceOf}.
|
||||
*/
|
||||
function balanceOf(address owner) public view virtual returns (uint256) {
|
||||
if (owner == address(0)) {
|
||||
revert ERC721InvalidOwner(address(0));
|
||||
}
|
||||
return _balances[owner];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-ownerOf}.
|
||||
*/
|
||||
function ownerOf(uint256 tokenId) public view virtual returns (address) {
|
||||
return _requireOwned(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-name}.
|
||||
*/
|
||||
function name() public view virtual returns (string memory) {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-symbol}.
|
||||
*/
|
||||
function symbol() public view virtual returns (string memory) {
|
||||
return _symbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-tokenURI}.
|
||||
*/
|
||||
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
|
||||
_requireOwned(tokenId);
|
||||
|
||||
string memory baseURI = _baseURI();
|
||||
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
|
||||
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
|
||||
* by default, can be overridden in child contracts.
|
||||
*/
|
||||
function _baseURI() internal view virtual returns (string memory) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-approve}.
|
||||
*/
|
||||
function approve(address to, uint256 tokenId) public virtual {
|
||||
_approve(to, tokenId, _msgSender());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-getApproved}.
|
||||
*/
|
||||
function getApproved(uint256 tokenId) public view virtual returns (address) {
|
||||
_requireOwned(tokenId);
|
||||
|
||||
return _getApproved(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-setApprovalForAll}.
|
||||
*/
|
||||
function setApprovalForAll(address operator, bool approved) public virtual {
|
||||
_setApprovalForAll(_msgSender(), operator, approved);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-isApprovedForAll}.
|
||||
*/
|
||||
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
|
||||
return _operatorApprovals[owner][operator];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-transferFrom}.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 tokenId) public virtual {
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
|
||||
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
|
||||
address previousOwner = _update(to, tokenId, _msgSender());
|
||||
if (previousOwner != from) {
|
||||
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-safeTransferFrom}.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId) public {
|
||||
safeTransferFrom(from, to, tokenId, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-safeTransferFrom}.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
|
||||
transferFrom(from, to, tokenId);
|
||||
_checkOnERC721Received(from, to, tokenId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
|
||||
*
|
||||
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
|
||||
* core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
|
||||
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
|
||||
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
|
||||
*/
|
||||
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
|
||||
return _owners[tokenId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
|
||||
*/
|
||||
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
|
||||
return _tokenApprovals[tokenId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
|
||||
* particular (ignoring whether it is owned by `owner`).
|
||||
*
|
||||
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
|
||||
* assumption.
|
||||
*/
|
||||
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
|
||||
return
|
||||
spender != address(0) &&
|
||||
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
|
||||
* Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
|
||||
* the `spender` for the specific `tokenId`.
|
||||
*
|
||||
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
|
||||
* assumption.
|
||||
*/
|
||||
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
|
||||
if (!_isAuthorized(owner, spender, tokenId)) {
|
||||
if (owner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
} else {
|
||||
revert ERC721InsufficientApproval(spender, tokenId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
|
||||
*
|
||||
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
|
||||
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
|
||||
*
|
||||
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
|
||||
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
|
||||
* remain consistent with one another.
|
||||
*/
|
||||
function _increaseBalance(address account, uint128 value) internal virtual {
|
||||
unchecked {
|
||||
_balances[account] += value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
|
||||
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
|
||||
*
|
||||
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
|
||||
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*
|
||||
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
|
||||
*/
|
||||
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
|
||||
address from = _ownerOf(tokenId);
|
||||
|
||||
// Perform (optional) operator check
|
||||
if (auth != address(0)) {
|
||||
_checkAuthorized(from, auth, tokenId);
|
||||
}
|
||||
|
||||
// Execute the update
|
||||
if (from != address(0)) {
|
||||
// Clear approval. No need to re-authorize or emit the Approval event
|
||||
_approve(address(0), tokenId, address(0), false);
|
||||
|
||||
unchecked {
|
||||
_balances[from] -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (to != address(0)) {
|
||||
unchecked {
|
||||
_balances[to] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
_owners[tokenId] = to;
|
||||
|
||||
emit Transfer(from, to, tokenId);
|
||||
|
||||
return from;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mints `tokenId` and transfers it to `to`.
|
||||
*
|
||||
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must not exist.
|
||||
* - `to` cannot be the zero address.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _mint(address to, uint256 tokenId) internal {
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
address previousOwner = _update(to, tokenId, address(0));
|
||||
if (previousOwner != address(0)) {
|
||||
revert ERC721InvalidSender(address(0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must not exist.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _safeMint(address to, uint256 tokenId) internal {
|
||||
_safeMint(to, tokenId, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
|
||||
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
|
||||
*/
|
||||
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
|
||||
_mint(to, tokenId);
|
||||
_checkOnERC721Received(address(0), to, tokenId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys `tokenId`.
|
||||
* The approval is cleared when the token is burned.
|
||||
* This is an internal function that does not check if the sender is authorized to operate on the token.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must exist.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _burn(uint256 tokenId) internal {
|
||||
address previousOwner = _update(address(0), tokenId, address(0));
|
||||
if (previousOwner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers `tokenId` from `from` to `to`.
|
||||
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must be owned by `from`.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _transfer(address from, address to, uint256 tokenId) internal {
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
address previousOwner = _update(to, tokenId, address(0));
|
||||
if (previousOwner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
} else if (previousOwner != from) {
|
||||
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
|
||||
* are aware of the ERC721 standard to prevent tokens from being forever locked.
|
||||
*
|
||||
* `data` is additional data, it has no specified format and it is sent in call to `to`.
|
||||
*
|
||||
* This internal function is like {safeTransferFrom} in the sense that it invokes
|
||||
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
|
||||
* implement alternative mechanisms to perform token transfer, such as signature-based.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` token must exist and be owned by `from`.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `from` cannot be the zero address.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _safeTransfer(address from, address to, uint256 tokenId) internal {
|
||||
_safeTransfer(from, to, tokenId, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
|
||||
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
|
||||
*/
|
||||
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
|
||||
_transfer(from, to, tokenId);
|
||||
_checkOnERC721Received(from, to, tokenId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Approve `to` to operate on `tokenId`
|
||||
*
|
||||
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
|
||||
* either the owner of the token, or approved to operate on all tokens held by this owner.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
|
||||
*/
|
||||
function _approve(address to, uint256 tokenId, address auth) internal {
|
||||
_approve(to, tokenId, auth, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
|
||||
* emitted in the context of transfers.
|
||||
*/
|
||||
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
|
||||
// Avoid reading the owner unless necessary
|
||||
if (emitEvent || auth != address(0)) {
|
||||
address owner = _requireOwned(tokenId);
|
||||
|
||||
// We do not use _isAuthorized because single-token approvals should not be able to call approve
|
||||
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
|
||||
revert ERC721InvalidApprover(auth);
|
||||
}
|
||||
|
||||
if (emitEvent) {
|
||||
emit Approval(owner, to, tokenId);
|
||||
}
|
||||
}
|
||||
|
||||
_tokenApprovals[tokenId] = to;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Approve `operator` to operate on all of `owner` tokens
|
||||
*
|
||||
* Requirements:
|
||||
* - operator can't be the address zero.
|
||||
*
|
||||
* Emits an {ApprovalForAll} event.
|
||||
*/
|
||||
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
|
||||
if (operator == address(0)) {
|
||||
revert ERC721InvalidOperator(operator);
|
||||
}
|
||||
_operatorApprovals[owner][operator] = approved;
|
||||
emit ApprovalForAll(owner, operator, approved);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
|
||||
* Returns the owner.
|
||||
*
|
||||
* Overrides to ownership logic should be done to {_ownerOf}.
|
||||
*/
|
||||
function _requireOwned(uint256 tokenId) internal view returns (address) {
|
||||
address owner = _ownerOf(tokenId);
|
||||
if (owner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
}
|
||||
return owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
|
||||
* recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
|
||||
*
|
||||
* @param from address representing the previous owner of the given token ID
|
||||
* @param to target address that will receive the tokens
|
||||
* @param tokenId uint256 ID of the token to be transferred
|
||||
* @param data bytes optional data to send along with the call
|
||||
*/
|
||||
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {
|
||||
if (to.code.length > 0) {
|
||||
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
|
||||
if (retval != IERC721Receiver.onERC721Received.selector) {
|
||||
revert ERC721InvalidReceiver(to);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
revert ERC721InvalidReceiver(to);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../../utils/introspection/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Required interface of an ERC721 compliant contract.
|
||||
*/
|
||||
interface IERC721 is IERC165 {
|
||||
/**
|
||||
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
|
||||
*/
|
||||
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
|
||||
*/
|
||||
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
|
||||
*/
|
||||
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
|
||||
|
||||
/**
|
||||
* @dev Returns the number of tokens in ``owner``'s account.
|
||||
*/
|
||||
function balanceOf(address owner) external view returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Returns the owner of the `tokenId` token.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must exist.
|
||||
*/
|
||||
function ownerOf(uint256 tokenId) external view returns (address owner);
|
||||
|
||||
/**
|
||||
* @dev Safely transfers `tokenId` token from `from` to `to`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must exist and be owned by `from`.
|
||||
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
|
||||
* a safe transfer.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
|
||||
|
||||
/**
|
||||
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
|
||||
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must exist and be owned by `from`.
|
||||
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
|
||||
* {setApprovalForAll}.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
|
||||
* a safe transfer.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId) external;
|
||||
|
||||
/**
|
||||
* @dev Transfers `tokenId` token from `from` to `to`.
|
||||
*
|
||||
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
|
||||
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
|
||||
* understand this adds an external call which potentially creates a reentrancy vulnerability.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must be owned by `from`.
|
||||
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 tokenId) external;
|
||||
|
||||
/**
|
||||
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
|
||||
* The approval is cleared when the token is transferred.
|
||||
*
|
||||
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The caller must own the token or be an approved operator.
|
||||
* - `tokenId` must exist.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*/
|
||||
function approve(address to, uint256 tokenId) external;
|
||||
|
||||
/**
|
||||
* @dev Approve or remove `operator` as an operator for the caller.
|
||||
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The `operator` cannot be the address zero.
|
||||
*
|
||||
* Emits an {ApprovalForAll} event.
|
||||
*/
|
||||
function setApprovalForAll(address operator, bool approved) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the account approved for `tokenId` token.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must exist.
|
||||
*/
|
||||
function getApproved(uint256 tokenId) external view returns (address operator);
|
||||
|
||||
/**
|
||||
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
|
||||
*
|
||||
* See {setApprovalForAll}
|
||||
*/
|
||||
function isApprovedForAll(address owner, address operator) external view returns (bool);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @title ERC721 token receiver interface
|
||||
* @dev Interface for any contract that wants to support safeTransfers
|
||||
* from ERC721 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);
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721URIStorage.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {Strings} from "../../../utils/Strings.sol";
|
||||
import {IERC4906} from "../../../interfaces/IERC4906.sol";
|
||||
import {IERC165} from "../../../interfaces/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC721 token with storage based token URI management.
|
||||
*/
|
||||
abstract contract ERC721URIStorage is IERC4906, ERC721 {
|
||||
using Strings for uint256;
|
||||
|
||||
// Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only
|
||||
// defines events and does not include any external function.
|
||||
bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);
|
||||
|
||||
// Optional mapping for token URIs
|
||||
mapping(uint256 tokenId => string) private _tokenURIs;
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) {
|
||||
return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-tokenURI}.
|
||||
*/
|
||||
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
|
||||
_requireOwned(tokenId);
|
||||
|
||||
string memory _tokenURI = _tokenURIs[tokenId];
|
||||
string memory base = _baseURI();
|
||||
|
||||
// If there is no base URI, return the token URI.
|
||||
if (bytes(base).length == 0) {
|
||||
return _tokenURI;
|
||||
}
|
||||
// If both are set, concatenate the baseURI and tokenURI (via string.concat).
|
||||
if (bytes(_tokenURI).length > 0) {
|
||||
return string.concat(base, _tokenURI);
|
||||
}
|
||||
|
||||
return super.tokenURI(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
|
||||
*
|
||||
* Emits {MetadataUpdate}.
|
||||
*/
|
||||
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
|
||||
_tokenURIs[tokenId] = _tokenURI;
|
||||
emit MetadataUpdate(tokenId);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "../IERC721.sol";
|
||||
|
||||
/**
|
||||
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
|
||||
* @dev See https://eips.ethereum.org/EIPS/eip-721
|
||||
*/
|
||||
interface IERC721Metadata is IERC721 {
|
||||
/**
|
||||
* @dev Returns the token collection name.
|
||||
*/
|
||||
function name() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the token collection symbol.
|
||||
*/
|
||||
function symbol() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
|
||||
*/
|
||||
function tokenURI(uint256 tokenId) external view returns (string memory);
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Collection of functions related to the address type
|
||||
*/
|
||||
library Address {
|
||||
/**
|
||||
* @dev The ETH balance of the account is not enough to perform the operation.
|
||||
*/
|
||||
error AddressInsufficientBalance(address account);
|
||||
|
||||
/**
|
||||
* @dev There's no code at `target` (it is not a contract).
|
||||
*/
|
||||
error AddressEmptyCode(address target);
|
||||
|
||||
/**
|
||||
* @dev A call to an address target failed. The target may have reverted.
|
||||
*/
|
||||
error FailedInnerCall();
|
||||
|
||||
/**
|
||||
* @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 AddressInsufficientBalance(address(this));
|
||||
}
|
||||
|
||||
(bool success, ) = recipient.call{value: amount}("");
|
||||
if (!success) {
|
||||
revert FailedInnerCall();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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
|
||||
* {FailedInnerCall} 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 AddressInsufficientBalance(address(this));
|
||||
}
|
||||
(bool success, bytes memory returndata) = target.call{value: value}(data);
|
||||
return verifyCallResultFromTarget(target, success, returndata);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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, bytes memory returndata) = target.staticcall(data);
|
||||
return verifyCallResultFromTarget(target, success, returndata);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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, bytes memory returndata) = target.delegatecall(data);
|
||||
return verifyCallResultFromTarget(target, success, returndata);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 {FailedInnerCall}) in case of an
|
||||
* unsuccessful call.
|
||||
*/
|
||||
function verifyCallResultFromTarget(
|
||||
address target,
|
||||
bool success,
|
||||
bytes memory returndata
|
||||
) internal view returns (bytes memory) {
|
||||
if (!success) {
|
||||
_revert(returndata);
|
||||
} else {
|
||||
// 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 (returndata.length == 0 && target.code.length == 0) {
|
||||
revert AddressEmptyCode(target);
|
||||
}
|
||||
return returndata;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 {FailedInnerCall} error.
|
||||
*/
|
||||
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
|
||||
if (!success) {
|
||||
_revert(returndata);
|
||||
} else {
|
||||
return returndata;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
|
||||
*/
|
||||
function _revert(bytes memory returndata) private pure {
|
||||
// Look for revert reason and bubble it up if present
|
||||
if (returndata.length > 0) {
|
||||
// The easiest way to bubble the revert reason is using memory via assembly
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
let returndata_size := mload(returndata)
|
||||
revert(add(32, returndata), returndata_size)
|
||||
}
|
||||
} else {
|
||||
revert FailedInnerCall();
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.2) (utils/Base64.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Provides a set of functions to operate with Base64 strings.
|
||||
*/
|
||||
library Base64 {
|
||||
/**
|
||||
* @dev Base64 Encoding/Decoding Table
|
||||
*/
|
||||
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/**
|
||||
* @dev Converts a `bytes` to its Bytes64 `string` representation.
|
||||
*/
|
||||
function encode(bytes memory data) internal pure returns (string memory) {
|
||||
/**
|
||||
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
|
||||
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
|
||||
*/
|
||||
if (data.length == 0) return "";
|
||||
|
||||
// Loads the table into memory
|
||||
string memory table = _TABLE;
|
||||
|
||||
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
|
||||
// and split into 4 numbers of 6 bits.
|
||||
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
|
||||
// - `data.length + 2` -> Round up
|
||||
// - `/ 3` -> Number of 3-bytes chunks
|
||||
// - `4 *` -> 4 characters for each chunk
|
||||
string memory result = new string(4 * ((data.length + 2) / 3));
|
||||
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
// Prepare the lookup table (skip the first "length" byte)
|
||||
let tablePtr := add(table, 1)
|
||||
|
||||
// Prepare result pointer, jump over length
|
||||
let resultPtr := add(result, 0x20)
|
||||
let dataPtr := data
|
||||
let endPtr := add(data, mload(data))
|
||||
|
||||
// In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
|
||||
// set it to zero to make sure no dirty bytes are read in that section.
|
||||
let afterPtr := add(endPtr, 0x20)
|
||||
let afterCache := mload(afterPtr)
|
||||
mstore(afterPtr, 0x00)
|
||||
|
||||
// Run over the input, 3 bytes at a time
|
||||
for {
|
||||
|
||||
} lt(dataPtr, endPtr) {
|
||||
|
||||
} {
|
||||
// Advance 3 bytes
|
||||
dataPtr := add(dataPtr, 3)
|
||||
let input := mload(dataPtr)
|
||||
|
||||
// To write each character, shift the 3 byte (24 bits) chunk
|
||||
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
|
||||
// and apply logical AND with 0x3F to bitmask the least significant 6 bits.
|
||||
// Use this as an index into the lookup table, mload an entire word
|
||||
// so the desired character is in the least significant byte, and
|
||||
// mstore8 this least significant byte into the result and continue.
|
||||
|
||||
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
|
||||
resultPtr := add(resultPtr, 1) // Advance
|
||||
|
||||
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
|
||||
resultPtr := add(resultPtr, 1) // Advance
|
||||
|
||||
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
|
||||
resultPtr := add(resultPtr, 1) // Advance
|
||||
|
||||
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
|
||||
resultPtr := add(resultPtr, 1) // Advance
|
||||
}
|
||||
|
||||
// Reset the value that was cached
|
||||
mstore(afterPtr, afterCache)
|
||||
|
||||
// When data `bytes` is not exactly 3 bytes long
|
||||
// it is padded with `=` characters at the end
|
||||
switch mod(mload(data), 3)
|
||||
case 1 {
|
||||
mstore8(sub(resultPtr, 1), 0x3d)
|
||||
mstore8(sub(resultPtr, 2), 0x3d)
|
||||
}
|
||||
case 2 {
|
||||
mstore8(sub(resultPtr, 1), 0x3d)
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.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 Initializes the contract in unpaused state.
|
||||
*/
|
||||
constructor() {
|
||||
_paused = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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());
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.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 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;
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {StorageSlot} from "./StorageSlot.sol";
|
||||
|
||||
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
|
||||
// | length | 0x BB |
|
||||
type ShortString is bytes32;
|
||||
|
||||
/**
|
||||
* @dev This library provides functions to convert short memory strings
|
||||
* into a `ShortString` type that can be used as an immutable variable.
|
||||
*
|
||||
* Strings of arbitrary length can be optimized using this library if
|
||||
* they are short enough (up to 31 bytes) by packing them with their
|
||||
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
|
||||
* fallback mechanism can be used for every other case.
|
||||
*
|
||||
* Usage example:
|
||||
*
|
||||
* ```solidity
|
||||
* contract Named {
|
||||
* using ShortStrings for *;
|
||||
*
|
||||
* ShortString private immutable _name;
|
||||
* string private _nameFallback;
|
||||
*
|
||||
* constructor(string memory contractName) {
|
||||
* _name = contractName.toShortStringWithFallback(_nameFallback);
|
||||
* }
|
||||
*
|
||||
* function name() external view returns (string memory) {
|
||||
* return _name.toStringWithFallback(_nameFallback);
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
library ShortStrings {
|
||||
// Used as an identifier for strings longer than 31 bytes.
|
||||
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
|
||||
|
||||
error StringTooLong(string str);
|
||||
error InvalidShortString();
|
||||
|
||||
/**
|
||||
* @dev Encode a string of at most 31 chars into a `ShortString`.
|
||||
*
|
||||
* This will trigger a `StringTooLong` error is the input string is too long.
|
||||
*/
|
||||
function toShortString(string memory str) internal pure returns (ShortString) {
|
||||
bytes memory bstr = bytes(str);
|
||||
if (bstr.length > 31) {
|
||||
revert StringTooLong(str);
|
||||
}
|
||||
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Decode a `ShortString` back to a "normal" string.
|
||||
*/
|
||||
function toString(ShortString sstr) internal pure returns (string memory) {
|
||||
uint256 len = byteLength(sstr);
|
||||
// using `new string(len)` would work locally but is not memory safe.
|
||||
string memory str = new string(32);
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
mstore(str, len)
|
||||
mstore(add(str, 0x20), sstr)
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the length of a `ShortString`.
|
||||
*/
|
||||
function byteLength(ShortString sstr) internal pure returns (uint256) {
|
||||
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
|
||||
if (result > 31) {
|
||||
revert InvalidShortString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
|
||||
*/
|
||||
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
|
||||
if (bytes(value).length < 32) {
|
||||
return toShortString(value);
|
||||
} else {
|
||||
StorageSlot.getStringSlot(store).value = value;
|
||||
return ShortString.wrap(FALLBACK_SENTINEL);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
|
||||
*/
|
||||
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
|
||||
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
|
||||
return toString(value);
|
||||
} else {
|
||||
return store;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
|
||||
* {setWithFallback}.
|
||||
*
|
||||
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
|
||||
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
|
||||
*/
|
||||
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
|
||||
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
|
||||
return byteLength(value);
|
||||
} else {
|
||||
return bytes(store).length;
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
|
||||
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Library for reading and writing primitive types to specific storage slots.
|
||||
*
|
||||
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
|
||||
* This library helps with reading and writing to such slots without the need for inline assembly.
|
||||
*
|
||||
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
|
||||
*
|
||||
* Example usage to set ERC1967 implementation slot:
|
||||
* ```solidity
|
||||
* contract ERC1967 {
|
||||
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
|
||||
*
|
||||
* function _getImplementation() internal view returns (address) {
|
||||
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
|
||||
* }
|
||||
*
|
||||
* function _setImplementation(address newImplementation) internal {
|
||||
* require(newImplementation.code.length > 0);
|
||||
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
library StorageSlot {
|
||||
struct AddressSlot {
|
||||
address value;
|
||||
}
|
||||
|
||||
struct BooleanSlot {
|
||||
bool value;
|
||||
}
|
||||
|
||||
struct Bytes32Slot {
|
||||
bytes32 value;
|
||||
}
|
||||
|
||||
struct Uint256Slot {
|
||||
uint256 value;
|
||||
}
|
||||
|
||||
struct StringSlot {
|
||||
string value;
|
||||
}
|
||||
|
||||
struct BytesSlot {
|
||||
bytes value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
|
||||
*/
|
||||
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
|
||||
*/
|
||||
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
|
||||
*/
|
||||
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
|
||||
*/
|
||||
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `StringSlot` with member `value` located at `slot`.
|
||||
*/
|
||||
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
|
||||
*/
|
||||
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := store.slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
|
||||
*/
|
||||
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
|
||||
*/
|
||||
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r.slot := store.slot
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Math} from "./math/Math.sol";
|
||||
import {SignedMath} from "./math/SignedMath.sol";
|
||||
|
||||
/**
|
||||
* @dev String operations.
|
||||
*/
|
||||
library Strings {
|
||||
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
|
||||
uint8 private constant ADDRESS_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* @dev The `value` string doesn't fit in the specified `length`.
|
||||
*/
|
||||
error StringsInsufficientHexLength(uint256 value, uint256 length);
|
||||
|
||||
/**
|
||||
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
|
||||
*/
|
||||
function toString(uint256 value) internal pure returns (string memory) {
|
||||
unchecked {
|
||||
uint256 length = Math.log10(value) + 1;
|
||||
string memory buffer = new string(length);
|
||||
uint256 ptr;
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
ptr := add(buffer, add(32, length))
|
||||
}
|
||||
while (true) {
|
||||
ptr--;
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
|
||||
}
|
||||
value /= 10;
|
||||
if (value == 0) break;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Converts a `int256` to its ASCII `string` decimal representation.
|
||||
*/
|
||||
function toStringSigned(int256 value) internal pure returns (string memory) {
|
||||
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
|
||||
*/
|
||||
function toHexString(uint256 value) internal pure returns (string memory) {
|
||||
unchecked {
|
||||
return toHexString(value, Math.log256(value) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
|
||||
*/
|
||||
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
|
||||
uint256 localValue = value;
|
||||
bytes memory buffer = new bytes(2 * length + 2);
|
||||
buffer[0] = "0";
|
||||
buffer[1] = "x";
|
||||
for (uint256 i = 2 * length + 1; i > 1; --i) {
|
||||
buffer[i] = HEX_DIGITS[localValue & 0xf];
|
||||
localValue >>= 4;
|
||||
}
|
||||
if (localValue != 0) {
|
||||
revert StringsInsufficientHexLength(value, length);
|
||||
}
|
||||
return string(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
|
||||
* representation.
|
||||
*/
|
||||
function toHexString(address addr) internal pure returns (string memory) {
|
||||
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns true if the two strings are equal.
|
||||
*/
|
||||
function equal(string memory a, string memory b) internal pure returns (bool) {
|
||||
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
|
||||
*
|
||||
* These functions can be used to verify that a message was signed by the holder
|
||||
* of the private keys of a given address.
|
||||
*/
|
||||
library ECDSA {
|
||||
enum RecoverError {
|
||||
NoError,
|
||||
InvalidSignature,
|
||||
InvalidSignatureLength,
|
||||
InvalidSignatureS
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The signature derives the `address(0)`.
|
||||
*/
|
||||
error ECDSAInvalidSignature();
|
||||
|
||||
/**
|
||||
* @dev The signature has an invalid length.
|
||||
*/
|
||||
error ECDSAInvalidSignatureLength(uint256 length);
|
||||
|
||||
/**
|
||||
* @dev The signature has an S value that is in the upper half order.
|
||||
*/
|
||||
error ECDSAInvalidSignatureS(bytes32 s);
|
||||
|
||||
/**
|
||||
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
|
||||
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
|
||||
* and a bytes32 providing additional information about the error.
|
||||
*
|
||||
* If no error is returned, then the address can be used for verification purposes.
|
||||
*
|
||||
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
|
||||
* this function rejects them by requiring the `s` value to be in the lower
|
||||
* half order, and the `v` value to be either 27 or 28.
|
||||
*
|
||||
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
|
||||
* verification to be secure: it is possible to craft signatures that
|
||||
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
|
||||
* this is by receiving a hash of the original message (which may otherwise
|
||||
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
|
||||
*
|
||||
* Documentation for signature generation:
|
||||
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
|
||||
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
|
||||
*/
|
||||
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
|
||||
if (signature.length == 65) {
|
||||
bytes32 r;
|
||||
bytes32 s;
|
||||
uint8 v;
|
||||
// ecrecover takes the signature parameters, and the only way to get them
|
||||
// currently is to use assembly.
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
r := mload(add(signature, 0x20))
|
||||
s := mload(add(signature, 0x40))
|
||||
v := byte(0, mload(add(signature, 0x60)))
|
||||
}
|
||||
return tryRecover(hash, v, r, s);
|
||||
} else {
|
||||
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address that signed a hashed message (`hash`) with
|
||||
* `signature`. This address can then be used for verification purposes.
|
||||
*
|
||||
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
|
||||
* this function rejects them by requiring the `s` value to be in the lower
|
||||
* half order, and the `v` value to be either 27 or 28.
|
||||
*
|
||||
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
|
||||
* verification to be secure: it is possible to craft signatures that
|
||||
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
|
||||
* this is by receiving a hash of the original message (which may otherwise
|
||||
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
|
||||
*/
|
||||
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
|
||||
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
|
||||
_throwError(error, errorArg);
|
||||
return recovered;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
|
||||
*
|
||||
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
|
||||
*/
|
||||
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
|
||||
unchecked {
|
||||
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
|
||||
// We do not check for an overflow here since the shift operation results in 0 or 1.
|
||||
uint8 v = uint8((uint256(vs) >> 255) + 27);
|
||||
return tryRecover(hash, v, r, s);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
|
||||
*/
|
||||
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
|
||||
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
|
||||
_throwError(error, errorArg);
|
||||
return recovered;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
|
||||
* `r` and `s` signature fields separately.
|
||||
*/
|
||||
function tryRecover(
|
||||
bytes32 hash,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) internal pure returns (address, RecoverError, bytes32) {
|
||||
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
|
||||
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
|
||||
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
|
||||
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
|
||||
//
|
||||
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
|
||||
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
|
||||
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
|
||||
// these malleable signatures as well.
|
||||
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
|
||||
return (address(0), RecoverError.InvalidSignatureS, s);
|
||||
}
|
||||
|
||||
// If the signature is valid (and not malleable), return the signer address
|
||||
address signer = ecrecover(hash, v, r, s);
|
||||
if (signer == address(0)) {
|
||||
return (address(0), RecoverError.InvalidSignature, bytes32(0));
|
||||
}
|
||||
|
||||
return (signer, RecoverError.NoError, bytes32(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload of {ECDSA-recover} that receives the `v`,
|
||||
* `r` and `s` signature fields separately.
|
||||
*/
|
||||
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
|
||||
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
|
||||
_throwError(error, errorArg);
|
||||
return recovered;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
|
||||
*/
|
||||
function _throwError(RecoverError error, bytes32 errorArg) private pure {
|
||||
if (error == RecoverError.NoError) {
|
||||
return; // no error: do nothing
|
||||
} else if (error == RecoverError.InvalidSignature) {
|
||||
revert ECDSAInvalidSignature();
|
||||
} else if (error == RecoverError.InvalidSignatureLength) {
|
||||
revert ECDSAInvalidSignatureLength(uint256(errorArg));
|
||||
} else if (error == RecoverError.InvalidSignatureS) {
|
||||
revert ECDSAInvalidSignatureS(errorArg);
|
||||
}
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {MessageHashUtils} from "./MessageHashUtils.sol";
|
||||
import {ShortStrings, ShortString} from "../ShortStrings.sol";
|
||||
import {IERC5267} from "../../interfaces/IERC5267.sol";
|
||||
|
||||
/**
|
||||
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
|
||||
*
|
||||
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
|
||||
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
|
||||
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
|
||||
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
|
||||
*
|
||||
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
|
||||
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
|
||||
* ({_hashTypedDataV4}).
|
||||
*
|
||||
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
|
||||
* the chain id to protect against replay attacks on an eventual fork of the chain.
|
||||
*
|
||||
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
|
||||
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
|
||||
*
|
||||
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
|
||||
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
|
||||
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
|
||||
*
|
||||
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
|
||||
*/
|
||||
abstract contract EIP712 is IERC5267 {
|
||||
using ShortStrings for *;
|
||||
|
||||
bytes32 private constant TYPE_HASH =
|
||||
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
|
||||
|
||||
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
|
||||
// invalidate the cached domain separator if the chain id changes.
|
||||
bytes32 private immutable _cachedDomainSeparator;
|
||||
uint256 private immutable _cachedChainId;
|
||||
address private immutable _cachedThis;
|
||||
|
||||
bytes32 private immutable _hashedName;
|
||||
bytes32 private immutable _hashedVersion;
|
||||
|
||||
ShortString private immutable _name;
|
||||
ShortString private immutable _version;
|
||||
string private _nameFallback;
|
||||
string private _versionFallback;
|
||||
|
||||
/**
|
||||
* @dev Initializes the domain separator and parameter caches.
|
||||
*
|
||||
* The meaning of `name` and `version` is specified in
|
||||
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
|
||||
*
|
||||
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
|
||||
* - `version`: the current major version of the signing domain.
|
||||
*
|
||||
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
|
||||
* contract upgrade].
|
||||
*/
|
||||
constructor(string memory name, string memory version) {
|
||||
_name = name.toShortStringWithFallback(_nameFallback);
|
||||
_version = version.toShortStringWithFallback(_versionFallback);
|
||||
_hashedName = keccak256(bytes(name));
|
||||
_hashedVersion = keccak256(bytes(version));
|
||||
|
||||
_cachedChainId = block.chainid;
|
||||
_cachedDomainSeparator = _buildDomainSeparator();
|
||||
_cachedThis = address(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the domain separator for the current chain.
|
||||
*/
|
||||
function _domainSeparatorV4() internal view returns (bytes32) {
|
||||
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
|
||||
return _cachedDomainSeparator;
|
||||
} else {
|
||||
return _buildDomainSeparator();
|
||||
}
|
||||
}
|
||||
|
||||
function _buildDomainSeparator() private view returns (bytes32) {
|
||||
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
|
||||
* function returns the hash of the fully encoded EIP712 message for this domain.
|
||||
*
|
||||
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
|
||||
*
|
||||
* ```solidity
|
||||
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
|
||||
* keccak256("Mail(address to,string contents)"),
|
||||
* mailTo,
|
||||
* keccak256(bytes(mailContents))
|
||||
* )));
|
||||
* address signer = ECDSA.recover(digest, signature);
|
||||
* ```
|
||||
*/
|
||||
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
|
||||
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC-5267}.
|
||||
*/
|
||||
function eip712Domain()
|
||||
public
|
||||
view
|
||||
virtual
|
||||
returns (
|
||||
bytes1 fields,
|
||||
string memory name,
|
||||
string memory version,
|
||||
uint256 chainId,
|
||||
address verifyingContract,
|
||||
bytes32 salt,
|
||||
uint256[] memory extensions
|
||||
)
|
||||
{
|
||||
return (
|
||||
hex"0f", // 01111
|
||||
_EIP712Name(),
|
||||
_EIP712Version(),
|
||||
block.chainid,
|
||||
address(this),
|
||||
bytes32(0),
|
||||
new uint256[](0)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The name parameter for the EIP712 domain.
|
||||
*
|
||||
* NOTE: By default this function reads _name which is an immutable value.
|
||||
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function _EIP712Name() internal view returns (string memory) {
|
||||
return _name.toStringWithFallback(_nameFallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The version parameter for the EIP712 domain.
|
||||
*
|
||||
* NOTE: By default this function reads _version which is an immutable value.
|
||||
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function _EIP712Version() internal view returns (string memory) {
|
||||
return _version.toStringWithFallback(_versionFallback);
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Strings} from "../Strings.sol";
|
||||
|
||||
/**
|
||||
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
|
||||
*
|
||||
* The library provides methods for generating a hash of a message that conforms to the
|
||||
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
|
||||
* specifications.
|
||||
*/
|
||||
library MessageHashUtils {
|
||||
/**
|
||||
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
|
||||
* `0x45` (`personal_sign` messages).
|
||||
*
|
||||
* The digest is calculated by prefixing a bytes32 `messageHash` with
|
||||
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
|
||||
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
|
||||
*
|
||||
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
|
||||
* keccak256, although any bytes32 value can be safely used because the final digest will
|
||||
* be re-hashed.
|
||||
*
|
||||
* See {ECDSA-recover}.
|
||||
*/
|
||||
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
|
||||
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
|
||||
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
|
||||
* `0x45` (`personal_sign` messages).
|
||||
*
|
||||
* The digest is calculated by prefixing an arbitrary `message` with
|
||||
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
|
||||
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
|
||||
*
|
||||
* See {ECDSA-recover}.
|
||||
*/
|
||||
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
|
||||
return
|
||||
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
|
||||
* `0x00` (data with intended validator).
|
||||
*
|
||||
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
|
||||
* `validator` address. Then hashing the result.
|
||||
*
|
||||
* See {ECDSA-recover}.
|
||||
*/
|
||||
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
|
||||
return keccak256(abi.encodePacked(hex"19_00", validator, data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
|
||||
*
|
||||
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
|
||||
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
|
||||
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
|
||||
*
|
||||
* See {ECDSA-recover}.
|
||||
*/
|
||||
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
let ptr := mload(0x40)
|
||||
mstore(ptr, hex"19_01")
|
||||
mstore(add(ptr, 0x02), domainSeparator)
|
||||
mstore(add(ptr, 0x22), structHash)
|
||||
digest := keccak256(ptr, 0x42)
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.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 ERC165 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;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC165 standard, as defined in the
|
||||
* https://eips.ethereum.org/EIPS/eip-165[EIP].
|
||||
*
|
||||
* 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[EIP 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);
|
||||
}
|
||||
+415
@@ -0,0 +1,415 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Standard math utilities missing in the Solidity language.
|
||||
*/
|
||||
library Math {
|
||||
/**
|
||||
* @dev Muldiv operation overflow.
|
||||
*/
|
||||
error MathOverflowedMulDiv();
|
||||
|
||||
enum Rounding {
|
||||
Floor, // Toward negative infinity
|
||||
Ceil, // Toward positive infinity
|
||||
Trunc, // Toward zero
|
||||
Expand // Away from zero
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the addition of two unsigned integers, with an overflow flag.
|
||||
*/
|
||||
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
|
||||
unchecked {
|
||||
uint256 c = a + b;
|
||||
if (c < a) return (false, 0);
|
||||
return (true, c);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
|
||||
*/
|
||||
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
|
||||
unchecked {
|
||||
if (b > a) return (false, 0);
|
||||
return (true, a - b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
|
||||
*/
|
||||
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
|
||||
unchecked {
|
||||
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
|
||||
// benefit is lost if 'b' is also tested.
|
||||
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
|
||||
if (a == 0) return (true, 0);
|
||||
uint256 c = a * b;
|
||||
if (c / a != b) return (false, 0);
|
||||
return (true, c);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the division of two unsigned integers, with a division by zero flag.
|
||||
*/
|
||||
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
|
||||
unchecked {
|
||||
if (b == 0) return (false, 0);
|
||||
return (true, a / b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
|
||||
*/
|
||||
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
|
||||
unchecked {
|
||||
if (b == 0) return (false, 0);
|
||||
return (true, a % b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the largest of two numbers.
|
||||
*/
|
||||
function max(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the smallest of two numbers.
|
||||
*/
|
||||
function min(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the average of two numbers. The result is rounded towards
|
||||
* zero.
|
||||
*/
|
||||
function average(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
// (a + b) / 2 can overflow.
|
||||
return (a & b) + (a ^ b) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the ceiling of the division of two numbers.
|
||||
*
|
||||
* This differs from standard division with `/` in that it rounds towards infinity instead
|
||||
* of rounding towards zero.
|
||||
*/
|
||||
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
if (b == 0) {
|
||||
// Guarantee the same behavior as in a regular Solidity division.
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// (a + b - 1) / b can overflow on addition, so we distribute.
|
||||
return a == 0 ? 0 : (a - 1) / b + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
|
||||
* denominator == 0.
|
||||
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
|
||||
* Uniswap Labs also under MIT license.
|
||||
*/
|
||||
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
|
||||
unchecked {
|
||||
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
|
||||
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
|
||||
// variables such that product = prod1 * 2^256 + prod0.
|
||||
uint256 prod0 = x * y; // Least significant 256 bits of the product
|
||||
uint256 prod1; // Most significant 256 bits of the product
|
||||
assembly {
|
||||
let mm := mulmod(x, y, not(0))
|
||||
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
|
||||
}
|
||||
|
||||
// Handle non-overflow cases, 256 by 256 division.
|
||||
if (prod1 == 0) {
|
||||
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
|
||||
// The surrounding unchecked block does not change this fact.
|
||||
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
|
||||
return prod0 / denominator;
|
||||
}
|
||||
|
||||
// Make sure the result is less than 2^256. Also prevents denominator == 0.
|
||||
if (denominator <= prod1) {
|
||||
revert MathOverflowedMulDiv();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////
|
||||
// 512 by 256 division.
|
||||
///////////////////////////////////////////////
|
||||
|
||||
// Make division exact by subtracting the remainder from [prod1 prod0].
|
||||
uint256 remainder;
|
||||
assembly {
|
||||
// Compute remainder using mulmod.
|
||||
remainder := mulmod(x, y, denominator)
|
||||
|
||||
// Subtract 256 bit number from 512 bit number.
|
||||
prod1 := sub(prod1, gt(remainder, prod0))
|
||||
prod0 := sub(prod0, remainder)
|
||||
}
|
||||
|
||||
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
|
||||
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
|
||||
|
||||
uint256 twos = denominator & (0 - denominator);
|
||||
assembly {
|
||||
// Divide denominator by twos.
|
||||
denominator := div(denominator, twos)
|
||||
|
||||
// Divide [prod1 prod0] by twos.
|
||||
prod0 := div(prod0, twos)
|
||||
|
||||
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
|
||||
twos := add(div(sub(0, twos), twos), 1)
|
||||
}
|
||||
|
||||
// Shift in bits from prod1 into prod0.
|
||||
prod0 |= prod1 * twos;
|
||||
|
||||
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
|
||||
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
|
||||
// four bits. That is, denominator * inv = 1 mod 2^4.
|
||||
uint256 inverse = (3 * denominator) ^ 2;
|
||||
|
||||
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
|
||||
// works in modular arithmetic, doubling the correct bits in each step.
|
||||
inverse *= 2 - denominator * inverse; // inverse mod 2^8
|
||||
inverse *= 2 - denominator * inverse; // inverse mod 2^16
|
||||
inverse *= 2 - denominator * inverse; // inverse mod 2^32
|
||||
inverse *= 2 - denominator * inverse; // inverse mod 2^64
|
||||
inverse *= 2 - denominator * inverse; // inverse mod 2^128
|
||||
inverse *= 2 - denominator * inverse; // inverse mod 2^256
|
||||
|
||||
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
|
||||
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
|
||||
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
|
||||
// is no longer required.
|
||||
result = prod0 * inverse;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
|
||||
*/
|
||||
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
|
||||
uint256 result = mulDiv(x, y, denominator);
|
||||
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
|
||||
result += 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
|
||||
* towards zero.
|
||||
*
|
||||
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
|
||||
*/
|
||||
function sqrt(uint256 a) internal pure returns (uint256) {
|
||||
if (a == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
|
||||
//
|
||||
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
|
||||
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
|
||||
//
|
||||
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
|
||||
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
|
||||
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
|
||||
//
|
||||
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
|
||||
uint256 result = 1 << (log2(a) >> 1);
|
||||
|
||||
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
|
||||
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
|
||||
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
|
||||
// into the expected uint128 result.
|
||||
unchecked {
|
||||
result = (result + a / result) >> 1;
|
||||
result = (result + a / result) >> 1;
|
||||
result = (result + a / result) >> 1;
|
||||
result = (result + a / result) >> 1;
|
||||
result = (result + a / result) >> 1;
|
||||
result = (result + a / result) >> 1;
|
||||
result = (result + a / result) >> 1;
|
||||
return min(result, a / result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Calculates sqrt(a), following the selected rounding direction.
|
||||
*/
|
||||
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
|
||||
unchecked {
|
||||
uint256 result = sqrt(a);
|
||||
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the log in base 2 of a positive value rounded towards zero.
|
||||
* Returns 0 if given 0.
|
||||
*/
|
||||
function log2(uint256 value) internal pure returns (uint256) {
|
||||
uint256 result = 0;
|
||||
unchecked {
|
||||
if (value >> 128 > 0) {
|
||||
value >>= 128;
|
||||
result += 128;
|
||||
}
|
||||
if (value >> 64 > 0) {
|
||||
value >>= 64;
|
||||
result += 64;
|
||||
}
|
||||
if (value >> 32 > 0) {
|
||||
value >>= 32;
|
||||
result += 32;
|
||||
}
|
||||
if (value >> 16 > 0) {
|
||||
value >>= 16;
|
||||
result += 16;
|
||||
}
|
||||
if (value >> 8 > 0) {
|
||||
value >>= 8;
|
||||
result += 8;
|
||||
}
|
||||
if (value >> 4 > 0) {
|
||||
value >>= 4;
|
||||
result += 4;
|
||||
}
|
||||
if (value >> 2 > 0) {
|
||||
value >>= 2;
|
||||
result += 2;
|
||||
}
|
||||
if (value >> 1 > 0) {
|
||||
result += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
|
||||
* Returns 0 if given 0.
|
||||
*/
|
||||
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
|
||||
unchecked {
|
||||
uint256 result = log2(value);
|
||||
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the log in base 10 of a positive value rounded towards zero.
|
||||
* Returns 0 if given 0.
|
||||
*/
|
||||
function log10(uint256 value) internal pure returns (uint256) {
|
||||
uint256 result = 0;
|
||||
unchecked {
|
||||
if (value >= 10 ** 64) {
|
||||
value /= 10 ** 64;
|
||||
result += 64;
|
||||
}
|
||||
if (value >= 10 ** 32) {
|
||||
value /= 10 ** 32;
|
||||
result += 32;
|
||||
}
|
||||
if (value >= 10 ** 16) {
|
||||
value /= 10 ** 16;
|
||||
result += 16;
|
||||
}
|
||||
if (value >= 10 ** 8) {
|
||||
value /= 10 ** 8;
|
||||
result += 8;
|
||||
}
|
||||
if (value >= 10 ** 4) {
|
||||
value /= 10 ** 4;
|
||||
result += 4;
|
||||
}
|
||||
if (value >= 10 ** 2) {
|
||||
value /= 10 ** 2;
|
||||
result += 2;
|
||||
}
|
||||
if (value >= 10 ** 1) {
|
||||
result += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
|
||||
* Returns 0 if given 0.
|
||||
*/
|
||||
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
|
||||
unchecked {
|
||||
uint256 result = log10(value);
|
||||
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the log in base 256 of a positive value rounded towards zero.
|
||||
* Returns 0 if given 0.
|
||||
*
|
||||
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
|
||||
*/
|
||||
function log256(uint256 value) internal pure returns (uint256) {
|
||||
uint256 result = 0;
|
||||
unchecked {
|
||||
if (value >> 128 > 0) {
|
||||
value >>= 128;
|
||||
result += 16;
|
||||
}
|
||||
if (value >> 64 > 0) {
|
||||
value >>= 64;
|
||||
result += 8;
|
||||
}
|
||||
if (value >> 32 > 0) {
|
||||
value >>= 32;
|
||||
result += 4;
|
||||
}
|
||||
if (value >> 16 > 0) {
|
||||
value >>= 16;
|
||||
result += 2;
|
||||
}
|
||||
if (value >> 8 > 0) {
|
||||
result += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
|
||||
* Returns 0 if given 0.
|
||||
*/
|
||||
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
|
||||
unchecked {
|
||||
uint256 result = log256(value);
|
||||
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
|
||||
*/
|
||||
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
|
||||
return uint8(rounding) % 2 == 1;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Standard signed math utilities missing in the Solidity language.
|
||||
*/
|
||||
library SignedMath {
|
||||
/**
|
||||
* @dev Returns the largest of two signed numbers.
|
||||
*/
|
||||
function max(int256 a, int256 b) internal pure returns (int256) {
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the smallest of two signed numbers.
|
||||
*/
|
||||
function min(int256 a, int256 b) internal pure returns (int256) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the average of two signed numbers without overflow.
|
||||
* The result is rounded towards zero.
|
||||
*/
|
||||
function average(int256 a, int256 b) internal pure returns (int256) {
|
||||
// Formula from the book "Hacker's Delight"
|
||||
int256 x = (a & b) + ((a ^ b) >> 1);
|
||||
return x + (int256(uint256(x) >> 255) & (a ^ b));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the absolute unsigned value of a signed value.
|
||||
*/
|
||||
function abs(int256 n) internal pure returns (uint256) {
|
||||
unchecked {
|
||||
// must be unchecked in order to support `n = type(int256).min`
|
||||
return uint256(n >= 0 ? n : -n);
|
||||
}
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "./interfaces/IAlltraTransport.sol";
|
||||
|
||||
/**
|
||||
* @title AlltraCustomBridge
|
||||
* @notice Custom transport for 138 <-> ALL Mainnet (651940). Locks tokens and emits event; no CCIP.
|
||||
* @dev Deploy at same address on 138 and 651940 via CREATE2. On 138: lock + emit LockForAlltra.
|
||||
* Off-chain relayer or contract on 651940 completes mint/unlock. On 651940: implement
|
||||
* unlockOrMint (called by relayer or same contract) to complete the flow.
|
||||
*/
|
||||
contract AlltraCustomBridge is IAlltraTransport, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
|
||||
uint256 public constant ALL_MAINNET_CHAIN_ID = 651940;
|
||||
|
||||
mapping(bytes32 => LockRecord) public locks;
|
||||
mapping(bytes32 => bool) public releasedOnAlltra; // on 651940: prevent double release
|
||||
mapping(address => uint256) public nonces;
|
||||
bool private _hasRelayer;
|
||||
|
||||
struct LockRecord {
|
||||
address sender;
|
||||
address token;
|
||||
uint256 amount;
|
||||
address recipient;
|
||||
uint256 createdAt;
|
||||
bool released;
|
||||
}
|
||||
|
||||
event LockForAlltra(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
address recipient,
|
||||
uint256 sourceChainId
|
||||
);
|
||||
|
||||
event UnlockOnAlltra(
|
||||
bytes32 indexed requestId,
|
||||
address indexed recipient,
|
||||
address indexed token,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(RELAYER_ROLE, admin);
|
||||
_hasRelayer = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Lock tokens and emit event for relay to ALL Mainnet. Does not use CCIP.
|
||||
*/
|
||||
function lockAndRelay(
|
||||
address token,
|
||||
uint256 amount,
|
||||
address recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(recipient != address(0), "zero recipient");
|
||||
require(amount > 0, "zero amount");
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
recipient,
|
||||
nonces[msg.sender]++,
|
||||
block.chainid,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "insufficient value");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
locks[requestId] = LockRecord({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
recipient: recipient,
|
||||
createdAt: block.timestamp,
|
||||
released: false
|
||||
});
|
||||
|
||||
emit LockForAlltra(requestId, msg.sender, token, amount, recipient, block.chainid);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function isConfigured() external view override returns (bool) {
|
||||
return _hasRelayer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice On ALL Mainnet (651940): release tokens to recipient after relay proof.
|
||||
* @dev Only RELAYER_ROLE; in production, verify merkle proof or signature from source chain.
|
||||
* Uses releasedOnAlltra[requestId] to prevent double release on this chain.
|
||||
*/
|
||||
function releaseOnAlltra(
|
||||
bytes32 requestId,
|
||||
address token,
|
||||
uint256 amount,
|
||||
address recipient
|
||||
) external onlyRole(RELAYER_ROLE) nonReentrant {
|
||||
require(!releasedOnAlltra[requestId], "already released");
|
||||
releasedOnAlltra[requestId] = true;
|
||||
|
||||
if (token == address(0)) {
|
||||
(bool sent,) = payable(recipient).call{value: amount}("");
|
||||
require(sent, "transfer failed");
|
||||
} else {
|
||||
IERC20(token).safeTransfer(recipient, amount);
|
||||
}
|
||||
|
||||
emit UnlockOnAlltra(requestId, recipient, token, amount);
|
||||
}
|
||||
|
||||
receive() external payable {}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
|
||||
import "../registry/UniversalAssetRegistry.sol";
|
||||
import "./UniversalCCIPBridge.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeOrchestrator
|
||||
* @notice Routes bridge requests to appropriate asset-specific bridges
|
||||
* @dev Central routing layer for multi-asset bridge system
|
||||
*/
|
||||
contract BridgeOrchestrator is
|
||||
Initializable,
|
||||
AccessControlUpgradeable,
|
||||
UUPSUpgradeable
|
||||
{
|
||||
bytes32 public constant ROUTER_ADMIN_ROLE = keccak256("ROUTER_ADMIN_ROLE");
|
||||
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
|
||||
|
||||
// Core dependencies
|
||||
UniversalAssetRegistry public assetRegistry;
|
||||
UniversalCCIPBridge public defaultBridge;
|
||||
|
||||
// Asset type to bridge mapping
|
||||
mapping(bytes32 => address) public assetTypeToBridge;
|
||||
mapping(address => bool) public isRegisteredBridge;
|
||||
|
||||
// Routing statistics
|
||||
struct RoutingStats {
|
||||
uint256 totalBridges;
|
||||
uint256 successfulBridges;
|
||||
uint256 failedBridges;
|
||||
uint256 lastBridgeTime;
|
||||
}
|
||||
|
||||
mapping(address => RoutingStats) public bridgeStats;
|
||||
mapping(UniversalAssetRegistry.AssetType => RoutingStats) public assetTypeStats;
|
||||
|
||||
event BridgeRouted(
|
||||
address indexed token,
|
||||
UniversalAssetRegistry.AssetType assetType,
|
||||
address indexed bridgeContract,
|
||||
bytes32 indexed messageId
|
||||
);
|
||||
|
||||
event AssetTypeBridgeRegistered(
|
||||
bytes32 indexed assetTypeHash,
|
||||
UniversalAssetRegistry.AssetType assetType,
|
||||
address bridgeContract
|
||||
);
|
||||
|
||||
event BridgeUnregistered(
|
||||
bytes32 indexed assetTypeHash,
|
||||
address bridgeContract
|
||||
);
|
||||
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor() {
|
||||
_disableInitializers();
|
||||
}
|
||||
|
||||
function initialize(
|
||||
address _assetRegistry,
|
||||
address _defaultBridge,
|
||||
address admin
|
||||
) external initializer {
|
||||
__AccessControl_init();
|
||||
__UUPSUpgradeable_init();
|
||||
|
||||
require(_assetRegistry != address(0), "Zero registry");
|
||||
require(_defaultBridge != address(0), "Zero bridge");
|
||||
|
||||
assetRegistry = UniversalAssetRegistry(_assetRegistry);
|
||||
defaultBridge = UniversalCCIPBridge(payable(_defaultBridge));
|
||||
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(ROUTER_ADMIN_ROLE, admin);
|
||||
_grantRole(UPGRADER_ROLE, admin);
|
||||
}
|
||||
|
||||
function _authorizeUpgrade(address newImplementation)
|
||||
internal override onlyRole(UPGRADER_ROLE) {}
|
||||
|
||||
/**
|
||||
* @notice Route bridge request to appropriate bridge
|
||||
*/
|
||||
function bridge(
|
||||
UniversalCCIPBridge.BridgeOperation calldata op
|
||||
) external payable returns (bytes32 messageId) {
|
||||
// Get asset information
|
||||
UniversalAssetRegistry.UniversalAsset memory asset = assetRegistry.getAsset(op.token);
|
||||
require(asset.isActive, "Asset not active");
|
||||
|
||||
// Get bridge contract for this asset type
|
||||
bytes32 assetTypeHash = bytes32(uint256(asset.assetType));
|
||||
address bridgeContract = assetTypeToBridge[assetTypeHash];
|
||||
|
||||
// Use default bridge if no specialized bridge
|
||||
if (bridgeContract == address(0)) {
|
||||
bridgeContract = address(defaultBridge);
|
||||
}
|
||||
|
||||
require(isRegisteredBridge[bridgeContract], "Bridge not registered");
|
||||
|
||||
// Forward call to specialized bridge
|
||||
(bool success, bytes memory data) = bridgeContract.call{value: msg.value}(
|
||||
abi.encodeWithSelector(
|
||||
UniversalCCIPBridge.bridge.selector,
|
||||
op
|
||||
)
|
||||
);
|
||||
|
||||
require(success, "Bridge call failed");
|
||||
messageId = abi.decode(data, (bytes32));
|
||||
|
||||
// Update statistics
|
||||
_updateStats(bridgeContract, asset.assetType, true);
|
||||
|
||||
emit BridgeRouted(op.token, asset.assetType, bridgeContract, messageId);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register asset type bridge
|
||||
*/
|
||||
function registerAssetTypeBridge(
|
||||
UniversalAssetRegistry.AssetType assetType,
|
||||
address bridgeContract
|
||||
) external onlyRole(ROUTER_ADMIN_ROLE) {
|
||||
require(bridgeContract != address(0), "Zero address");
|
||||
require(bridgeContract.code.length > 0, "Not a contract");
|
||||
|
||||
bytes32 assetTypeHash = bytes32(uint256(assetType));
|
||||
assetTypeToBridge[assetTypeHash] = bridgeContract;
|
||||
isRegisteredBridge[bridgeContract] = true;
|
||||
|
||||
emit AssetTypeBridgeRegistered(assetTypeHash, assetType, bridgeContract);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unregister bridge
|
||||
*/
|
||||
function unregisterBridge(
|
||||
UniversalAssetRegistry.AssetType assetType
|
||||
) external onlyRole(ROUTER_ADMIN_ROLE) {
|
||||
bytes32 assetTypeHash = bytes32(uint256(assetType));
|
||||
address bridgeContract = assetTypeToBridge[assetTypeHash];
|
||||
|
||||
delete assetTypeToBridge[assetTypeHash];
|
||||
// Note: We don't remove from isRegisteredBridge in case it's used elsewhere
|
||||
|
||||
emit BridgeUnregistered(assetTypeHash, bridgeContract);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update routing statistics
|
||||
*/
|
||||
function _updateStats(
|
||||
address bridgeContract,
|
||||
UniversalAssetRegistry.AssetType assetType,
|
||||
bool success
|
||||
) internal {
|
||||
RoutingStats storage bridgeStat = bridgeStats[bridgeContract];
|
||||
RoutingStats storage typeStat = assetTypeStats[assetType];
|
||||
|
||||
bridgeStat.totalBridges++;
|
||||
typeStat.totalBridges++;
|
||||
|
||||
if (success) {
|
||||
bridgeStat.successfulBridges++;
|
||||
typeStat.successfulBridges++;
|
||||
} else {
|
||||
bridgeStat.failedBridges++;
|
||||
typeStat.failedBridges++;
|
||||
}
|
||||
|
||||
bridgeStat.lastBridgeTime = block.timestamp;
|
||||
typeStat.lastBridgeTime = block.timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set default bridge
|
||||
*/
|
||||
function setDefaultBridge(address _defaultBridge) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(_defaultBridge != address(0), "Zero address");
|
||||
defaultBridge = UniversalCCIPBridge(payable(_defaultBridge));
|
||||
isRegisteredBridge[_defaultBridge] = true;
|
||||
}
|
||||
|
||||
// View functions
|
||||
|
||||
function getBridgeForAssetType(UniversalAssetRegistry.AssetType assetType)
|
||||
external view returns (address) {
|
||||
bytes32 assetTypeHash = bytes32(uint256(assetType));
|
||||
address bridge = assetTypeToBridge[assetTypeHash];
|
||||
return bridge != address(0) ? bridge : address(defaultBridge);
|
||||
}
|
||||
|
||||
function getBridgeStats(address bridgeContract)
|
||||
external view returns (RoutingStats memory) {
|
||||
return bridgeStats[bridgeContract];
|
||||
}
|
||||
|
||||
function getAssetTypeStats(UniversalAssetRegistry.AssetType assetType)
|
||||
external view returns (RoutingStats memory) {
|
||||
return assetTypeStats[assetType];
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "./UniversalCCIPBridge.sol";
|
||||
|
||||
/**
|
||||
* @title CommodityCCIPBridge
|
||||
* @notice Specialized bridge for commodity-backed tokens (gold, oil, etc.)
|
||||
* @dev Includes certificate validation and physical delivery coordination
|
||||
*/
|
||||
contract CommodityCCIPBridge is UniversalCCIPBridge {
|
||||
|
||||
// Certificate registry (authenticity verification)
|
||||
mapping(address => mapping(bytes32 => bool)) public validCertificates;
|
||||
mapping(address => mapping(bytes32 => CertificateInfo)) public certificates;
|
||||
|
||||
struct CertificateInfo {
|
||||
bytes32 certificateHash;
|
||||
address custodian;
|
||||
uint256 quantity;
|
||||
string commodityType;
|
||||
uint256 issuedAt;
|
||||
uint256 expiresAt;
|
||||
bool isValid;
|
||||
}
|
||||
|
||||
// Custodian registry
|
||||
mapping(address => address) public tokenCustodians;
|
||||
mapping(address => bool) public approvedCustodians;
|
||||
|
||||
// Physical delivery tracking
|
||||
struct DeliveryRequest {
|
||||
bytes32 messageId;
|
||||
address token;
|
||||
uint256 amount;
|
||||
address requester;
|
||||
string deliveryAddress;
|
||||
uint256 requestedAt;
|
||||
DeliveryStatus status;
|
||||
}
|
||||
|
||||
enum DeliveryStatus {
|
||||
Requested,
|
||||
Confirmed,
|
||||
InTransit,
|
||||
Delivered,
|
||||
Cancelled
|
||||
}
|
||||
|
||||
mapping(bytes32 => DeliveryRequest) public deliveryRequests;
|
||||
bytes32[] public deliveryIds;
|
||||
|
||||
event CertificateRegistered(
|
||||
address indexed token,
|
||||
bytes32 indexed certificateHash,
|
||||
address custodian
|
||||
);
|
||||
|
||||
event PhysicalDeliveryRequested(
|
||||
bytes32 indexed deliveryId,
|
||||
bytes32 indexed messageId,
|
||||
address token,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
event DeliveryStatusUpdated(
|
||||
bytes32 indexed deliveryId,
|
||||
DeliveryStatus status
|
||||
);
|
||||
|
||||
/**
|
||||
* @notice Bridge commodity token with certificate validation
|
||||
*/
|
||||
function bridgeCommodity(
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint64 destinationChain,
|
||||
address recipient,
|
||||
bytes32 certificateHash,
|
||||
bytes calldata custodianSignature
|
||||
) external nonReentrant returns (bytes32 messageId) {
|
||||
// Verify asset is Commodity type
|
||||
UniversalAssetRegistry.UniversalAsset memory asset = assetRegistry.getAsset(token);
|
||||
require(asset.assetType == UniversalAssetRegistry.AssetType.Commodity, "Not commodity");
|
||||
require(asset.isActive, "Asset not active");
|
||||
|
||||
// Verify certificate
|
||||
require(validCertificates[token][certificateHash], "Invalid certificate");
|
||||
|
||||
CertificateInfo memory cert = certificates[token][certificateHash];
|
||||
require(cert.isValid, "Certificate not valid");
|
||||
require(block.timestamp < cert.expiresAt, "Certificate expired");
|
||||
require(cert.quantity >= amount, "Certificate insufficient");
|
||||
|
||||
// Verify custodian
|
||||
require(approvedCustodians[cert.custodian], "Custodian not approved");
|
||||
|
||||
// Verify custodian signature
|
||||
_verifyCustodianSignature(token, amount, certificateHash, custodianSignature, cert.custodian);
|
||||
|
||||
// Execute bridge
|
||||
BridgeOperation memory op = BridgeOperation({
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationChain: destinationChain,
|
||||
recipient: recipient,
|
||||
assetType: bytes32(uint256(UniversalAssetRegistry.AssetType.Commodity)),
|
||||
usePMM: true, // Commodities can use PMM
|
||||
useVault: false,
|
||||
complianceProof: abi.encode(certificateHash),
|
||||
vaultInstructions: ""
|
||||
});
|
||||
|
||||
messageId = this.bridge(op);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Initiate physical delivery of commodity
|
||||
*/
|
||||
function initiatePhysicalDelivery(
|
||||
bytes32 messageId,
|
||||
string calldata deliveryAddress
|
||||
) external returns (bytes32 deliveryId) {
|
||||
require(messageId != bytes32(0), "Invalid message ID");
|
||||
|
||||
deliveryId = keccak256(abi.encode(messageId, msg.sender, block.timestamp));
|
||||
|
||||
// This would integrate with off-chain logistics systems
|
||||
deliveryRequests[deliveryId] = DeliveryRequest({
|
||||
messageId: messageId,
|
||||
token: address(0), // Would be fetched from bridge record
|
||||
amount: 0, // Would be fetched from bridge record
|
||||
requester: msg.sender,
|
||||
deliveryAddress: deliveryAddress,
|
||||
requestedAt: block.timestamp,
|
||||
status: DeliveryStatus.Requested
|
||||
});
|
||||
|
||||
deliveryIds.push(deliveryId);
|
||||
|
||||
emit PhysicalDeliveryRequested(deliveryId, messageId, address(0), 0);
|
||||
|
||||
return deliveryId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update physical delivery status
|
||||
*/
|
||||
function updateDeliveryStatus(
|
||||
bytes32 deliveryId,
|
||||
DeliveryStatus status
|
||||
) external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
require(deliveryRequests[deliveryId].requestedAt > 0, "Delivery not found");
|
||||
|
||||
deliveryRequests[deliveryId].status = status;
|
||||
|
||||
emit DeliveryStatusUpdated(deliveryId, status);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify custodian signature
|
||||
*/
|
||||
function _verifyCustodianSignature(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes32 certificateHash,
|
||||
bytes memory signature,
|
||||
address custodian
|
||||
) internal view {
|
||||
// In production, this would use EIP-712 signature verification
|
||||
// For now, simplified check
|
||||
require(signature.length > 0, "Missing signature");
|
||||
require(custodian != address(0), "Invalid custodian");
|
||||
}
|
||||
|
||||
// Admin functions
|
||||
|
||||
function registerCertificate(
|
||||
address token,
|
||||
bytes32 certificateHash,
|
||||
address custodian,
|
||||
uint256 quantity,
|
||||
string calldata commodityType,
|
||||
uint256 expiresAt
|
||||
) external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
validCertificates[token][certificateHash] = true;
|
||||
|
||||
certificates[token][certificateHash] = CertificateInfo({
|
||||
certificateHash: certificateHash,
|
||||
custodian: custodian,
|
||||
quantity: quantity,
|
||||
commodityType: commodityType,
|
||||
issuedAt: block.timestamp,
|
||||
expiresAt: expiresAt,
|
||||
isValid: true
|
||||
});
|
||||
|
||||
emit CertificateRegistered(token, certificateHash, custodian);
|
||||
}
|
||||
|
||||
function approveCustodian(address custodian, bool approved) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
approvedCustodians[custodian] = approved;
|
||||
}
|
||||
|
||||
function revokeCertificate(address token, bytes32 certificateHash)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
validCertificates[token][certificateHash] = false;
|
||||
certificates[token][certificateHash].isValid = false;
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
/**
|
||||
* @title EtherlinkRelayReceiver
|
||||
* @notice Relay-compatible receiver on Etherlink (chain 42793). Accepts relayMintOrUnlock from off-chain relay.
|
||||
* @dev When CCIP does not support Etherlink, custom relay monitors source and calls this contract.
|
||||
* Idempotency via messageId; only RELAYER_ROLE can call.
|
||||
*/
|
||||
contract EtherlinkRelayReceiver is AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
|
||||
|
||||
mapping(bytes32 => bool) public processed;
|
||||
|
||||
event RelayMintOrUnlock(
|
||||
bytes32 indexed messageId,
|
||||
address indexed token,
|
||||
address indexed recipient,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(RELAYER_ROLE, admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Mint or unlock tokens to recipient. Only relayer; idempotent per messageId.
|
||||
* @param messageId Source chain message id (for idempotency).
|
||||
* @param token Token address (address(0) for native).
|
||||
* @param recipient Recipient on Etherlink.
|
||||
* @param amount Amount to transfer.
|
||||
*/
|
||||
function relayMintOrUnlock(
|
||||
bytes32 messageId,
|
||||
address token,
|
||||
address recipient,
|
||||
uint256 amount
|
||||
) external onlyRole(RELAYER_ROLE) nonReentrant {
|
||||
require(!processed[messageId], "already processed");
|
||||
require(recipient != address(0), "zero recipient");
|
||||
require(amount > 0, "zero amount");
|
||||
processed[messageId] = true;
|
||||
|
||||
if (token == address(0)) {
|
||||
(bool sent,) = payable(recipient).call{value: amount}("");
|
||||
require(sent, "transfer failed");
|
||||
} else {
|
||||
IERC20(token).safeTransfer(recipient, amount);
|
||||
}
|
||||
|
||||
emit RelayMintOrUnlock(messageId, token, recipient, amount);
|
||||
}
|
||||
|
||||
receive() external payable {}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "./UniversalCCIPBridge.sol";
|
||||
import "../vault/libraries/GRUConstants.sol";
|
||||
|
||||
/**
|
||||
* @title GRUCCIPBridge
|
||||
* @notice Specialized bridge for Global Reserve Unit (GRU) tokens
|
||||
* @dev Supports layer conversions (M00/M0/M1) and XAU triangulation
|
||||
*/
|
||||
contract GRUCCIPBridge is UniversalCCIPBridge {
|
||||
using GRUConstants for *;
|
||||
|
||||
struct GRUBridgeOperation {
|
||||
address token;
|
||||
uint256 amount;
|
||||
uint64 destinationChain;
|
||||
address recipient;
|
||||
string sourceLayer;
|
||||
string targetLayer;
|
||||
bool useXAUTriangulation;
|
||||
}
|
||||
|
||||
event GRULayerConversion(
|
||||
bytes32 indexed messageId,
|
||||
string sourceLayer,
|
||||
string targetLayer,
|
||||
uint256 sourceAmount,
|
||||
uint256 targetAmount
|
||||
);
|
||||
|
||||
event GRUCrossCurrencyBridge(
|
||||
bytes32 indexed messageId,
|
||||
address sourceToken,
|
||||
address destToken,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
/**
|
||||
* @notice Bridge GRU with layer conversion
|
||||
*/
|
||||
function bridgeGRUWithConversion(
|
||||
address token,
|
||||
string calldata sourceLayer,
|
||||
uint256 amount,
|
||||
uint64 destinationChain,
|
||||
string calldata targetLayer,
|
||||
address recipient
|
||||
) external nonReentrant returns (bytes32 messageId) {
|
||||
require(GRUConstants.isValidGRULayer(sourceLayer), "Invalid source layer");
|
||||
require(GRUConstants.isValidGRULayer(targetLayer), "Invalid target layer");
|
||||
|
||||
UniversalAssetRegistry.UniversalAsset memory asset = assetRegistry.getAsset(token);
|
||||
require(asset.assetType == UniversalAssetRegistry.AssetType.GRU, "Not GRU asset");
|
||||
require(asset.isActive, "Asset not active");
|
||||
|
||||
uint256 targetAmount = _convertGRULayers(sourceLayer, targetLayer, amount);
|
||||
|
||||
BridgeOperation memory op = BridgeOperation({
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationChain: destinationChain,
|
||||
recipient: recipient,
|
||||
assetType: bytes32(uint256(UniversalAssetRegistry.AssetType.GRU)),
|
||||
usePMM: false,
|
||||
useVault: false,
|
||||
complianceProof: "",
|
||||
vaultInstructions: ""
|
||||
});
|
||||
|
||||
messageId = this.bridge(op);
|
||||
|
||||
emit GRULayerConversion(messageId, sourceLayer, targetLayer, amount, targetAmount);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Convert between GRU layers
|
||||
*/
|
||||
function _convertGRULayers(
|
||||
string memory sourceLayer,
|
||||
string memory targetLayer,
|
||||
uint256 amount
|
||||
) internal pure returns (uint256) {
|
||||
bytes32 sourceHash = keccak256(bytes(sourceLayer));
|
||||
bytes32 targetHash = keccak256(bytes(targetLayer));
|
||||
bytes32 m00Hash = keccak256(bytes(GRUConstants.GRU_M00));
|
||||
bytes32 m0Hash = keccak256(bytes(GRUConstants.GRU_M0));
|
||||
bytes32 m1Hash = keccak256(bytes(GRUConstants.GRU_M1));
|
||||
|
||||
if (sourceHash == m00Hash && targetHash == m0Hash) {
|
||||
return GRUConstants.m00ToM0(amount);
|
||||
}
|
||||
if (sourceHash == m00Hash && targetHash == m1Hash) {
|
||||
return GRUConstants.m00ToM1(amount);
|
||||
}
|
||||
if (sourceHash == m0Hash && targetHash == m00Hash) {
|
||||
return GRUConstants.m0ToM00(amount);
|
||||
}
|
||||
if (sourceHash == m0Hash && targetHash == m1Hash) {
|
||||
return GRUConstants.m0ToM1(amount);
|
||||
}
|
||||
if (sourceHash == m1Hash && targetHash == m00Hash) {
|
||||
return GRUConstants.m1ToM00(amount);
|
||||
}
|
||||
if (sourceHash == m1Hash && targetHash == m0Hash) {
|
||||
return GRUConstants.m1ToM0(amount);
|
||||
}
|
||||
|
||||
return amount;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "./UniversalCCIPBridge.sol";
|
||||
import "../iso4217w/interfaces/IISO4217WToken.sol";
|
||||
|
||||
/**
|
||||
* @title ISO4217WCCIPBridge
|
||||
* @notice Specialized bridge for ISO-4217W eMoney/CBDC tokens
|
||||
* @dev Enforces KYC compliance and reserve backing verification
|
||||
*/
|
||||
contract ISO4217WCCIPBridge is UniversalCCIPBridge {
|
||||
|
||||
mapping(address => bool) public kycVerified;
|
||||
mapping(address => uint256) public kycExpiration;
|
||||
mapping(string => bool) public allowedJurisdictions;
|
||||
mapping(address => string) public userJurisdictions;
|
||||
mapping(address => uint256) public verifiedReserves;
|
||||
|
||||
event KYCVerified(address indexed user, uint256 expirationTime);
|
||||
event KYCRevoked(address indexed user);
|
||||
event JurisdictionEnabled(string indexed jurisdiction);
|
||||
event ReserveVerified(address indexed token, uint256 amount);
|
||||
|
||||
function bridgeISO4217W(
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint64 destinationChain,
|
||||
address recipient,
|
||||
bytes calldata complianceProof
|
||||
) external nonReentrant returns (bytes32 messageId) {
|
||||
UniversalAssetRegistry.UniversalAsset memory asset = assetRegistry.getAsset(token);
|
||||
require(asset.assetType == UniversalAssetRegistry.AssetType.ISO4217W, "Not ISO-4217W");
|
||||
require(asset.isActive, "Asset not active");
|
||||
|
||||
require(_checkKYC(msg.sender), "KYC required");
|
||||
require(_checkKYC(recipient), "Recipient KYC required");
|
||||
|
||||
string memory senderJurisdiction = userJurisdictions[msg.sender];
|
||||
string memory recipientJurisdiction = userJurisdictions[recipient];
|
||||
require(
|
||||
allowedJurisdictions[senderJurisdiction] &&
|
||||
allowedJurisdictions[recipientJurisdiction],
|
||||
"Jurisdiction not allowed"
|
||||
);
|
||||
|
||||
require(_verifyReserveBacking(token, amount), "Insufficient reserves");
|
||||
|
||||
BridgeOperation memory op = BridgeOperation({
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationChain: destinationChain,
|
||||
recipient: recipient,
|
||||
assetType: bytes32(uint256(UniversalAssetRegistry.AssetType.ISO4217W)),
|
||||
usePMM: false,
|
||||
useVault: false,
|
||||
complianceProof: complianceProof,
|
||||
vaultInstructions: ""
|
||||
});
|
||||
|
||||
messageId = this.bridge(op);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
function _verifyReserveBacking(address token, uint256 amount) internal view returns (bool) {
|
||||
try IISO4217WToken(token).verifiedReserve() returns (uint256 reserve) {
|
||||
return reserve >= amount;
|
||||
} catch {
|
||||
return verifiedReserves[token] >= amount;
|
||||
}
|
||||
}
|
||||
|
||||
function _checkKYC(address user) internal view returns (bool) {
|
||||
return kycVerified[user] && block.timestamp < kycExpiration[user];
|
||||
}
|
||||
|
||||
function setKYCStatus(address user, bool status, uint256 expirationTime)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
kycVerified[user] = status;
|
||||
kycExpiration[user] = expirationTime;
|
||||
|
||||
if (status) {
|
||||
emit KYCVerified(user, expirationTime);
|
||||
} else {
|
||||
emit KYCRevoked(user);
|
||||
}
|
||||
}
|
||||
|
||||
function enableJurisdiction(string calldata jurisdiction) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
allowedJurisdictions[jurisdiction] = true;
|
||||
emit JurisdictionEnabled(jurisdiction);
|
||||
}
|
||||
|
||||
function setUserJurisdiction(address user, string calldata jurisdiction)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
userJurisdictions[user] = jurisdiction;
|
||||
}
|
||||
|
||||
function updateVerifiedReserve(address token, uint256 reserve)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
verifiedReserves[token] = reserve;
|
||||
emit ReserveVerified(token, reserve);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "../ccip/IRouterClient.sol";
|
||||
|
||||
interface IERC20 {
|
||||
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||
function transfer(address to, uint256 amount) external returns (bool);
|
||||
function approve(address spender, uint256 amount) external returns (bool);
|
||||
function balanceOf(address account) external view returns (uint256);
|
||||
}
|
||||
|
||||
/**
|
||||
* @title TwoWayTokenBridgeL1
|
||||
* @notice L1/LMain chain side: locks canonical tokens and triggers CCIP message to mint on L2
|
||||
* @dev Uses escrow for locked tokens; release on inbound messages
|
||||
*/
|
||||
contract TwoWayTokenBridgeL1 {
|
||||
IRouterClient public immutable ccipRouter;
|
||||
address public immutable canonicalToken;
|
||||
address public feeToken; // LINK
|
||||
address public admin;
|
||||
|
||||
struct DestinationConfig {
|
||||
uint64 chainSelector;
|
||||
address l2Bridge;
|
||||
bool enabled;
|
||||
}
|
||||
|
||||
mapping(uint64 => DestinationConfig) public destinations;
|
||||
uint64[] public destinationChains;
|
||||
|
||||
mapping(bytes32 => bool) public processed; // replay protection
|
||||
|
||||
event Locked(address indexed user, uint256 amount);
|
||||
event Released(address indexed recipient, uint256 amount);
|
||||
event CcipSend(bytes32 indexed messageId, uint64 destChain, address recipient, uint256 amount);
|
||||
event DestinationAdded(uint64 chainSelector, address l2Bridge);
|
||||
event DestinationUpdated(uint64 chainSelector, address l2Bridge);
|
||||
event DestinationRemoved(uint64 chainSelector);
|
||||
|
||||
modifier onlyAdmin() {
|
||||
require(msg.sender == admin, "only admin");
|
||||
_;
|
||||
}
|
||||
|
||||
modifier onlyRouter() {
|
||||
require(msg.sender == address(ccipRouter), "only router");
|
||||
_;
|
||||
}
|
||||
|
||||
constructor(address _router, address _token, address _feeToken) {
|
||||
require(_router != address(0) && _token != address(0) && _feeToken != address(0), "zero addr");
|
||||
ccipRouter = IRouterClient(_router);
|
||||
canonicalToken = _token;
|
||||
feeToken = _feeToken;
|
||||
admin = msg.sender;
|
||||
}
|
||||
|
||||
function addDestination(uint64 chainSelector, address l2Bridge) external onlyAdmin {
|
||||
require(l2Bridge != address(0), "zero l2");
|
||||
require(!destinations[chainSelector].enabled, "exists");
|
||||
destinations[chainSelector] = DestinationConfig(chainSelector, l2Bridge, true);
|
||||
destinationChains.push(chainSelector);
|
||||
emit DestinationAdded(chainSelector, l2Bridge);
|
||||
}
|
||||
|
||||
function updateDestination(uint64 chainSelector, address l2Bridge) external onlyAdmin {
|
||||
require(destinations[chainSelector].enabled, "missing");
|
||||
require(l2Bridge != address(0), "zero l2");
|
||||
destinations[chainSelector].l2Bridge = l2Bridge;
|
||||
emit DestinationUpdated(chainSelector, l2Bridge);
|
||||
}
|
||||
|
||||
function removeDestination(uint64 chainSelector) external onlyAdmin {
|
||||
require(destinations[chainSelector].enabled, "missing");
|
||||
destinations[chainSelector].enabled = false;
|
||||
for (uint256 i = 0; i < destinationChains.length; i++) {
|
||||
if (destinationChains[i] == chainSelector) {
|
||||
destinationChains[i] = destinationChains[destinationChains.length - 1];
|
||||
destinationChains.pop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
emit DestinationRemoved(chainSelector);
|
||||
}
|
||||
|
||||
function updateFeeToken(address newFee) external onlyAdmin {
|
||||
require(newFee != address(0), "zero");
|
||||
feeToken = newFee;
|
||||
}
|
||||
|
||||
function changeAdmin(address newAdmin) external onlyAdmin {
|
||||
require(newAdmin != address(0), "zero");
|
||||
admin = newAdmin;
|
||||
}
|
||||
|
||||
function getDestinationChains() external view returns (uint64[] memory) {
|
||||
return destinationChains;
|
||||
}
|
||||
|
||||
// User-facing: lock canonical tokens and send CCIP to mint on L2
|
||||
function lockAndSend(uint64 destSelector, address recipient, uint256 amount) external returns (bytes32 messageId) {
|
||||
require(amount > 0 && recipient != address(0), "bad args");
|
||||
DestinationConfig memory dest = destinations[destSelector];
|
||||
require(dest.enabled, "dest disabled");
|
||||
|
||||
// Pull tokens into escrow
|
||||
require(IERC20(canonicalToken).transferFrom(msg.sender, address(this), amount), "pull fail");
|
||||
emit Locked(msg.sender, amount);
|
||||
|
||||
// Encode payload
|
||||
bytes memory data = abi.encode(recipient, amount);
|
||||
|
||||
// Build message
|
||||
IRouterClient.EVM2AnyMessage memory m = IRouterClient.EVM2AnyMessage({
|
||||
receiver: abi.encode(dest.l2Bridge),
|
||||
data: data,
|
||||
tokenAmounts: new IRouterClient.TokenAmount[](0),
|
||||
feeToken: feeToken,
|
||||
extraArgs: ""
|
||||
});
|
||||
|
||||
// Get fee and pay in LINK held by user: bridge expects to have LINK pre-funded by admin or via separate topup
|
||||
uint256 fee = ccipRouter.getFee(destSelector, m);
|
||||
if (fee > 0) {
|
||||
// Expect admin has prefunded LINK to this contract; otherwise approvals/pull pattern can be added
|
||||
require(IERC20(feeToken).approve(address(ccipRouter), fee), "fee approve");
|
||||
}
|
||||
|
||||
(messageId, ) = ccipRouter.ccipSend(destSelector, m);
|
||||
emit CcipSend(messageId, destSelector, recipient, amount);
|
||||
return messageId;
|
||||
}
|
||||
|
||||
// Inbound from L2: release canonical tokens to recipient
|
||||
function ccipReceive(IRouterClient.Any2EVMMessage calldata message) external onlyRouter {
|
||||
require(!processed[message.messageId], "replayed");
|
||||
processed[message.messageId] = true;
|
||||
(address recipient, uint256 amount) = abi.decode(message.data, (address, uint256));
|
||||
require(recipient != address(0) && amount > 0, "bad msg");
|
||||
require(IERC20(canonicalToken).transfer(recipient, amount), "release fail");
|
||||
emit Released(recipient, amount);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
|
||||
import "../ccip/IRouterClient.sol";
|
||||
|
||||
interface IMintableERC20 {
|
||||
function mint(address to, uint256 amount) external;
|
||||
function burnFrom(address from, uint256 amount) external;
|
||||
function balanceOf(address account) external view returns (uint256);
|
||||
}
|
||||
|
||||
/**
|
||||
* @title TwoWayTokenBridgeL2
|
||||
* @notice L2/secondary chain side: mints mirrored tokens on inbound and burns on outbound
|
||||
*/
|
||||
contract TwoWayTokenBridgeL2 {
|
||||
IRouterClient public immutable ccipRouter;
|
||||
address public immutable mirroredToken;
|
||||
address public feeToken; // LINK
|
||||
address public admin;
|
||||
|
||||
struct DestinationConfig {
|
||||
uint64 chainSelector;
|
||||
address l1Bridge;
|
||||
bool enabled;
|
||||
}
|
||||
|
||||
mapping(uint64 => DestinationConfig) public destinations;
|
||||
uint64[] public destinationChains;
|
||||
mapping(bytes32 => bool) public processed;
|
||||
|
||||
event Minted(address indexed recipient, uint256 amount);
|
||||
event Burned(address indexed user, uint256 amount);
|
||||
event CcipSend(bytes32 indexed messageId, uint64 destChain, address recipient, uint256 amount);
|
||||
event DestinationAdded(uint64 chainSelector, address l1Bridge);
|
||||
event DestinationUpdated(uint64 chainSelector, address l1Bridge);
|
||||
event DestinationRemoved(uint64 chainSelector);
|
||||
|
||||
modifier onlyAdmin() {
|
||||
require(msg.sender == admin, "only admin");
|
||||
_;
|
||||
}
|
||||
|
||||
modifier onlyRouter() {
|
||||
require(msg.sender == address(ccipRouter), "only router");
|
||||
_;
|
||||
}
|
||||
|
||||
constructor(address _router, address _token, address _feeToken) {
|
||||
require(_router != address(0) && _token != address(0) && _feeToken != address(0), "zero addr");
|
||||
ccipRouter = IRouterClient(_router);
|
||||
mirroredToken = _token;
|
||||
feeToken = _feeToken;
|
||||
admin = msg.sender;
|
||||
}
|
||||
|
||||
function addDestination(uint64 chainSelector, address l1Bridge) external onlyAdmin {
|
||||
require(l1Bridge != address(0), "zero l1");
|
||||
require(!destinations[chainSelector].enabled, "exists");
|
||||
destinations[chainSelector] = DestinationConfig(chainSelector, l1Bridge, true);
|
||||
destinationChains.push(chainSelector);
|
||||
emit DestinationAdded(chainSelector, l1Bridge);
|
||||
}
|
||||
|
||||
function updateDestination(uint64 chainSelector, address l1Bridge) external onlyAdmin {
|
||||
require(destinations[chainSelector].enabled, "missing");
|
||||
require(l1Bridge != address(0), "zero l1");
|
||||
destinations[chainSelector].l1Bridge = l1Bridge;
|
||||
emit DestinationUpdated(chainSelector, l1Bridge);
|
||||
}
|
||||
|
||||
function removeDestination(uint64 chainSelector) external onlyAdmin {
|
||||
require(destinations[chainSelector].enabled, "missing");
|
||||
destinations[chainSelector].enabled = false;
|
||||
for (uint256 i = 0; i < destinationChains.length; i++) {
|
||||
if (destinationChains[i] == chainSelector) {
|
||||
destinationChains[i] = destinationChains[destinationChains.length - 1];
|
||||
destinationChains.pop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
emit DestinationRemoved(chainSelector);
|
||||
}
|
||||
|
||||
function updateFeeToken(address newFee) external onlyAdmin {
|
||||
require(newFee != address(0), "zero");
|
||||
feeToken = newFee;
|
||||
}
|
||||
|
||||
function changeAdmin(address newAdmin) external onlyAdmin {
|
||||
require(newAdmin != address(0), "zero");
|
||||
admin = newAdmin;
|
||||
}
|
||||
|
||||
function getDestinationChains() external view returns (uint64[] memory) {
|
||||
return destinationChains;
|
||||
}
|
||||
|
||||
// Inbound from L1: mint mirrored tokens to recipient
|
||||
function ccipReceive(IRouterClient.Any2EVMMessage calldata message) external onlyRouter {
|
||||
require(!processed[message.messageId], "replayed");
|
||||
processed[message.messageId] = true;
|
||||
(address recipient, uint256 amount) = abi.decode(message.data, (address, uint256));
|
||||
require(recipient != address(0) && amount > 0, "bad msg");
|
||||
IMintableERC20(mirroredToken).mint(recipient, amount);
|
||||
emit Minted(recipient, amount);
|
||||
}
|
||||
|
||||
// Outbound to L1: burn mirrored tokens and signal release on L1
|
||||
function burnAndSend(uint64 destSelector, address recipient, uint256 amount) external returns (bytes32 messageId) {
|
||||
require(amount > 0 && recipient != address(0), "bad args");
|
||||
DestinationConfig memory dest = destinations[destSelector];
|
||||
require(dest.enabled, "dest disabled");
|
||||
|
||||
IMintableERC20(mirroredToken).burnFrom(msg.sender, amount);
|
||||
emit Burned(msg.sender, amount);
|
||||
|
||||
bytes memory data = abi.encode(recipient, amount);
|
||||
IRouterClient.EVM2AnyMessage memory m = IRouterClient.EVM2AnyMessage({
|
||||
receiver: abi.encode(dest.l1Bridge),
|
||||
data: data,
|
||||
tokenAmounts: new IRouterClient.TokenAmount[](0),
|
||||
feeToken: feeToken,
|
||||
extraArgs: ""
|
||||
});
|
||||
uint256 fee = ccipRouter.getFee(destSelector, m);
|
||||
if (fee > 0) {
|
||||
require(IERC20(feeToken).approve(address(ccipRouter), fee), "fee approve");
|
||||
}
|
||||
(messageId, ) = ccipRouter.ccipSend(destSelector, m);
|
||||
emit CcipSend(messageId, destSelector, recipient, amount);
|
||||
return messageId;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "../registry/UniversalAssetRegistry.sol";
|
||||
import "../ccip/IRouterClient.sol";
|
||||
|
||||
/**
|
||||
* @title UniversalCCIPBridge
|
||||
* @notice Main bridge contract supporting all asset types via CCIP
|
||||
* @dev Extends CCIP infrastructure with dynamic asset routing and PMM integration
|
||||
*/
|
||||
contract UniversalCCIPBridge is
|
||||
Initializable,
|
||||
AccessControlUpgradeable,
|
||||
ReentrancyGuardUpgradeable,
|
||||
UUPSUpgradeable
|
||||
{
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
|
||||
|
||||
struct BridgeOperation {
|
||||
address token;
|
||||
uint256 amount;
|
||||
uint64 destinationChain;
|
||||
address recipient;
|
||||
bytes32 assetType;
|
||||
bool usePMM;
|
||||
bool useVault;
|
||||
bytes complianceProof;
|
||||
bytes vaultInstructions;
|
||||
}
|
||||
|
||||
struct Destination {
|
||||
address receiverBridge;
|
||||
bool enabled;
|
||||
uint256 addedAt;
|
||||
}
|
||||
|
||||
// Core dependencies
|
||||
UniversalAssetRegistry public assetRegistry;
|
||||
IRouterClient public ccipRouter;
|
||||
address public liquidityManager;
|
||||
address public vaultFactory;
|
||||
|
||||
// State
|
||||
mapping(address => mapping(uint64 => Destination)) public destinations;
|
||||
mapping(address => address) public userVaults;
|
||||
mapping(bytes32 => bool) public processedMessages;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
// Events
|
||||
event BridgeExecuted(
|
||||
bytes32 indexed messageId,
|
||||
address indexed token,
|
||||
address indexed sender,
|
||||
uint256 amount,
|
||||
uint64 destinationChain,
|
||||
address recipient,
|
||||
bool usedPMM
|
||||
);
|
||||
|
||||
event DestinationAdded(
|
||||
address indexed token,
|
||||
uint64 indexed chainSelector,
|
||||
address receiverBridge
|
||||
);
|
||||
|
||||
event DestinationRemoved(
|
||||
address indexed token,
|
||||
uint64 indexed chainSelector
|
||||
);
|
||||
|
||||
event MessageReceived(
|
||||
bytes32 indexed messageId,
|
||||
uint64 indexed sourceChainSelector,
|
||||
address sender,
|
||||
address token,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor() {
|
||||
_disableInitializers();
|
||||
}
|
||||
|
||||
function initialize(
|
||||
address _assetRegistry,
|
||||
address _ccipRouter,
|
||||
address admin
|
||||
) external initializer {
|
||||
__AccessControl_init();
|
||||
__ReentrancyGuard_init();
|
||||
__UUPSUpgradeable_init();
|
||||
|
||||
require(_assetRegistry != address(0), "Zero registry");
|
||||
|
||||
assetRegistry = UniversalAssetRegistry(_assetRegistry);
|
||||
if (_ccipRouter != address(0)) {
|
||||
ccipRouter = IRouterClient(_ccipRouter);
|
||||
}
|
||||
// If _ccipRouter is zero, set via setCCIPRouter() after deployment (enables same initData for deterministic proxy address)
|
||||
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(UPGRADER_ROLE, admin);
|
||||
}
|
||||
|
||||
function _authorizeUpgrade(address newImplementation)
|
||||
internal override onlyRole(UPGRADER_ROLE) {}
|
||||
|
||||
/**
|
||||
* @notice Set CCIP router (for deterministic deployment: initialize with router=0, then set per chain)
|
||||
*/
|
||||
function setCCIPRouter(address _ccipRouter) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(_ccipRouter != address(0), "Zero router");
|
||||
ccipRouter = IRouterClient(_ccipRouter);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Main bridge function with asset type routing
|
||||
*/
|
||||
function bridge(
|
||||
BridgeOperation calldata op
|
||||
) external payable nonReentrant returns (bytes32 messageId) {
|
||||
// Validate asset is registered and active
|
||||
UniversalAssetRegistry.UniversalAsset memory asset = assetRegistry.getAsset(op.token);
|
||||
require(asset.isActive, "Asset not active");
|
||||
require(asset.tokenAddress != address(0), "Asset not registered");
|
||||
|
||||
// Verify destination is enabled
|
||||
Destination memory dest = destinations[op.token][op.destinationChain];
|
||||
require(dest.enabled, "Destination not enabled");
|
||||
require(dest.receiverBridge != address(0), "Invalid receiver");
|
||||
|
||||
// Validate amounts
|
||||
require(op.amount > 0, "Invalid amount");
|
||||
require(op.amount >= asset.minBridgeAmount, "Below minimum");
|
||||
require(op.amount <= asset.maxBridgeAmount, "Above maximum");
|
||||
|
||||
// Transfer tokens from user
|
||||
IERC20(op.token).safeTransferFrom(msg.sender, address(this), op.amount);
|
||||
|
||||
// Execute bridge with optional PMM
|
||||
if (op.usePMM && liquidityManager != address(0)) {
|
||||
_executeBridgeWithPMM(op);
|
||||
}
|
||||
|
||||
// Execute bridge with optional vault
|
||||
if (op.useVault && vaultFactory != address(0)) {
|
||||
_executeBridgeWithVault(op);
|
||||
}
|
||||
|
||||
// Send CCIP message
|
||||
messageId = _sendCCIPMessage(op, dest);
|
||||
|
||||
// Increment nonce
|
||||
nonces[msg.sender]++;
|
||||
|
||||
emit BridgeExecuted(
|
||||
messageId,
|
||||
op.token,
|
||||
msg.sender,
|
||||
op.amount,
|
||||
op.destinationChain,
|
||||
op.recipient,
|
||||
op.usePMM
|
||||
);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute bridge with PMM liquidity
|
||||
*/
|
||||
function _executeBridgeWithPMM(BridgeOperation calldata op) internal {
|
||||
if (liquidityManager == address(0)) return;
|
||||
|
||||
// Call liquidity manager to provide liquidity
|
||||
(bool success, ) = liquidityManager.call(
|
||||
abi.encodeWithSignature(
|
||||
"provideLiquidity(address,uint256,bytes)",
|
||||
op.token,
|
||||
op.amount,
|
||||
""
|
||||
)
|
||||
);
|
||||
|
||||
// PMM is optional, don't revert if it fails
|
||||
if (!success) {
|
||||
// Log or handle PMM failure gracefully
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute bridge with vault
|
||||
*/
|
||||
function _executeBridgeWithVault(BridgeOperation calldata op) internal {
|
||||
if (vaultFactory == address(0)) return;
|
||||
|
||||
// Get or create vault for user
|
||||
address vault = userVaults[msg.sender];
|
||||
if (vault == address(0)) {
|
||||
// Call vault factory to create vault
|
||||
(bool success, bytes memory data) = vaultFactory.call(
|
||||
abi.encodeWithSignature("createVault(address)", msg.sender)
|
||||
);
|
||||
if (success) {
|
||||
vault = abi.decode(data, (address));
|
||||
userVaults[msg.sender] = vault;
|
||||
}
|
||||
}
|
||||
|
||||
// If vault exists, record operation
|
||||
if (vault != address(0)) {
|
||||
// Call vault to record bridge operation
|
||||
(bool success, ) = vault.call(
|
||||
abi.encodeWithSignature(
|
||||
"recordBridgeOperation(bytes32,address,uint256,uint64)",
|
||||
bytes32(0), // messageId will be set after CCIP send
|
||||
op.token,
|
||||
op.amount,
|
||||
op.destinationChain
|
||||
)
|
||||
);
|
||||
// Vault recording is optional
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Send CCIP message
|
||||
*/
|
||||
function _sendCCIPMessage(
|
||||
BridgeOperation calldata op,
|
||||
Destination memory dest
|
||||
) internal returns (bytes32 messageId) {
|
||||
// Encode message data
|
||||
bytes memory data = abi.encode(
|
||||
op.recipient,
|
||||
op.amount,
|
||||
msg.sender,
|
||||
nonces[msg.sender]
|
||||
);
|
||||
|
||||
// Prepare CCIP message
|
||||
IRouterClient.EVM2AnyMessage memory message = IRouterClient.EVM2AnyMessage({
|
||||
receiver: abi.encode(dest.receiverBridge),
|
||||
data: data,
|
||||
tokenAmounts: new IRouterClient.TokenAmount[](1),
|
||||
feeToken: address(0), // Pay in native
|
||||
extraArgs: ""
|
||||
});
|
||||
|
||||
// Set token amount
|
||||
message.tokenAmounts[0] = IRouterClient.TokenAmount({
|
||||
token: op.token,
|
||||
amount: op.amount,
|
||||
amountType: IRouterClient.TokenAmountType.Fiat
|
||||
});
|
||||
|
||||
// Calculate fee
|
||||
uint256 fee = ccipRouter.getFee(op.destinationChain, message);
|
||||
require(address(this).balance >= fee, "Insufficient fee");
|
||||
|
||||
// Send via CCIP
|
||||
(messageId, ) = ccipRouter.ccipSend{value: fee}(op.destinationChain, message);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Add destination for token
|
||||
*/
|
||||
function addDestination(
|
||||
address token,
|
||||
uint64 chainSelector,
|
||||
address receiverBridge
|
||||
) external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
require(token != address(0), "Zero token");
|
||||
require(receiverBridge != address(0), "Zero receiver");
|
||||
|
||||
destinations[token][chainSelector] = Destination({
|
||||
receiverBridge: receiverBridge,
|
||||
enabled: true,
|
||||
addedAt: block.timestamp
|
||||
});
|
||||
|
||||
emit DestinationAdded(token, chainSelector, receiverBridge);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Remove destination
|
||||
*/
|
||||
function removeDestination(
|
||||
address token,
|
||||
uint64 chainSelector
|
||||
) external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
destinations[token][chainSelector].enabled = false;
|
||||
|
||||
emit DestinationRemoved(token, chainSelector);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set liquidity manager
|
||||
*/
|
||||
function setLiquidityManager(address _liquidityManager) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
liquidityManager = _liquidityManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set vault factory
|
||||
*/
|
||||
function setVaultFactory(address _vaultFactory) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
vaultFactory = _vaultFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Receive native tokens
|
||||
*/
|
||||
receive() external payable {}
|
||||
|
||||
/**
|
||||
* @notice Withdraw native tokens
|
||||
*/
|
||||
function withdraw() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
payable(msg.sender).transfer(address(this).balance);
|
||||
}
|
||||
|
||||
// View functions
|
||||
|
||||
function getDestination(address token, uint64 chainSelector)
|
||||
external view returns (Destination memory) {
|
||||
return destinations[token][chainSelector];
|
||||
}
|
||||
|
||||
function getUserVault(address user) external view returns (address) {
|
||||
return userVaults[user];
|
||||
}
|
||||
|
||||
function getUserNonce(address user) external view returns (uint256) {
|
||||
return nonces[user];
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "./UniversalCCIPBridge.sol";
|
||||
|
||||
contract VaultBridgeAdapter is AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant ADAPTER_ADMIN_ROLE = keccak256("ADAPTER_ADMIN_ROLE");
|
||||
|
||||
address public vaultFactory;
|
||||
UniversalCCIPBridge public bridge;
|
||||
|
||||
mapping(address => address) public userVaults;
|
||||
|
||||
event VaultCreated(address indexed user, address indexed vault);
|
||||
|
||||
constructor(address _vaultFactory, address _bridge, address admin) {
|
||||
require(_vaultFactory != address(0), "Zero factory");
|
||||
require(_bridge != address(0), "Zero bridge");
|
||||
|
||||
vaultFactory = _vaultFactory;
|
||||
bridge = UniversalCCIPBridge(payable(_bridge));
|
||||
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(ADAPTER_ADMIN_ROLE, admin);
|
||||
}
|
||||
|
||||
function getOrCreateVault(address user) public returns (address vault) {
|
||||
vault = userVaults[user];
|
||||
if (vault == address(0)) {
|
||||
(bool success, bytes memory data) = vaultFactory.call(
|
||||
abi.encodeWithSignature("createVault(address)", user)
|
||||
);
|
||||
if (success) {
|
||||
vault = abi.decode(data, (address));
|
||||
userVaults[user] = vault;
|
||||
emit VaultCreated(user, vault);
|
||||
}
|
||||
}
|
||||
return vault;
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
import "../../interfaces/IAlltraTransport.sol";
|
||||
import "../../UniversalCCIPBridge.sol";
|
||||
|
||||
/**
|
||||
* @title AlltraAdapter
|
||||
* @notice Bridge adapter for ALL Mainnet (EVM-compatible)
|
||||
* @dev ALL Mainnet (651940) is not supported by CCIP. Use setAlltraTransport() to set
|
||||
* AlltraCustomBridge (or other IAlltraTransport) for 138 <-> 651940 flows.
|
||||
* @dev Chain ID: 651940 (0x9f2a4) - https://chainlist.org/chain/651940
|
||||
*/
|
||||
contract AlltraAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
|
||||
// ALL Mainnet Chain ID - confirmed from ChainList
|
||||
uint256 public constant ALLTRA_MAINNET = 651940;
|
||||
|
||||
UniversalCCIPBridge public universalBridge;
|
||||
IAlltraTransport public alltraTransport; // When set, used for 651940 instead of CCIP
|
||||
bool public isActive;
|
||||
/// @notice Configurable bridge fee (default 0.001 ALL). Set via setBridgeFee() after deployment.
|
||||
uint256 public bridgeFee;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event AlltraBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
address recipient
|
||||
);
|
||||
|
||||
event AlltraBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
bytes32 indexed alltraTxHash
|
||||
);
|
||||
|
||||
constructor(address admin, address _bridge) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
universalBridge = UniversalCCIPBridge(payable(_bridge));
|
||||
isActive = true;
|
||||
bridgeFee = 1000000000000000; // 0.001 ALL default; update via setBridgeFee() per ALL Mainnet fee structure
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set custom transport for 138 <-> 651940 (no CCIP). When set, bridge() uses this instead of UniversalCCIPBridge.
|
||||
*/
|
||||
function setAlltraTransport(address _transport) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
alltraTransport = IAlltraTransport(_transport);
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "EVM"; // Generic chain type to distinguish from ALLTRA (orchestration layer)
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (ALLTRA_MAINNET, "ALL-Mainnet"); // Updated identifier
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
// Standard EVM address validation
|
||||
if (destination.length != 20) return false;
|
||||
address dest = address(bytes20(destination));
|
||||
return dest != address(0);
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
require(this.validateDestination(destination), "Invalid destination");
|
||||
|
||||
address recipientAddr = address(bytes20(destination));
|
||||
|
||||
// Generate request ID
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
recipientAddr,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
// Lock tokens
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
// Create bridge request
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
// ALL Mainnet (651940) is not supported by CCIP. Use custom transport when set.
|
||||
if (address(alltraTransport) != address(0) && alltraTransport.isConfigured()) {
|
||||
alltraTransport.lockAndRelay{value: msg.value}(token, amount, recipientAddr);
|
||||
} else {
|
||||
// Fallback to UniversalCCIPBridge only if destination were CCIP-supported; 651940 is not.
|
||||
revert("AlltraAdapter: set AlltraCustomBridge via setAlltraTransport for 651940");
|
||||
}
|
||||
|
||||
emit AlltraBridgeInitiated(requestId, msg.sender, token, amount, recipientAddr);
|
||||
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
// Refund tokens
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @notice Returns the current bridge fee (configurable via setBridgeFee).
|
||||
/// @param token Unused; fee is global per adapter.
|
||||
/// @param amount Unused.
|
||||
/// @param destination Unused.
|
||||
/// @return fee Current bridgeFee in wei.
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return bridgeFee;
|
||||
}
|
||||
|
||||
/// @notice Update bridge fee. Call after deployment when ALL Mainnet fee structure is known.
|
||||
function setBridgeFee(uint256 _fee) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
bridgeFee = _fee;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
|
||||
function confirmBridge(bytes32 requestId, bytes32 alltraTxHash)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
|
||||
emit AlltraBridgeConfirmed(requestId, alltraTxHash);
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
import "../../UniversalCCIPBridge.sol";
|
||||
|
||||
/**
|
||||
* @title EVMAdapter
|
||||
* @notice Standard bridge adapter for EVM-compatible chains
|
||||
* @dev Template adapter for Polygon, Arbitrum, Optimism, Base, Avalanche, BSC, Ethereum
|
||||
*/
|
||||
contract EVMAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
|
||||
uint256 public immutable chainId;
|
||||
string public chainName;
|
||||
UniversalCCIPBridge public universalBridge;
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event EVMBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
uint256 destinationChainId,
|
||||
address recipient
|
||||
);
|
||||
|
||||
event EVMBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
bytes32 indexed txHash
|
||||
);
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address _bridge,
|
||||
uint256 _chainId,
|
||||
string memory _chainName
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
universalBridge = UniversalCCIPBridge(payable(_bridge));
|
||||
chainId = _chainId;
|
||||
chainName = _chainName;
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "EVM";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external view override returns (uint256, string memory) {
|
||||
return (chainId, chainName);
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
if (destination.length != 20) return false;
|
||||
address dest = address(bytes20(destination));
|
||||
return dest != address(0);
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
require(this.validateDestination(destination), "Invalid destination");
|
||||
|
||||
address recipientAddr = address(bytes20(destination));
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
recipientAddr,
|
||||
chainId,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
IERC20(token).forceApprove(address(universalBridge), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
UniversalCCIPBridge.BridgeOperation memory op = UniversalCCIPBridge.BridgeOperation({
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationChain: uint64(chainId),
|
||||
recipient: recipientAddr,
|
||||
assetType: bytes32(0),
|
||||
usePMM: false,
|
||||
useVault: false,
|
||||
complianceProof: "",
|
||||
vaultInstructions: ""
|
||||
});
|
||||
|
||||
bytes32 messageId = universalBridge.bridge{value: msg.value}(op);
|
||||
|
||||
emit EVMBridgeInitiated(requestId, msg.sender, token, amount, chainId, recipientAddr);
|
||||
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
|
||||
function confirmBridge(bytes32 requestId, bytes32 txHash)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
|
||||
emit EVMBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
import "../../UniversalCCIPBridge.sol";
|
||||
|
||||
/**
|
||||
* @title XDCAdapter
|
||||
* @notice Bridge adapter for XDC Network (EVM-compatible with xdc address prefix)
|
||||
* @dev XDC uses xdc prefix instead of 0x for addresses
|
||||
*/
|
||||
contract XDCAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
|
||||
uint256 public constant XDC_MAINNET = 50;
|
||||
uint256 public constant XDC_APOTHEM_TESTNET = 51;
|
||||
|
||||
UniversalCCIPBridge public universalBridge;
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event XDCBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string xdcDestination
|
||||
);
|
||||
|
||||
event XDCBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
bytes32 indexed xdcTxHash
|
||||
);
|
||||
|
||||
constructor(address admin, address _bridge) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
universalBridge = UniversalCCIPBridge(payable(_bridge));
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "XDC";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (XDC_MAINNET, "XDC-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
string memory addr = string(destination);
|
||||
bytes memory addrBytes = bytes(addr);
|
||||
|
||||
if (addrBytes.length != 43) return false;
|
||||
if (addrBytes[0] != 'x' || addrBytes[1] != 'd' || addrBytes[2] != 'c') return false;
|
||||
|
||||
for (uint256 i = 3; i < 43; i++) {
|
||||
bytes1 char = addrBytes[i];
|
||||
if (!((char >= 0x30 && char <= 0x39) || (char >= 0x61 && char <= 0x66))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function convertXdcToEth(string memory xdcAddr) public pure returns (address) {
|
||||
bytes memory xdcBytes = bytes(xdcAddr);
|
||||
require(xdcBytes.length == 43, "Invalid XDC address length");
|
||||
require(xdcBytes[0] == 'x' && xdcBytes[1] == 'd' && xdcBytes[2] == 'c', "Invalid XDC prefix");
|
||||
// Parse 40 hex chars (20 bytes) to address; do not use bytes32(hexBytes) which truncates 42 bytes
|
||||
uint160 result = 0;
|
||||
for (uint256 i = 0; i < 40; i++) {
|
||||
result = result * 16 + _hexCharToNibble(xdcBytes[i + 3]);
|
||||
}
|
||||
return address(result);
|
||||
}
|
||||
|
||||
function _hexCharToNibble(bytes1 c) internal pure returns (uint8) {
|
||||
if (c >= 0x30 && c <= 0x39) return uint8(c) - 0x30; // '0'-'9'
|
||||
if (c >= 0x61 && c <= 0x66) return uint8(c) - 0x61 + 10; // 'a'-'f'
|
||||
if (c >= 0x41 && c <= 0x46) return uint8(c) - 0x41 + 10; // 'A'-'F'
|
||||
revert("Invalid hex character");
|
||||
}
|
||||
|
||||
function convertEthToXdc(address ethAddr) public pure returns (string memory) {
|
||||
bytes20 addr = bytes20(ethAddr);
|
||||
bytes memory hexString = new bytes(43);
|
||||
hexString[0] = 'x';
|
||||
hexString[1] = 'd';
|
||||
hexString[2] = 'c';
|
||||
|
||||
for (uint256 i = 0; i < 20; i++) {
|
||||
uint8 byteValue = uint8(addr[i]);
|
||||
uint8 high = byteValue >> 4;
|
||||
uint8 low = byteValue & 0x0f;
|
||||
|
||||
hexString[3 + i * 2] = bytes1(high < 10 ? 48 + high : 87 + high);
|
||||
hexString[4 + i * 2] = bytes1(low < 10 ? 48 + low : 87 + low);
|
||||
}
|
||||
|
||||
return string(hexString);
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory xdcDestination = string(destination);
|
||||
require(this.validateDestination(destination), "Invalid XDC address");
|
||||
|
||||
address evmRecipient = convertXdcToEth(xdcDestination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
xdcDestination,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
UniversalCCIPBridge.BridgeOperation memory op = UniversalCCIPBridge.BridgeOperation({
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationChain: uint64(XDC_MAINNET),
|
||||
recipient: evmRecipient,
|
||||
assetType: bytes32(0),
|
||||
usePMM: false,
|
||||
useVault: false,
|
||||
complianceProof: "",
|
||||
vaultInstructions: ""
|
||||
});
|
||||
|
||||
bytes32 messageId = universalBridge.bridge{value: msg.value}(op);
|
||||
|
||||
emit XDCBridgeInitiated(requestId, msg.sender, token, amount, xdcDestination);
|
||||
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
|
||||
function confirmBridge(bytes32 requestId, bytes32 xdcTxHash)
|
||||
external onlyRole(BRIDGE_OPERATOR_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
|
||||
emit XDCBridgeConfirmed(requestId, xdcTxHash);
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract CactiAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant CACTI_OPERATOR_ROLE = keccak256("CACTI_OPERATOR_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
string public cactiApiUrl;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public cactiTxIds;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event CactiBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string sourceLedger,
|
||||
string destLedger,
|
||||
string cactiTxId
|
||||
);
|
||||
|
||||
event CactiBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed cactiTxId,
|
||||
string sourceLedger,
|
||||
string destLedger
|
||||
);
|
||||
|
||||
constructor(address admin, string memory _cactiApiUrl) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(CACTI_OPERATOR_ROLE, admin);
|
||||
cactiApiUrl = _cactiApiUrl;
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Cacti";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Cacti-Interoperability");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
(string memory sourceLedger, string memory destLedger) = abi.decode(destination, (string, string));
|
||||
require(bytes(sourceLedger).length > 0 && bytes(destLedger).length > 0, "Invalid ledgers");
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
sourceLedger,
|
||||
destLedger,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit CactiBridgeInitiated(requestId, msg.sender, token, amount, sourceLedger, destLedger, "");
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmCactiOperation(
|
||||
bytes32 requestId,
|
||||
string calldata cactiTxId,
|
||||
string calldata sourceLedger,
|
||||
string calldata destLedger
|
||||
) external onlyRole(CACTI_OPERATOR_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
cactiTxIds[requestId] = cactiTxId;
|
||||
|
||||
emit CactiBridgeConfirmed(requestId, cactiTxId, sourceLedger, destLedger);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract FabricAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant FABRIC_OPERATOR_ROLE = keccak256("FABRIC_OPERATOR_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
string public fabricChannel;
|
||||
string public fabricChaincode;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public fabricTxIds;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event FabricBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string fabricChannel,
|
||||
string fabricChaincode
|
||||
);
|
||||
|
||||
event FabricBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed fabricTxId,
|
||||
string fabricChannel
|
||||
);
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
string memory _fabricChannel,
|
||||
string memory _fabricChaincode
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(FABRIC_OPERATOR_ROLE, admin);
|
||||
fabricChannel = _fabricChannel;
|
||||
fabricChaincode = _fabricChaincode;
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Fabric";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external view override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, string(abi.encodePacked("Fabric-", fabricChannel)));
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
destination,
|
||||
fabricChannel,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit FabricBridgeInitiated(requestId, msg.sender, token, amount, fabricChannel, fabricChaincode);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmFabricOperation(
|
||||
bytes32 requestId,
|
||||
string calldata fabricTxId
|
||||
) external onlyRole(FABRIC_OPERATOR_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
fabricTxIds[requestId] = fabricTxId;
|
||||
|
||||
emit FabricBridgeConfirmed(requestId, fabricTxId, fabricChannel);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
/**
|
||||
* @title FireflyAdapter
|
||||
* @notice Bridge adapter for Hyperledger Firefly orchestration layer
|
||||
* @dev Firefly coordinates multi-chain operations - this adapter interfaces with Firefly API
|
||||
*/
|
||||
contract FireflyAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant FIREFLY_OPERATOR_ROLE = keccak256("FIREFLY_OPERATOR_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
string public fireflyNamespace;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public fireflyTxIds;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event FireflyBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string fireflyTxId,
|
||||
string namespace
|
||||
);
|
||||
|
||||
event FireflyBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed fireflyTxId,
|
||||
string sourceChain
|
||||
);
|
||||
|
||||
constructor(address admin, string memory _namespace) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(FIREFLY_OPERATOR_ROLE, admin);
|
||||
fireflyNamespace = _namespace;
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Firefly";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Firefly-Orchestration");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
destination,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit FireflyBridgeInitiated(requestId, msg.sender, token, amount, "", fireflyNamespace);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmFireflyOperation(
|
||||
bytes32 requestId,
|
||||
string calldata fireflyTxId,
|
||||
string calldata sourceChain
|
||||
) external onlyRole(FIREFLY_OPERATOR_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
fireflyTxIds[requestId] = fireflyTxId;
|
||||
|
||||
emit FireflyBridgeConfirmed(requestId, fireflyTxId, sourceChain);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract AlgorandAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event AlgorandBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event AlgorandBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Algorand";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Algorand-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit AlgorandBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit AlgorandBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract CosmosAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event CosmosBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event CosmosBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Cosmos";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Cosmos-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit CosmosBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit CosmosBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract HederaAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event HederaBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event HederaBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Hedera";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Hedera-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit HederaBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit HederaBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract SolanaAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event SolanaBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event SolanaBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Solana";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Solana-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit SolanaBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit SolanaBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract StellarAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public stellarTxHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event StellarBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string stellarAccount
|
||||
);
|
||||
|
||||
event StellarBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed stellarTxHash,
|
||||
uint256 ledgerSequence
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Stellar";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Stellar-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
string memory addr = string(destination);
|
||||
bytes memory addrBytes = bytes(addr);
|
||||
|
||||
// Stellar addresses: G + 55 base32 chars = 56 chars
|
||||
if (addrBytes.length != 56) return false;
|
||||
if (addrBytes[0] != 'G') return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
require(this.validateDestination(destination), "Invalid Stellar address");
|
||||
|
||||
string memory stellarAccount = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
stellarAccount,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit StellarBridgeInitiated(requestId, msg.sender, token, amount, stellarAccount);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmStellarTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata stellarTxHash,
|
||||
uint256 ledgerSequence
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
stellarTxHashes[requestId] = stellarTxHash;
|
||||
|
||||
emit StellarBridgeConfirmed(requestId, stellarTxHash, ledgerSequence);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external pure override returns (uint256 fee) {
|
||||
return 100; // 0.00001 XLM (Stellar fees are very low)
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract TONAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event TONBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event TONBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "TON";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "TON-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit TONBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit TONBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
/**
|
||||
* @title TezosAdapter
|
||||
* @notice Bridge adapter for Tezos L1 (native Michelson)
|
||||
* @dev Lock tokens on this chain; off-chain relayer watches events and performs Tezos-side mint/transfer.
|
||||
* Oracle calls confirmTransaction when Tezos tx is confirmed.
|
||||
*/
|
||||
contract TezosAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event TezosBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event TezosBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Tezos";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Tezos-Mainnet");
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Validate Tezos destination (tz1/tz2/tz3/KT1 address format; length 35-64 bytes when UTF-8)
|
||||
*/
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
if (destination.length == 0 || destination.length > 64) return false;
|
||||
// Tezos addresses: tz1, tz2, tz3 (implicit), KT1 (contract)
|
||||
return destination.length >= 35 && destination.length <= 64;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
require(this.validateDestination(destination), "Invalid Tezos destination");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit TezosBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Called by oracle/relayer when Tezos tx is confirmed
|
||||
*/
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit TezosBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(
|
||||
request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked,
|
||||
"Cannot cancel"
|
||||
);
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
contract TronAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => string) public txHashes;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event TronBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string destination
|
||||
);
|
||||
|
||||
event TronBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
string indexed txHash
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "Tron";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "Tron-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
return destination.length > 0;
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
|
||||
string memory dest = string(destination);
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
dest,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit TronBridgeInitiated(requestId, msg.sender, token, amount, dest);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function confirmTransaction(
|
||||
bytes32 requestId,
|
||||
string calldata txHash
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
txHashes[requestId] = txHash;
|
||||
|
||||
emit TronBridgeConfirmed(requestId, txHash);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view override returns (uint256 fee) {
|
||||
return 1000000000000000;
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../interfaces/IChainAdapter.sol";
|
||||
|
||||
/**
|
||||
* @title XRPLAdapter
|
||||
* @notice Bridge adapter for XRP Ledger (XRPL)
|
||||
* @dev Uses oracle/relayer pattern for non-EVM chain integration
|
||||
*/
|
||||
contract XRPLAdapter is IChainAdapter, AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
|
||||
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
|
||||
|
||||
bool public isActive;
|
||||
|
||||
mapping(bytes32 => BridgeRequest) public bridgeRequests;
|
||||
mapping(bytes32 => bytes32) public xrplTxHashes; // requestId => xrplTxHash
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
// XRPL address validation: starts with 'r', 25-35 chars
|
||||
mapping(string => bool) public validatedXRPLAddresses;
|
||||
|
||||
event XRPLBridgeInitiated(
|
||||
bytes32 indexed requestId,
|
||||
address indexed sender,
|
||||
address indexed token,
|
||||
uint256 amount,
|
||||
string xrplDestination,
|
||||
uint32 destinationTag
|
||||
);
|
||||
|
||||
event XRPLBridgeConfirmed(
|
||||
bytes32 indexed requestId,
|
||||
bytes32 indexed xrplTxHash,
|
||||
uint256 ledgerIndex
|
||||
);
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(BRIDGE_OPERATOR_ROLE, admin);
|
||||
_grantRole(ORACLE_ROLE, admin);
|
||||
isActive = true;
|
||||
}
|
||||
|
||||
function getChainType() external pure override returns (string memory) {
|
||||
return "XRPL";
|
||||
}
|
||||
|
||||
function getChainIdentifier() external pure override returns (uint256 chainId, string memory identifier) {
|
||||
return (0, "XRPL-Mainnet");
|
||||
}
|
||||
|
||||
function validateDestination(bytes calldata destination) external pure override returns (bool) {
|
||||
string memory addr = string(destination);
|
||||
bytes memory addrBytes = bytes(addr);
|
||||
|
||||
// XRPL addresses: r + 25-34 base58 chars
|
||||
if (addrBytes.length < 26 || addrBytes.length > 35) return false;
|
||||
if (addrBytes[0] != 'r') return false;
|
||||
|
||||
// Basic validation - full validation requires base58 decoding
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Convert XRP drops to wei (1 XRP = 1,000,000 drops)
|
||||
*/
|
||||
function dropsToWei(uint64 drops) public pure returns (uint256) {
|
||||
return uint256(drops) * 1e12; // 1 drop = 0.000001 XRP, 1 XRP = 1e18 wei
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Convert wei to XRP drops
|
||||
*/
|
||||
function weiToDrops(uint256 weiAmount) public pure returns (uint64) {
|
||||
return uint64(weiAmount / 1e12);
|
||||
}
|
||||
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable override nonReentrant returns (bytes32 requestId) {
|
||||
require(isActive, "Adapter inactive");
|
||||
require(amount > 0, "Zero amount");
|
||||
require(this.validateDestination(destination), "Invalid XRPL address");
|
||||
|
||||
string memory xrplDestination = string(destination);
|
||||
uint32 destinationTag = 0;
|
||||
|
||||
// Parse destination tag if provided in recipient bytes
|
||||
if (recipient.length >= 4) {
|
||||
destinationTag = abi.decode(recipient, (uint32));
|
||||
}
|
||||
|
||||
requestId = keccak256(abi.encodePacked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
xrplDestination,
|
||||
destinationTag,
|
||||
nonces[msg.sender]++,
|
||||
block.timestamp
|
||||
));
|
||||
|
||||
// Lock tokens on EVM side
|
||||
if (token == address(0)) {
|
||||
require(msg.value >= amount, "Insufficient ETH");
|
||||
} else {
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
}
|
||||
|
||||
bridgeRequests[requestId] = BridgeRequest({
|
||||
sender: msg.sender,
|
||||
token: token,
|
||||
amount: amount,
|
||||
destinationData: destination,
|
||||
requestId: requestId,
|
||||
status: BridgeStatus.Locked,
|
||||
createdAt: block.timestamp,
|
||||
completedAt: 0
|
||||
});
|
||||
|
||||
emit XRPLBridgeInitiated(requestId, msg.sender, token, amount, xrplDestination, destinationTag);
|
||||
|
||||
return requestId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Oracle confirms XRPL transaction
|
||||
*/
|
||||
function confirmXRPLTransaction(
|
||||
bytes32 requestId,
|
||||
bytes32 xrplTxHash,
|
||||
uint256 ledgerIndex
|
||||
) external onlyRole(ORACLE_ROLE) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Locked, "Invalid status");
|
||||
|
||||
request.status = BridgeStatus.Confirmed;
|
||||
request.completedAt = block.timestamp;
|
||||
xrplTxHashes[requestId] = xrplTxHash;
|
||||
|
||||
emit XRPLBridgeConfirmed(requestId, xrplTxHash, ledgerIndex);
|
||||
}
|
||||
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view override returns (BridgeRequest memory) {
|
||||
return bridgeRequests[requestId];
|
||||
}
|
||||
|
||||
function cancelBridge(bytes32 requestId) external override returns (bool) {
|
||||
BridgeRequest storage request = bridgeRequests[requestId];
|
||||
require(request.status == BridgeStatus.Pending || request.status == BridgeStatus.Locked, "Cannot cancel");
|
||||
require(msg.sender == request.sender, "Not request sender");
|
||||
|
||||
// Refund tokens
|
||||
if (request.token == address(0)) {
|
||||
payable(request.sender).transfer(request.amount);
|
||||
} else {
|
||||
IERC20(request.token).safeTransfer(request.sender, request.amount);
|
||||
}
|
||||
|
||||
request.status = BridgeStatus.Cancelled;
|
||||
return true;
|
||||
}
|
||||
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external pure override returns (uint256 fee) {
|
||||
// XRPL fees are very low (~0.000012 XRP per transaction)
|
||||
return 12000; // 0.000012 XRP in drops
|
||||
}
|
||||
|
||||
function setIsActive(bool _isActive) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
isActive = _isActive;
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "../interop/BridgeRegistry.sol";
|
||||
import "../../vault/VaultFactory.sol";
|
||||
import "../../vault/tokens/DepositToken.sol";
|
||||
|
||||
/**
|
||||
* @title VaultBridgeIntegration
|
||||
* @notice Automatically registers vault deposit tokens with BridgeRegistry
|
||||
* @dev Extends VaultFactory to auto-register deposit tokens on creation
|
||||
*/
|
||||
contract VaultBridgeIntegration is AccessControl {
|
||||
bytes32 public constant INTEGRATOR_ROLE = keccak256("INTEGRATOR_ROLE");
|
||||
|
||||
VaultFactory public vaultFactory;
|
||||
BridgeRegistry public bridgeRegistry;
|
||||
|
||||
// Default bridge configuration for vault tokens
|
||||
uint256 public defaultMinBridgeAmount = 1e18; // 1 token minimum
|
||||
uint256 public defaultMaxBridgeAmount = 1_000_000e18; // 1M tokens maximum
|
||||
uint8 public defaultRiskLevel = 50; // Medium risk
|
||||
uint256 public defaultBridgeFeeBps = 10; // 0.1% default fee
|
||||
|
||||
// Destination chain IDs allowed by default (Polygon, Optimism, Base, Arbitrum, Avalanche, BNB Chain, Monad)
|
||||
uint256[] public defaultDestinations;
|
||||
|
||||
event DepositTokenRegistered(
|
||||
address indexed depositToken,
|
||||
address indexed vault,
|
||||
uint256[] destinationChainIds
|
||||
);
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address vaultFactory_,
|
||||
address bridgeRegistry_
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(INTEGRATOR_ROLE, admin);
|
||||
|
||||
require(vaultFactory_ != address(0), "VaultBridgeIntegration: zero vault factory");
|
||||
require(bridgeRegistry_ != address(0), "VaultBridgeIntegration: zero bridge registry");
|
||||
|
||||
vaultFactory = VaultFactory(vaultFactory_);
|
||||
bridgeRegistry = BridgeRegistry(bridgeRegistry_);
|
||||
|
||||
// Set default destinations (EVM chains only for now)
|
||||
defaultDestinations.push(137); // Polygon
|
||||
defaultDestinations.push(10); // Optimism
|
||||
defaultDestinations.push(8453); // Base
|
||||
defaultDestinations.push(42161); // Arbitrum
|
||||
defaultDestinations.push(43114); // Avalanche
|
||||
defaultDestinations.push(56); // BNB Chain
|
||||
defaultDestinations.push(10143); // Monad (example chain ID)
|
||||
defaultDestinations.push(42793); // Etherlink (Tezos EVM L2)
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a deposit token with bridge registry
|
||||
* @param depositToken Deposit token address
|
||||
* @param destinationChainIds Array of allowed destination chain IDs
|
||||
* @param minAmount Minimum bridge amount
|
||||
* @param maxAmount Maximum bridge amount
|
||||
* @param riskLevel Risk level (0-255)
|
||||
* @param bridgeFeeBps Bridge fee in basis points
|
||||
*/
|
||||
function registerDepositToken(
|
||||
address depositToken,
|
||||
uint256[] memory destinationChainIds,
|
||||
uint256 minAmount,
|
||||
uint256 maxAmount,
|
||||
uint8 riskLevel,
|
||||
uint256 bridgeFeeBps
|
||||
) public onlyRole(INTEGRATOR_ROLE) {
|
||||
require(depositToken != address(0), "VaultBridgeIntegration: zero deposit token");
|
||||
require(destinationChainIds.length > 0, "VaultBridgeIntegration: no destinations");
|
||||
|
||||
bridgeRegistry.registerToken(
|
||||
depositToken,
|
||||
minAmount,
|
||||
maxAmount,
|
||||
destinationChainIds,
|
||||
riskLevel,
|
||||
bridgeFeeBps
|
||||
);
|
||||
|
||||
// Find associated vault (would need to track this in VaultFactory)
|
||||
// For now, emit event with deposit token only
|
||||
emit DepositTokenRegistered(depositToken, address(0), destinationChainIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a deposit token with default configuration
|
||||
* @param depositToken Deposit token address
|
||||
*/
|
||||
function registerDepositTokenDefault(address depositToken) external onlyRole(INTEGRATOR_ROLE) {
|
||||
registerDepositToken(
|
||||
depositToken,
|
||||
defaultDestinations,
|
||||
defaultMinBridgeAmount,
|
||||
defaultMaxBridgeAmount,
|
||||
defaultRiskLevel,
|
||||
defaultBridgeFeeBps
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set default bridge configuration
|
||||
*/
|
||||
function setDefaultMinBridgeAmount(uint256 minAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
defaultMinBridgeAmount = minAmount;
|
||||
}
|
||||
|
||||
function setDefaultMaxBridgeAmount(uint256 maxAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
defaultMaxBridgeAmount = maxAmount;
|
||||
}
|
||||
|
||||
function setDefaultRiskLevel(uint8 riskLevel) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(riskLevel <= 255, "VaultBridgeIntegration: invalid risk level");
|
||||
defaultRiskLevel = riskLevel;
|
||||
}
|
||||
|
||||
function setDefaultBridgeFeeBps(uint256 feeBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(feeBps <= 10000, "VaultBridgeIntegration: fee > 100%");
|
||||
defaultBridgeFeeBps = feeBps;
|
||||
}
|
||||
|
||||
function setDefaultDestinations(uint256[] memory chainIds) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(chainIds.length > 0, "VaultBridgeIntegration: no destinations");
|
||||
defaultDestinations = chainIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get default destinations
|
||||
*/
|
||||
function getDefaultDestinations() external view returns (uint256[] memory) {
|
||||
return defaultDestinations;
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "../interop/BridgeRegistry.sol";
|
||||
import "../../iso4217w/TokenFactory.sol";
|
||||
import "../../iso4217w/registry/TokenRegistry.sol";
|
||||
|
||||
/**
|
||||
* @title WTokenBridgeIntegration
|
||||
* @notice Automatically registers ISO-4217 W tokens with BridgeRegistry
|
||||
* @dev Extends TokenFactory to auto-register W tokens on creation
|
||||
*/
|
||||
contract WTokenBridgeIntegration is AccessControl {
|
||||
bytes32 public constant INTEGRATOR_ROLE = keccak256("INTEGRATOR_ROLE");
|
||||
|
||||
TokenFactory public tokenFactory;
|
||||
BridgeRegistry public bridgeRegistry;
|
||||
ITokenRegistry public wTokenRegistry;
|
||||
|
||||
// Default bridge configuration for W tokens (more conservative due to compliance)
|
||||
uint256 public defaultMinBridgeAmount = 100e2; // 100 USD minimum
|
||||
uint256 public defaultMaxBridgeAmount = 10_000_000e2; // 10M USD maximum
|
||||
uint8 public defaultRiskLevel = 20; // Low risk (fiat-backed)
|
||||
uint256 public defaultBridgeFeeBps = 5; // 0.05% default fee (lower due to compliance)
|
||||
|
||||
// Destination chain IDs (includes XRPL and Fabric in addition to EVM)
|
||||
uint256[] public defaultEvmDestinations;
|
||||
uint256[] public defaultNonEvmDestinations; // 0 for XRPL, 1 for Fabric (example)
|
||||
|
||||
event WTokenRegistered(
|
||||
address indexed token,
|
||||
string indexed currencyCode,
|
||||
uint256[] destinationChainIds
|
||||
);
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address tokenFactory_,
|
||||
address bridgeRegistry_,
|
||||
address wTokenRegistry_
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(INTEGRATOR_ROLE, admin);
|
||||
|
||||
require(tokenFactory_ != address(0), "WTokenBridgeIntegration: zero token factory");
|
||||
require(bridgeRegistry_ != address(0), "WTokenBridgeIntegration: zero bridge registry");
|
||||
require(wTokenRegistry_ != address(0), "WTokenBridgeIntegration: zero W token registry");
|
||||
|
||||
tokenFactory = TokenFactory(tokenFactory_);
|
||||
bridgeRegistry = BridgeRegistry(bridgeRegistry_);
|
||||
wTokenRegistry = ITokenRegistry(wTokenRegistry_);
|
||||
|
||||
// Set default EVM destinations
|
||||
defaultEvmDestinations.push(137); // Polygon
|
||||
defaultEvmDestinations.push(10); // Optimism
|
||||
defaultEvmDestinations.push(8453); // Base
|
||||
defaultEvmDestinations.push(42161); // Arbitrum
|
||||
defaultEvmDestinations.push(43114); // Avalanche
|
||||
defaultEvmDestinations.push(56); // BNB Chain
|
||||
defaultEvmDestinations.push(10143); // Monad
|
||||
defaultEvmDestinations.push(42793); // Etherlink (Tezos EVM L2)
|
||||
|
||||
// Set default non-EVM destinations
|
||||
defaultNonEvmDestinations.push(0); // XRPL (0 = non-EVM identifier)
|
||||
defaultNonEvmDestinations.push(1); // Fabric (1 = non-EVM identifier)
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a W token with bridge registry
|
||||
* @param currencyCode ISO-4217 currency code (e.g., "USD")
|
||||
* @param destinationChainIds Array of allowed destination chain IDs
|
||||
* @param minAmount Minimum bridge amount (in token decimals)
|
||||
* @param maxAmount Maximum bridge amount (in token decimals)
|
||||
* @param riskLevel Risk level (0-255)
|
||||
* @param bridgeFeeBps Bridge fee in basis points
|
||||
*/
|
||||
function registerWToken(
|
||||
string memory currencyCode,
|
||||
uint256[] memory destinationChainIds,
|
||||
uint256 minAmount,
|
||||
uint256 maxAmount,
|
||||
uint8 riskLevel,
|
||||
uint256 bridgeFeeBps
|
||||
) public onlyRole(INTEGRATOR_ROLE) {
|
||||
address token = wTokenRegistry.getTokenAddress(currencyCode);
|
||||
require(token != address(0), "WTokenBridgeIntegration: token not found");
|
||||
|
||||
require(destinationChainIds.length > 0, "WTokenBridgeIntegration: no destinations");
|
||||
require(minAmount > 0, "WTokenBridgeIntegration: zero min amount");
|
||||
require(maxAmount >= minAmount, "WTokenBridgeIntegration: max < min");
|
||||
require(bridgeFeeBps <= 10000, "WTokenBridgeIntegration: fee > 100%");
|
||||
|
||||
bridgeRegistry.registerToken(
|
||||
token,
|
||||
minAmount,
|
||||
maxAmount,
|
||||
destinationChainIds,
|
||||
riskLevel,
|
||||
bridgeFeeBps
|
||||
);
|
||||
|
||||
emit WTokenRegistered(token, currencyCode, destinationChainIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a W token with default configuration
|
||||
* @param currencyCode ISO-4217 currency code
|
||||
*/
|
||||
function registerWTokenDefault(string memory currencyCode) public onlyRole(INTEGRATOR_ROLE) {
|
||||
// Combine EVM and non-EVM destinations
|
||||
uint256[] memory allDestinations = new uint256[](
|
||||
defaultEvmDestinations.length + defaultNonEvmDestinations.length
|
||||
);
|
||||
|
||||
uint256 i = 0;
|
||||
for (uint256 j = 0; j < defaultEvmDestinations.length; j++) {
|
||||
allDestinations[i++] = defaultEvmDestinations[j];
|
||||
}
|
||||
for (uint256 j = 0; j < defaultNonEvmDestinations.length; j++) {
|
||||
allDestinations[i++] = defaultNonEvmDestinations[j];
|
||||
}
|
||||
|
||||
registerWToken(
|
||||
currencyCode,
|
||||
allDestinations,
|
||||
defaultMinBridgeAmount,
|
||||
defaultMaxBridgeAmount,
|
||||
defaultRiskLevel,
|
||||
defaultBridgeFeeBps
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register multiple W tokens with default configuration
|
||||
* @param currencyCodes Array of ISO-4217 currency codes
|
||||
*/
|
||||
function registerMultipleWTokensDefault(string[] memory currencyCodes) external onlyRole(INTEGRATOR_ROLE) {
|
||||
for (uint256 i = 0; i < currencyCodes.length; i++) {
|
||||
registerWTokenDefault(currencyCodes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set default bridge configuration
|
||||
*/
|
||||
function setDefaultMinBridgeAmount(uint256 minAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(minAmount > 0, "WTokenBridgeIntegration: zero min amount");
|
||||
defaultMinBridgeAmount = minAmount;
|
||||
}
|
||||
|
||||
function setDefaultMaxBridgeAmount(uint256 maxAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(maxAmount >= defaultMinBridgeAmount, "WTokenBridgeIntegration: max < min");
|
||||
defaultMaxBridgeAmount = maxAmount;
|
||||
}
|
||||
|
||||
function setDefaultRiskLevel(uint8 riskLevel) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(riskLevel <= 255, "WTokenBridgeIntegration: invalid risk level");
|
||||
defaultRiskLevel = riskLevel;
|
||||
}
|
||||
|
||||
function setDefaultBridgeFeeBps(uint256 feeBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(feeBps <= 10000, "WTokenBridgeIntegration: fee > 100%");
|
||||
defaultBridgeFeeBps = feeBps;
|
||||
}
|
||||
|
||||
function setDefaultEvmDestinations(uint256[] memory chainIds) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(chainIds.length > 0, "WTokenBridgeIntegration: no destinations");
|
||||
defaultEvmDestinations = chainIds;
|
||||
}
|
||||
|
||||
function setDefaultNonEvmDestinations(uint256[] memory chainIds) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
defaultNonEvmDestinations = chainIds;
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "../interop/BridgeEscrowVault.sol";
|
||||
import "../../iso4217w/interfaces/IISO4217WToken.sol";
|
||||
import "../../iso4217w/ComplianceGuard.sol";
|
||||
|
||||
/**
|
||||
* @title WTokenComplianceEnforcer
|
||||
* @notice Enforces W token compliance rules on bridge operations
|
||||
* @dev Ensures money multiplier = 1.0 and GRU isolation on bridge
|
||||
*/
|
||||
contract WTokenComplianceEnforcer is AccessControl {
|
||||
bytes32 public constant ENFORCER_ROLE = keccak256("ENFORCER_ROLE");
|
||||
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
|
||||
|
||||
BridgeEscrowVault public bridgeEscrowVault;
|
||||
ComplianceGuard public complianceGuard;
|
||||
mapping(address => bool) public enabledTokens; // W token => enabled
|
||||
|
||||
event TokenEnabled(address indexed token, bool enabled);
|
||||
event ComplianceChecked(
|
||||
address indexed token,
|
||||
bytes32 reasonCode,
|
||||
bool compliant
|
||||
);
|
||||
|
||||
error ComplianceViolation(bytes32 reasonCode);
|
||||
error TokenNotEnabled();
|
||||
error InvalidToken();
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address bridgeEscrowVault_,
|
||||
address complianceGuard_
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(ENFORCER_ROLE, admin);
|
||||
_grantRole(OPERATOR_ROLE, admin);
|
||||
|
||||
require(bridgeEscrowVault_ != address(0), "WTokenComplianceEnforcer: zero bridge");
|
||||
require(complianceGuard_ != address(0), "WTokenComplianceEnforcer: zero guard");
|
||||
|
||||
bridgeEscrowVault = BridgeEscrowVault(bridgeEscrowVault_);
|
||||
complianceGuard = ComplianceGuard(complianceGuard_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check compliance before bridge operation
|
||||
* @param token W token address
|
||||
* @param bridgeAmount Amount to bridge
|
||||
* @return compliant True if compliant
|
||||
*/
|
||||
function checkComplianceBeforeBridge(
|
||||
address token,
|
||||
uint256 bridgeAmount
|
||||
) external returns (bool compliant) {
|
||||
if (!enabledTokens[token]) revert TokenNotEnabled();
|
||||
|
||||
IISO4217WToken wToken = IISO4217WToken(token);
|
||||
string memory currencyCode = wToken.currencyCode();
|
||||
uint256 verifiedReserve = wToken.verifiedReserve();
|
||||
uint256 currentSupply = wToken.totalSupply();
|
||||
uint256 newSupply = currentSupply - bridgeAmount; // Supply after bridge
|
||||
|
||||
// Validate mint operation (simulating future state)
|
||||
(bool isValid, bytes32 reasonCode) = complianceGuard.validateMint(
|
||||
currencyCode,
|
||||
bridgeAmount,
|
||||
newSupply,
|
||||
verifiedReserve
|
||||
);
|
||||
|
||||
if (!isValid) {
|
||||
emit ComplianceChecked(token, reasonCode, false);
|
||||
revert ComplianceViolation(reasonCode);
|
||||
}
|
||||
|
||||
// Validate money multiplier = 1.0
|
||||
if (!complianceGuard.validateMoneyMultiplier(verifiedReserve, newSupply)) {
|
||||
bytes32 multiplierReason = keccak256("MONEY_MULTIPLIER_VIOLATION");
|
||||
emit ComplianceChecked(token, multiplierReason, false);
|
||||
revert ComplianceViolation(multiplierReason);
|
||||
}
|
||||
|
||||
// Validate GRU isolation
|
||||
if (complianceGuard.violatesGRUIsolation(currencyCode)) {
|
||||
bytes32 gruReason = keccak256("GRU_ISOLATION_VIOLATION");
|
||||
emit ComplianceChecked(token, gruReason, false);
|
||||
revert ComplianceViolation(gruReason);
|
||||
}
|
||||
|
||||
emit ComplianceChecked(token, bytes32(0), true);
|
||||
compliant = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check compliance on destination chain (before minting bridged amount)
|
||||
* @param currencyCode ISO-4217 currency code
|
||||
* @param bridgeAmount Amount to mint on destination
|
||||
* @param destinationReserve Reserve on destination chain
|
||||
* @param destinationSupply Supply on destination chain (before mint)
|
||||
* @return compliant True if compliant
|
||||
*/
|
||||
function checkDestinationCompliance(
|
||||
string memory currencyCode,
|
||||
uint256 bridgeAmount,
|
||||
uint256 destinationReserve,
|
||||
uint256 destinationSupply
|
||||
) external returns (bool compliant) {
|
||||
uint256 newSupply = destinationSupply + bridgeAmount;
|
||||
|
||||
// Validate mint operation
|
||||
(bool isValid, bytes32 reasonCode) = complianceGuard.validateMint(
|
||||
currencyCode,
|
||||
bridgeAmount,
|
||||
destinationSupply, // Current supply
|
||||
destinationReserve
|
||||
);
|
||||
|
||||
if (!isValid) {
|
||||
emit ComplianceChecked(address(0), reasonCode, false);
|
||||
revert ComplianceViolation(reasonCode);
|
||||
}
|
||||
|
||||
// Validate money multiplier = 1.0 after mint
|
||||
if (!complianceGuard.validateMoneyMultiplier(destinationReserve, newSupply)) {
|
||||
bytes32 multiplierReason = keccak256("MONEY_MULTIPLIER_VIOLATION");
|
||||
emit ComplianceChecked(address(0), multiplierReason, false);
|
||||
revert ComplianceViolation(multiplierReason);
|
||||
}
|
||||
|
||||
// Validate GRU isolation
|
||||
if (complianceGuard.violatesGRUIsolation(currencyCode)) {
|
||||
bytes32 gruReason = keccak256("GRU_ISOLATION_VIOLATION");
|
||||
emit ComplianceChecked(address(0), gruReason, false);
|
||||
revert ComplianceViolation(gruReason);
|
||||
}
|
||||
|
||||
emit ComplianceChecked(address(0), bytes32(0), true);
|
||||
compliant = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Enable a W token for compliance checking
|
||||
* @param token W token address
|
||||
*/
|
||||
function enableToken(address token) external onlyRole(OPERATOR_ROLE) {
|
||||
require(token != address(0), "WTokenComplianceEnforcer: zero token");
|
||||
|
||||
// Verify it's a valid W token
|
||||
try IISO4217WToken(token).currencyCode() returns (string memory) {
|
||||
enabledTokens[token] = true;
|
||||
emit TokenEnabled(token, true);
|
||||
} catch {
|
||||
revert InvalidToken();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Disable a W token
|
||||
* @param token W token address
|
||||
*/
|
||||
function disableToken(address token) external onlyRole(OPERATOR_ROLE) {
|
||||
enabledTokens[token] = false;
|
||||
emit TokenEnabled(token, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if token is enabled
|
||||
*/
|
||||
function isTokenEnabled(address token) external view returns (bool) {
|
||||
return enabledTokens[token];
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "../interop/BridgeEscrowVault.sol";
|
||||
import "../../iso4217w/interfaces/IISO4217WToken.sol";
|
||||
import "../../iso4217w/oracle/ReserveOracle.sol";
|
||||
|
||||
/**
|
||||
* @title WTokenReserveVerifier
|
||||
* @notice Verifies W token reserves before allowing bridge operations
|
||||
* @dev Ensures 1:1 backing maintained across bridge operations
|
||||
*/
|
||||
contract WTokenReserveVerifier is AccessControl {
|
||||
bytes32 public constant VERIFIER_ROLE = keccak256("VERIFIER_ROLE");
|
||||
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
|
||||
|
||||
BridgeEscrowVault public bridgeEscrowVault;
|
||||
ReserveOracle public reserveOracle;
|
||||
mapping(address => bool) public verifiedTokens; // W token => verified
|
||||
|
||||
// Reserve verification threshold (10000 = 100%)
|
||||
uint256 public reserveThreshold = 10000; // 100% (must be fully backed)
|
||||
|
||||
event TokenVerified(address indexed token, bool verified);
|
||||
event ReserveVerified(
|
||||
address indexed token,
|
||||
uint256 reserve,
|
||||
uint256 supply,
|
||||
uint256 bridgeAmount,
|
||||
bool sufficient
|
||||
);
|
||||
|
||||
error InsufficientReserve();
|
||||
error TokenNotVerified();
|
||||
error InvalidToken();
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address bridgeEscrowVault_,
|
||||
address reserveOracle_
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(VERIFIER_ROLE, admin);
|
||||
_grantRole(OPERATOR_ROLE, admin);
|
||||
|
||||
require(bridgeEscrowVault_ != address(0), "WTokenReserveVerifier: zero bridge");
|
||||
require(reserveOracle_ != address(0), "WTokenReserveVerifier: zero oracle");
|
||||
|
||||
bridgeEscrowVault = BridgeEscrowVault(bridgeEscrowVault_);
|
||||
reserveOracle = ReserveOracle(reserveOracle_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify reserve before bridge operation
|
||||
* @param token W token address
|
||||
* @param bridgeAmount Amount to bridge
|
||||
* @return verified True if reserve is sufficient
|
||||
*/
|
||||
function verifyReserveBeforeBridge(
|
||||
address token,
|
||||
uint256 bridgeAmount
|
||||
) external returns (bool verified) {
|
||||
if (!verifiedTokens[token]) revert TokenNotVerified();
|
||||
|
||||
IISO4217WToken wToken = IISO4217WToken(token);
|
||||
|
||||
uint256 verifiedReserve = wToken.verifiedReserve();
|
||||
uint256 currentSupply = wToken.totalSupply();
|
||||
|
||||
// After bridge, supply on this chain decreases, but reserve must still cover remaining supply
|
||||
// Reserve must be >= (currentSupply - bridgeAmount) * reserveThreshold / 10000
|
||||
uint256 requiredReserve = ((currentSupply - bridgeAmount) * reserveThreshold) / 10000;
|
||||
|
||||
verified = verifiedReserve >= requiredReserve;
|
||||
|
||||
if (!verified) revert InsufficientReserve();
|
||||
|
||||
emit ReserveVerified(token, verifiedReserve, currentSupply, bridgeAmount, verified);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify reserve on destination chain (after bridge)
|
||||
* @param token W token address on destination chain
|
||||
* @param bridgeAmount Amount bridged
|
||||
* @param destinationReserve Reserve on destination chain
|
||||
* @param destinationSupply Supply on destination chain (before minting bridged amount)
|
||||
* @return verified True if destination reserve is sufficient
|
||||
*/
|
||||
function verifyDestinationReserve(
|
||||
address token,
|
||||
uint256 bridgeAmount,
|
||||
uint256 destinationReserve,
|
||||
uint256 destinationSupply
|
||||
) external returns (bool verified) {
|
||||
// After minting bridged amount on destination: newSupply = destinationSupply + bridgeAmount
|
||||
// Required reserve: (newSupply * reserveThreshold) / 10000
|
||||
uint256 newSupply = destinationSupply + bridgeAmount;
|
||||
uint256 requiredReserve = (newSupply * reserveThreshold) / 10000;
|
||||
|
||||
verified = destinationReserve >= requiredReserve;
|
||||
|
||||
if (!verified) revert InsufficientReserve();
|
||||
|
||||
emit ReserveVerified(token, destinationReserve, newSupply, bridgeAmount, verified);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify reserve sufficiency using oracle
|
||||
* @param token W token address
|
||||
* @param bridgeAmount Amount to bridge
|
||||
* @return verified True if reserve is sufficient according to oracle
|
||||
*/
|
||||
function verifyReserveWithOracle(
|
||||
address token,
|
||||
uint256 bridgeAmount
|
||||
) external returns (bool verified) {
|
||||
if (!verifiedTokens[token]) revert TokenNotVerified();
|
||||
|
||||
IISO4217WToken wToken = IISO4217WToken(token);
|
||||
|
||||
// Get currency code from token
|
||||
string memory currencyCode = wToken.currencyCode();
|
||||
|
||||
// Get verified reserve from oracle (consensus)
|
||||
(uint256 verifiedReserve, ) = reserveOracle.getVerifiedReserve(currencyCode);
|
||||
|
||||
uint256 currentSupply = wToken.totalSupply();
|
||||
|
||||
// Required reserve after bridge
|
||||
uint256 requiredReserve = ((currentSupply - bridgeAmount) * reserveThreshold) / 10000;
|
||||
|
||||
verified = verifiedReserve >= requiredReserve;
|
||||
|
||||
if (!verified) revert InsufficientReserve();
|
||||
|
||||
emit ReserveVerified(token, verifiedReserve, currentSupply, bridgeAmount, verified);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a W token for reserve verification
|
||||
* @param token W token address
|
||||
*/
|
||||
function registerToken(address token) external onlyRole(OPERATOR_ROLE) {
|
||||
require(token != address(0), "WTokenReserveVerifier: zero token");
|
||||
|
||||
// Verify it's a valid W token (implements IISO4217WToken)
|
||||
try IISO4217WToken(token).currencyCode() returns (string memory) {
|
||||
verifiedTokens[token] = true;
|
||||
emit TokenVerified(token, true);
|
||||
} catch {
|
||||
revert InvalidToken();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unregister a W token
|
||||
* @param token W token address
|
||||
*/
|
||||
function unregisterToken(address token) external onlyRole(OPERATOR_ROLE) {
|
||||
verifiedTokens[token] = false;
|
||||
emit TokenVerified(token, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set reserve verification threshold
|
||||
* @param threshold Threshold in basis points (10000 = 100%)
|
||||
*/
|
||||
function setReserveThreshold(uint256 threshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(threshold <= 10000, "WTokenReserveVerifier: threshold > 100%");
|
||||
require(threshold >= 10000, "WTokenReserveVerifier: threshold must be 100%"); // Hard requirement
|
||||
reserveThreshold = threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if token is verified
|
||||
*/
|
||||
function isTokenVerified(address token) external view returns (bool) {
|
||||
return verifiedTokens[token];
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "../interop/BridgeRegistry.sol";
|
||||
import "../../emoney/TokenFactory138.sol";
|
||||
|
||||
/**
|
||||
* @title eMoneyBridgeIntegration
|
||||
* @notice Automatically registers eMoney tokens with BridgeRegistry
|
||||
* @dev Extends eMoney token system to auto-register tokens with bridge
|
||||
*/
|
||||
contract eMoneyBridgeIntegration is AccessControl {
|
||||
bytes32 public constant INTEGRATOR_ROLE = keccak256("INTEGRATOR_ROLE");
|
||||
|
||||
BridgeRegistry public bridgeRegistry;
|
||||
|
||||
// Default bridge configuration for eMoney tokens
|
||||
uint256 public defaultMinBridgeAmount = 100e18; // 100 tokens minimum
|
||||
uint256 public defaultMaxBridgeAmount = 1_000_000e18; // 1M tokens maximum
|
||||
uint8 public defaultRiskLevel = 60; // Medium-high risk (credit instrument)
|
||||
uint256 public defaultBridgeFeeBps = 15; // 0.15% default fee
|
||||
|
||||
// Destination chain IDs (regulated entities only - EVM chains)
|
||||
uint256[] public defaultDestinations;
|
||||
|
||||
event eMoneyTokenRegistered(
|
||||
address indexed token,
|
||||
string indexed currencyCode,
|
||||
uint256[] destinationChainIds
|
||||
);
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address bridgeRegistry_
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(INTEGRATOR_ROLE, admin);
|
||||
|
||||
require(bridgeRegistry_ != address(0), "eMoneyBridgeIntegration: zero bridge registry");
|
||||
|
||||
bridgeRegistry = BridgeRegistry(bridgeRegistry_);
|
||||
|
||||
// Set default destinations (EVM chains only - regulated entities)
|
||||
defaultDestinations.push(137); // Polygon
|
||||
defaultDestinations.push(10); // Optimism
|
||||
defaultDestinations.push(8453); // Base
|
||||
defaultDestinations.push(42161); // Arbitrum
|
||||
defaultDestinations.push(43114); // Avalanche
|
||||
defaultDestinations.push(56); // BNB Chain
|
||||
defaultDestinations.push(42793); // Etherlink (Tezos EVM L2)
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register an eMoney token with bridge registry
|
||||
* @param token eMoney token address
|
||||
* @param currencyCode Currency code (for tracking)
|
||||
* @param destinationChainIds Array of allowed destination chain IDs
|
||||
* @param minAmount Minimum bridge amount
|
||||
* @param maxAmount Maximum bridge amount
|
||||
* @param riskLevel Risk level (0-255)
|
||||
* @param bridgeFeeBps Bridge fee in basis points
|
||||
*/
|
||||
function registereMoneyToken(
|
||||
address token,
|
||||
string memory currencyCode,
|
||||
uint256[] memory destinationChainIds,
|
||||
uint256 minAmount,
|
||||
uint256 maxAmount,
|
||||
uint8 riskLevel,
|
||||
uint256 bridgeFeeBps
|
||||
) public onlyRole(INTEGRATOR_ROLE) {
|
||||
require(token != address(0), "eMoneyBridgeIntegration: zero token");
|
||||
require(destinationChainIds.length > 0, "eMoneyBridgeIntegration: no destinations");
|
||||
require(minAmount > 0, "eMoneyBridgeIntegration: zero min amount");
|
||||
require(maxAmount >= minAmount, "eMoneyBridgeIntegration: max < min");
|
||||
require(bridgeFeeBps <= 10000, "eMoneyBridgeIntegration: fee > 100%");
|
||||
|
||||
bridgeRegistry.registerToken(
|
||||
token,
|
||||
minAmount,
|
||||
maxAmount,
|
||||
destinationChainIds,
|
||||
riskLevel,
|
||||
bridgeFeeBps
|
||||
);
|
||||
|
||||
emit eMoneyTokenRegistered(token, currencyCode, destinationChainIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register an eMoney token with default configuration
|
||||
* @param token eMoney token address
|
||||
* @param currencyCode Currency code
|
||||
*/
|
||||
function registereMoneyTokenDefault(
|
||||
address token,
|
||||
string memory currencyCode
|
||||
) external onlyRole(INTEGRATOR_ROLE) {
|
||||
registereMoneyToken(
|
||||
token,
|
||||
currencyCode,
|
||||
defaultDestinations,
|
||||
defaultMinBridgeAmount,
|
||||
defaultMaxBridgeAmount,
|
||||
defaultRiskLevel,
|
||||
defaultBridgeFeeBps
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set default bridge configuration
|
||||
*/
|
||||
function setDefaultMinBridgeAmount(uint256 minAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(minAmount > 0, "eMoneyBridgeIntegration: zero min amount");
|
||||
defaultMinBridgeAmount = minAmount;
|
||||
}
|
||||
|
||||
function setDefaultMaxBridgeAmount(uint256 maxAmount) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(maxAmount >= defaultMinBridgeAmount, "eMoneyBridgeIntegration: max < min");
|
||||
defaultMaxBridgeAmount = maxAmount;
|
||||
}
|
||||
|
||||
function setDefaultRiskLevel(uint8 riskLevel) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(riskLevel <= 255, "eMoneyBridgeIntegration: invalid risk level");
|
||||
defaultRiskLevel = riskLevel;
|
||||
}
|
||||
|
||||
function setDefaultBridgeFeeBps(uint256 feeBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(feeBps <= 10000, "eMoneyBridgeIntegration: fee > 100%");
|
||||
defaultBridgeFeeBps = feeBps;
|
||||
}
|
||||
|
||||
function setDefaultDestinations(uint256[] memory chainIds) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
require(chainIds.length > 0, "eMoneyBridgeIntegration: no destinations");
|
||||
defaultDestinations = chainIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get default destinations
|
||||
*/
|
||||
function getDefaultDestinations() external view returns (uint256[] memory) {
|
||||
return defaultDestinations;
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "../interop/BridgeEscrowVault.sol";
|
||||
import "../../emoney/PolicyManager.sol";
|
||||
import "../../emoney/ComplianceRegistry.sol";
|
||||
|
||||
/**
|
||||
* @title eMoneyPolicyEnforcer
|
||||
* @notice Enforces eMoney transfer restrictions on bridge operations
|
||||
* @dev Integrates PolicyManager and ComplianceRegistry with bridge
|
||||
*/
|
||||
contract eMoneyPolicyEnforcer is AccessControl {
|
||||
bytes32 public constant ENFORCER_ROLE = keccak256("ENFORCER_ROLE");
|
||||
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
|
||||
|
||||
BridgeEscrowVault public bridgeEscrowVault;
|
||||
PolicyManager public policyManager;
|
||||
ComplianceRegistry public complianceRegistry;
|
||||
mapping(address => bool) public enabledTokens; // eMoney token => enabled
|
||||
|
||||
event TokenEnabled(address indexed token, bool enabled);
|
||||
event TransferAuthorized(
|
||||
address indexed token,
|
||||
address indexed from,
|
||||
address indexed to,
|
||||
uint256 amount,
|
||||
bool authorized
|
||||
);
|
||||
|
||||
error TransferNotAuthorized();
|
||||
error TokenNotEnabled();
|
||||
error InvalidToken();
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
address bridgeEscrowVault_,
|
||||
address policyManager_,
|
||||
address complianceRegistry_
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(ENFORCER_ROLE, admin);
|
||||
_grantRole(OPERATOR_ROLE, admin);
|
||||
|
||||
require(bridgeEscrowVault_ != address(0), "eMoneyPolicyEnforcer: zero bridge");
|
||||
require(policyManager_ != address(0), "eMoneyPolicyEnforcer: zero policy manager");
|
||||
require(complianceRegistry_ != address(0), "eMoneyPolicyEnforcer: zero compliance registry");
|
||||
|
||||
bridgeEscrowVault = BridgeEscrowVault(bridgeEscrowVault_);
|
||||
policyManager = PolicyManager(policyManager_);
|
||||
complianceRegistry = ComplianceRegistry(complianceRegistry_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if transfer is authorized before bridge operation
|
||||
* @param token eMoney token address
|
||||
* @param from Source address
|
||||
* @param to Destination address (bridge escrow)
|
||||
* @param amount Amount to bridge
|
||||
* @return authorized True if transfer is authorized
|
||||
*/
|
||||
function checkTransferAuthorization(
|
||||
address token,
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount
|
||||
) external returns (bool authorized) {
|
||||
if (!enabledTokens[token]) revert TokenNotEnabled();
|
||||
|
||||
// Check PolicyManager authorization
|
||||
(bool isAuthorized, bytes32 reasonCode) = policyManager.canTransfer(
|
||||
token,
|
||||
from,
|
||||
to,
|
||||
amount
|
||||
);
|
||||
|
||||
if (!isAuthorized) {
|
||||
emit TransferAuthorized(token, from, to, amount, false);
|
||||
revert TransferNotAuthorized();
|
||||
}
|
||||
|
||||
// Check ComplianceRegistry restrictions
|
||||
bool complianceAllowed = complianceRegistry.canTransfer(token, from, to, amount);
|
||||
|
||||
if (!complianceAllowed) {
|
||||
emit TransferAuthorized(token, from, to, amount, false);
|
||||
revert TransferNotAuthorized();
|
||||
}
|
||||
|
||||
emit TransferAuthorized(token, from, to, amount, true);
|
||||
authorized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check transfer authorization with additional context
|
||||
* @param token eMoney token address
|
||||
* @param from Source address
|
||||
* @param to Destination address
|
||||
* @param amount Amount to transfer
|
||||
* @param context Additional context data
|
||||
* @return authorized True if transfer is authorized
|
||||
*/
|
||||
function checkTransferAuthorizationWithContext(
|
||||
address token,
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount,
|
||||
bytes memory context
|
||||
) external returns (bool authorized) {
|
||||
if (!enabledTokens[token]) revert TokenNotEnabled();
|
||||
|
||||
// Check PolicyManager with context
|
||||
(bool isAuthorized, bytes32 reasonCode) = policyManager.canTransferWithContext(
|
||||
token,
|
||||
from,
|
||||
to,
|
||||
amount,
|
||||
context
|
||||
);
|
||||
|
||||
if (!isAuthorized) {
|
||||
emit TransferAuthorized(token, from, to, amount, false);
|
||||
revert TransferNotAuthorized();
|
||||
}
|
||||
|
||||
// Check ComplianceRegistry
|
||||
bool complianceAllowed = complianceRegistry.canTransfer(token, from, to, amount);
|
||||
|
||||
if (!complianceAllowed) {
|
||||
emit TransferAuthorized(token, from, to, amount, false);
|
||||
revert TransferNotAuthorized();
|
||||
}
|
||||
|
||||
emit TransferAuthorized(token, from, to, amount, true);
|
||||
authorized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Enable an eMoney token for policy enforcement
|
||||
* @param token eMoney token address
|
||||
*/
|
||||
function enableToken(address token) external onlyRole(OPERATOR_ROLE) {
|
||||
require(token != address(0), "eMoneyPolicyEnforcer: zero token");
|
||||
enabledTokens[token] = true;
|
||||
emit TokenEnabled(token, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Disable an eMoney token
|
||||
* @param token eMoney token address
|
||||
*/
|
||||
function disableToken(address token) external onlyRole(OPERATOR_ROLE) {
|
||||
enabledTokens[token] = false;
|
||||
emit TokenEnabled(token, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if token is enabled
|
||||
*/
|
||||
function isTokenEnabled(address token) external view returns (bool) {
|
||||
return enabledTokens[token];
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @title IAlltraTransport
|
||||
* @notice Transport for 138 <-> ALL Mainnet (651940); does not use CCIP.
|
||||
* @dev ALL Mainnet is not supported by CCIP. This interface is used by AlltraAdapter
|
||||
* to delegate the actual lock/relay/mint flow to a custom bridge or relay.
|
||||
*/
|
||||
interface IAlltraTransport {
|
||||
/**
|
||||
* @notice Lock tokens and initiate transfer to ALL Mainnet (651940).
|
||||
* @param token Token address (address(0) for native).
|
||||
* @param amount Amount to bridge.
|
||||
* @param recipient Recipient on ALL Mainnet.
|
||||
* @return requestId Unique request id for status/confirmation.
|
||||
*/
|
||||
function lockAndRelay(
|
||||
address token,
|
||||
uint256 amount,
|
||||
address recipient
|
||||
) external payable returns (bytes32 requestId);
|
||||
|
||||
/**
|
||||
* @notice Check if this transport is configured (e.g. relayer set).
|
||||
*/
|
||||
function isConfigured() external view returns (bool);
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @title IChainAdapter
|
||||
* @notice Interface for chain-specific bridge adapters
|
||||
* @dev All chain adapters must implement this interface
|
||||
*/
|
||||
interface IChainAdapter {
|
||||
enum BridgeStatus {
|
||||
Pending,
|
||||
Locked,
|
||||
Confirmed,
|
||||
Completed,
|
||||
Failed,
|
||||
Cancelled
|
||||
}
|
||||
|
||||
struct BridgeRequest {
|
||||
address sender;
|
||||
address token;
|
||||
uint256 amount;
|
||||
bytes destinationData; // Chain-specific destination (address, account, etc.)
|
||||
bytes32 requestId;
|
||||
BridgeStatus status;
|
||||
uint256 createdAt;
|
||||
uint256 completedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get chain type identifier
|
||||
*/
|
||||
function getChainType() external pure returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice Get chain identifier (chainId for EVM, string for non-EVM)
|
||||
*/
|
||||
function getChainIdentifier() external view returns (uint256 chainId, string memory identifier);
|
||||
|
||||
/**
|
||||
* @notice Validate destination address/identifier for this chain
|
||||
*/
|
||||
function validateDestination(bytes calldata destination) external pure returns (bool);
|
||||
|
||||
/**
|
||||
* @notice Initiate bridge operation
|
||||
* @param token Token address (address(0) for native)
|
||||
* @param amount Amount to bridge
|
||||
* @param destination Chain-specific destination data
|
||||
* @param recipient Recipient address/identifier
|
||||
* @return requestId Unique request identifier
|
||||
*/
|
||||
function bridge(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination,
|
||||
bytes calldata recipient
|
||||
) external payable returns (bytes32 requestId);
|
||||
|
||||
/**
|
||||
* @notice Get bridge request status
|
||||
*/
|
||||
function getBridgeStatus(bytes32 requestId)
|
||||
external view returns (BridgeRequest memory);
|
||||
|
||||
/**
|
||||
* @notice Cancel pending bridge (if supported)
|
||||
*/
|
||||
function cancelBridge(bytes32 requestId) external returns (bool);
|
||||
|
||||
/**
|
||||
* @notice Estimate bridge fee
|
||||
*/
|
||||
function estimateFee(
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata destination
|
||||
) external view returns (uint256 fee);
|
||||
|
||||
/**
|
||||
* @notice Check if adapter is active
|
||||
*/
|
||||
function isActive() external view returns (bool);
|
||||
}
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "@openzeppelin/contracts/utils/Pausable.sol";
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
|
||||
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeEscrowVault
|
||||
* @notice Enhanced escrow vault for multi-rail bridging (EVM, XRPL, Fabric)
|
||||
* @dev Supports HSM-backed admin functions via EIP-712 signatures
|
||||
*/
|
||||
contract BridgeEscrowVault is ReentrancyGuard, Pausable, AccessControl, EIP712 {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
|
||||
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
|
||||
bytes32 public constant REFUND_ROLE = keccak256("REFUND_ROLE");
|
||||
|
||||
enum DestinationType {
|
||||
EVM,
|
||||
XRPL,
|
||||
FABRIC
|
||||
}
|
||||
|
||||
enum TransferStatus {
|
||||
INITIATED,
|
||||
DEPOSIT_CONFIRMED,
|
||||
ROUTE_SELECTED,
|
||||
EXECUTING,
|
||||
DESTINATION_SENT,
|
||||
FINALITY_CONFIRMED,
|
||||
COMPLETED,
|
||||
FAILED,
|
||||
REFUND_PENDING,
|
||||
REFUNDED
|
||||
}
|
||||
|
||||
struct Transfer {
|
||||
bytes32 transferId;
|
||||
address depositor;
|
||||
address asset; // address(0) for native ETH
|
||||
uint256 amount;
|
||||
DestinationType destinationType;
|
||||
bytes destinationData; // Encoded destination address/identifier
|
||||
uint256 timestamp;
|
||||
uint256 timeout;
|
||||
TransferStatus status;
|
||||
bool refunded;
|
||||
}
|
||||
|
||||
struct RefundRequest {
|
||||
bytes32 transferId;
|
||||
uint256 deadline;
|
||||
bytes hsmSignature;
|
||||
}
|
||||
|
||||
// EIP-712 type hashes
|
||||
bytes32 private constant REFUND_TYPEHASH =
|
||||
keccak256("RefundRequest(bytes32 transferId,uint256 deadline)");
|
||||
|
||||
mapping(bytes32 => Transfer) public transfers;
|
||||
mapping(bytes32 => bool) public processedTransferIds;
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
event Deposit(
|
||||
bytes32 indexed transferId,
|
||||
address indexed depositor,
|
||||
address indexed asset,
|
||||
uint256 amount,
|
||||
DestinationType destinationType,
|
||||
bytes destinationData,
|
||||
uint256 timestamp
|
||||
);
|
||||
|
||||
event TransferStatusUpdated(
|
||||
bytes32 indexed transferId,
|
||||
TransferStatus oldStatus,
|
||||
TransferStatus newStatus
|
||||
);
|
||||
|
||||
event RefundInitiated(
|
||||
bytes32 indexed transferId,
|
||||
address indexed depositor,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
event RefundExecuted(
|
||||
bytes32 indexed transferId,
|
||||
address indexed depositor,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
error ZeroAmount();
|
||||
error ZeroRecipient();
|
||||
error ZeroAsset();
|
||||
error TransferAlreadyProcessed();
|
||||
error TransferNotFound();
|
||||
error TransferNotRefundable();
|
||||
error InvalidTimeout();
|
||||
error InvalidSignature();
|
||||
error TransferNotTimedOut();
|
||||
error InvalidStatus();
|
||||
|
||||
constructor(address admin) EIP712("BridgeEscrowVault", "1") {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(PAUSER_ROLE, admin);
|
||||
_grantRole(OPERATOR_ROLE, admin);
|
||||
_grantRole(REFUND_ROLE, admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Deposit native ETH for cross-chain transfer
|
||||
* @param destinationType Type of destination (EVM, XRPL, Fabric)
|
||||
* @param destinationData Encoded destination address/identifier
|
||||
* @param timeout Timeout in seconds for refund eligibility
|
||||
* @param nonce User-provided nonce for replay protection
|
||||
* @return transferId Unique transfer identifier
|
||||
*/
|
||||
function depositNative(
|
||||
DestinationType destinationType,
|
||||
bytes calldata destinationData,
|
||||
uint256 timeout,
|
||||
bytes32 nonce
|
||||
) external payable nonReentrant whenNotPaused returns (bytes32 transferId) {
|
||||
if (msg.value == 0) revert ZeroAmount();
|
||||
if (destinationData.length == 0) revert ZeroRecipient();
|
||||
if (timeout == 0) revert InvalidTimeout();
|
||||
|
||||
nonces[msg.sender]++;
|
||||
|
||||
transferId = _generateTransferId(
|
||||
address(0),
|
||||
msg.value,
|
||||
destinationType,
|
||||
destinationData,
|
||||
nonce
|
||||
);
|
||||
|
||||
if (processedTransferIds[transferId]) revert TransferAlreadyProcessed();
|
||||
processedTransferIds[transferId] = true;
|
||||
|
||||
transfers[transferId] = Transfer({
|
||||
transferId: transferId,
|
||||
depositor: msg.sender,
|
||||
asset: address(0),
|
||||
amount: msg.value,
|
||||
destinationType: destinationType,
|
||||
destinationData: destinationData,
|
||||
timestamp: block.timestamp,
|
||||
timeout: timeout,
|
||||
status: TransferStatus.INITIATED,
|
||||
refunded: false
|
||||
});
|
||||
|
||||
emit Deposit(
|
||||
transferId,
|
||||
msg.sender,
|
||||
address(0),
|
||||
msg.value,
|
||||
destinationType,
|
||||
destinationData,
|
||||
block.timestamp
|
||||
);
|
||||
|
||||
return transferId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Deposit ERC-20 tokens for cross-chain transfer
|
||||
* @param token ERC-20 token address
|
||||
* @param amount Amount to deposit
|
||||
* @param destinationType Type of destination (EVM, XRPL, Fabric)
|
||||
* @param destinationData Encoded destination address/identifier
|
||||
* @param timeout Timeout in seconds for refund eligibility
|
||||
* @param nonce User-provided nonce for replay protection
|
||||
* @return transferId Unique transfer identifier
|
||||
*/
|
||||
function depositERC20(
|
||||
address token,
|
||||
uint256 amount,
|
||||
DestinationType destinationType,
|
||||
bytes calldata destinationData,
|
||||
uint256 timeout,
|
||||
bytes32 nonce
|
||||
) external nonReentrant whenNotPaused returns (bytes32 transferId) {
|
||||
if (token == address(0)) revert ZeroAsset();
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
if (destinationData.length == 0) revert ZeroRecipient();
|
||||
if (timeout == 0) revert InvalidTimeout();
|
||||
|
||||
nonces[msg.sender]++;
|
||||
|
||||
transferId = _generateTransferId(
|
||||
token,
|
||||
amount,
|
||||
destinationType,
|
||||
destinationData,
|
||||
nonce
|
||||
);
|
||||
|
||||
if (processedTransferIds[transferId]) revert TransferAlreadyProcessed();
|
||||
processedTransferIds[transferId] = true;
|
||||
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
|
||||
transfers[transferId] = Transfer({
|
||||
transferId: transferId,
|
||||
depositor: msg.sender,
|
||||
asset: token,
|
||||
amount: amount,
|
||||
destinationType: destinationType,
|
||||
destinationData: destinationData,
|
||||
timestamp: block.timestamp,
|
||||
timeout: timeout,
|
||||
status: TransferStatus.INITIATED,
|
||||
refunded: false
|
||||
});
|
||||
|
||||
emit Deposit(
|
||||
transferId,
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
destinationType,
|
||||
destinationData,
|
||||
block.timestamp
|
||||
);
|
||||
|
||||
return transferId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update transfer status (operator only)
|
||||
* @param transferId Transfer identifier
|
||||
* @param newStatus New status
|
||||
*/
|
||||
function updateTransferStatus(
|
||||
bytes32 transferId,
|
||||
TransferStatus newStatus
|
||||
) external onlyRole(OPERATOR_ROLE) {
|
||||
Transfer storage transfer = transfers[transferId];
|
||||
if (transfer.transferId == bytes32(0)) revert TransferNotFound();
|
||||
|
||||
TransferStatus oldStatus = transfer.status;
|
||||
transfer.status = newStatus;
|
||||
|
||||
emit TransferStatusUpdated(transferId, oldStatus, newStatus);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Initiate refund (requires HSM signature)
|
||||
* @param request Refund request with HSM signature
|
||||
* @param hsmSigner HSM signer address
|
||||
*/
|
||||
function initiateRefund(
|
||||
RefundRequest calldata request,
|
||||
address hsmSigner
|
||||
) external onlyRole(REFUND_ROLE) {
|
||||
Transfer storage transfer = transfers[request.transferId];
|
||||
if (transfer.transferId == bytes32(0)) revert TransferNotFound();
|
||||
if (transfer.refunded) revert TransferNotRefundable();
|
||||
if (block.timestamp < transfer.timestamp + transfer.timeout) {
|
||||
revert TransferNotTimedOut();
|
||||
}
|
||||
|
||||
// Verify HSM signature
|
||||
bytes32 structHash = keccak256(
|
||||
abi.encode(REFUND_TYPEHASH, request.transferId, request.deadline)
|
||||
);
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
if (ECDSA.recover(hash, request.hsmSignature) != hsmSigner) {
|
||||
revert InvalidSignature();
|
||||
}
|
||||
|
||||
if (block.timestamp > request.deadline) revert InvalidSignature();
|
||||
|
||||
transfer.status = TransferStatus.REFUND_PENDING;
|
||||
emit RefundInitiated(request.transferId, transfer.depositor, transfer.amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute refund after initiation
|
||||
* @param transferId Transfer identifier
|
||||
*/
|
||||
function executeRefund(bytes32 transferId) external nonReentrant onlyRole(REFUND_ROLE) {
|
||||
Transfer storage transfer = transfers[transferId];
|
||||
if (transfer.transferId == bytes32(0)) revert TransferNotFound();
|
||||
if (transfer.refunded) revert TransferNotRefundable();
|
||||
if (transfer.status != TransferStatus.REFUND_PENDING) revert InvalidStatus();
|
||||
|
||||
transfer.refunded = true;
|
||||
transfer.status = TransferStatus.REFUNDED;
|
||||
|
||||
if (transfer.asset == address(0)) {
|
||||
(bool success, ) = transfer.depositor.call{value: transfer.amount}("");
|
||||
require(success, "Refund failed");
|
||||
} else {
|
||||
IERC20(transfer.asset).safeTransfer(transfer.depositor, transfer.amount);
|
||||
}
|
||||
|
||||
emit RefundExecuted(transferId, transfer.depositor, transfer.amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get transfer details
|
||||
* @param transferId Transfer identifier
|
||||
* @return Transfer struct
|
||||
*/
|
||||
function getTransfer(bytes32 transferId) external view returns (Transfer memory) {
|
||||
return transfers[transferId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if transfer is refundable
|
||||
* @param transferId Transfer identifier
|
||||
* @return True if refundable
|
||||
*/
|
||||
function isRefundable(bytes32 transferId) external view returns (bool) {
|
||||
Transfer storage transfer = transfers[transferId];
|
||||
if (transfer.transferId == bytes32(0)) return false;
|
||||
if (transfer.refunded) return false;
|
||||
return block.timestamp >= transfer.timestamp + transfer.timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Generate unique transfer ID
|
||||
* @param asset Asset address
|
||||
* @param amount Amount
|
||||
* @param destinationType Destination type
|
||||
* @param destinationData Destination data
|
||||
* @param nonce User nonce
|
||||
* @return transferId Unique identifier
|
||||
*/
|
||||
function _generateTransferId(
|
||||
address asset,
|
||||
uint256 amount,
|
||||
DestinationType destinationType,
|
||||
bytes calldata destinationData,
|
||||
bytes32 nonce
|
||||
) internal view returns (bytes32) {
|
||||
return
|
||||
keccak256(
|
||||
abi.encodePacked(
|
||||
asset,
|
||||
amount,
|
||||
uint8(destinationType),
|
||||
destinationData,
|
||||
nonce,
|
||||
msg.sender,
|
||||
block.timestamp,
|
||||
block.number
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Pause contract
|
||||
*/
|
||||
function pause() external onlyRole(PAUSER_ROLE) {
|
||||
_pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unpause contract
|
||||
*/
|
||||
function unpause() external onlyRole(PAUSER_ROLE) {
|
||||
_unpause();
|
||||
}
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/utils/Pausable.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeRegistry
|
||||
* @notice Registry for bridge configuration: destinations, tokens, fees, and routing
|
||||
*/
|
||||
contract BridgeRegistry is AccessControl, Pausable {
|
||||
bytes32 public constant REGISTRAR_ROLE = keccak256("REGISTRAR_ROLE");
|
||||
|
||||
struct Destination {
|
||||
uint256 chainId; // 0 for non-EVM
|
||||
string chainName;
|
||||
bool enabled;
|
||||
uint256 minFinalityBlocks;
|
||||
uint256 timeoutSeconds;
|
||||
uint256 baseFee; // Base fee in basis points (10000 = 100%)
|
||||
address feeRecipient;
|
||||
}
|
||||
|
||||
struct TokenConfig {
|
||||
address tokenAddress;
|
||||
bool allowed;
|
||||
uint256 minAmount;
|
||||
uint256 maxAmount;
|
||||
uint256[] allowedDestinations; // Chain IDs or 0 for non-EVM
|
||||
uint8 riskLevel; // 0-255, higher = riskier
|
||||
uint256 bridgeFeeBps; // Bridge fee in basis points
|
||||
}
|
||||
|
||||
struct RouteHealth {
|
||||
uint256 successCount;
|
||||
uint256 failureCount;
|
||||
uint256 lastUpdate;
|
||||
uint256 avgSettlementTime; // In seconds
|
||||
}
|
||||
|
||||
mapping(uint256 => Destination) public destinations; // chainId -> Destination
|
||||
mapping(address => TokenConfig) public tokenConfigs;
|
||||
mapping(uint256 => mapping(address => RouteHealth)) public routeHealth; // chainId -> token -> health
|
||||
mapping(address => bool) public allowedTokens;
|
||||
|
||||
uint256[] public destinationChainIds;
|
||||
address[] public registeredTokens;
|
||||
|
||||
event DestinationRegistered(
|
||||
uint256 indexed chainId,
|
||||
string chainName,
|
||||
uint256 minFinalityBlocks,
|
||||
uint256 timeoutSeconds
|
||||
);
|
||||
|
||||
event DestinationUpdated(uint256 indexed chainId, bool enabled);
|
||||
|
||||
event TokenRegistered(
|
||||
address indexed token,
|
||||
uint256 minAmount,
|
||||
uint256 maxAmount,
|
||||
uint8 riskLevel
|
||||
);
|
||||
|
||||
event TokenUpdated(address indexed token, bool allowed);
|
||||
|
||||
event RouteHealthUpdated(
|
||||
uint256 indexed chainId,
|
||||
address indexed token,
|
||||
bool success,
|
||||
uint256 settlementTime
|
||||
);
|
||||
|
||||
error DestinationNotFound();
|
||||
error TokenNotAllowed();
|
||||
error InvalidAmount();
|
||||
error InvalidDestination();
|
||||
error InvalidFee();
|
||||
|
||||
constructor(address admin) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(REGISTRAR_ROLE, admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a new destination chain
|
||||
* @param chainId Chain ID (0 for non-EVM like XRPL)
|
||||
* @param chainName Human-readable chain name
|
||||
* @param minFinalityBlocks Minimum blocks/ledgers for finality
|
||||
* @param timeoutSeconds Timeout for refund eligibility
|
||||
* @param baseFee Base fee in basis points
|
||||
* @param feeRecipient Address to receive fees
|
||||
*/
|
||||
function registerDestination(
|
||||
uint256 chainId,
|
||||
string calldata chainName,
|
||||
uint256 minFinalityBlocks,
|
||||
uint256 timeoutSeconds,
|
||||
uint256 baseFee,
|
||||
address feeRecipient
|
||||
) external onlyRole(REGISTRAR_ROLE) {
|
||||
if (baseFee > 10000) revert InvalidFee(); // Max 100%
|
||||
|
||||
destinations[chainId] = Destination({
|
||||
chainId: chainId,
|
||||
chainName: chainName,
|
||||
enabled: true,
|
||||
minFinalityBlocks: minFinalityBlocks,
|
||||
timeoutSeconds: timeoutSeconds,
|
||||
baseFee: baseFee,
|
||||
feeRecipient: feeRecipient
|
||||
});
|
||||
|
||||
// Add to list if not already present
|
||||
bool exists = false;
|
||||
for (uint256 i = 0; i < destinationChainIds.length; i++) {
|
||||
if (destinationChainIds[i] == chainId) {
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!exists) {
|
||||
destinationChainIds.push(chainId);
|
||||
}
|
||||
|
||||
emit DestinationRegistered(chainId, chainName, minFinalityBlocks, timeoutSeconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update destination enabled status
|
||||
* @param chainId Chain ID
|
||||
* @param enabled Enabled status
|
||||
*/
|
||||
function updateDestination(
|
||||
uint256 chainId,
|
||||
bool enabled
|
||||
) external onlyRole(REGISTRAR_ROLE) {
|
||||
if (destinations[chainId].chainId == 0 && chainId != 0) revert DestinationNotFound();
|
||||
destinations[chainId].enabled = enabled;
|
||||
emit DestinationUpdated(chainId, enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a token for bridging
|
||||
* @param token Token address
|
||||
* @param minAmount Minimum bridge amount
|
||||
* @param maxAmount Maximum bridge amount
|
||||
* @param allowedDestinations Array of allowed destination chain IDs
|
||||
* @param riskLevel Risk level (0-255)
|
||||
* @param bridgeFeeBps Bridge fee in basis points
|
||||
*/
|
||||
function registerToken(
|
||||
address token,
|
||||
uint256 minAmount,
|
||||
uint256 maxAmount,
|
||||
uint256[] calldata allowedDestinations,
|
||||
uint8 riskLevel,
|
||||
uint256 bridgeFeeBps
|
||||
) external onlyRole(REGISTRAR_ROLE) {
|
||||
if (bridgeFeeBps > 10000) revert InvalidFee();
|
||||
|
||||
tokenConfigs[token] = TokenConfig({
|
||||
tokenAddress: token,
|
||||
allowed: true,
|
||||
minAmount: minAmount,
|
||||
maxAmount: maxAmount,
|
||||
allowedDestinations: allowedDestinations,
|
||||
riskLevel: riskLevel,
|
||||
bridgeFeeBps: bridgeFeeBps
|
||||
});
|
||||
|
||||
allowedTokens[token] = true;
|
||||
|
||||
// Add to list if not already present
|
||||
bool exists = false;
|
||||
for (uint256 i = 0; i < registeredTokens.length; i++) {
|
||||
if (registeredTokens[i] == token) {
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!exists) {
|
||||
registeredTokens.push(token);
|
||||
}
|
||||
|
||||
emit TokenRegistered(token, minAmount, maxAmount, riskLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update token allowed status
|
||||
* @param token Token address
|
||||
* @param allowed Allowed status
|
||||
*/
|
||||
function updateToken(address token, bool allowed) external onlyRole(REGISTRAR_ROLE) {
|
||||
if (tokenConfigs[token].tokenAddress == address(0)) revert TokenNotAllowed();
|
||||
tokenConfigs[token].allowed = allowed;
|
||||
allowedTokens[token] = allowed;
|
||||
emit TokenUpdated(token, allowed);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update route health metrics
|
||||
* @param chainId Destination chain ID
|
||||
* @param token Token address
|
||||
* @param success Whether the route succeeded
|
||||
* @param settlementTime Settlement time in seconds
|
||||
*/
|
||||
function updateRouteHealth(
|
||||
uint256 chainId,
|
||||
address token,
|
||||
bool success,
|
||||
uint256 settlementTime
|
||||
) external onlyRole(REGISTRAR_ROLE) {
|
||||
RouteHealth storage health = routeHealth[chainId][token];
|
||||
|
||||
if (success) {
|
||||
health.successCount++;
|
||||
// Update average settlement time (simple moving average)
|
||||
if (health.successCount == 1) {
|
||||
health.avgSettlementTime = settlementTime;
|
||||
} else {
|
||||
health.avgSettlementTime =
|
||||
(health.avgSettlementTime * (health.successCount - 1) + settlementTime) /
|
||||
health.successCount;
|
||||
}
|
||||
} else {
|
||||
health.failureCount++;
|
||||
}
|
||||
|
||||
health.lastUpdate = block.timestamp;
|
||||
|
||||
emit RouteHealthUpdated(chainId, token, success, settlementTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Validate bridge request
|
||||
* @param token Token address (address(0) for native)
|
||||
* @param amount Amount to bridge
|
||||
* @param destinationChainId Destination chain ID
|
||||
* @return isValid Whether request is valid
|
||||
* @return fee Fee amount
|
||||
*/
|
||||
function validateBridgeRequest(
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint256 destinationChainId
|
||||
) external view returns (bool isValid, uint256 fee) {
|
||||
// Check destination exists and is enabled
|
||||
Destination memory dest = destinations[destinationChainId];
|
||||
if (dest.chainId == 0 && destinationChainId != 0) {
|
||||
return (false, 0);
|
||||
}
|
||||
if (!dest.enabled) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
// For native ETH, allow if destination is enabled
|
||||
if (token == address(0)) {
|
||||
fee = (amount * dest.baseFee) / 10000;
|
||||
return (true, fee);
|
||||
}
|
||||
|
||||
// Check token is registered and allowed
|
||||
TokenConfig memory config = tokenConfigs[token];
|
||||
if (!config.allowed || config.tokenAddress == address(0)) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
// Check amount limits
|
||||
if (amount < config.minAmount || amount > config.maxAmount) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
// Check destination is allowed for this token
|
||||
bool destAllowed = false;
|
||||
for (uint256 i = 0; i < config.allowedDestinations.length; i++) {
|
||||
if (config.allowedDestinations[i] == destinationChainId) {
|
||||
destAllowed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!destAllowed) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
// Calculate fee (base fee + token-specific fee)
|
||||
uint256 baseFeeAmount = (amount * dest.baseFee) / 10000;
|
||||
uint256 tokenFeeAmount = (amount * config.bridgeFeeBps) / 10000;
|
||||
fee = baseFeeAmount + tokenFeeAmount;
|
||||
|
||||
return (true, fee);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get route health score (0-10000, higher is better)
|
||||
* @param chainId Destination chain ID
|
||||
* @param token Token address
|
||||
* @return score Health score
|
||||
*/
|
||||
function getRouteHealthScore(
|
||||
uint256 chainId,
|
||||
address token
|
||||
) external view returns (uint256 score) {
|
||||
RouteHealth memory health = routeHealth[chainId][token];
|
||||
uint256 total = health.successCount + health.failureCount;
|
||||
if (total == 0) return 5000; // Default 50% if no data
|
||||
|
||||
score = (health.successCount * 10000) / total;
|
||||
return score;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get all registered destinations
|
||||
* @return chainIds Array of chain IDs
|
||||
*/
|
||||
function getAllDestinations() external view returns (uint256[] memory) {
|
||||
return destinationChainIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get all registered tokens
|
||||
* @return tokens Array of token addresses
|
||||
*/
|
||||
function getAllTokens() external view returns (address[] memory) {
|
||||
return registeredTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Pause registry
|
||||
*/
|
||||
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unpause registry
|
||||
*/
|
||||
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_unpause();
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
|
||||
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeVerifier
|
||||
* @notice Verifies cross-chain proofs and attestor signatures for bridge operations
|
||||
* @dev Supports multi-sig quorum for attestations
|
||||
*/
|
||||
contract BridgeVerifier is AccessControl, EIP712 {
|
||||
using ECDSA for bytes32;
|
||||
|
||||
bytes32 public constant ATTESTOR_ROLE = keccak256("ATTESTOR_ROLE");
|
||||
|
||||
bytes32 private constant ATTESTATION_TYPEHASH =
|
||||
keccak256("Attestation(bytes32 transferId,bytes32 proofHash,uint256 nonce,uint256 deadline)");
|
||||
|
||||
struct Attestation {
|
||||
bytes32 transferId;
|
||||
bytes32 proofHash;
|
||||
uint256 nonce;
|
||||
uint256 deadline;
|
||||
bytes signature;
|
||||
}
|
||||
|
||||
struct AttestorConfig {
|
||||
address attestor;
|
||||
bool enabled;
|
||||
uint256 weight; // Weight for quorum calculation
|
||||
}
|
||||
|
||||
mapping(address => AttestorConfig) public attestors;
|
||||
mapping(bytes32 => mapping(address => bool)) public attestations; // transferId -> attestor -> attested
|
||||
mapping(bytes32 => uint256) public attestationWeights; // transferId -> total weight
|
||||
mapping(uint256 => bool) public usedNonces;
|
||||
|
||||
address[] public attestorList;
|
||||
uint256 public totalAttestorWeight;
|
||||
uint256 public quorumThreshold; // Minimum weight required (in basis points, 10000 = 100%)
|
||||
|
||||
event AttestationSubmitted(
|
||||
bytes32 indexed transferId,
|
||||
address indexed attestor,
|
||||
bytes32 proofHash
|
||||
);
|
||||
|
||||
event AttestationVerified(
|
||||
bytes32 indexed transferId,
|
||||
uint256 totalWeight,
|
||||
bool quorumMet
|
||||
);
|
||||
|
||||
event AttestorAdded(address indexed attestor, uint256 weight);
|
||||
event AttestorRemoved(address indexed attestor);
|
||||
event AttestorUpdated(address indexed attestor, bool enabled, uint256 weight);
|
||||
event QuorumThresholdUpdated(uint256 oldThreshold, uint256 newThreshold);
|
||||
|
||||
error ZeroAddress();
|
||||
error AttestorNotFound();
|
||||
error InvalidSignature();
|
||||
error NonceAlreadyUsed();
|
||||
error DeadlineExpired();
|
||||
error InvalidQuorum();
|
||||
error AlreadyAttested();
|
||||
|
||||
constructor(
|
||||
address admin,
|
||||
uint256 _quorumThreshold
|
||||
) EIP712("BridgeVerifier", "1") {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(ATTESTOR_ROLE, admin);
|
||||
if (_quorumThreshold > 10000) revert InvalidQuorum();
|
||||
quorumThreshold = _quorumThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Add an attestor
|
||||
* @param attestor Attestor address
|
||||
* @param weight Weight for quorum calculation
|
||||
*/
|
||||
function addAttestor(
|
||||
address attestor,
|
||||
uint256 weight
|
||||
) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
if (attestor == address(0)) revert ZeroAddress();
|
||||
if (attestors[attestor].attestor != address(0)) revert AttestorNotFound();
|
||||
|
||||
attestors[attestor] = AttestorConfig({
|
||||
attestor: attestor,
|
||||
enabled: true,
|
||||
weight: weight
|
||||
});
|
||||
|
||||
attestorList.push(attestor);
|
||||
totalAttestorWeight += weight;
|
||||
|
||||
emit AttestorAdded(attestor, weight);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Remove an attestor
|
||||
* @param attestor Attestor address
|
||||
*/
|
||||
function removeAttestor(address attestor) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
AttestorConfig memory config = attestors[attestor];
|
||||
if (config.attestor == address(0)) revert AttestorNotFound();
|
||||
|
||||
totalAttestorWeight -= config.weight;
|
||||
delete attestors[attestor];
|
||||
|
||||
// Remove from list
|
||||
for (uint256 i = 0; i < attestorList.length; i++) {
|
||||
if (attestorList[i] == attestor) {
|
||||
attestorList[i] = attestorList[attestorList.length - 1];
|
||||
attestorList.pop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
emit AttestorRemoved(attestor);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update attestor configuration
|
||||
* @param attestor Attestor address
|
||||
* @param enabled Enabled status
|
||||
* @param weight New weight
|
||||
*/
|
||||
function updateAttestor(
|
||||
address attestor,
|
||||
bool enabled,
|
||||
uint256 weight
|
||||
) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
AttestorConfig storage config = attestors[attestor];
|
||||
if (config.attestor == address(0)) revert AttestorNotFound();
|
||||
|
||||
uint256 oldWeight = config.weight;
|
||||
totalAttestorWeight = totalAttestorWeight - oldWeight + weight;
|
||||
|
||||
config.enabled = enabled;
|
||||
config.weight = weight;
|
||||
|
||||
emit AttestorUpdated(attestor, enabled, weight);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update quorum threshold
|
||||
* @param newThreshold New threshold in basis points
|
||||
*/
|
||||
function setQuorumThreshold(uint256 newThreshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
if (newThreshold > 10000) revert InvalidQuorum();
|
||||
uint256 oldThreshold = quorumThreshold;
|
||||
quorumThreshold = newThreshold;
|
||||
emit QuorumThresholdUpdated(oldThreshold, newThreshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Submit an attestation
|
||||
* @param attestation Attestation with signature
|
||||
*/
|
||||
function submitAttestation(Attestation calldata attestation) external {
|
||||
AttestorConfig memory config = attestors[msg.sender];
|
||||
if (config.attestor == address(0) || !config.enabled) revert AttestorNotFound();
|
||||
if (block.timestamp > attestation.deadline) revert DeadlineExpired();
|
||||
if (usedNonces[attestation.nonce]) revert NonceAlreadyUsed();
|
||||
if (attestations[attestation.transferId][msg.sender]) revert AlreadyAttested();
|
||||
|
||||
// Verify signature
|
||||
bytes32 structHash = keccak256(
|
||||
abi.encode(
|
||||
ATTESTATION_TYPEHASH,
|
||||
attestation.transferId,
|
||||
attestation.proofHash,
|
||||
attestation.nonce,
|
||||
attestation.deadline
|
||||
)
|
||||
);
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
if (hash.recover(attestation.signature) != msg.sender) {
|
||||
revert InvalidSignature();
|
||||
}
|
||||
|
||||
usedNonces[attestation.nonce] = true;
|
||||
attestations[attestation.transferId][msg.sender] = true;
|
||||
attestationWeights[attestation.transferId] += config.weight;
|
||||
|
||||
emit AttestationSubmitted(attestation.transferId, msg.sender, attestation.proofHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify if quorum is met for a transfer
|
||||
* @param transferId Transfer identifier
|
||||
* @return quorumMet Whether quorum threshold is met
|
||||
* @return totalWeight Total weight of attestations
|
||||
* @return requiredWeight Required weight for quorum
|
||||
*/
|
||||
function verifyQuorum(
|
||||
bytes32 transferId
|
||||
) external view returns (bool quorumMet, uint256 totalWeight, uint256 requiredWeight) {
|
||||
totalWeight = attestationWeights[transferId];
|
||||
requiredWeight = (totalAttestorWeight * quorumThreshold) / 10000;
|
||||
quorumMet = totalWeight >= requiredWeight;
|
||||
return (quorumMet, totalWeight, requiredWeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if an attestor has attested to a transfer
|
||||
* @param transferId Transfer identifier
|
||||
* @param attestor Attestor address
|
||||
* @return True if attested
|
||||
*/
|
||||
function hasAttested(
|
||||
bytes32 transferId,
|
||||
address attestor
|
||||
) external view returns (bool) {
|
||||
return attestations[transferId][attestor];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get all attestors
|
||||
* @return Array of attestor addresses
|
||||
*/
|
||||
function getAllAttestors() external view returns (address[] memory) {
|
||||
return attestorList;
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/utils/Pausable.sol";
|
||||
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
|
||||
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||
import "./wXRP.sol";
|
||||
|
||||
/**
|
||||
* @title MintBurnController
|
||||
* @notice HSM-backed controller for wXRP mint/burn operations
|
||||
* @dev Uses EIP-712 signatures for HSM authorization
|
||||
*/
|
||||
contract MintBurnController is AccessControl, Pausable, EIP712 {
|
||||
using ECDSA for bytes32;
|
||||
|
||||
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
|
||||
|
||||
bytes32 private constant MINT_TYPEHASH =
|
||||
keccak256("MintRequest(address to,uint256 amount,bytes32 xrplTxHash,uint256 nonce,uint256 deadline)");
|
||||
bytes32 private constant BURN_TYPEHASH =
|
||||
keccak256("BurnRequest(address from,uint256 amount,bytes32 xrplTxHash,uint256 nonce,uint256 deadline)");
|
||||
|
||||
wXRP public immutable wXRP_TOKEN;
|
||||
|
||||
mapping(uint256 => bool) public usedNonces;
|
||||
address public hsmSigner;
|
||||
|
||||
event MintExecuted(
|
||||
address indexed to,
|
||||
uint256 amount,
|
||||
bytes32 xrplTxHash,
|
||||
address executor
|
||||
);
|
||||
|
||||
event BurnExecuted(
|
||||
address indexed from,
|
||||
uint256 amount,
|
||||
bytes32 xrplTxHash,
|
||||
address executor
|
||||
);
|
||||
|
||||
event HSMSignerUpdated(address oldSigner, address newSigner);
|
||||
|
||||
struct MintRequest {
|
||||
address to;
|
||||
uint256 amount;
|
||||
bytes32 xrplTxHash;
|
||||
uint256 nonce;
|
||||
uint256 deadline;
|
||||
bytes hsmSignature;
|
||||
}
|
||||
|
||||
struct BurnRequest {
|
||||
address from;
|
||||
uint256 amount;
|
||||
bytes32 xrplTxHash;
|
||||
uint256 nonce;
|
||||
uint256 deadline;
|
||||
bytes hsmSignature;
|
||||
}
|
||||
|
||||
error ZeroAmount();
|
||||
error ZeroAddress();
|
||||
error InvalidSignature();
|
||||
error NonceAlreadyUsed();
|
||||
error DeadlineExpired();
|
||||
error InvalidNonce();
|
||||
|
||||
constructor(address admin, address _wXRP, address _hsmSigner) EIP712("MintBurnController", "1") {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(OPERATOR_ROLE, admin);
|
||||
wXRP_TOKEN = wXRP(_wXRP);
|
||||
hsmSigner = _hsmSigner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update HSM signer address
|
||||
* @param newSigner New HSM signer address
|
||||
*/
|
||||
function setHSMSigner(address newSigner) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
if (newSigner == address(0)) revert ZeroAddress();
|
||||
address oldSigner = hsmSigner;
|
||||
hsmSigner = newSigner;
|
||||
emit HSMSignerUpdated(oldSigner, newSigner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute mint with HSM signature
|
||||
* @param request Mint request with HSM signature
|
||||
*/
|
||||
function executeMint(MintRequest calldata request) external onlyRole(OPERATOR_ROLE) whenNotPaused {
|
||||
if (request.to == address(0)) revert ZeroAddress();
|
||||
if (request.amount == 0) revert ZeroAmount();
|
||||
if (block.timestamp > request.deadline) revert DeadlineExpired();
|
||||
if (usedNonces[request.nonce]) revert NonceAlreadyUsed();
|
||||
|
||||
// Verify HSM signature
|
||||
bytes32 structHash = keccak256(
|
||||
abi.encode(
|
||||
MINT_TYPEHASH,
|
||||
request.to,
|
||||
request.amount,
|
||||
request.xrplTxHash,
|
||||
request.nonce,
|
||||
request.deadline
|
||||
)
|
||||
);
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
if (hash.recover(request.hsmSignature) != hsmSigner) {
|
||||
revert InvalidSignature();
|
||||
}
|
||||
|
||||
usedNonces[request.nonce] = true;
|
||||
|
||||
wXRP_TOKEN.mint(request.to, request.amount, request.xrplTxHash);
|
||||
|
||||
emit MintExecuted(request.to, request.amount, request.xrplTxHash, msg.sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute burn with HSM signature
|
||||
* @param request Burn request with HSM signature
|
||||
*/
|
||||
function executeBurn(BurnRequest calldata request) external onlyRole(OPERATOR_ROLE) whenNotPaused {
|
||||
if (request.from == address(0)) revert ZeroAddress();
|
||||
if (request.amount == 0) revert ZeroAmount();
|
||||
if (block.timestamp > request.deadline) revert DeadlineExpired();
|
||||
if (usedNonces[request.nonce]) revert NonceAlreadyUsed();
|
||||
|
||||
// Verify HSM signature
|
||||
bytes32 structHash = keccak256(
|
||||
abi.encode(
|
||||
BURN_TYPEHASH,
|
||||
request.from,
|
||||
request.amount,
|
||||
request.xrplTxHash,
|
||||
request.nonce,
|
||||
request.deadline
|
||||
)
|
||||
);
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
if (hash.recover(request.hsmSignature) != hsmSigner) {
|
||||
revert InvalidSignature();
|
||||
}
|
||||
|
||||
usedNonces[request.nonce] = true;
|
||||
|
||||
wXRP_TOKEN.burnFrom(request.from, request.amount, request.xrplTxHash);
|
||||
|
||||
emit BurnExecuted(request.from, request.amount, request.xrplTxHash, msg.sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Pause controller
|
||||
*/
|
||||
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unpause controller
|
||||
*/
|
||||
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_unpause();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/utils/Pausable.sol";
|
||||
|
||||
/**
|
||||
* @title wXRP
|
||||
* @notice Wrapped XRP token (ERC-20) representing XRP locked on XRPL
|
||||
* @dev Mintable/burnable by authorized bridge controller only
|
||||
*/
|
||||
contract wXRP is ERC20, ERC20Burnable, AccessControl, Pausable {
|
||||
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
|
||||
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
|
||||
|
||||
uint8 private constant DECIMALS = 18;
|
||||
|
||||
event Minted(address indexed to, uint256 amount, bytes32 xrplTxHash);
|
||||
event Burned(address indexed from, uint256 amount, bytes32 xrplTxHash);
|
||||
|
||||
error ZeroAmount();
|
||||
error ZeroAddress();
|
||||
|
||||
constructor(address admin) ERC20("Wrapped XRP", "wXRP") {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(MINTER_ROLE, admin);
|
||||
_grantRole(BURNER_ROLE, admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Mint wXRP tokens (bridge controller only)
|
||||
* @param to Recipient address
|
||||
* @param amount Amount to mint
|
||||
* @param xrplTxHash XRPL transaction hash that locked the XRP
|
||||
*/
|
||||
function mint(
|
||||
address to,
|
||||
uint256 amount,
|
||||
bytes32 xrplTxHash
|
||||
) external onlyRole(MINTER_ROLE) whenNotPaused {
|
||||
if (to == address(0)) revert ZeroAddress();
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
|
||||
_mint(to, amount);
|
||||
emit Minted(to, amount, xrplTxHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Burn wXRP tokens to unlock XRP on XRPL (bridge controller only)
|
||||
* @param from Address to burn from
|
||||
* @param amount Amount to burn
|
||||
* @param xrplTxHash XRPL transaction hash for the unlock
|
||||
*/
|
||||
function burnFrom(
|
||||
address from,
|
||||
uint256 amount,
|
||||
bytes32 xrplTxHash
|
||||
) external onlyRole(BURNER_ROLE) whenNotPaused {
|
||||
if (from == address(0)) revert ZeroAddress();
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
|
||||
_burn(from, amount);
|
||||
emit Burned(from, amount, xrplTxHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Override decimals to return 18
|
||||
*/
|
||||
function decimals() public pure override returns (uint8) {
|
||||
return DECIMALS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Pause token transfers
|
||||
*/
|
||||
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unpause token transfers
|
||||
*/
|
||||
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_unpause();
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
|
||||
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeModuleRegistry
|
||||
* @notice Registry for bridge modules (hooks, validators, fee calculators)
|
||||
* @dev Enables extending bridge functionality without modifying core contracts
|
||||
*/
|
||||
contract BridgeModuleRegistry is
|
||||
Initializable,
|
||||
AccessControlUpgradeable,
|
||||
UUPSUpgradeable
|
||||
{
|
||||
bytes32 public constant MODULE_ADMIN_ROLE = keccak256("MODULE_ADMIN_ROLE");
|
||||
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
|
||||
|
||||
enum ModuleType {
|
||||
PreBridgeHook, // Execute before bridge (e.g., compliance check)
|
||||
PostBridgeHook, // Execute after bridge (e.g., notification)
|
||||
FeeCalculator, // Custom fee calculation
|
||||
RateLimiter, // Rate limiting logic
|
||||
Validator // Custom validation
|
||||
}
|
||||
|
||||
struct Module {
|
||||
address implementation;
|
||||
bool active;
|
||||
uint256 priority;
|
||||
uint256 registeredAt;
|
||||
}
|
||||
|
||||
// Storage
|
||||
mapping(ModuleType => address[]) public modules;
|
||||
mapping(ModuleType => mapping(address => Module)) public moduleInfo;
|
||||
mapping(ModuleType => uint256) public moduleCount;
|
||||
|
||||
event ModuleRegistered(
|
||||
ModuleType indexed moduleType,
|
||||
address indexed module,
|
||||
uint256 priority
|
||||
);
|
||||
|
||||
event ModuleUnregistered(
|
||||
ModuleType indexed moduleType,
|
||||
address indexed module
|
||||
);
|
||||
|
||||
event ModuleExecuted(
|
||||
ModuleType indexed moduleType,
|
||||
address indexed module,
|
||||
bool success
|
||||
);
|
||||
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor() {
|
||||
_disableInitializers();
|
||||
}
|
||||
|
||||
function initialize(address admin) external initializer {
|
||||
__AccessControl_init();
|
||||
__UUPSUpgradeable_init();
|
||||
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
_grantRole(MODULE_ADMIN_ROLE, admin);
|
||||
_grantRole(UPGRADER_ROLE, admin);
|
||||
}
|
||||
|
||||
function _authorizeUpgrade(address newImplementation)
|
||||
internal override onlyRole(UPGRADER_ROLE) {}
|
||||
|
||||
/**
|
||||
* @notice Register module
|
||||
*/
|
||||
function registerModule(
|
||||
ModuleType moduleType,
|
||||
address module,
|
||||
uint256 priority
|
||||
) external onlyRole(MODULE_ADMIN_ROLE) {
|
||||
require(module != address(0), "Zero address");
|
||||
require(module.code.length > 0, "Not a contract");
|
||||
require(moduleInfo[moduleType][module].implementation == address(0), "Already registered");
|
||||
|
||||
modules[moduleType].push(module);
|
||||
moduleInfo[moduleType][module] = Module({
|
||||
implementation: module,
|
||||
active: true,
|
||||
priority: priority,
|
||||
registeredAt: block.timestamp
|
||||
});
|
||||
|
||||
moduleCount[moduleType]++;
|
||||
|
||||
emit ModuleRegistered(moduleType, module, priority);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Unregister module
|
||||
*/
|
||||
function unregisterModule(
|
||||
ModuleType moduleType,
|
||||
address module
|
||||
) external onlyRole(MODULE_ADMIN_ROLE) {
|
||||
require(moduleInfo[moduleType][module].implementation != address(0), "Not registered");
|
||||
|
||||
moduleInfo[moduleType][module].active = false;
|
||||
moduleCount[moduleType]--;
|
||||
|
||||
emit ModuleUnregistered(moduleType, module);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute all modules of a type
|
||||
*/
|
||||
function executeModules(
|
||||
ModuleType moduleType,
|
||||
bytes calldata data
|
||||
) external returns (bytes[] memory results) {
|
||||
address[] memory activeModules = modules[moduleType];
|
||||
uint256 activeCount = 0;
|
||||
|
||||
// Count active modules
|
||||
for (uint256 i = 0; i < activeModules.length; i++) {
|
||||
if (moduleInfo[moduleType][activeModules[i]].active) {
|
||||
activeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
results = new bytes[](activeCount);
|
||||
uint256 resultIndex = 0;
|
||||
|
||||
// Execute each active module
|
||||
for (uint256 i = 0; i < activeModules.length; i++) {
|
||||
address module = activeModules[i];
|
||||
|
||||
if (!moduleInfo[moduleType][module].active) continue;
|
||||
|
||||
(bool success, bytes memory result) = module.call(data);
|
||||
|
||||
emit ModuleExecuted(moduleType, module, success);
|
||||
|
||||
if (success) {
|
||||
results[resultIndex] = result;
|
||||
resultIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute single module
|
||||
*/
|
||||
function executeModule(
|
||||
ModuleType moduleType,
|
||||
address module,
|
||||
bytes calldata data
|
||||
) external returns (bytes memory result) {
|
||||
require(moduleInfo[moduleType][module].active, "Module not active");
|
||||
|
||||
(bool success, bytes memory returnData) = module.call(data);
|
||||
|
||||
emit ModuleExecuted(moduleType, module, success);
|
||||
|
||||
require(success, "Module execution failed");
|
||||
|
||||
return returnData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set module priority
|
||||
*/
|
||||
function setModulePriority(
|
||||
ModuleType moduleType,
|
||||
address module,
|
||||
uint256 priority
|
||||
) external onlyRole(MODULE_ADMIN_ROLE) {
|
||||
require(moduleInfo[moduleType][module].implementation != address(0), "Not registered");
|
||||
|
||||
moduleInfo[moduleType][module].priority = priority;
|
||||
}
|
||||
|
||||
// View functions
|
||||
|
||||
function getModules(ModuleType moduleType) external view returns (address[] memory) {
|
||||
return modules[moduleType];
|
||||
}
|
||||
|
||||
function getActiveModules(ModuleType moduleType) external view returns (address[] memory) {
|
||||
address[] memory allModules = modules[moduleType];
|
||||
uint256 activeCount = 0;
|
||||
|
||||
for (uint256 i = 0; i < allModules.length; i++) {
|
||||
if (moduleInfo[moduleType][allModules[i]].active) {
|
||||
activeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
address[] memory activeModules = new address[](activeCount);
|
||||
uint256 index = 0;
|
||||
|
||||
for (uint256 i = 0; i < allModules.length; i++) {
|
||||
if (moduleInfo[moduleType][allModules[i]].active) {
|
||||
activeModules[index] = allModules[i];
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
return activeModules;
|
||||
}
|
||||
|
||||
function getModuleInfo(ModuleType moduleType, address module)
|
||||
external view returns (Module memory) {
|
||||
return moduleInfo[moduleType][module];
|
||||
}
|
||||
|
||||
function getModuleCount(ModuleType moduleType) external view returns (uint256) {
|
||||
return moduleCount[moduleType];
|
||||
}
|
||||
|
||||
function isModuleActive(ModuleType moduleType, address module) external view returns (bool) {
|
||||
return moduleInfo[moduleType][module].active;
|
||||
}
|
||||
}
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
/**
|
||||
* @title BondManager
|
||||
* @notice Manages bonds for trustless bridge claims with dynamic sizing and slashing
|
||||
* @dev Bonds are posted in ETH. Slashed bonds split 50% to challenger, 50% burned (sent to address(0)).
|
||||
*/
|
||||
contract BondManager is ReentrancyGuard {
|
||||
// Bond configuration
|
||||
uint256 public immutable bondMultiplier; // Basis points (11000 = 110%)
|
||||
uint256 public immutable minBond; // Minimum bond amount in wei
|
||||
|
||||
// Bond tracking
|
||||
struct Bond {
|
||||
address relayer; // Slot 0 (20 bytes) + 12 bytes padding
|
||||
uint256 amount; // Slot 1
|
||||
uint256 depositId; // Slot 2
|
||||
bool slashed; // Slot 3 (1 byte) + 31 bytes padding
|
||||
bool released; // Slot 4 (1 byte) + 31 bytes padding
|
||||
// Note: Could pack slashed and released in same slot, but keeping separate for clarity
|
||||
}
|
||||
|
||||
mapping(uint256 => Bond) public bonds; // depositId => Bond
|
||||
mapping(address => uint256) public totalBonds; // relayer => total bonded amount
|
||||
|
||||
event BondPosted(
|
||||
uint256 indexed depositId,
|
||||
address indexed relayer,
|
||||
uint256 bondAmount
|
||||
);
|
||||
|
||||
event BondSlashed(
|
||||
uint256 indexed depositId,
|
||||
address indexed relayer,
|
||||
address indexed challenger,
|
||||
uint256 bondAmount,
|
||||
uint256 challengerReward,
|
||||
uint256 burnedAmount
|
||||
);
|
||||
|
||||
event BondReleased(
|
||||
uint256 indexed depositId,
|
||||
address indexed relayer,
|
||||
uint256 bondAmount
|
||||
);
|
||||
|
||||
error ZeroDepositId();
|
||||
error ZeroRelayer();
|
||||
error InsufficientBond();
|
||||
error BondNotFound();
|
||||
error BondAlreadySlashed();
|
||||
error BondAlreadyReleased();
|
||||
error BondNotReleased();
|
||||
|
||||
/**
|
||||
* @notice Constructor sets bond parameters
|
||||
* @param _bondMultiplier Bond multiplier in basis points (11000 = 110% = 1.1x)
|
||||
* @param _minBond Minimum bond amount in wei
|
||||
*/
|
||||
constructor(uint256 _bondMultiplier, uint256 _minBond) {
|
||||
require(_bondMultiplier >= 10000, "BondManager: multiplier must be >= 100%");
|
||||
require(_minBond > 0, "BondManager: minBond must be > 0");
|
||||
bondMultiplier = _bondMultiplier;
|
||||
minBond = _minBond;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Post bond for a claim
|
||||
* @param depositId Deposit ID from source chain
|
||||
* @param depositAmount Amount of the deposit (used to calculate bond size)
|
||||
* @param relayer Address of the relayer posting the bond (can be different from msg.sender if called by InboxETH)
|
||||
* @return bondAmount The bond amount that was posted
|
||||
*/
|
||||
function postBond(
|
||||
uint256 depositId,
|
||||
uint256 depositAmount,
|
||||
address relayer
|
||||
) external payable nonReentrant returns (uint256) {
|
||||
if (depositId == 0) revert ZeroDepositId();
|
||||
if (relayer == address(0)) revert ZeroRelayer();
|
||||
|
||||
// Check if bond already exists
|
||||
require(bonds[depositId].relayer == address(0), "BondManager: bond already posted");
|
||||
|
||||
// Calculate required bond amount
|
||||
uint256 requiredBond = getRequiredBond(depositAmount);
|
||||
if (msg.value < requiredBond) revert InsufficientBond();
|
||||
|
||||
// Store bond information
|
||||
bonds[depositId] = Bond({
|
||||
relayer: relayer,
|
||||
amount: msg.value,
|
||||
depositId: depositId,
|
||||
slashed: false,
|
||||
released: false
|
||||
});
|
||||
|
||||
totalBonds[relayer] += msg.value;
|
||||
|
||||
emit BondPosted(depositId, msg.sender, msg.value);
|
||||
|
||||
return msg.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Slash bond due to fraudulent claim
|
||||
* @param depositId Deposit ID associated with the bond
|
||||
* @param challenger Address of the challenger proving fraud
|
||||
* @return challengerReward Amount sent to challenger
|
||||
* @return burnedAmount Amount burned (sent to address(0))
|
||||
*/
|
||||
function slashBond(
|
||||
uint256 depositId,
|
||||
address challenger
|
||||
) external nonReentrant returns (uint256 challengerReward, uint256 burnedAmount) {
|
||||
Bond storage bond = bonds[depositId];
|
||||
|
||||
if (bond.relayer == address(0)) revert BondNotFound();
|
||||
if (bond.slashed) revert BondAlreadySlashed();
|
||||
if (challenger == address(0)) revert ZeroRelayer();
|
||||
|
||||
// Mark bond as slashed
|
||||
bond.slashed = true;
|
||||
|
||||
uint256 bondAmount = bond.amount;
|
||||
|
||||
// Update relayer's total bonds
|
||||
totalBonds[bond.relayer] -= bondAmount;
|
||||
|
||||
// Split bond: 50% to challenger, 50% burned
|
||||
challengerReward = bondAmount / 2;
|
||||
burnedAmount = bondAmount - challengerReward; // Handle odd amounts
|
||||
|
||||
// Transfer to challenger
|
||||
(bool success1, ) = payable(challenger).call{value: challengerReward}("");
|
||||
require(success1, "BondManager: challenger transfer failed");
|
||||
|
||||
// Burn remaining amount (send to address(0))
|
||||
// Note: In practice, sending ETH to address(0) doesn't actually burn it,
|
||||
// but it makes the funds inaccessible. For true burning, consider using a burn mechanism.
|
||||
(bool success2, ) = payable(address(0)).call{value: burnedAmount}("");
|
||||
require(success2, "BondManager: burn transfer failed");
|
||||
|
||||
emit BondSlashed(
|
||||
depositId,
|
||||
bond.relayer,
|
||||
challenger,
|
||||
bondAmount,
|
||||
challengerReward,
|
||||
burnedAmount
|
||||
);
|
||||
|
||||
return (challengerReward, burnedAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Release bond after successful claim finalization
|
||||
* @param depositId Deposit ID associated with the bond
|
||||
* @return bondAmount Amount returned to relayer
|
||||
*/
|
||||
function releaseBond(
|
||||
uint256 depositId
|
||||
) external nonReentrant returns (uint256) {
|
||||
Bond storage bond = bonds[depositId];
|
||||
|
||||
if (bond.relayer == address(0)) revert BondNotFound();
|
||||
if (bond.slashed) revert BondAlreadySlashed();
|
||||
if (bond.released) revert BondAlreadyReleased();
|
||||
|
||||
// Mark bond as released
|
||||
bond.released = true;
|
||||
|
||||
uint256 bondAmount = bond.amount;
|
||||
address relayer = bond.relayer; // Cache to save gas
|
||||
|
||||
// Update relayer's total bonds
|
||||
totalBonds[relayer] -= bondAmount;
|
||||
|
||||
// Transfer bond back to relayer
|
||||
(bool success, ) = payable(relayer).call{value: bondAmount}("");
|
||||
require(success, "BondManager: release transfer failed");
|
||||
|
||||
emit BondReleased(depositId, relayer, bondAmount);
|
||||
|
||||
return bondAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Release multiple bonds in batch (gas optimization)
|
||||
* @param depositIds Array of deposit IDs to release bonds for
|
||||
* @return totalReleased Total amount released
|
||||
*/
|
||||
function releaseBondsBatch(uint256[] calldata depositIds) external nonReentrant returns (uint256 totalReleased) {
|
||||
uint256 length = depositIds.length;
|
||||
require(length > 0, "BondManager: empty array");
|
||||
require(length <= 50, "BondManager: batch too large"); // Prevent gas limit issues
|
||||
|
||||
for (uint256 i = 0; i < length; i++) {
|
||||
uint256 depositId = depositIds[i];
|
||||
if (depositId == 0) continue; // Skip zero IDs
|
||||
|
||||
Bond storage bond = bonds[depositId];
|
||||
if (bond.relayer == address(0)) continue; // Skip non-existent bonds
|
||||
if (bond.slashed) continue; // Skip slashed bonds
|
||||
if (bond.released) continue; // Skip already released
|
||||
|
||||
bond.released = true;
|
||||
uint256 bondAmount = bond.amount;
|
||||
address relayer = bond.relayer; // Cache to save gas
|
||||
|
||||
totalBonds[relayer] -= bondAmount;
|
||||
totalReleased += bondAmount;
|
||||
|
||||
(bool success, ) = payable(relayer).call{value: bondAmount}("");
|
||||
require(success, "BondManager: release transfer failed");
|
||||
|
||||
emit BondReleased(depositId, relayer, bondAmount);
|
||||
}
|
||||
|
||||
return totalReleased;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Calculate required bond amount for a deposit
|
||||
* @param depositAmount Amount of the deposit
|
||||
* @return requiredBond Minimum bond amount required
|
||||
*/
|
||||
function getRequiredBond(uint256 depositAmount) public view returns (uint256) {
|
||||
uint256 calculatedBond = (depositAmount * bondMultiplier) / 10000;
|
||||
return calculatedBond > minBond ? calculatedBond : minBond;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get bond information for a deposit
|
||||
* @param depositId Deposit ID to check
|
||||
* @return relayer Address that posted the bond
|
||||
* @return amount Bond amount
|
||||
* @return slashed Whether bond has been slashed
|
||||
* @return released Whether bond has been released
|
||||
*/
|
||||
function getBond(
|
||||
uint256 depositId
|
||||
) external view returns (
|
||||
address relayer,
|
||||
uint256 amount,
|
||||
bool slashed,
|
||||
bool released
|
||||
) {
|
||||
Bond memory bond = bonds[depositId];
|
||||
return (bond.relayer, bond.amount, bond.slashed, bond.released);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get total bonds posted by a relayer
|
||||
* @param relayer Address to check
|
||||
* @return Total amount of bonds posted
|
||||
*/
|
||||
function getTotalBonds(address relayer) external view returns (uint256) {
|
||||
return totalBonds[relayer];
|
||||
}
|
||||
|
||||
// Allow contract to receive ETH
|
||||
receive() external payable {}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "./InboxETH.sol";
|
||||
import "./LiquidityPoolETH.sol";
|
||||
import "./SwapRouter.sol";
|
||||
import "./ChallengeManager.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeSwapCoordinator
|
||||
* @notice Coordinates bridge release + swap in single transaction
|
||||
* @dev Verifies claim finalization, releases from liquidity pool, executes swap, transfers stablecoin
|
||||
*/
|
||||
contract BridgeSwapCoordinator is ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
InboxETH public immutable inbox;
|
||||
LiquidityPoolETH public immutable liquidityPool;
|
||||
SwapRouter public immutable swapRouter;
|
||||
ChallengeManager public immutable challengeManager;
|
||||
|
||||
event BridgeSwapExecuted(
|
||||
uint256 indexed depositId,
|
||||
address indexed recipient,
|
||||
LiquidityPoolETH.AssetType inputAsset,
|
||||
uint256 bridgeAmount,
|
||||
address stablecoinToken,
|
||||
uint256 stablecoinAmount
|
||||
);
|
||||
|
||||
error ZeroDepositId();
|
||||
error ZeroRecipient();
|
||||
error ClaimNotFinalized();
|
||||
error ClaimChallenged();
|
||||
error InsufficientOutput();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _inbox InboxETH contract address
|
||||
* @param _liquidityPool LiquidityPoolETH contract address
|
||||
* @param _swapRouter SwapRouter contract address
|
||||
* @param _challengeManager ChallengeManager contract address
|
||||
*/
|
||||
constructor(
|
||||
address _inbox,
|
||||
address _liquidityPool,
|
||||
address _swapRouter,
|
||||
address _challengeManager
|
||||
) {
|
||||
require(_inbox != address(0), "BridgeSwapCoordinator: zero inbox");
|
||||
require(_liquidityPool != address(0), "BridgeSwapCoordinator: zero liquidity pool");
|
||||
require(_swapRouter != address(0), "BridgeSwapCoordinator: zero swap router");
|
||||
require(_challengeManager != address(0), "BridgeSwapCoordinator: zero challenge manager");
|
||||
|
||||
inbox = InboxETH(payable(_inbox));
|
||||
liquidityPool = LiquidityPoolETH(payable(_liquidityPool));
|
||||
swapRouter = SwapRouter(payable(_swapRouter));
|
||||
challengeManager = ChallengeManager(payable(_challengeManager));
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute bridge release + swap to stablecoin
|
||||
* @param depositId Deposit ID
|
||||
* @param recipient Recipient address (should match claim recipient)
|
||||
* @param outputAsset Asset type from bridge (ETH or WETH)
|
||||
* @param stablecoinToken Target stablecoin address (USDT, USDC, or DAI)
|
||||
* @param amountOutMin Minimum stablecoin output (slippage protection)
|
||||
* @param routeData Optional route data for swap (for 1inch)
|
||||
* @return stablecoinAmount Amount of stablecoin received
|
||||
*/
|
||||
function bridgeAndSwap(
|
||||
uint256 depositId,
|
||||
address recipient,
|
||||
LiquidityPoolETH.AssetType outputAsset,
|
||||
address stablecoinToken,
|
||||
uint256 amountOutMin,
|
||||
bytes calldata routeData
|
||||
) external nonReentrant returns (uint256 stablecoinAmount) {
|
||||
if (depositId == 0) revert ZeroDepositId();
|
||||
if (recipient == address(0)) revert ZeroRecipient();
|
||||
|
||||
// Verify claim is finalized
|
||||
ChallengeManager.Claim memory claim = challengeManager.getClaim(depositId);
|
||||
if (claim.depositId == 0) revert("BridgeSwapCoordinator: claim not found");
|
||||
if (!claim.finalized) revert ClaimNotFinalized();
|
||||
if (claim.challenged) revert ClaimChallenged();
|
||||
if (claim.recipient != recipient) revert("BridgeSwapCoordinator: recipient mismatch");
|
||||
|
||||
// Use amount from claim (ChallengeManager has the claim data)
|
||||
uint256 bridgeAmount = claim.amount;
|
||||
|
||||
// Add pending claim (this should have been done during claim submission, but check anyway)
|
||||
// Note: In production, you'd want to track whether funds have already been released
|
||||
|
||||
// Release funds from liquidity pool to this contract
|
||||
liquidityPool.releaseToRecipient(depositId, address(this), bridgeAmount, outputAsset);
|
||||
|
||||
// Execute swap
|
||||
if (outputAsset == LiquidityPoolETH.AssetType.ETH) {
|
||||
// Swap ETH to stablecoin via SwapRouter
|
||||
stablecoinAmount = swapRouter.swapToStablecoin{value: bridgeAmount}(
|
||||
outputAsset,
|
||||
stablecoinToken,
|
||||
bridgeAmount,
|
||||
amountOutMin,
|
||||
routeData
|
||||
);
|
||||
} else {
|
||||
// WETH case: approve and swap
|
||||
// Get WETH address from liquidity pool
|
||||
address wethAddress = liquidityPool.getWeth();
|
||||
IERC20 wethToken = IERC20(wethAddress);
|
||||
wethToken.approve(address(swapRouter), bridgeAmount);
|
||||
|
||||
stablecoinAmount = swapRouter.swapToStablecoin(
|
||||
outputAsset,
|
||||
stablecoinToken,
|
||||
bridgeAmount,
|
||||
amountOutMin,
|
||||
routeData
|
||||
);
|
||||
}
|
||||
|
||||
if (stablecoinAmount < amountOutMin) revert InsufficientOutput();
|
||||
|
||||
// Transfer stablecoin to recipient
|
||||
IERC20(stablecoinToken).safeTransfer(recipient, stablecoinAmount);
|
||||
|
||||
// Note: Bond release should be handled separately after finalization
|
||||
// This coordinator only handles bridge release + swap
|
||||
|
||||
emit BridgeSwapExecuted(
|
||||
depositId,
|
||||
recipient,
|
||||
outputAsset,
|
||||
bridgeAmount,
|
||||
stablecoinToken,
|
||||
stablecoinAmount
|
||||
);
|
||||
|
||||
return stablecoinAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if claim can be swapped
|
||||
* @param depositId Deposit ID
|
||||
* @return canSwap_ True if claim can be swapped
|
||||
* @return reason Reason if cannot swap
|
||||
*/
|
||||
function canSwap(uint256 depositId) external view returns (bool canSwap_, string memory reason) {
|
||||
ChallengeManager.Claim memory claim = challengeManager.getClaim(depositId);
|
||||
|
||||
if (claim.depositId == 0) {
|
||||
return (false, "Claim not found");
|
||||
}
|
||||
if (!claim.finalized) {
|
||||
return (false, "Claim not finalized");
|
||||
}
|
||||
if (claim.challenged) {
|
||||
return (false, "Claim was challenged");
|
||||
}
|
||||
|
||||
return (true, "");
|
||||
}
|
||||
|
||||
// Allow contract to receive ETH
|
||||
receive() external payable {}
|
||||
}
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "./BondManager.sol";
|
||||
import "./libraries/MerkleProofVerifier.sol";
|
||||
import "./libraries/FraudProofTypes.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
/**
|
||||
* @title ChallengeManager
|
||||
* @notice Manages fraud proof challenges for trustless bridge claims
|
||||
* @dev Permissionless challenging mechanism with automated slashing on successful challenges
|
||||
*/
|
||||
contract ChallengeManager is ReentrancyGuard {
|
||||
BondManager public immutable bondManager;
|
||||
uint256 public immutable challengeWindow; // Challenge window duration in seconds
|
||||
|
||||
enum FraudProofType {
|
||||
NonExistentDeposit, // Deposit doesn't exist on source chain
|
||||
IncorrectAmount, // Amount mismatch
|
||||
IncorrectRecipient, // Recipient mismatch
|
||||
DoubleSpend // Deposit already claimed elsewhere
|
||||
}
|
||||
|
||||
struct Challenge {
|
||||
address challenger;
|
||||
uint256 depositId;
|
||||
FraudProofType proofType;
|
||||
bytes proof;
|
||||
uint256 timestamp;
|
||||
bool resolved;
|
||||
}
|
||||
|
||||
struct Claim {
|
||||
uint256 depositId; // Slot 0
|
||||
address asset; // Slot 1 (20 bytes) + 12 bytes padding
|
||||
address recipient; // Slot 2 (20 bytes) + 12 bytes padding
|
||||
uint256 amount; // Slot 3
|
||||
uint256 challengeWindowEnd; // Slot 4
|
||||
bool finalized; // Slot 5 (1 byte) + 31 bytes padding
|
||||
bool challenged; // Slot 6 (1 byte) + 31 bytes padding
|
||||
// Note: Could pack finalized and challenged in same slot, but keeping separate for clarity
|
||||
}
|
||||
|
||||
mapping(uint256 => Claim) public claims; // depositId => Claim
|
||||
mapping(uint256 => Challenge) public challenges; // depositId => Challenge
|
||||
|
||||
event ClaimSubmitted(
|
||||
uint256 indexed depositId,
|
||||
address indexed asset,
|
||||
uint256 amount,
|
||||
address indexed recipient,
|
||||
uint256 challengeWindowEnd
|
||||
);
|
||||
|
||||
event ClaimChallenged(
|
||||
uint256 indexed depositId,
|
||||
address indexed challenger,
|
||||
FraudProofType proofType
|
||||
);
|
||||
|
||||
event FraudProven(
|
||||
uint256 indexed depositId,
|
||||
address indexed challenger,
|
||||
FraudProofType proofType,
|
||||
uint256 slashedAmount
|
||||
);
|
||||
|
||||
event ChallengeRejected(
|
||||
uint256 indexed depositId,
|
||||
address indexed challenger
|
||||
);
|
||||
|
||||
event ClaimFinalized(
|
||||
uint256 indexed depositId
|
||||
);
|
||||
|
||||
error ZeroDepositId();
|
||||
error ClaimNotFound();
|
||||
error ClaimAlreadyFinalized();
|
||||
error ClaimAlreadyChallenged();
|
||||
error ChallengeWindowExpired();
|
||||
error ChallengeWindowNotExpired();
|
||||
error InvalidFraudProof();
|
||||
error ChallengeNotFound();
|
||||
error ChallengeAlreadyResolved();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _bondManager Address of BondManager contract
|
||||
* @param _challengeWindow Challenge window duration in seconds
|
||||
*/
|
||||
constructor(address _bondManager, uint256 _challengeWindow) {
|
||||
require(_bondManager != address(0), "ChallengeManager: zero bond manager");
|
||||
require(_challengeWindow > 0, "ChallengeManager: zero challenge window");
|
||||
bondManager = BondManager(payable(_bondManager));
|
||||
challengeWindow = _challengeWindow;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a claim (called by InboxETH)
|
||||
* @param depositId Deposit ID from source chain
|
||||
* @param asset Asset address (address(0) for native ETH)
|
||||
* @param amount Deposit amount
|
||||
* @param recipient Recipient address
|
||||
*/
|
||||
function registerClaim(
|
||||
uint256 depositId,
|
||||
address asset,
|
||||
uint256 amount,
|
||||
address recipient
|
||||
) external {
|
||||
if (depositId == 0) revert ZeroDepositId();
|
||||
|
||||
// Only allow one claim per deposit ID
|
||||
require(claims[depositId].depositId == 0, "ChallengeManager: claim already registered");
|
||||
|
||||
uint256 challengeWindowEnd = block.timestamp + challengeWindow;
|
||||
|
||||
claims[depositId] = Claim({
|
||||
depositId: depositId,
|
||||
asset: asset,
|
||||
amount: amount,
|
||||
recipient: recipient,
|
||||
challengeWindowEnd: challengeWindowEnd,
|
||||
finalized: false,
|
||||
challenged: false
|
||||
});
|
||||
|
||||
emit ClaimSubmitted(depositId, asset, amount, recipient, challengeWindowEnd);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Challenge a claim with fraud proof
|
||||
* @param depositId Deposit ID of the claim to challenge
|
||||
* @param proofType Type of fraud proof
|
||||
* @param proof Fraud proof data (format depends on proofType)
|
||||
*/
|
||||
function challengeClaim(
|
||||
uint256 depositId,
|
||||
FraudProofType proofType,
|
||||
bytes calldata proof
|
||||
) external nonReentrant {
|
||||
if (depositId == 0) revert ZeroDepositId();
|
||||
|
||||
Claim storage claim = claims[depositId];
|
||||
if (claim.depositId == 0) revert ClaimNotFound();
|
||||
if (claim.finalized) revert ClaimAlreadyFinalized();
|
||||
if (claim.challenged) revert ClaimAlreadyChallenged();
|
||||
if (block.timestamp > claim.challengeWindowEnd) revert ChallengeWindowExpired();
|
||||
|
||||
// Verify fraud proof (pass storage reference to save gas)
|
||||
if (!_verifyFraudProof(depositId, claim, proofType, proof)) {
|
||||
revert InvalidFraudProof();
|
||||
}
|
||||
|
||||
// Mark claim as challenged
|
||||
claim.challenged = true;
|
||||
|
||||
// Store challenge
|
||||
challenges[depositId] = Challenge({
|
||||
challenger: msg.sender,
|
||||
depositId: depositId,
|
||||
proofType: proofType,
|
||||
proof: proof,
|
||||
timestamp: block.timestamp,
|
||||
resolved: false
|
||||
});
|
||||
|
||||
emit ClaimChallenged(depositId, msg.sender, proofType);
|
||||
|
||||
// Automatically slash bond and mark challenge as resolved
|
||||
(uint256 challengerReward, ) = bondManager.slashBond(depositId, msg.sender);
|
||||
|
||||
challenges[depositId].resolved = true;
|
||||
|
||||
emit FraudProven(depositId, msg.sender, proofType, challengerReward * 2); // Total slashed amount
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Finalize a claim after challenge window expires without challenge
|
||||
* @param depositId Deposit ID to finalize
|
||||
*/
|
||||
function finalizeClaim(uint256 depositId) external {
|
||||
if (depositId == 0) revert ZeroDepositId();
|
||||
|
||||
Claim storage claim = claims[depositId];
|
||||
if (claim.depositId == 0) revert ClaimNotFound();
|
||||
if (claim.finalized) revert ClaimAlreadyFinalized();
|
||||
if (claim.challenged) revert ClaimAlreadyChallenged();
|
||||
if (block.timestamp <= claim.challengeWindowEnd) revert ChallengeWindowNotExpired();
|
||||
|
||||
claim.finalized = true;
|
||||
|
||||
emit ClaimFinalized(depositId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Finalize multiple claims in batch (gas optimization)
|
||||
* @param depositIds Array of deposit IDs to finalize
|
||||
*/
|
||||
function finalizeClaimsBatch(uint256[] calldata depositIds) external {
|
||||
uint256 length = depositIds.length;
|
||||
require(length > 0, "ChallengeManager: empty array");
|
||||
require(length <= 50, "ChallengeManager: batch too large"); // Prevent gas limit issues
|
||||
|
||||
for (uint256 i = 0; i < length; i++) {
|
||||
uint256 depositId = depositIds[i];
|
||||
if (depositId == 0) continue; // Skip zero IDs
|
||||
|
||||
Claim storage claim = claims[depositId];
|
||||
if (claim.depositId == 0) continue; // Skip non-existent claims
|
||||
if (claim.finalized) continue; // Skip already finalized
|
||||
if (claim.challenged) continue; // Skip challenged claims
|
||||
if (block.timestamp <= claim.challengeWindowEnd) continue; // Skip if window not expired
|
||||
|
||||
claim.finalized = true;
|
||||
emit ClaimFinalized(depositId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify fraud proof (internal function)
|
||||
* @dev Verifies fraud proofs against source chain state using Merkle proofs
|
||||
* @param depositId Deposit ID
|
||||
* @param claim Claim data
|
||||
* @param proofType Type of fraud proof
|
||||
* @param proof Proof data (encoded according to proofType)
|
||||
* @return True if fraud proof is valid
|
||||
*/
|
||||
function _verifyFraudProof(
|
||||
uint256 depositId,
|
||||
Claim storage claim, // Changed to storage to save gas
|
||||
FraudProofType proofType,
|
||||
bytes calldata proof
|
||||
) internal view returns (bool) {
|
||||
if (proof.length == 0) return false;
|
||||
|
||||
if (proofType == FraudProofType.NonExistentDeposit) {
|
||||
return _verifyNonExistentDeposit(depositId, claim, proof);
|
||||
} else if (proofType == FraudProofType.IncorrectAmount) {
|
||||
return _verifyIncorrectAmount(depositId, claim, proof);
|
||||
} else if (proofType == FraudProofType.IncorrectRecipient) {
|
||||
return _verifyIncorrectRecipient(depositId, claim, proof);
|
||||
} else if (proofType == FraudProofType.DoubleSpend) {
|
||||
return _verifyDoubleSpend(depositId, claim, proof);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify non-existent deposit fraud proof
|
||||
* @param depositId Deposit ID
|
||||
* @param claim Claim data
|
||||
* @param proof Encoded NonExistentDepositProof
|
||||
* @return True if proof is valid
|
||||
*/
|
||||
function _verifyNonExistentDeposit(
|
||||
uint256 depositId,
|
||||
Claim storage claim, // Changed to storage to save gas
|
||||
bytes calldata proof
|
||||
) internal view returns (bool) {
|
||||
FraudProofTypes.NonExistentDepositProof memory fraudProof =
|
||||
FraudProofTypes.decodeNonExistentDeposit(proof);
|
||||
|
||||
// Verify state root against block header
|
||||
if (!MerkleProofVerifier.verifyStateRoot(fraudProof.blockHeader, fraudProof.stateRoot)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Hash the claimed deposit data
|
||||
bytes32 claimedDepositHash = MerkleProofVerifier.hashDepositData(
|
||||
depositId,
|
||||
claim.asset,
|
||||
claim.amount,
|
||||
claim.recipient,
|
||||
block.timestamp // Note: In production, use actual deposit timestamp from source chain
|
||||
);
|
||||
|
||||
// Verify that the claimed deposit hash matches the proof
|
||||
if (claimedDepositHash != fraudProof.depositHash) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify non-existence proof (deposit doesn't exist in Merkle tree)
|
||||
return MerkleProofVerifier.verifyDepositNonExistence(
|
||||
fraudProof.stateRoot,
|
||||
fraudProof.depositHash,
|
||||
fraudProof.merkleProof,
|
||||
fraudProof.leftSibling,
|
||||
fraudProof.rightSibling
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify incorrect amount fraud proof
|
||||
* @param depositId Deposit ID
|
||||
* @param claim Claim data
|
||||
* @param proof Encoded IncorrectAmountProof
|
||||
* @return True if proof is valid
|
||||
*/
|
||||
function _verifyIncorrectAmount(
|
||||
uint256 depositId,
|
||||
Claim storage claim, // Changed to storage to save gas
|
||||
bytes calldata proof
|
||||
) internal view returns (bool) {
|
||||
FraudProofTypes.IncorrectAmountProof memory fraudProof =
|
||||
FraudProofTypes.decodeIncorrectAmount(proof);
|
||||
|
||||
// Verify state root against block header
|
||||
if (!MerkleProofVerifier.verifyStateRoot(fraudProof.blockHeader, fraudProof.stateRoot)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify that actual amount differs from claimed amount
|
||||
if (fraudProof.actualAmount == claim.amount) {
|
||||
return false; // Amounts match, not a fraud
|
||||
}
|
||||
|
||||
// Hash the actual deposit data
|
||||
bytes32 actualDepositHash = MerkleProofVerifier.hashDepositData(
|
||||
depositId,
|
||||
claim.asset,
|
||||
fraudProof.actualAmount,
|
||||
claim.recipient,
|
||||
block.timestamp // Note: In production, use actual deposit timestamp
|
||||
);
|
||||
|
||||
// Verify Merkle proof for actual deposit
|
||||
return MerkleProofVerifier.verifyDepositExistence(
|
||||
fraudProof.stateRoot,
|
||||
actualDepositHash,
|
||||
fraudProof.merkleProof
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify incorrect recipient fraud proof
|
||||
* @param depositId Deposit ID
|
||||
* @param claim Claim data
|
||||
* @param proof Encoded IncorrectRecipientProof
|
||||
* @return True if proof is valid
|
||||
*/
|
||||
function _verifyIncorrectRecipient(
|
||||
uint256 depositId,
|
||||
Claim storage claim, // Changed to storage to save gas
|
||||
bytes calldata proof
|
||||
) internal view returns (bool) {
|
||||
FraudProofTypes.IncorrectRecipientProof memory fraudProof =
|
||||
FraudProofTypes.decodeIncorrectRecipient(proof);
|
||||
|
||||
// Verify state root against block header
|
||||
if (!MerkleProofVerifier.verifyStateRoot(fraudProof.blockHeader, fraudProof.stateRoot)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify that actual recipient differs from claimed recipient
|
||||
if (fraudProof.actualRecipient == claim.recipient) {
|
||||
return false; // Recipients match, not a fraud
|
||||
}
|
||||
|
||||
// Hash the actual deposit data
|
||||
bytes32 actualDepositHash = MerkleProofVerifier.hashDepositData(
|
||||
depositId,
|
||||
claim.asset,
|
||||
claim.amount,
|
||||
fraudProof.actualRecipient,
|
||||
block.timestamp // Note: In production, use actual deposit timestamp
|
||||
);
|
||||
|
||||
// Verify Merkle proof for actual deposit
|
||||
return MerkleProofVerifier.verifyDepositExistence(
|
||||
fraudProof.stateRoot,
|
||||
actualDepositHash,
|
||||
fraudProof.merkleProof
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify double spend fraud proof
|
||||
* @param depositId Deposit ID
|
||||
* @param claim Claim data
|
||||
* @param proof Encoded DoubleSpendProof
|
||||
* @return True if proof is valid
|
||||
*/
|
||||
function _verifyDoubleSpend(
|
||||
uint256 depositId,
|
||||
Claim storage claim, // Changed to storage to save gas
|
||||
bytes calldata proof
|
||||
) internal view returns (bool) {
|
||||
FraudProofTypes.DoubleSpendProof memory fraudProof =
|
||||
FraudProofTypes.decodeDoubleSpend(proof);
|
||||
|
||||
// Verify that the previous claim ID is different (same deposit claimed twice)
|
||||
if (fraudProof.previousClaimId == depositId) {
|
||||
// Check if previous claim exists and is finalized (use storage to save gas)
|
||||
Claim storage previousClaim = claims[fraudProof.previousClaimId];
|
||||
if (previousClaim.depositId == 0 || !previousClaim.finalized) {
|
||||
return false; // Previous claim doesn't exist or isn't finalized
|
||||
}
|
||||
|
||||
// Verify that the deposit data matches (same deposit, different claim)
|
||||
if (
|
||||
previousClaim.asset == claim.asset &&
|
||||
previousClaim.amount == claim.amount &&
|
||||
previousClaim.recipient == claim.recipient
|
||||
) {
|
||||
return true; // Double spend detected
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if a claim can be finalized
|
||||
* @param depositId Deposit ID to check
|
||||
* @return canFinalize_ True if claim can be finalized
|
||||
* @return reason Reason if cannot finalize
|
||||
*/
|
||||
function canFinalize(uint256 depositId) external view returns (bool canFinalize_, string memory reason) {
|
||||
Claim memory claim = claims[depositId];
|
||||
|
||||
if (claim.depositId == 0) {
|
||||
return (false, "Claim not found");
|
||||
}
|
||||
if (claim.finalized) {
|
||||
return (false, "Already finalized");
|
||||
}
|
||||
if (claim.challenged) {
|
||||
return (false, "Claim was challenged");
|
||||
}
|
||||
if (block.timestamp <= claim.challengeWindowEnd) {
|
||||
return (false, "Challenge window not expired");
|
||||
}
|
||||
|
||||
return (true, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get claim information
|
||||
* @param depositId Deposit ID
|
||||
* @return Claim data
|
||||
*/
|
||||
function getClaim(uint256 depositId) external view returns (Claim memory) {
|
||||
return claims[depositId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get challenge information
|
||||
* @param depositId Deposit ID
|
||||
* @return Challenge data
|
||||
*/
|
||||
function getChallenge(uint256 depositId) external view returns (Challenge memory) {
|
||||
return challenges[depositId];
|
||||
}
|
||||
}
|
||||
+689
@@ -0,0 +1,689 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/access/AccessControl.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "./LiquidityPoolETH.sol";
|
||||
import "./interfaces/ISwapRouter.sol";
|
||||
import "./interfaces/ICurvePool.sol";
|
||||
import "./interfaces/IAggregationRouter.sol";
|
||||
import "./interfaces/IDodoexRouter.sol";
|
||||
import "./interfaces/IBalancerVault.sol";
|
||||
import "./interfaces/IWETH.sol";
|
||||
|
||||
/**
|
||||
* @title EnhancedSwapRouter
|
||||
* @notice Multi-protocol swap router with intelligent routing and decision logic
|
||||
* @dev Supports Uniswap V3, Curve, Dodoex PMM, Balancer, and 1inch aggregation
|
||||
*/
|
||||
contract EnhancedSwapRouter is AccessControl, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
bytes32 public constant COORDINATOR_ROLE = keccak256("COORDINATOR_ROLE");
|
||||
bytes32 public constant ROUTING_MANAGER_ROLE = keccak256("ROUTING_MANAGER_ROLE");
|
||||
|
||||
enum SwapProvider {
|
||||
UniswapV3,
|
||||
Curve,
|
||||
Dodoex,
|
||||
Balancer,
|
||||
OneInch
|
||||
}
|
||||
|
||||
// Protocol addresses
|
||||
address public immutable uniswapV3Router;
|
||||
address public immutable curve3Pool;
|
||||
address public immutable dodoexRouter;
|
||||
address public immutable balancerVault;
|
||||
address public immutable oneInchRouter;
|
||||
|
||||
// Token addresses
|
||||
address public immutable weth;
|
||||
address public immutable usdt;
|
||||
address public immutable usdc;
|
||||
address public immutable dai;
|
||||
|
||||
// Routing configuration
|
||||
struct RoutingConfig {
|
||||
SwapProvider[] providers; // Ordered list of providers to try
|
||||
uint256[] sizeThresholds; // Size thresholds in wei
|
||||
bool enabled;
|
||||
}
|
||||
|
||||
mapping(SwapProvider => bool) public providerEnabled;
|
||||
mapping(uint256 => RoutingConfig) public sizeBasedRouting; // size category => config
|
||||
uint256 public constant SMALL_SWAP_THRESHOLD = 10_000 * 1e18; // $10k
|
||||
uint256 public constant MEDIUM_SWAP_THRESHOLD = 100_000 * 1e18; // $100k
|
||||
|
||||
// Uniswap V3 fee tiers
|
||||
uint24 public constant FEE_TIER_LOW = 500;
|
||||
uint24 public constant FEE_TIER_MEDIUM = 3000;
|
||||
uint24 public constant FEE_TIER_HIGH = 10000;
|
||||
|
||||
// Balancer pool IDs (example - would be set via admin)
|
||||
mapping(address => mapping(address => bytes32)) public balancerPoolIds; // tokenIn => tokenOut => poolId
|
||||
|
||||
// Dodoex PMM pool addresses (tokenIn => tokenOut => PMM pool address)
|
||||
mapping(address => mapping(address => address)) public dodoPoolAddresses;
|
||||
|
||||
/// @dev Uniswap V3 Quoter for on-chain quotes; set via setUniswapQuoter when deployed on 138/651940
|
||||
address public uniswapQuoter;
|
||||
|
||||
event SwapExecuted(
|
||||
SwapProvider indexed provider,
|
||||
LiquidityPoolETH.AssetType indexed inputAsset,
|
||||
address indexed tokenIn,
|
||||
address tokenOut,
|
||||
uint256 amountIn,
|
||||
uint256 amountOut,
|
||||
uint256 gasUsed
|
||||
);
|
||||
|
||||
event RoutingConfigUpdated(uint256 sizeCategory, SwapProvider[] providers);
|
||||
event ProviderToggled(SwapProvider provider, bool enabled);
|
||||
|
||||
error ZeroAddress();
|
||||
error ZeroAmount();
|
||||
error SwapFailed();
|
||||
error InvalidProvider();
|
||||
error ProviderDisabled();
|
||||
error InsufficientOutput();
|
||||
error InvalidRoutingConfig();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _uniswapV3Router Uniswap V3 SwapRouter address
|
||||
* @param _curve3Pool Curve 3pool address
|
||||
* @param _dodoexRouter Dodoex Router address
|
||||
* @param _balancerVault Balancer Vault address
|
||||
* @param _oneInchRouter 1inch Router address (can be address(0))
|
||||
* @param _weth WETH address
|
||||
* @param _usdt USDT address
|
||||
* @param _usdc USDC address
|
||||
* @param _dai DAI address
|
||||
*/
|
||||
constructor(
|
||||
address _uniswapV3Router,
|
||||
address _curve3Pool,
|
||||
address _dodoexRouter,
|
||||
address _balancerVault,
|
||||
address _oneInchRouter,
|
||||
address _weth,
|
||||
address _usdt,
|
||||
address _usdc,
|
||||
address _dai
|
||||
) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
|
||||
|
||||
if (_uniswapV3Router == address(0) || _curve3Pool == address(0) ||
|
||||
_dodoexRouter == address(0) || _balancerVault == address(0) ||
|
||||
_weth == address(0) || _usdt == address(0) || _usdc == address(0) || _dai == address(0)) {
|
||||
revert ZeroAddress();
|
||||
}
|
||||
|
||||
uniswapV3Router = _uniswapV3Router;
|
||||
curve3Pool = _curve3Pool;
|
||||
dodoexRouter = _dodoexRouter;
|
||||
balancerVault = _balancerVault;
|
||||
oneInchRouter = _oneInchRouter;
|
||||
weth = _weth;
|
||||
usdt = _usdt;
|
||||
usdc = _usdc;
|
||||
dai = _dai;
|
||||
|
||||
// Enable all providers by default
|
||||
providerEnabled[SwapProvider.UniswapV3] = true;
|
||||
providerEnabled[SwapProvider.Curve] = true;
|
||||
providerEnabled[SwapProvider.Dodoex] = true;
|
||||
providerEnabled[SwapProvider.Balancer] = true;
|
||||
if (_oneInchRouter != address(0)) {
|
||||
providerEnabled[SwapProvider.OneInch] = true;
|
||||
}
|
||||
|
||||
// Initialize default routing configs
|
||||
_initializeDefaultRouting();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Swap to stablecoin using intelligent routing
|
||||
* @param inputAsset Input asset type (ETH or WETH)
|
||||
* @param stablecoinToken Target stablecoin
|
||||
* @param amountIn Input amount
|
||||
* @param amountOutMin Minimum output (slippage protection)
|
||||
* @param preferredProvider Optional preferred provider (0 = auto-select)
|
||||
* @return amountOut Output amount
|
||||
* @return providerUsed Provider that executed the swap
|
||||
*/
|
||||
function swapToStablecoin(
|
||||
LiquidityPoolETH.AssetType inputAsset,
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin,
|
||||
SwapProvider preferredProvider
|
||||
) external payable nonReentrant returns (uint256 amountOut, SwapProvider providerUsed) {
|
||||
if (amountIn == 0) revert ZeroAmount();
|
||||
if (stablecoinToken == address(0)) revert ZeroAddress();
|
||||
if (!_isValidStablecoin(stablecoinToken)) revert("EnhancedSwapRouter: invalid stablecoin");
|
||||
|
||||
// Convert ETH to WETH if needed
|
||||
if (inputAsset == LiquidityPoolETH.AssetType.ETH) {
|
||||
require(msg.value == amountIn, "EnhancedSwapRouter: ETH amount mismatch");
|
||||
IWETH(weth).deposit{value: amountIn}();
|
||||
}
|
||||
|
||||
// Get routing providers based on swap size
|
||||
SwapProvider[] memory providers = _getRoutingProviders(amountIn, preferredProvider);
|
||||
|
||||
// Try each provider in order
|
||||
for (uint256 i = 0; i < providers.length; i++) {
|
||||
if (!providerEnabled[providers[i]]) continue;
|
||||
|
||||
try this._executeSwap(
|
||||
providers[i],
|
||||
stablecoinToken,
|
||||
amountIn,
|
||||
amountOutMin
|
||||
) returns (uint256 output) {
|
||||
if (output >= amountOutMin) {
|
||||
// Transfer output to caller
|
||||
IERC20(stablecoinToken).safeTransfer(msg.sender, output);
|
||||
|
||||
emit SwapExecuted(
|
||||
providers[i],
|
||||
inputAsset,
|
||||
weth,
|
||||
stablecoinToken,
|
||||
amountIn,
|
||||
output,
|
||||
gasleft()
|
||||
);
|
||||
|
||||
return (output, providers[i]);
|
||||
}
|
||||
} catch {
|
||||
// Try next provider
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
revert SwapFailed();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get quote from all enabled providers
|
||||
* @param stablecoinToken Target stablecoin
|
||||
* @param amountIn Input amount
|
||||
* @return providers Array of providers that returned quotes
|
||||
* @return amounts Array of output amounts for each provider
|
||||
*/
|
||||
function getQuotes(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn
|
||||
) external view returns (SwapProvider[] memory providers, uint256[] memory amounts) {
|
||||
SwapProvider[] memory enabledProviders = new SwapProvider[](5);
|
||||
uint256[] memory quotes = new uint256[](5);
|
||||
uint256 count = 0;
|
||||
|
||||
// Query each enabled provider
|
||||
if (providerEnabled[SwapProvider.UniswapV3]) {
|
||||
try this._getUniswapV3Quote(stablecoinToken, amountIn) returns (uint256 quote) {
|
||||
enabledProviders[count] = SwapProvider.UniswapV3;
|
||||
quotes[count] = quote;
|
||||
count++;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (providerEnabled[SwapProvider.Dodoex]) {
|
||||
try this._getDodoexQuote(stablecoinToken, amountIn) returns (uint256 quote) {
|
||||
enabledProviders[count] = SwapProvider.Dodoex;
|
||||
quotes[count] = quote;
|
||||
count++;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (providerEnabled[SwapProvider.Balancer]) {
|
||||
try this._getBalancerQuote(stablecoinToken, amountIn) returns (uint256 quote) {
|
||||
enabledProviders[count] = SwapProvider.Balancer;
|
||||
quotes[count] = quote;
|
||||
count++;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Resize arrays
|
||||
SwapProvider[] memory resultProviders = new SwapProvider[](count);
|
||||
uint256[] memory resultQuotes = new uint256[](count);
|
||||
for (uint256 i = 0; i < count; i++) {
|
||||
resultProviders[i] = enabledProviders[i];
|
||||
resultQuotes[i] = quotes[i];
|
||||
}
|
||||
|
||||
return (resultProviders, resultQuotes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set routing configuration for a size category
|
||||
* @param sizeCategory 0 = small, 1 = medium, 2 = large
|
||||
* @param providers Ordered list of providers to try
|
||||
*/
|
||||
function setRoutingConfig(
|
||||
uint256 sizeCategory,
|
||||
SwapProvider[] calldata providers
|
||||
) external onlyRole(ROUTING_MANAGER_ROLE) {
|
||||
require(sizeCategory < 3, "EnhancedSwapRouter: invalid size category");
|
||||
require(providers.length > 0, "EnhancedSwapRouter: empty providers");
|
||||
|
||||
sizeBasedRouting[sizeCategory] = RoutingConfig({
|
||||
providers: providers,
|
||||
sizeThresholds: new uint256[](0),
|
||||
enabled: true
|
||||
});
|
||||
|
||||
emit RoutingConfigUpdated(sizeCategory, providers);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Toggle provider on/off
|
||||
* @param provider Provider to toggle
|
||||
* @param enabled Whether to enable
|
||||
*/
|
||||
function setProviderEnabled(
|
||||
SwapProvider provider,
|
||||
bool enabled
|
||||
) external onlyRole(ROUTING_MANAGER_ROLE) {
|
||||
providerEnabled[provider] = enabled;
|
||||
emit ProviderToggled(provider, enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set Balancer pool ID for a token pair
|
||||
* @param tokenIn Input token
|
||||
* @param tokenOut Output token
|
||||
* @param poolId Balancer pool ID
|
||||
*/
|
||||
function setBalancerPoolId(
|
||||
address tokenIn,
|
||||
address tokenOut,
|
||||
bytes32 poolId
|
||||
) external onlyRole(ROUTING_MANAGER_ROLE) {
|
||||
balancerPoolIds[tokenIn][tokenOut] = poolId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set Dodoex PMM pool address for a token pair
|
||||
* @param tokenIn Input token
|
||||
* @param tokenOut Output token
|
||||
* @param poolAddress Dodo PMM pool address
|
||||
*/
|
||||
function setDodoPoolAddress(
|
||||
address tokenIn,
|
||||
address tokenOut,
|
||||
address poolAddress
|
||||
) external onlyRole(ROUTING_MANAGER_ROLE) {
|
||||
dodoPoolAddresses[tokenIn][tokenOut] = poolAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set Uniswap V3 Quoter address for on-chain quotes
|
||||
* @param _quoter Quoter contract address (address(0) to use 0.5% slippage estimate)
|
||||
*/
|
||||
function setUniswapQuoter(address _quoter) external onlyRole(ROUTING_MANAGER_ROLE) {
|
||||
uniswapQuoter = _quoter;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Swap arbitrary token pair via Dodoex when pool is configured
|
||||
* @param tokenIn Input token
|
||||
* @param tokenOut Output token
|
||||
* @param amountIn Input amount
|
||||
* @param amountOutMin Minimum output (slippage protection)
|
||||
* @return amountOut Output amount
|
||||
*/
|
||||
function swapTokenToToken(
|
||||
address tokenIn,
|
||||
address tokenOut,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) external nonReentrant returns (uint256 amountOut) {
|
||||
if (amountIn == 0) revert ZeroAmount();
|
||||
if (tokenIn == address(0) || tokenOut == address(0)) revert ZeroAddress();
|
||||
address pool = dodoPoolAddresses[tokenIn][tokenOut];
|
||||
require(pool != address(0), "EnhancedSwapRouter: Dodoex pool not configured");
|
||||
|
||||
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
|
||||
IERC20(tokenIn).approve(dodoexRouter, amountIn);
|
||||
|
||||
address[] memory dodoPairs = new address[](1);
|
||||
dodoPairs[0] = pool;
|
||||
|
||||
IDodoexRouter.DodoSwapParams memory params = IDodoexRouter.DodoSwapParams({
|
||||
fromToken: tokenIn,
|
||||
toToken: tokenOut,
|
||||
fromTokenAmount: amountIn,
|
||||
minReturnAmount: amountOutMin,
|
||||
dodoPairs: dodoPairs,
|
||||
directions: 0,
|
||||
isIncentive: false,
|
||||
deadLine: block.timestamp + 300
|
||||
});
|
||||
|
||||
amountOut = IDodoexRouter(dodoexRouter).dodoSwapV2TokenToToken(params);
|
||||
require(amountOut >= amountOutMin, "EnhancedSwapRouter: insufficient output");
|
||||
IERC20(tokenOut).safeTransfer(msg.sender, amountOut);
|
||||
return amountOut;
|
||||
}
|
||||
|
||||
// ============ Internal Functions ============
|
||||
|
||||
/**
|
||||
* @notice Execute swap via specified provider
|
||||
*/
|
||||
function _executeSwap(
|
||||
SwapProvider provider,
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) external returns (uint256) {
|
||||
require(msg.sender == address(this), "EnhancedSwapRouter: internal only");
|
||||
|
||||
if (provider == SwapProvider.UniswapV3) {
|
||||
return _executeUniswapV3Swap(stablecoinToken, amountIn, amountOutMin);
|
||||
} else if (provider == SwapProvider.Dodoex) {
|
||||
return _executeDodoexSwap(stablecoinToken, amountIn, amountOutMin);
|
||||
} else if (provider == SwapProvider.Balancer) {
|
||||
return _executeBalancerSwap(stablecoinToken, amountIn, amountOutMin);
|
||||
} else if (provider == SwapProvider.Curve) {
|
||||
return _executeCurveSwap(stablecoinToken, amountIn, amountOutMin);
|
||||
} else if (provider == SwapProvider.OneInch && oneInchRouter != address(0)) {
|
||||
return _execute1inchSwap(stablecoinToken, amountIn, amountOutMin);
|
||||
}
|
||||
|
||||
revert InvalidProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get routing providers based on swap size
|
||||
*/
|
||||
function _getRoutingProviders(
|
||||
uint256 amountIn,
|
||||
SwapProvider preferredProvider
|
||||
) internal view returns (SwapProvider[] memory) {
|
||||
// If preferred provider is specified and enabled, use it first
|
||||
if (preferredProvider != SwapProvider.UniswapV3 && providerEnabled[preferredProvider]) {
|
||||
SwapProvider[] memory providers = new SwapProvider[](1);
|
||||
providers[0] = preferredProvider;
|
||||
return providers;
|
||||
}
|
||||
|
||||
// Determine size category
|
||||
uint256 category;
|
||||
if (amountIn < SMALL_SWAP_THRESHOLD) {
|
||||
category = 0; // Small
|
||||
} else if (amountIn < MEDIUM_SWAP_THRESHOLD) {
|
||||
category = 1; // Medium
|
||||
} else {
|
||||
category = 2; // Large
|
||||
}
|
||||
|
||||
RoutingConfig memory config = sizeBasedRouting[category];
|
||||
if (config.enabled && config.providers.length > 0) {
|
||||
return config.providers;
|
||||
}
|
||||
|
||||
// Default fallback routing
|
||||
SwapProvider[] memory defaultProviders = new SwapProvider[](5);
|
||||
defaultProviders[0] = SwapProvider.Dodoex;
|
||||
defaultProviders[1] = SwapProvider.UniswapV3;
|
||||
defaultProviders[2] = SwapProvider.Balancer;
|
||||
defaultProviders[3] = SwapProvider.Curve;
|
||||
defaultProviders[4] = SwapProvider.OneInch;
|
||||
return defaultProviders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute Uniswap V3 swap
|
||||
*/
|
||||
function _executeUniswapV3Swap(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) internal returns (uint256) {
|
||||
// Approve for swap
|
||||
IERC20 wethToken = IERC20(weth);
|
||||
wethToken.approve(uniswapV3Router, amountIn);
|
||||
|
||||
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
|
||||
tokenIn: weth,
|
||||
tokenOut: stablecoinToken,
|
||||
fee: FEE_TIER_MEDIUM,
|
||||
recipient: address(this),
|
||||
deadline: block.timestamp + 300,
|
||||
amountIn: amountIn,
|
||||
amountOutMinimum: amountOutMin,
|
||||
sqrtPriceLimitX96: 0
|
||||
});
|
||||
|
||||
return ISwapRouter(uniswapV3Router).exactInputSingle(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute Dodoex PMM swap
|
||||
*/
|
||||
function _executeDodoexSwap(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) internal returns (uint256) {
|
||||
address pool = dodoPoolAddresses[weth][stablecoinToken];
|
||||
require(pool != address(0), "EnhancedSwapRouter: Dodoex pool not configured");
|
||||
|
||||
IERC20 wethToken = IERC20(weth);
|
||||
wethToken.approve(dodoexRouter, amountIn);
|
||||
|
||||
address[] memory dodoPairs = new address[](1);
|
||||
dodoPairs[0] = pool;
|
||||
|
||||
IDodoexRouter.DodoSwapParams memory params = IDodoexRouter.DodoSwapParams({
|
||||
fromToken: weth,
|
||||
toToken: stablecoinToken,
|
||||
fromTokenAmount: amountIn,
|
||||
minReturnAmount: amountOutMin,
|
||||
dodoPairs: dodoPairs,
|
||||
directions: 0,
|
||||
isIncentive: false,
|
||||
deadLine: block.timestamp + 300
|
||||
});
|
||||
|
||||
return IDodoexRouter(dodoexRouter).dodoSwapV2TokenToToken(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute Balancer swap
|
||||
*/
|
||||
function _executeBalancerSwap(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) internal returns (uint256) {
|
||||
bytes32 poolId = balancerPoolIds[weth][stablecoinToken];
|
||||
require(poolId != bytes32(0), "EnhancedSwapRouter: pool not configured");
|
||||
|
||||
IERC20 wethToken = IERC20(weth);
|
||||
wethToken.approve(balancerVault, amountIn);
|
||||
|
||||
IBalancerVault.SingleSwap memory singleSwap = IBalancerVault.SingleSwap({
|
||||
poolId: poolId,
|
||||
kind: IBalancerVault.SwapKind.GIVEN_IN,
|
||||
assetIn: weth,
|
||||
assetOut: stablecoinToken,
|
||||
amount: amountIn,
|
||||
userData: ""
|
||||
});
|
||||
|
||||
IBalancerVault.FundManagement memory funds = IBalancerVault.FundManagement({
|
||||
sender: address(this),
|
||||
fromInternalBalance: false,
|
||||
recipient: payable(address(this)),
|
||||
toInternalBalance: false
|
||||
});
|
||||
|
||||
return IBalancerVault(balancerVault).swap(
|
||||
singleSwap,
|
||||
funds,
|
||||
amountOutMin,
|
||||
block.timestamp + 300
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute Curve swap
|
||||
*/
|
||||
function _executeCurveSwap(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) internal returns (uint256) {
|
||||
// Curve 3pool doesn't support WETH directly
|
||||
// Would need intermediate swap or different pool
|
||||
revert("EnhancedSwapRouter: Curve direct swap not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute 1inch swap
|
||||
*/
|
||||
function _execute1inchSwap(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) internal returns (uint256) {
|
||||
if (oneInchRouter == address(0)) revert ProviderDisabled();
|
||||
|
||||
IERC20 wethToken = IERC20(weth);
|
||||
wethToken.approve(oneInchRouter, amountIn);
|
||||
|
||||
// 1inch: requires route data from 1inch API (e.g. /swap/v5.2/138/swap). Use 1inch SDK or API to get calldata and execute separately.
|
||||
revert("EnhancedSwapRouter: 1inch requires route calldata from API; use 1inch aggregator SDK");
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get Uniswap V3 quote (view)
|
||||
* When UNISWAP_QUOTER_ADDRESS is configured, queries quoter. Otherwise returns
|
||||
* estimate via amountIn * 9950/10000 (0.5% slippage) for stablecoin pairs.
|
||||
*/
|
||||
function _getUniswapV3Quote(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn
|
||||
) external view returns (uint256) {
|
||||
if (uniswapQuoter != address(0) && _isValidStablecoin(stablecoinToken)) {
|
||||
// IQuoter.quoteExactInputSingle(tokenIn, tokenOut, fee, amountIn, sqrtPriceLimitX96)
|
||||
(bool ok, bytes memory data) = uniswapQuoter.staticcall(
|
||||
abi.encodeWithSignature(
|
||||
"quoteExactInputSingle(address,address,uint24,uint256,uint160)",
|
||||
weth,
|
||||
stablecoinToken,
|
||||
FEE_TIER_MEDIUM,
|
||||
amountIn,
|
||||
uint160(0)
|
||||
)
|
||||
);
|
||||
if (ok && data.length >= 32) {
|
||||
uint256 quoted = abi.decode(data, (uint256));
|
||||
if (quoted > 0) return quoted;
|
||||
}
|
||||
}
|
||||
if (_isValidStablecoin(stablecoinToken)) {
|
||||
return (amountIn * 9950) / 10000; // 0.5% slippage estimate for WETH->stable
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get Dodoex quote (view)
|
||||
*/
|
||||
function _getDodoexQuote(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn
|
||||
) external view returns (uint256) {
|
||||
return IDodoexRouter(dodoexRouter).getDodoSwapQuote(weth, stablecoinToken, amountIn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get Balancer quote (view)
|
||||
* When poolId configured, would query Balancer. Otherwise estimate for stablecoins.
|
||||
*/
|
||||
function _getBalancerQuote(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn
|
||||
) external view returns (uint256) {
|
||||
bytes32 poolId = balancerPoolIds[weth][stablecoinToken];
|
||||
if (poolId != bytes32(0)) {
|
||||
(address[] memory tokens, uint256[] memory balances,) =
|
||||
IBalancerVault(balancerVault).getPoolTokens(poolId);
|
||||
if (tokens.length >= 2 && balances.length >= 2) {
|
||||
uint256 wethIdx = type(uint256).max;
|
||||
uint256 stableIdx = type(uint256).max;
|
||||
for (uint256 i = 0; i < tokens.length; i++) {
|
||||
if (tokens[i] == weth) wethIdx = i;
|
||||
if (tokens[i] == stablecoinToken) stableIdx = i;
|
||||
}
|
||||
if (wethIdx != type(uint256).max && stableIdx != type(uint256).max && balances[wethIdx] > 0) {
|
||||
uint256 amountOut = (amountIn * balances[stableIdx]) / balances[wethIdx];
|
||||
return (amountOut * 9950) / 10000; // 0.5% slippage
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_isValidStablecoin(stablecoinToken)) {
|
||||
return (amountIn * 9950) / 10000; // 0.5% slippage estimate when pool not configured
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Initialize default routing configurations
|
||||
*/
|
||||
function _initializeDefaultRouting() internal {
|
||||
// Small swaps (< $10k): Uniswap V3, Dodoex
|
||||
SwapProvider[] memory smallProviders = new SwapProvider[](2);
|
||||
smallProviders[0] = SwapProvider.UniswapV3;
|
||||
smallProviders[1] = SwapProvider.Dodoex;
|
||||
sizeBasedRouting[0] = RoutingConfig({
|
||||
providers: smallProviders,
|
||||
sizeThresholds: new uint256[](0),
|
||||
enabled: true
|
||||
});
|
||||
|
||||
// Medium swaps ($10k-$100k): Dodoex, Balancer, Uniswap V3
|
||||
SwapProvider[] memory mediumProviders = new SwapProvider[](3);
|
||||
mediumProviders[0] = SwapProvider.Dodoex;
|
||||
mediumProviders[1] = SwapProvider.Balancer;
|
||||
mediumProviders[2] = SwapProvider.UniswapV3;
|
||||
sizeBasedRouting[1] = RoutingConfig({
|
||||
providers: mediumProviders,
|
||||
sizeThresholds: new uint256[](0),
|
||||
enabled: true
|
||||
});
|
||||
|
||||
// Large swaps (> $100k): Dodoex, Curve, Balancer
|
||||
SwapProvider[] memory largeProviders = new SwapProvider[](3);
|
||||
largeProviders[0] = SwapProvider.Dodoex;
|
||||
largeProviders[1] = SwapProvider.Curve;
|
||||
largeProviders[2] = SwapProvider.Balancer;
|
||||
sizeBasedRouting[2] = RoutingConfig({
|
||||
providers: largeProviders,
|
||||
sizeThresholds: new uint256[](0),
|
||||
enabled: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if token is valid stablecoin
|
||||
*/
|
||||
function _isValidStablecoin(address token) internal view returns (bool) {
|
||||
return token == usdt || token == usdc || token == dai;
|
||||
}
|
||||
|
||||
// Allow contract to receive ETH
|
||||
receive() external payable {}
|
||||
}
|
||||
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "./BondManager.sol";
|
||||
import "./ChallengeManager.sol";
|
||||
import "./LiquidityPoolETH.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
/**
|
||||
* @title InboxETH
|
||||
* @notice Receives and processes claims from relayers for trustless bridge deposits
|
||||
* @dev Permissionless claim submission requiring bonds and challenge mechanism
|
||||
*/
|
||||
contract InboxETH is ReentrancyGuard {
|
||||
BondManager public immutable bondManager;
|
||||
ChallengeManager public immutable challengeManager;
|
||||
LiquidityPoolETH public immutable liquidityPool;
|
||||
|
||||
// Rate limiting
|
||||
uint256 public constant MIN_DEPOSIT = 0.001 ether; // Minimum deposit to prevent dust
|
||||
uint256 public constant COOLDOWN_PERIOD = 60 seconds; // Cooldown between claims per relayer
|
||||
mapping(address => uint256) public lastClaimTime; // relayer => last claim timestamp
|
||||
mapping(address => uint256) public claimsPerHour; // relayer => claims in current hour
|
||||
mapping(address => uint256) public hourStart; // relayer => current hour start timestamp
|
||||
uint256 public constant MAX_CLAIMS_PER_HOUR = 100; // Max claims per hour per relayer
|
||||
|
||||
// Relayer fees (optional, can be enabled via governance)
|
||||
uint256 public relayerFeeBps = 0; // Basis points (0 = disabled, 100 = 1%)
|
||||
mapping(uint256 => RelayerFee) public relayerFees; // depositId => RelayerFee
|
||||
|
||||
struct RelayerFee {
|
||||
address relayer;
|
||||
uint256 amount;
|
||||
bool claimed;
|
||||
}
|
||||
|
||||
struct ClaimData {
|
||||
uint256 depositId;
|
||||
address asset;
|
||||
uint256 amount;
|
||||
address recipient;
|
||||
address relayer;
|
||||
uint256 timestamp;
|
||||
bool exists;
|
||||
}
|
||||
|
||||
mapping(uint256 => ClaimData) public claims; // depositId => ClaimData
|
||||
|
||||
event RelayerFeeSet(uint256 newFeeBps);
|
||||
event RelayerFeeClaimed(uint256 indexed depositId, address indexed relayer, uint256 amount);
|
||||
|
||||
event ClaimSubmitted(
|
||||
uint256 indexed depositId,
|
||||
address indexed relayer,
|
||||
address asset,
|
||||
uint256 amount,
|
||||
address indexed recipient,
|
||||
uint256 bondAmount,
|
||||
uint256 challengeWindowEnd
|
||||
);
|
||||
|
||||
error ZeroDepositId();
|
||||
error ZeroAsset();
|
||||
error ZeroAmount();
|
||||
error ZeroRecipient();
|
||||
error ClaimAlreadyExists();
|
||||
error InsufficientBond();
|
||||
error DepositTooSmall();
|
||||
error CooldownActive();
|
||||
error RateLimitExceeded();
|
||||
error RelayerFeeNotEnabled();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _bondManager Address of BondManager contract
|
||||
* @param _challengeManager Address of ChallengeManager contract
|
||||
* @param _liquidityPool Address of LiquidityPoolETH contract
|
||||
*/
|
||||
constructor(
|
||||
address _bondManager,
|
||||
address _challengeManager,
|
||||
address _liquidityPool
|
||||
) {
|
||||
require(_bondManager != address(0), "InboxETH: zero bond manager");
|
||||
require(_challengeManager != address(0), "InboxETH: zero challenge manager");
|
||||
require(_liquidityPool != address(0), "InboxETH: zero liquidity pool");
|
||||
|
||||
bondManager = BondManager(payable(_bondManager));
|
||||
challengeManager = ChallengeManager(payable(_challengeManager));
|
||||
liquidityPool = LiquidityPoolETH(payable(_liquidityPool));
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Submit a claim for a deposit from source chain
|
||||
* @param depositId Deposit ID from source chain (ChainID 138)
|
||||
* @param asset Asset address (address(0) for native ETH)
|
||||
* @param amount Deposit amount
|
||||
* @param recipient Recipient address on Ethereum
|
||||
* @param proof Optional proof data (not used in optimistic model, but reserved for future light client)
|
||||
* @return bondAmount Amount of bond posted
|
||||
*/
|
||||
function submitClaim(
|
||||
uint256 depositId,
|
||||
address asset,
|
||||
uint256 amount,
|
||||
address recipient,
|
||||
bytes calldata proof
|
||||
) external payable nonReentrant returns (uint256 bondAmount) {
|
||||
if (depositId == 0) revert ZeroDepositId();
|
||||
if (asset == address(0) && amount == 0) revert ZeroAmount();
|
||||
if (recipient == address(0)) revert ZeroRecipient();
|
||||
|
||||
// Rate limiting checks
|
||||
if (amount < MIN_DEPOSIT) revert DepositTooSmall();
|
||||
|
||||
// Cooldown check
|
||||
if (block.timestamp < lastClaimTime[msg.sender] + COOLDOWN_PERIOD) {
|
||||
revert CooldownActive();
|
||||
}
|
||||
|
||||
// Hourly rate limit check
|
||||
uint256 currentHour = block.timestamp / 3600;
|
||||
if (hourStart[msg.sender] != currentHour) {
|
||||
hourStart[msg.sender] = currentHour;
|
||||
claimsPerHour[msg.sender] = 0;
|
||||
}
|
||||
if (claimsPerHour[msg.sender] >= MAX_CLAIMS_PER_HOUR) {
|
||||
revert RateLimitExceeded();
|
||||
}
|
||||
|
||||
// Check if claim already exists
|
||||
if (claims[depositId].exists) revert ClaimAlreadyExists();
|
||||
|
||||
// Calculate required bond
|
||||
uint256 requiredBond = bondManager.getRequiredBond(amount);
|
||||
|
||||
// Calculate relayer fee if enabled
|
||||
uint256 relayerFee = 0;
|
||||
uint256 bridgeAmount = amount;
|
||||
if (relayerFeeBps > 0) {
|
||||
relayerFee = (amount * relayerFeeBps) / 10000;
|
||||
bridgeAmount = amount - relayerFee;
|
||||
|
||||
// Store relayer fee
|
||||
relayerFees[depositId] = RelayerFee({
|
||||
relayer: msg.sender,
|
||||
amount: relayerFee,
|
||||
claimed: false
|
||||
});
|
||||
}
|
||||
|
||||
if (msg.value < requiredBond) revert InsufficientBond();
|
||||
|
||||
// Post bond (pass relayer address explicitly)
|
||||
bondAmount = bondManager.postBond{value: requiredBond}(depositId, bridgeAmount, msg.sender);
|
||||
|
||||
// Update rate limiting
|
||||
lastClaimTime[msg.sender] = block.timestamp;
|
||||
claimsPerHour[msg.sender]++;
|
||||
|
||||
// Register claim with ChallengeManager (use bridgeAmount after fee)
|
||||
challengeManager.registerClaim(depositId, asset, bridgeAmount, recipient);
|
||||
|
||||
// Determine asset type for liquidity pool
|
||||
LiquidityPoolETH.AssetType assetType = asset == address(0)
|
||||
? LiquidityPoolETH.AssetType.ETH
|
||||
: LiquidityPoolETH.AssetType.WETH;
|
||||
|
||||
// Add pending claim to liquidity pool (use bridgeAmount after fee deduction)
|
||||
liquidityPool.addPendingClaim(bridgeAmount, assetType);
|
||||
|
||||
// Store claim data (use bridgeAmount for amount)
|
||||
claims[depositId] = ClaimData({
|
||||
depositId: depositId,
|
||||
asset: asset,
|
||||
amount: bridgeAmount, // Store bridge amount (after fee)
|
||||
recipient: recipient,
|
||||
relayer: msg.sender,
|
||||
timestamp: block.timestamp,
|
||||
exists: true
|
||||
});
|
||||
|
||||
// Get challenge window end time
|
||||
(uint256 challengeWindowEnd, ) = _getChallengeWindowEnd(depositId);
|
||||
|
||||
emit ClaimSubmitted(
|
||||
depositId,
|
||||
msg.sender,
|
||||
asset,
|
||||
bridgeAmount, // Emit bridge amount (after fee)
|
||||
recipient,
|
||||
bondAmount,
|
||||
challengeWindowEnd
|
||||
);
|
||||
|
||||
return bondAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Submit multiple claims in batch (gas optimization)
|
||||
* @param depositIds Array of deposit IDs
|
||||
* @param assets Array of asset addresses
|
||||
* @param amounts Array of deposit amounts
|
||||
* @param recipients Array of recipient addresses
|
||||
* @param proofs Array of proof data
|
||||
* @return totalBondAmount Total bond amount posted
|
||||
*/
|
||||
function submitClaimsBatch(
|
||||
uint256[] calldata depositIds,
|
||||
address[] calldata assets,
|
||||
uint256[] calldata amounts,
|
||||
address[] calldata recipients,
|
||||
bytes[] calldata proofs
|
||||
) external payable nonReentrant returns (uint256 totalBondAmount) {
|
||||
uint256 length = depositIds.length;
|
||||
require(length > 0, "InboxETH: empty array");
|
||||
require(length <= 20, "InboxETH: batch too large"); // Prevent gas limit issues
|
||||
require(length == assets.length && length == amounts.length &&
|
||||
length == recipients.length && length == proofs.length,
|
||||
"InboxETH: length mismatch");
|
||||
|
||||
// Calculate total required bond
|
||||
uint256 totalRequiredBond = 0;
|
||||
for (uint256 i = 0; i < length; i++) {
|
||||
if (depositIds[i] == 0) revert ZeroDepositId();
|
||||
if (assets[i] == address(0) && amounts[i] == 0) revert ZeroAmount();
|
||||
if (recipients[i] == address(0)) revert ZeroRecipient();
|
||||
if (claims[depositIds[i]].exists) revert ClaimAlreadyExists();
|
||||
|
||||
totalRequiredBond += bondManager.getRequiredBond(amounts[i]);
|
||||
}
|
||||
|
||||
if (msg.value < totalRequiredBond) revert InsufficientBond();
|
||||
|
||||
// Process each claim
|
||||
for (uint256 i = 0; i < length; i++) {
|
||||
// Rate limiting checks (simplified for batch - check first item)
|
||||
if (i == 0) {
|
||||
if (amounts[i] < MIN_DEPOSIT) revert DepositTooSmall();
|
||||
if (block.timestamp < lastClaimTime[msg.sender] + COOLDOWN_PERIOD) {
|
||||
revert CooldownActive();
|
||||
}
|
||||
uint256 currentHour = block.timestamp / 3600;
|
||||
if (hourStart[msg.sender] != currentHour) {
|
||||
hourStart[msg.sender] = currentHour;
|
||||
claimsPerHour[msg.sender] = 0;
|
||||
}
|
||||
}
|
||||
if (claimsPerHour[msg.sender] + i >= MAX_CLAIMS_PER_HOUR) {
|
||||
revert RateLimitExceeded();
|
||||
}
|
||||
|
||||
// Calculate relayer fee if enabled
|
||||
uint256 relayerFee = 0;
|
||||
uint256 bridgeAmount = amounts[i];
|
||||
if (relayerFeeBps > 0) {
|
||||
relayerFee = (amounts[i] * relayerFeeBps) / 10000;
|
||||
bridgeAmount = amounts[i] - relayerFee;
|
||||
relayerFees[depositIds[i]] = RelayerFee({
|
||||
relayer: msg.sender,
|
||||
amount: relayerFee,
|
||||
claimed: false
|
||||
});
|
||||
}
|
||||
|
||||
uint256 requiredBond = bondManager.getRequiredBond(bridgeAmount);
|
||||
|
||||
// Post bond
|
||||
uint256 bondAmount = bondManager.postBond{value: requiredBond}(
|
||||
depositIds[i],
|
||||
bridgeAmount,
|
||||
msg.sender
|
||||
);
|
||||
totalBondAmount += bondAmount;
|
||||
|
||||
// Register claim (use bridgeAmount)
|
||||
challengeManager.registerClaim(depositIds[i], assets[i], bridgeAmount, recipients[i]);
|
||||
|
||||
// Determine asset type
|
||||
LiquidityPoolETH.AssetType assetType = assets[i] == address(0)
|
||||
? LiquidityPoolETH.AssetType.ETH
|
||||
: LiquidityPoolETH.AssetType.WETH;
|
||||
|
||||
// Add pending claim (use bridgeAmount)
|
||||
liquidityPool.addPendingClaim(bridgeAmount, assetType);
|
||||
|
||||
// Store claim data (use bridgeAmount)
|
||||
claims[depositIds[i]] = ClaimData({
|
||||
depositId: depositIds[i],
|
||||
asset: assets[i],
|
||||
amount: bridgeAmount,
|
||||
recipient: recipients[i],
|
||||
relayer: msg.sender,
|
||||
timestamp: block.timestamp,
|
||||
exists: true
|
||||
});
|
||||
|
||||
// Get challenge window end time
|
||||
(uint256 challengeWindowEnd, ) = _getChallengeWindowEnd(depositIds[i]);
|
||||
|
||||
emit ClaimSubmitted(
|
||||
depositIds[i],
|
||||
msg.sender,
|
||||
assets[i],
|
||||
bridgeAmount,
|
||||
recipients[i],
|
||||
bondAmount,
|
||||
challengeWindowEnd
|
||||
);
|
||||
}
|
||||
|
||||
// Update rate limiting
|
||||
lastClaimTime[msg.sender] = block.timestamp;
|
||||
claimsPerHour[msg.sender] += length;
|
||||
|
||||
// Refund excess bond if any
|
||||
if (msg.value > totalBondAmount) {
|
||||
(bool success, ) = payable(msg.sender).call{value: msg.value - totalBondAmount}("");
|
||||
require(success, "InboxETH: refund failed");
|
||||
}
|
||||
|
||||
return totalBondAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get claim status
|
||||
* @param depositId Deposit ID
|
||||
* @return exists True if claim exists
|
||||
* @return finalized True if claim is finalized
|
||||
* @return challenged True if claim was challenged
|
||||
* @return challengeWindowEnd Timestamp when challenge window ends
|
||||
*/
|
||||
function getClaimStatus(
|
||||
uint256 depositId
|
||||
) external view returns (
|
||||
bool exists,
|
||||
bool finalized,
|
||||
bool challenged,
|
||||
uint256 challengeWindowEnd
|
||||
) {
|
||||
if (!claims[depositId].exists) {
|
||||
return (false, false, false, 0);
|
||||
}
|
||||
|
||||
ChallengeManager.Claim memory claim = challengeManager.getClaim(depositId);
|
||||
(challengeWindowEnd, ) = _getChallengeWindowEnd(depositId);
|
||||
|
||||
return (
|
||||
true,
|
||||
claim.finalized,
|
||||
claim.challenged,
|
||||
challengeWindowEnd
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get claim data
|
||||
* @param depositId Deposit ID
|
||||
* @return Claim data
|
||||
*/
|
||||
function getClaim(uint256 depositId) external view returns (ClaimData memory) {
|
||||
return claims[depositId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Internal function to get challenge window end time
|
||||
* @param depositId Deposit ID
|
||||
* @return challengeWindowEnd Timestamp
|
||||
* @return exists True if claim exists
|
||||
*/
|
||||
function _getChallengeWindowEnd(
|
||||
uint256 depositId
|
||||
) internal view returns (uint256 challengeWindowEnd, bool exists) {
|
||||
ChallengeManager.Claim memory claim = challengeManager.getClaim(depositId);
|
||||
if (claim.depositId == 0) {
|
||||
return (0, false);
|
||||
}
|
||||
return (claim.challengeWindowEnd, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set relayer fee (only callable by owner/multisig in future upgrade)
|
||||
* @param _relayerFeeBps New relayer fee in basis points (0 = disabled)
|
||||
*/
|
||||
function setRelayerFee(uint256 _relayerFeeBps) external {
|
||||
// Note: In production, add access control (owner/multisig)
|
||||
// For now, this is a placeholder for future governance
|
||||
require(_relayerFeeBps <= 1000, "InboxETH: fee too high"); // Max 10%
|
||||
relayerFeeBps = _relayerFeeBps;
|
||||
emit RelayerFeeSet(_relayerFeeBps);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Claim relayer fee for a finalized deposit
|
||||
* @param depositId Deposit ID to claim fee for
|
||||
*/
|
||||
function claimRelayerFee(uint256 depositId) external nonReentrant {
|
||||
if (relayerFeeBps == 0) revert RelayerFeeNotEnabled();
|
||||
|
||||
RelayerFee storage fee = relayerFees[depositId];
|
||||
if (fee.relayer == address(0)) revert("InboxETH: no fee for deposit");
|
||||
if (fee.claimed) revert("InboxETH: fee already claimed");
|
||||
if (fee.relayer != msg.sender) revert("InboxETH: not fee recipient");
|
||||
|
||||
// Verify claim is finalized
|
||||
ChallengeManager.Claim memory claim = challengeManager.getClaim(depositId);
|
||||
if (!claim.finalized) revert("InboxETH: claim not finalized");
|
||||
|
||||
fee.claimed = true;
|
||||
|
||||
// Transfer fee to relayer
|
||||
(bool success, ) = payable(msg.sender).call{value: fee.amount}("");
|
||||
require(success, "InboxETH: fee transfer failed");
|
||||
|
||||
emit RelayerFeeClaimed(depositId, msg.sender, fee.amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get relayer fee for a deposit
|
||||
* @param depositId Deposit ID
|
||||
* @return fee Relayer fee information
|
||||
*/
|
||||
function getRelayerFee(uint256 depositId) external view returns (RelayerFee memory) {
|
||||
return relayerFees[depositId];
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
/**
|
||||
* @title LiquidityPoolETH
|
||||
* @notice Liquidity pool for ETH and WETH with fee model and minimum liquidity ratio enforcement
|
||||
* @dev Supports separate pools for native ETH and WETH (ERC-20)
|
||||
*/
|
||||
contract LiquidityPoolETH is ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
enum AssetType {
|
||||
ETH, // Native ETH
|
||||
WETH // Wrapped ETH (ERC-20)
|
||||
}
|
||||
|
||||
// Pool configuration
|
||||
uint256 public immutable lpFeeBps; // Liquidity provider fee in basis points (default: 5 = 0.05%)
|
||||
uint256 public immutable minLiquidityRatioBps; // Minimum liquidity ratio in basis points (default: 11000 = 110%)
|
||||
address public immutable weth; // WETH token address
|
||||
|
||||
// WETH getter for external access
|
||||
function getWeth() external view returns (address) {
|
||||
return weth;
|
||||
}
|
||||
|
||||
// Pool state
|
||||
struct PoolState {
|
||||
uint256 totalLiquidity;
|
||||
uint256 pendingClaims; // Total amount of pending claims to be released
|
||||
mapping(address => uint256) lpShares; // LP address => amount provided
|
||||
}
|
||||
|
||||
mapping(AssetType => PoolState) public pools;
|
||||
mapping(address => bool) public authorizedRelease; // Contracts authorized to release funds
|
||||
|
||||
event LiquidityProvided(
|
||||
AssetType indexed assetType,
|
||||
address indexed provider,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
event LiquidityWithdrawn(
|
||||
AssetType indexed assetType,
|
||||
address indexed provider,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
event FundsReleased(
|
||||
AssetType indexed assetType,
|
||||
uint256 indexed depositId,
|
||||
address indexed recipient,
|
||||
uint256 amount,
|
||||
uint256 feeAmount
|
||||
);
|
||||
|
||||
event PendingClaimAdded(
|
||||
AssetType indexed assetType,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
event PendingClaimRemoved(
|
||||
AssetType indexed assetType,
|
||||
uint256 amount
|
||||
);
|
||||
|
||||
error ZeroAmount();
|
||||
error ZeroAddress();
|
||||
error InsufficientLiquidity();
|
||||
error WithdrawalBlockedByLiquidityRatio();
|
||||
error UnauthorizedRelease();
|
||||
error InvalidAssetType();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _weth WETH token address
|
||||
* @param _lpFeeBps LP fee in basis points (5 = 0.05%)
|
||||
* @param _minLiquidityRatioBps Minimum liquidity ratio in basis points (11000 = 110%)
|
||||
*/
|
||||
constructor(
|
||||
address _weth,
|
||||
uint256 _lpFeeBps,
|
||||
uint256 _minLiquidityRatioBps
|
||||
) {
|
||||
require(_weth != address(0), "LiquidityPoolETH: zero WETH address");
|
||||
require(_lpFeeBps <= 10000, "LiquidityPoolETH: fee exceeds 100%");
|
||||
require(_minLiquidityRatioBps >= 10000, "LiquidityPoolETH: min ratio must be >= 100%");
|
||||
|
||||
weth = _weth;
|
||||
lpFeeBps = _lpFeeBps;
|
||||
minLiquidityRatioBps = _minLiquidityRatioBps;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Authorize a contract to release funds (called during deployment)
|
||||
* @param releaser Address authorized to release funds
|
||||
*/
|
||||
function authorizeRelease(address releaser) external {
|
||||
require(releaser != address(0), "LiquidityPoolETH: zero address");
|
||||
authorizedRelease[releaser] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Provide liquidity to the pool
|
||||
* @param assetType Type of asset (ETH or WETH)
|
||||
*/
|
||||
function provideLiquidity(AssetType assetType) external payable nonReentrant {
|
||||
uint256 amount;
|
||||
|
||||
if (assetType == AssetType.ETH) {
|
||||
if (msg.value == 0) revert ZeroAmount();
|
||||
amount = msg.value;
|
||||
} else if (assetType == AssetType.WETH) {
|
||||
if (msg.value != 0) revert("LiquidityPoolETH: WETH deposits must use depositWETH()");
|
||||
revert("LiquidityPoolETH: use depositWETH() for WETH deposits");
|
||||
} else {
|
||||
revert InvalidAssetType();
|
||||
}
|
||||
|
||||
pools[assetType].totalLiquidity += amount;
|
||||
pools[assetType].lpShares[msg.sender] += amount;
|
||||
|
||||
emit LiquidityProvided(assetType, msg.sender, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Provide WETH liquidity to the pool
|
||||
* @param amount Amount of WETH to deposit
|
||||
*/
|
||||
function depositWETH(uint256 amount) external nonReentrant {
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
|
||||
IERC20(weth).safeTransferFrom(msg.sender, address(this), amount);
|
||||
|
||||
pools[AssetType.WETH].totalLiquidity += amount;
|
||||
pools[AssetType.WETH].lpShares[msg.sender] += amount;
|
||||
|
||||
emit LiquidityProvided(AssetType.WETH, msg.sender, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Withdraw liquidity from the pool
|
||||
* @param amount Amount to withdraw
|
||||
* @param assetType Type of asset (ETH or WETH)
|
||||
*/
|
||||
function withdrawLiquidity(
|
||||
uint256 amount,
|
||||
AssetType assetType
|
||||
) external nonReentrant {
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
if (pools[assetType].lpShares[msg.sender] < amount) revert InsufficientLiquidity();
|
||||
|
||||
// Check minimum liquidity ratio
|
||||
uint256 availableLiquidity = pools[assetType].totalLiquidity - pools[assetType].pendingClaims;
|
||||
uint256 newAvailableLiquidity = availableLiquidity - amount;
|
||||
uint256 minRequired = (pools[assetType].pendingClaims * minLiquidityRatioBps) / 10000;
|
||||
|
||||
if (newAvailableLiquidity < minRequired) {
|
||||
revert WithdrawalBlockedByLiquidityRatio();
|
||||
}
|
||||
|
||||
pools[assetType].totalLiquidity -= amount;
|
||||
pools[assetType].lpShares[msg.sender] -= amount;
|
||||
|
||||
if (assetType == AssetType.ETH) {
|
||||
(bool success, ) = payable(msg.sender).call{value: amount}("");
|
||||
require(success, "LiquidityPoolETH: ETH transfer failed");
|
||||
} else {
|
||||
IERC20(weth).safeTransfer(msg.sender, amount);
|
||||
}
|
||||
|
||||
emit LiquidityWithdrawn(assetType, msg.sender, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Release funds to recipient (only authorized contracts)
|
||||
* @param depositId Deposit ID (for event tracking)
|
||||
* @param recipient Recipient address
|
||||
* @param amount Amount to release (before fees)
|
||||
* @param assetType Type of asset (ETH or WETH)
|
||||
*/
|
||||
function releaseToRecipient(
|
||||
uint256 depositId,
|
||||
address recipient,
|
||||
uint256 amount,
|
||||
AssetType assetType
|
||||
) external nonReentrant {
|
||||
if (!authorizedRelease[msg.sender]) revert UnauthorizedRelease();
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
if (recipient == address(0)) revert ZeroAddress();
|
||||
|
||||
// Calculate fee
|
||||
uint256 feeAmount = (amount * lpFeeBps) / 10000;
|
||||
uint256 releaseAmount = amount - feeAmount;
|
||||
|
||||
// Check available liquidity
|
||||
PoolState storage pool = pools[assetType];
|
||||
uint256 availableLiquidity = pool.totalLiquidity - pool.pendingClaims;
|
||||
|
||||
if (availableLiquidity < releaseAmount) {
|
||||
revert InsufficientLiquidity();
|
||||
}
|
||||
|
||||
// Reduce pending claims
|
||||
pool.pendingClaims -= amount;
|
||||
|
||||
// Release funds to recipient
|
||||
if (assetType == AssetType.ETH) {
|
||||
(bool success, ) = payable(recipient).call{value: releaseAmount}("");
|
||||
require(success, "LiquidityPoolETH: ETH transfer failed");
|
||||
} else {
|
||||
IERC20(weth).safeTransfer(recipient, releaseAmount);
|
||||
}
|
||||
|
||||
// Fee remains in pool (increases totalLiquidity effectively by reducing pendingClaims)
|
||||
|
||||
emit FundsReleased(assetType, depositId, recipient, releaseAmount, feeAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Add pending claim (called when claim is submitted)
|
||||
* @param amount Amount of pending claim
|
||||
* @param assetType Type of asset
|
||||
*/
|
||||
function addPendingClaim(uint256 amount, AssetType assetType) external {
|
||||
if (!authorizedRelease[msg.sender]) revert UnauthorizedRelease();
|
||||
pools[assetType].pendingClaims += amount;
|
||||
emit PendingClaimAdded(assetType, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Remove pending claim (called when claim is challenged/slashed)
|
||||
* @param amount Amount of pending claim to remove
|
||||
* @param assetType Type of asset
|
||||
*/
|
||||
function removePendingClaim(uint256 amount, AssetType assetType) external {
|
||||
if (!authorizedRelease[msg.sender]) revert UnauthorizedRelease();
|
||||
pools[assetType].pendingClaims -= amount;
|
||||
emit PendingClaimRemoved(assetType, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get available liquidity for an asset type
|
||||
* @param assetType Type of asset
|
||||
* @return Available liquidity (total - pending claims)
|
||||
*/
|
||||
function getAvailableLiquidity(AssetType assetType) external view returns (uint256) {
|
||||
PoolState storage pool = pools[assetType];
|
||||
uint256 pending = pool.pendingClaims;
|
||||
if (pool.totalLiquidity <= pending) {
|
||||
return 0;
|
||||
}
|
||||
return pool.totalLiquidity - pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get LP share for a provider
|
||||
* @param provider LP provider address
|
||||
* @param assetType Type of asset
|
||||
* @return LP share amount
|
||||
*/
|
||||
function getLpShare(address provider, AssetType assetType) external view returns (uint256) {
|
||||
return pools[assetType].lpShares[provider];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get pool statistics
|
||||
* @param assetType Type of asset
|
||||
* @return totalLiquidity Total liquidity in pool
|
||||
* @return pendingClaims Total pending claims
|
||||
* @return availableLiquidity Available liquidity (total - pending)
|
||||
*/
|
||||
function getPoolStats(
|
||||
AssetType assetType
|
||||
) external view returns (
|
||||
uint256 totalLiquidity,
|
||||
uint256 pendingClaims,
|
||||
uint256 availableLiquidity
|
||||
) {
|
||||
PoolState storage pool = pools[assetType];
|
||||
totalLiquidity = pool.totalLiquidity;
|
||||
pendingClaims = pool.pendingClaims;
|
||||
if (totalLiquidity > pendingClaims) {
|
||||
availableLiquidity = totalLiquidity - pendingClaims;
|
||||
} else {
|
||||
availableLiquidity = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow contract to receive ETH
|
||||
receive() external payable {}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
|
||||
/**
|
||||
* @title Lockbox138
|
||||
* @notice Asset lock contract on ChainID 138 (Besu) for trustless bridge deposits
|
||||
* @dev Supports both native ETH and ERC-20 tokens. Immutable after deployment (no admin functions).
|
||||
*/
|
||||
contract Lockbox138 is ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
// Replay protection: track nonces per user
|
||||
mapping(address => uint256) public nonces;
|
||||
|
||||
// Track processed deposit IDs to prevent double deposits
|
||||
mapping(uint256 => bool) public processedDeposits;
|
||||
|
||||
event Deposit(
|
||||
uint256 indexed depositId,
|
||||
address indexed asset,
|
||||
uint256 amount,
|
||||
address indexed recipient,
|
||||
bytes32 nonce,
|
||||
address depositor,
|
||||
uint256 timestamp
|
||||
);
|
||||
|
||||
error ZeroAmount();
|
||||
error ZeroRecipient();
|
||||
error ZeroAsset();
|
||||
error DepositAlreadyProcessed();
|
||||
error TransferFailed();
|
||||
|
||||
/**
|
||||
* @notice Lock native ETH for cross-chain transfer
|
||||
* @param recipient Address on destination chain (Ethereum) to receive funds
|
||||
* @param nonce Unique nonce for this deposit (prevents replay attacks)
|
||||
* @return depositId Unique identifier for this deposit
|
||||
*/
|
||||
function depositNative(
|
||||
address recipient,
|
||||
bytes32 nonce
|
||||
) external payable nonReentrant returns (uint256 depositId) {
|
||||
if (msg.value == 0) revert ZeroAmount();
|
||||
if (recipient == address(0)) revert ZeroRecipient();
|
||||
|
||||
// Increment user nonce
|
||||
nonces[msg.sender]++;
|
||||
|
||||
// Generate unique deposit ID
|
||||
depositId = _generateDepositId(
|
||||
address(0), // Native ETH is represented as address(0)
|
||||
msg.value,
|
||||
recipient,
|
||||
nonce
|
||||
);
|
||||
|
||||
// Replay protection: ensure deposit ID hasn't been used
|
||||
if (processedDeposits[depositId]) revert DepositAlreadyProcessed();
|
||||
processedDeposits[depositId] = true;
|
||||
|
||||
emit Deposit(
|
||||
depositId,
|
||||
address(0), // address(0) represents native ETH
|
||||
msg.value,
|
||||
recipient,
|
||||
nonce,
|
||||
msg.sender,
|
||||
block.timestamp
|
||||
);
|
||||
|
||||
return depositId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Lock ERC-20 tokens (e.g., WETH) for cross-chain transfer
|
||||
* @param token ERC-20 token address to lock
|
||||
* @param amount Amount of tokens to lock
|
||||
* @param recipient Address on destination chain (Ethereum) to receive funds
|
||||
* @param nonce Unique nonce for this deposit (prevents replay attacks)
|
||||
* @return depositId Unique identifier for this deposit
|
||||
*/
|
||||
function depositERC20(
|
||||
address token,
|
||||
uint256 amount,
|
||||
address recipient,
|
||||
bytes32 nonce
|
||||
) external nonReentrant returns (uint256 depositId) {
|
||||
if (token == address(0)) revert ZeroAsset();
|
||||
if (amount == 0) revert ZeroAmount();
|
||||
if (recipient == address(0)) revert ZeroRecipient();
|
||||
|
||||
// Increment user nonce
|
||||
nonces[msg.sender]++;
|
||||
|
||||
// Generate unique deposit ID
|
||||
depositId = _generateDepositId(token, amount, recipient, nonce);
|
||||
|
||||
// Replay protection: ensure deposit ID hasn't been used
|
||||
if (processedDeposits[depositId]) revert DepositAlreadyProcessed();
|
||||
processedDeposits[depositId] = true;
|
||||
|
||||
// Transfer tokens from user to this contract
|
||||
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
|
||||
|
||||
emit Deposit(
|
||||
depositId,
|
||||
token,
|
||||
amount,
|
||||
recipient,
|
||||
nonce,
|
||||
msg.sender,
|
||||
block.timestamp
|
||||
);
|
||||
|
||||
return depositId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get current nonce for a user
|
||||
* @param user Address to check nonce for
|
||||
* @return Current nonce value
|
||||
*/
|
||||
function getNonce(address user) external view returns (uint256) {
|
||||
return nonces[user];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if a deposit ID has been processed
|
||||
* @param depositId Deposit ID to check
|
||||
* @return True if deposit has been processed
|
||||
*/
|
||||
function isDepositProcessed(uint256 depositId) external view returns (bool) {
|
||||
return processedDeposits[depositId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Generate a unique deposit ID from deposit parameters
|
||||
* @dev Uses keccak256 hash of all deposit parameters + sender + timestamp to ensure uniqueness
|
||||
* @param asset Asset address (address(0) for native ETH)
|
||||
* @param amount Deposit amount
|
||||
* @param recipient Recipient address on destination chain
|
||||
* @param nonce User-provided nonce
|
||||
* @return depositId Unique deposit identifier
|
||||
*/
|
||||
function _generateDepositId(
|
||||
address asset,
|
||||
uint256 amount,
|
||||
address recipient,
|
||||
bytes32 nonce
|
||||
) internal view returns (uint256) {
|
||||
return uint256(
|
||||
keccak256(
|
||||
abi.encodePacked(
|
||||
asset,
|
||||
amount,
|
||||
recipient,
|
||||
nonce,
|
||||
msg.sender,
|
||||
block.timestamp,
|
||||
block.number
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../UniversalCCIPBridge.sol";
|
||||
import "./EnhancedSwapRouter.sol";
|
||||
|
||||
/**
|
||||
* @title SwapBridgeSwapCoordinator
|
||||
* @notice Coordinates source-chain swap (token A -> bridgeable token) then CCIP bridge in one flow
|
||||
* @dev User approves coordinator for sourceToken; coordinator swaps via EnhancedSwapRouter (Dodoex) then calls UniversalCCIPBridge
|
||||
*/
|
||||
contract SwapBridgeSwapCoordinator is ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
EnhancedSwapRouter public immutable swapRouter;
|
||||
UniversalCCIPBridge public immutable bridge;
|
||||
|
||||
event SwapAndBridgeExecuted(
|
||||
address indexed sourceToken,
|
||||
address indexed bridgeableToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountBridged,
|
||||
uint64 destinationChain,
|
||||
address indexed recipient,
|
||||
bytes32 messageId
|
||||
);
|
||||
|
||||
error ZeroAddress();
|
||||
error ZeroAmount();
|
||||
error InsufficientOutput();
|
||||
error SameToken();
|
||||
|
||||
constructor(address _swapRouter, address _bridge) {
|
||||
if (_swapRouter == address(0) || _bridge == address(0)) revert ZeroAddress();
|
||||
swapRouter = EnhancedSwapRouter(payable(_swapRouter));
|
||||
bridge = UniversalCCIPBridge(payable(_bridge));
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Swap source token to bridgeable token then bridge to destination chain
|
||||
* @param sourceToken Token user is sending (will be swapped if different from bridgeableToken)
|
||||
* @param amountIn Amount of source token
|
||||
* @param amountOutMin Minimum bridgeable token from swap (slippage protection; ignored if sourceToken == bridgeableToken)
|
||||
* @param bridgeableToken Token to bridge (WETH or stablecoin); must be registered on bridge
|
||||
* @param destinationChainSelector CCIP destination chain selector
|
||||
* @param recipient Recipient on destination chain
|
||||
* @param assetType Asset type hash for bridge (from UniversalAssetRegistry)
|
||||
* @param usePMM Whether bridge should use PMM liquidity
|
||||
* @param useVault Whether bridge should use vault
|
||||
*/
|
||||
function swapAndBridge(
|
||||
address sourceToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin,
|
||||
address bridgeableToken,
|
||||
uint64 destinationChainSelector,
|
||||
address recipient,
|
||||
bytes32 assetType,
|
||||
bool usePMM,
|
||||
bool useVault
|
||||
) external payable nonReentrant returns (bytes32 messageId) {
|
||||
if (amountIn == 0) revert ZeroAmount();
|
||||
if (sourceToken == address(0) || bridgeableToken == address(0) || recipient == address(0)) revert ZeroAddress();
|
||||
|
||||
uint256 amountToBridge;
|
||||
|
||||
if (sourceToken == bridgeableToken) {
|
||||
IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), amountIn);
|
||||
amountToBridge = amountIn;
|
||||
} else {
|
||||
IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), amountIn);
|
||||
IERC20(sourceToken).approve(address(swapRouter), amountIn);
|
||||
amountToBridge = swapRouter.swapTokenToToken(sourceToken, bridgeableToken, amountIn, amountOutMin);
|
||||
if (amountToBridge < amountOutMin) revert InsufficientOutput();
|
||||
}
|
||||
|
||||
UniversalCCIPBridge.BridgeOperation memory op = UniversalCCIPBridge.BridgeOperation({
|
||||
token: bridgeableToken,
|
||||
amount: amountToBridge,
|
||||
destinationChain: destinationChainSelector,
|
||||
recipient: recipient,
|
||||
assetType: assetType,
|
||||
usePMM: usePMM,
|
||||
useVault: useVault,
|
||||
complianceProof: "",
|
||||
vaultInstructions: ""
|
||||
});
|
||||
|
||||
IERC20(bridgeableToken).approve(address(bridge), amountToBridge);
|
||||
(bool ok, bytes memory result) = address(bridge).call{value: msg.value}(
|
||||
abi.encodeWithSelector(bridge.bridge.selector, op)
|
||||
);
|
||||
require(ok, "SwapBridgeSwapCoordinator: bridge failed");
|
||||
messageId = abi.decode(result, (bytes32));
|
||||
|
||||
emit SwapAndBridgeExecuted(
|
||||
sourceToken,
|
||||
bridgeableToken,
|
||||
amountIn,
|
||||
amountToBridge,
|
||||
destinationChainSelector,
|
||||
recipient,
|
||||
messageId
|
||||
);
|
||||
return messageId;
|
||||
}
|
||||
|
||||
receive() external payable {}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "./LiquidityPoolETH.sol";
|
||||
import "./interfaces/ISwapRouter.sol";
|
||||
import "./interfaces/IWETH.sol";
|
||||
import "./interfaces/ICurvePool.sol";
|
||||
import "./interfaces/IAggregationRouter.sol";
|
||||
|
||||
/**
|
||||
* @title SwapRouter
|
||||
* @notice Swaps ETH/WETH to stablecoins via Uniswap V3, Curve, or 1inch
|
||||
* @dev Primary: Uniswap V3, Secondary: Curve, Optional: 1inch aggregation
|
||||
*/
|
||||
contract SwapRouter is ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
enum SwapProvider {
|
||||
UniswapV3,
|
||||
Curve,
|
||||
OneInch
|
||||
}
|
||||
|
||||
// Contract addresses (Ethereum Mainnet)
|
||||
address public immutable uniswapV3Router; // 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45
|
||||
address public immutable curve3Pool; // 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7
|
||||
address public immutable oneInchRouter; // 0x1111111254EEB25477B68fb85Ed929f73A960582 (optional)
|
||||
|
||||
// Token addresses (Ethereum Mainnet)
|
||||
address public immutable weth; // 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
|
||||
address public immutable usdt; // 0xdAC17F958D2ee523a2206206994597C13D831ec7
|
||||
address public immutable usdc; // 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
|
||||
address public immutable dai; // 0x6B175474E89094C44Da98b954EedeAC495271d0F
|
||||
|
||||
// Uniswap V3 fee tiers (0.05% = 500, 0.3% = 3000, 1% = 10000)
|
||||
uint24 public constant FEE_TIER_LOW = 500; // 0.05%
|
||||
uint24 public constant FEE_TIER_MEDIUM = 3000; // 0.3%
|
||||
uint24 public constant FEE_TIER_HIGH = 10000; // 1%
|
||||
|
||||
event SwapExecuted(
|
||||
SwapProvider provider,
|
||||
LiquidityPoolETH.AssetType inputAsset,
|
||||
address inputToken,
|
||||
address outputToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOut
|
||||
);
|
||||
|
||||
error ZeroAmount();
|
||||
error ZeroAddress();
|
||||
error InsufficientOutput();
|
||||
error InvalidAssetType();
|
||||
error SwapFailed();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _uniswapV3Router Uniswap V3 SwapRouter address
|
||||
* @param _curve3Pool Curve 3pool address
|
||||
* @param _oneInchRouter 1inch Router address (can be address(0) if not used)
|
||||
* @param _weth WETH address
|
||||
* @param _usdt USDT address
|
||||
* @param _usdc USDC address
|
||||
* @param _dai DAI address
|
||||
*/
|
||||
constructor(
|
||||
address _uniswapV3Router,
|
||||
address _curve3Pool,
|
||||
address _oneInchRouter,
|
||||
address _weth,
|
||||
address _usdt,
|
||||
address _usdc,
|
||||
address _dai
|
||||
) {
|
||||
require(_uniswapV3Router != address(0), "SwapRouter: zero Uniswap router");
|
||||
require(_curve3Pool != address(0), "SwapRouter: zero Curve pool");
|
||||
require(_weth != address(0), "SwapRouter: zero WETH");
|
||||
require(_usdt != address(0), "SwapRouter: zero USDT");
|
||||
require(_usdc != address(0), "SwapRouter: zero USDC");
|
||||
require(_dai != address(0), "SwapRouter: zero DAI");
|
||||
|
||||
uniswapV3Router = _uniswapV3Router;
|
||||
curve3Pool = _curve3Pool;
|
||||
oneInchRouter = _oneInchRouter;
|
||||
weth = _weth;
|
||||
usdt = _usdt;
|
||||
usdc = _usdc;
|
||||
dai = _dai;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Swap to stablecoin using best available route
|
||||
* @param inputAsset Input asset type (ETH or WETH)
|
||||
* @param stablecoinToken Target stablecoin address (USDT, USDC, or DAI)
|
||||
* @param amountIn Input amount
|
||||
* @param amountOutMin Minimum output amount (slippage protection)
|
||||
* @param routeData Optional route data for specific provider
|
||||
* @return amountOut Output amount
|
||||
*/
|
||||
function swapToStablecoin(
|
||||
LiquidityPoolETH.AssetType inputAsset,
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin,
|
||||
bytes calldata routeData
|
||||
) external payable nonReentrant returns (uint256 amountOut) {
|
||||
if (amountIn == 0) revert ZeroAmount();
|
||||
if (stablecoinToken == address(0)) revert ZeroAddress();
|
||||
if (!_isValidStablecoin(stablecoinToken)) revert("SwapRouter: invalid stablecoin");
|
||||
|
||||
// Convert ETH to WETH if needed
|
||||
if (inputAsset == LiquidityPoolETH.AssetType.ETH) {
|
||||
IWETH(weth).deposit{value: amountIn}();
|
||||
inputAsset = LiquidityPoolETH.AssetType.WETH;
|
||||
}
|
||||
|
||||
// Approve WETH for swap
|
||||
IERC20 wethToken = IERC20(weth);
|
||||
// Use forceApprove for OpenZeppelin 5.x (or approve directly)
|
||||
wethToken.approve(uniswapV3Router, amountIn);
|
||||
if (oneInchRouter != address(0)) {
|
||||
wethToken.approve(oneInchRouter, amountIn);
|
||||
}
|
||||
|
||||
// Try Uniswap V3 first (primary)
|
||||
uint256 outputAmount = _executeUniswapV3Swap(stablecoinToken, amountIn, amountOutMin);
|
||||
if (outputAmount >= amountOutMin) {
|
||||
// Transfer output to caller
|
||||
IERC20(stablecoinToken).safeTransfer(msg.sender, outputAmount);
|
||||
emit SwapExecuted(SwapProvider.UniswapV3, inputAsset, weth, stablecoinToken, amountIn, outputAmount);
|
||||
return outputAmount;
|
||||
}
|
||||
|
||||
// Try Curve for stable/stable swaps (if USDT/USDC/DAI and routeData provided)
|
||||
// Note: Curve 3pool doesn't support WETH directly, would need intermediate swap
|
||||
// For now, revert if Uniswap fails
|
||||
revert SwapFailed();
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Execute Uniswap V3 swap (internal)
|
||||
* @param stablecoinToken Target stablecoin
|
||||
* @param amountIn Input amount
|
||||
* @param amountOutMin Minimum output
|
||||
* @return amountOut Output amount
|
||||
*/
|
||||
function _executeUniswapV3Swap(
|
||||
address stablecoinToken,
|
||||
uint256 amountIn,
|
||||
uint256 amountOutMin
|
||||
) internal returns (uint256 amountOut) {
|
||||
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
|
||||
tokenIn: weth,
|
||||
tokenOut: stablecoinToken,
|
||||
fee: FEE_TIER_MEDIUM, // 0.3% fee tier
|
||||
recipient: address(this),
|
||||
deadline: block.timestamp + 300, // 5 minutes
|
||||
amountIn: amountIn,
|
||||
amountOutMinimum: amountOutMin,
|
||||
sqrtPriceLimitX96: 0 // No price limit
|
||||
});
|
||||
|
||||
amountOut = ISwapRouter(uniswapV3Router).exactInputSingle(params);
|
||||
return amountOut;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check if token is a valid stablecoin
|
||||
* @param token Token address to check
|
||||
* @return True if valid stablecoin
|
||||
*/
|
||||
function _isValidStablecoin(address token) internal view returns (bool) {
|
||||
return token == usdt || token == usdc || token == dai;
|
||||
}
|
||||
|
||||
// Allow contract to receive ETH
|
||||
receive() external payable {}
|
||||
}
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||
import "../BridgeSwapCoordinator.sol";
|
||||
import "../LiquidityPoolETH.sol";
|
||||
import "../../../reserve/IReserveSystem.sol";
|
||||
import "./IStablecoinPegManager.sol";
|
||||
import "./ICommodityPegManager.sol";
|
||||
import "./IISOCurrencyManager.sol";
|
||||
|
||||
/**
|
||||
* @title BridgeReserveCoordinator
|
||||
* @notice Orchestrates bridge operations with ReserveSystem, ensuring peg maintenance and asset backing
|
||||
* @dev Connects trustless bridge to ReserveSystem for reserve verification and peg maintenance
|
||||
*/
|
||||
contract BridgeReserveCoordinator is Ownable, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
BridgeSwapCoordinator public immutable bridgeSwapCoordinator;
|
||||
IReserveSystem public immutable reserveSystem;
|
||||
IStablecoinPegManager public immutable stablecoinPegManager;
|
||||
ICommodityPegManager public immutable commodityPegManager;
|
||||
IISOCurrencyManager public immutable isoCurrencyManager;
|
||||
|
||||
// Reserve verification threshold (basis points: 10000 = 100%)
|
||||
uint256 public reserveVerificationThresholdBps = 10000; // 100% - must have full backing
|
||||
uint256 public constant MAX_RESERVE_THRESHOLD_BPS = 15000; // 150% max
|
||||
|
||||
// Rebalancing parameters
|
||||
uint256 public rebalancingCooldown = 1 hours;
|
||||
mapping(address => uint256) public lastRebalancingTime;
|
||||
|
||||
struct ReserveStatus {
|
||||
address asset;
|
||||
uint256 bridgeAmount;
|
||||
uint256 reserveBalance;
|
||||
uint256 reserveRatio; // reserveBalance / bridgeAmount * 10000
|
||||
bool isSufficient;
|
||||
uint256 lastVerified;
|
||||
}
|
||||
|
||||
struct PegStatus {
|
||||
address asset;
|
||||
uint256 currentPrice;
|
||||
uint256 targetPrice;
|
||||
int256 deviationBps; // Can be negative
|
||||
bool isMaintained;
|
||||
}
|
||||
|
||||
event ReserveVerified(
|
||||
uint256 indexed depositId,
|
||||
address indexed asset,
|
||||
uint256 bridgeAmount,
|
||||
uint256 reserveBalance,
|
||||
bool isSufficient
|
||||
);
|
||||
|
||||
event RebalancingTriggered(
|
||||
address indexed asset,
|
||||
uint256 amount,
|
||||
address indexed recipient
|
||||
);
|
||||
|
||||
event ReserveThresholdUpdated(uint256 oldThreshold, uint256 newThreshold);
|
||||
|
||||
error ZeroAddress();
|
||||
error InsufficientReserve();
|
||||
error RebalancingCooldownActive();
|
||||
error InvalidReserveThreshold();
|
||||
error ReserveVerificationFailed();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _bridgeSwapCoordinator BridgeSwapCoordinator contract address
|
||||
* @param _reserveSystem ReserveSystem contract address
|
||||
* @param _stablecoinPegManager StablecoinPegManager contract address
|
||||
* @param _commodityPegManager CommodityPegManager contract address
|
||||
* @param _isoCurrencyManager ISOCurrencyManager contract address
|
||||
*/
|
||||
constructor(
|
||||
address _bridgeSwapCoordinator,
|
||||
address _reserveSystem,
|
||||
address _stablecoinPegManager,
|
||||
address _commodityPegManager,
|
||||
address _isoCurrencyManager
|
||||
) Ownable(msg.sender) {
|
||||
if (_bridgeSwapCoordinator == address(0) ||
|
||||
_reserveSystem == address(0) ||
|
||||
_stablecoinPegManager == address(0) ||
|
||||
_commodityPegManager == address(0) ||
|
||||
_isoCurrencyManager == address(0)) {
|
||||
revert ZeroAddress();
|
||||
}
|
||||
|
||||
bridgeSwapCoordinator = BridgeSwapCoordinator(payable(_bridgeSwapCoordinator));
|
||||
reserveSystem = IReserveSystem(_reserveSystem);
|
||||
stablecoinPegManager = IStablecoinPegManager(_stablecoinPegManager);
|
||||
commodityPegManager = ICommodityPegManager(_commodityPegManager);
|
||||
isoCurrencyManager = IISOCurrencyManager(_isoCurrencyManager);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Bridge transfer with automatic reserve verification
|
||||
* @param depositId Deposit ID from bridge
|
||||
* @param recipient Recipient address
|
||||
* @param outputAsset Asset type (ETH or WETH)
|
||||
* @param stablecoinToken Target stablecoin
|
||||
* @param amountOutMin Minimum output amount
|
||||
* @param routeData Optional route data for swap
|
||||
* @return stablecoinAmount Amount of stablecoin received
|
||||
*/
|
||||
function bridgeWithReserveBacking(
|
||||
uint256 depositId,
|
||||
address recipient,
|
||||
LiquidityPoolETH.AssetType outputAsset,
|
||||
address stablecoinToken,
|
||||
uint256 amountOutMin,
|
||||
bytes calldata routeData
|
||||
) external nonReentrant returns (uint256 stablecoinAmount) {
|
||||
// Get claim amount from bridge
|
||||
// Note: We need to get the amount from ChallengeManager via BridgeSwapCoordinator
|
||||
// For now, we'll verify reserves after the bridge operation
|
||||
|
||||
// Execute bridge and swap
|
||||
stablecoinAmount = bridgeSwapCoordinator.bridgeAndSwap(
|
||||
depositId,
|
||||
recipient,
|
||||
outputAsset,
|
||||
stablecoinToken,
|
||||
amountOutMin,
|
||||
routeData
|
||||
);
|
||||
|
||||
// Verify reserve backing for the stablecoin
|
||||
ReserveStatus memory status = verifyReserveStatus(stablecoinToken, stablecoinAmount);
|
||||
|
||||
if (!status.isSufficient) {
|
||||
// Trigger rebalancing if reserves insufficient
|
||||
_triggerRebalancing(stablecoinToken, stablecoinAmount);
|
||||
}
|
||||
|
||||
emit ReserveVerified(
|
||||
depositId,
|
||||
stablecoinToken,
|
||||
stablecoinAmount,
|
||||
status.reserveBalance,
|
||||
status.isSufficient
|
||||
);
|
||||
|
||||
return stablecoinAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Verify peg status for all assets
|
||||
* @return pegStatuses Array of peg statuses
|
||||
*/
|
||||
function verifyPegStatus() external view returns (PegStatus[] memory pegStatuses) {
|
||||
// Get stablecoin peg statuses
|
||||
address[] memory stablecoins = stablecoinPegManager.getSupportedAssets();
|
||||
uint256 stablecoinCount = stablecoins.length;
|
||||
|
||||
// Get commodity peg statuses
|
||||
address[] memory commodities = commodityPegManager.getSupportedCommodities();
|
||||
uint256 commodityCount = commodities.length;
|
||||
|
||||
uint256 totalCount = stablecoinCount + commodityCount;
|
||||
pegStatuses = new PegStatus[](totalCount);
|
||||
|
||||
uint256 index = 0;
|
||||
|
||||
// Add stablecoin peg statuses
|
||||
for (uint256 i = 0; i < stablecoinCount; i++) {
|
||||
(uint256 currentPrice, uint256 targetPrice, int256 deviationBps, bool isMaintained) =
|
||||
stablecoinPegManager.getPegStatus(stablecoins[i]);
|
||||
|
||||
pegStatuses[index] = PegStatus({
|
||||
asset: stablecoins[i],
|
||||
currentPrice: currentPrice,
|
||||
targetPrice: targetPrice,
|
||||
deviationBps: deviationBps,
|
||||
isMaintained: isMaintained
|
||||
});
|
||||
index++;
|
||||
}
|
||||
|
||||
// Add commodity peg statuses
|
||||
for (uint256 i = 0; i < commodityCount; i++) {
|
||||
(uint256 currentPrice, uint256 targetPrice, int256 deviationBps, bool isMaintained) =
|
||||
commodityPegManager.getCommodityPegStatus(commodities[i]);
|
||||
|
||||
pegStatuses[index] = PegStatus({
|
||||
asset: commodities[i],
|
||||
currentPrice: currentPrice,
|
||||
targetPrice: targetPrice,
|
||||
deviationBps: deviationBps,
|
||||
isMaintained: isMaintained
|
||||
});
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Trigger rebalancing if peg deviates
|
||||
* @param asset Asset address to rebalance
|
||||
* @param amount Amount that needs backing
|
||||
*/
|
||||
function triggerRebalancing(address asset, uint256 amount) external onlyOwner nonReentrant {
|
||||
if (block.timestamp < lastRebalancingTime[asset] + rebalancingCooldown) {
|
||||
revert RebalancingCooldownActive();
|
||||
}
|
||||
|
||||
_triggerRebalancing(asset, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get reserve status for an asset
|
||||
* @param asset Asset address
|
||||
* @param bridgeAmount Amount bridged/required
|
||||
* @return status Reserve status
|
||||
*/
|
||||
function getReserveStatus(
|
||||
address asset,
|
||||
uint256 bridgeAmount
|
||||
) external view returns (ReserveStatus memory status) {
|
||||
return verifyReserveStatus(asset, bridgeAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set reserve verification threshold
|
||||
* @param newThreshold New threshold in basis points
|
||||
*/
|
||||
function setReserveThreshold(uint256 newThreshold) external onlyOwner {
|
||||
if (newThreshold > MAX_RESERVE_THRESHOLD_BPS) {
|
||||
revert InvalidReserveThreshold();
|
||||
}
|
||||
|
||||
uint256 oldThreshold = reserveVerificationThresholdBps;
|
||||
reserveVerificationThresholdBps = newThreshold;
|
||||
|
||||
emit ReserveThresholdUpdated(oldThreshold, newThreshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set rebalancing cooldown period
|
||||
* @param newCooldown New cooldown in seconds
|
||||
*/
|
||||
function setRebalancingCooldown(uint256 newCooldown) external onlyOwner {
|
||||
rebalancingCooldown = newCooldown;
|
||||
}
|
||||
|
||||
// ============ Internal Functions ============
|
||||
|
||||
/**
|
||||
* @notice Verify reserve status for an asset
|
||||
* @param asset Asset address
|
||||
* @param bridgeAmount Amount bridged/required
|
||||
* @return status Reserve status
|
||||
*/
|
||||
function verifyReserveStatus(
|
||||
address asset,
|
||||
uint256 bridgeAmount
|
||||
) internal view returns (ReserveStatus memory status) {
|
||||
uint256 reserveBalance = reserveSystem.getReserveBalance(asset);
|
||||
uint256 reserveRatio = bridgeAmount > 0
|
||||
? (reserveBalance * 10000) / bridgeAmount
|
||||
: type(uint256).max;
|
||||
|
||||
bool isSufficient = reserveRatio >= reserveVerificationThresholdBps;
|
||||
|
||||
return ReserveStatus({
|
||||
asset: asset,
|
||||
bridgeAmount: bridgeAmount,
|
||||
reserveBalance: reserveBalance,
|
||||
reserveRatio: reserveRatio,
|
||||
isSufficient: isSufficient,
|
||||
lastVerified: block.timestamp
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Internal function to trigger rebalancing
|
||||
* @param asset Asset address
|
||||
* @param amount Amount that needs backing
|
||||
*/
|
||||
function _triggerRebalancing(address asset, uint256 amount) internal {
|
||||
lastRebalancingTime[asset] = block.timestamp;
|
||||
|
||||
// Check if we need to deposit reserves
|
||||
ReserveStatus memory status = verifyReserveStatus(asset, amount);
|
||||
|
||||
if (!status.isSufficient) {
|
||||
uint256 shortfall = amount - status.reserveBalance;
|
||||
|
||||
// In production, this would trigger reserve deposits or conversions
|
||||
// For now, we emit an event for off-chain monitoring
|
||||
emit RebalancingTriggered(asset, shortfall, address(this));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||||
import "../../../reserve/IReserveSystem.sol";
|
||||
import "./ICommodityPegManager.sol";
|
||||
|
||||
/**
|
||||
* @title CommodityPegManager
|
||||
* @notice Manages commodity pegging (gold XAU, silver, oil, etc.) via XAU triangulation
|
||||
* @dev All commodities are pegged through XAU (gold) as the base anchor
|
||||
*/
|
||||
contract CommodityPegManager is ICommodityPegManager, Ownable, ReentrancyGuard {
|
||||
IReserveSystem public immutable reserveSystem;
|
||||
|
||||
// XAU address (gold) - base anchor
|
||||
address public xauAddress;
|
||||
|
||||
// Commodity peg threshold (basis points: 10000 = 100%)
|
||||
uint256 public commodityPegThresholdBps = 100; // ±1.0% for commodities
|
||||
uint256 public constant MAX_PEG_THRESHOLD_BPS = 1000; // 10% max
|
||||
|
||||
struct Commodity {
|
||||
address commodityAddress;
|
||||
string symbol;
|
||||
uint256 xauRate; // Rate per 1 oz XAU (in 18 decimals)
|
||||
bool isActive;
|
||||
}
|
||||
|
||||
mapping(address => Commodity) public commodities;
|
||||
address[] public supportedCommodities;
|
||||
|
||||
// XAU rates: 1 oz XAU = xauRate units of commodity
|
||||
// Example: 1 oz XAU = 75 oz XAG (silver), so xauRate = 75e18
|
||||
|
||||
event CommodityRegistered(
|
||||
address indexed commodity,
|
||||
string symbol,
|
||||
uint256 xauRate
|
||||
);
|
||||
|
||||
event CommodityPegChecked(
|
||||
address indexed commodity,
|
||||
uint256 currentPrice,
|
||||
uint256 targetPrice,
|
||||
int256 deviationBps,
|
||||
bool isMaintained
|
||||
);
|
||||
|
||||
event RebalancingTriggered(
|
||||
address indexed commodity,
|
||||
int256 deviationBps
|
||||
);
|
||||
|
||||
error ZeroAddress();
|
||||
error CommodityNotRegistered();
|
||||
error InvalidXauRate();
|
||||
error InvalidThreshold();
|
||||
error XauNotSet();
|
||||
|
||||
/**
|
||||
* @notice Constructor
|
||||
* @param _reserveSystem ReserveSystem contract address
|
||||
*/
|
||||
constructor(address _reserveSystem) Ownable(msg.sender) {
|
||||
if (_reserveSystem == address(0)) revert ZeroAddress();
|
||||
reserveSystem = IReserveSystem(_reserveSystem);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set XAU (gold) address
|
||||
* @param _xauAddress XAU token address
|
||||
*/
|
||||
function setXAUAddress(address _xauAddress) external onlyOwner {
|
||||
if (_xauAddress == address(0)) revert ZeroAddress();
|
||||
xauAddress = _xauAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Register a commodity for pegging
|
||||
* @param commodity Commodity token address
|
||||
* @param symbol Commodity symbol (XAG, XPT, XPD, etc.)
|
||||
* @param xauRate Rate: 1 oz XAU = xauRate units of commodity (in 18 decimals)
|
||||
* @return success Whether registration was successful
|
||||
*/
|
||||
function registerCommodity(
|
||||
address commodity,
|
||||
string memory symbol,
|
||||
uint256 xauRate
|
||||
) external override onlyOwner returns (bool) {
|
||||
if (commodity == address(0)) revert ZeroAddress();
|
||||
if (xauRate == 0) revert InvalidXauRate();
|
||||
if (xauAddress == address(0)) revert XauNotSet();
|
||||
|
||||
commodities[commodity] = Commodity({
|
||||
commodityAddress: commodity,
|
||||
symbol: symbol,
|
||||
xauRate: xauRate,
|
||||
isActive: true
|
||||
});
|
||||
|
||||
// Add to supported commodities if not already present
|
||||
bool alreadyAdded = false;
|
||||
for (uint256 i = 0; i < supportedCommodities.length; i++) {
|
||||
if (supportedCommodities[i] == commodity) {
|
||||
alreadyAdded = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!alreadyAdded) {
|
||||
supportedCommodities.push(commodity);
|
||||
}
|
||||
|
||||
emit CommodityRegistered(commodity, symbol, xauRate);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Check commodity peg via XAU
|
||||
* @param commodity Commodity address
|
||||
* @return isMaintained Whether peg is maintained
|
||||
* @return deviationBps Deviation in basis points
|
||||
*/
|
||||
function checkCommodityPeg(
|
||||
address commodity
|
||||
) external view override returns (bool isMaintained, int256 deviationBps) {
|
||||
Commodity memory comm = commodities[commodity];
|
||||
if (comm.commodityAddress == address(0)) revert CommodityNotRegistered();
|
||||
|
||||
// Get XAU price in target currency (USD)
|
||||
(uint256 xauPrice, ) = reserveSystem.getPrice(xauAddress);
|
||||
|
||||
// Calculate target price: xauPrice / xauRate
|
||||
uint256 targetPrice = (xauPrice * 1e18) / comm.xauRate;
|
||||
|
||||
// Get current commodity price
|
||||
(uint256 currentPrice, ) = reserveSystem.getPrice(commodity);
|
||||
|
||||
// Calculate deviation
|
||||
if (targetPrice == 0) {
|
||||
return (false, type(int256).max);
|
||||
}
|
||||
|
||||
if (currentPrice >= targetPrice) {
|
||||
uint256 diff = currentPrice - targetPrice;
|
||||
deviationBps = int256((diff * 10000) / targetPrice);
|
||||
} else {
|
||||
uint256 diff = targetPrice - currentPrice;
|
||||
deviationBps = -int256((diff * 10000) / targetPrice);
|
||||
}
|
||||
|
||||
isMaintained = _abs(deviationBps) <= commodityPegThresholdBps;
|
||||
|
||||
return (isMaintained, deviationBps);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Triangulate commodity value through XAU to target currency
|
||||
* @param commodity Commodity address
|
||||
* @param amount Amount of commodity
|
||||
* @param targetCurrency Target currency address (e.g., USDT for USD)
|
||||
* @return targetAmount Amount in target currency
|
||||
*/
|
||||
function triangulateViaXAU(
|
||||
address commodity,
|
||||
uint256 amount,
|
||||
address targetCurrency
|
||||
) external view override returns (uint256 targetAmount) {
|
||||
Commodity memory comm = commodities[commodity];
|
||||
if (comm.commodityAddress == address(0)) revert CommodityNotRegistered();
|
||||
if (xauAddress == address(0)) revert XauNotSet();
|
||||
|
||||
// Convert commodity to XAU: amount / xauRate
|
||||
uint256 xauAmount = (amount * 1e18) / comm.xauRate;
|
||||
|
||||
// Get XAU price in target currency
|
||||
(uint256 xauPrice, ) = reserveSystem.getPrice(xauAddress);
|
||||
|
||||
// Get target currency price (should be 1e18 for stablecoins)
|
||||
(uint256 targetPrice, ) = reserveSystem.getPrice(targetCurrency);
|
||||
|
||||
// Calculate: xauAmount * xauPrice / targetPrice
|
||||
targetAmount = (xauAmount * xauPrice) / (targetPrice * 1e18);
|
||||
|
||||
return targetAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get commodity price in target currency
|
||||
* @param commodity Commodity address
|
||||
* @param targetCurrency Target currency address
|
||||
* @return price Price in target currency
|
||||
*/
|
||||
function getCommodityPrice(
|
||||
address commodity,
|
||||
address targetCurrency
|
||||
) external view override returns (uint256 price) {
|
||||
Commodity memory comm = commodities[commodity];
|
||||
if (comm.commodityAddress == address(0)) revert CommodityNotRegistered();
|
||||
if (xauAddress == address(0)) revert XauNotSet();
|
||||
|
||||
// Get XAU price in target currency
|
||||
(uint256 xauPrice, ) = reserveSystem.getPrice(xauAddress);
|
||||
|
||||
// Calculate commodity price: xauPrice / xauRate
|
||||
price = (xauPrice * 1e18) / comm.xauRate;
|
||||
|
||||
return price;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get commodity peg status
|
||||
* @param commodity Commodity address
|
||||
* @return currentPrice Current price
|
||||
* @return targetPrice Target price (via XAU)
|
||||
* @return deviationBps Deviation in basis points
|
||||
* @return isMaintained Whether peg is maintained
|
||||
*/
|
||||
function getCommodityPegStatus(
|
||||
address commodity
|
||||
) external view override returns (uint256 currentPrice, uint256 targetPrice, int256 deviationBps, bool isMaintained) {
|
||||
Commodity memory comm = commodities[commodity];
|
||||
if (comm.commodityAddress == address(0)) revert CommodityNotRegistered();
|
||||
if (xauAddress == address(0)) revert XauNotSet();
|
||||
|
||||
// Get XAU price
|
||||
(uint256 xauPrice, ) = reserveSystem.getPrice(xauAddress);
|
||||
|
||||
// Calculate target price
|
||||
targetPrice = (xauPrice * 1e18) / comm.xauRate;
|
||||
|
||||
// Get current price
|
||||
(currentPrice, ) = reserveSystem.getPrice(commodity);
|
||||
|
||||
// Calculate deviation
|
||||
if (targetPrice == 0) {
|
||||
return (currentPrice, targetPrice, type(int256).max, false);
|
||||
}
|
||||
|
||||
if (currentPrice >= targetPrice) {
|
||||
uint256 diff = currentPrice - targetPrice;
|
||||
deviationBps = int256((diff * 10000) / targetPrice);
|
||||
} else {
|
||||
uint256 diff = targetPrice - currentPrice;
|
||||
deviationBps = -int256((diff * 10000) / targetPrice);
|
||||
}
|
||||
|
||||
isMaintained = _abs(deviationBps) <= commodityPegThresholdBps;
|
||||
|
||||
// Note: Cannot emit in view function, events should be emitted by caller if needed
|
||||
|
||||
return (currentPrice, targetPrice, deviationBps, isMaintained);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get all supported commodities
|
||||
* @return Array of commodity addresses
|
||||
*/
|
||||
function getSupportedCommodities() external view override returns (address[] memory) {
|
||||
return supportedCommodities;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Set commodity peg threshold
|
||||
* @param newThreshold New threshold in basis points
|
||||
*/
|
||||
function setCommodityPegThreshold(uint256 newThreshold) external onlyOwner {
|
||||
if (newThreshold > MAX_PEG_THRESHOLD_BPS) revert InvalidThreshold();
|
||||
commodityPegThresholdBps = newThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Update XAU rate for a commodity
|
||||
* @param commodity Commodity address
|
||||
* @param newXauRate New XAU rate
|
||||
*/
|
||||
function updateXauRate(address commodity, uint256 newXauRate) external onlyOwner {
|
||||
if (commodities[commodity].commodityAddress == address(0)) revert CommodityNotRegistered();
|
||||
if (newXauRate == 0) revert InvalidXauRate();
|
||||
|
||||
commodities[commodity].xauRate = newXauRate;
|
||||
}
|
||||
|
||||
// ============ Internal Functions ============
|
||||
|
||||
/**
|
||||
* @notice Get absolute value of int256
|
||||
* @param value Input value
|
||||
* @return Absolute value
|
||||
*/
|
||||
function _abs(int256 value) internal pure returns (uint256) {
|
||||
return value < 0 ? uint256(-value) : uint256(value);
|
||||
}
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.19;
|
||||
|
||||
/**
|
||||
* @title ICommodityPegManager
|
||||
* @notice Interface for Commodity Peg Manager
|
||||
*/
|
||||
interface ICommodityPegManager {
|
||||
struct CommodityPegStatus {
|
||||
uint256 currentPrice;
|
||||
uint256 targetPrice;
|
||||
int256 deviationBps;
|
||||
bool isMaintained;
|
||||
}
|
||||
|
||||
function registerCommodity(address commodity, string memory symbol, uint256 xauRate) external returns (bool);
|
||||
function checkCommodityPeg(address commodity) external view returns (bool isMaintained, int256 deviationBps);
|
||||
function triangulateViaXAU(address commodity, uint256 amount, address targetCurrency) external view returns (uint256 targetAmount);
|
||||
function getCommodityPrice(address commodity, address targetCurrency) external view returns (uint256 price);
|
||||
function getCommodityPegStatus(address commodity) external view returns (uint256 currentPrice, uint256 targetPrice, int256 deviationBps, bool isMaintained);
|
||||
function getSupportedCommodities() external view returns (address[] memory);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user